I have implemented REST webservice using Spring 5 #RestController.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ag</groupId>
<artifactId>myFirstWeb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>myFirstWeb Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jdbc</artifactId>
<version>1.0.0.M3</version>
</dependency>
<!-- ojdbc6.jar example -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-libs-milestone</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build>
<finalName>myFirstWeb</finalName>
</build>
</project>
web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:ctx="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<ctx:component-scan base-package="com.*" />
<ctx:annotation-config />
<mvc:annotation-driven />
<!-- JSON Support -->
<bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE" />
<property name="username" value="SYSTEM" />
<property name="password" value="xlri#123" />
</bean>
</beans>
REST service
package com.pk;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.pk.services.StudentService;
import com.pk.vo.StudentVO;
#RestController
#RequestMapping(value="/first")
public class MyFirst{
public MyFirst() {
System.out.println("Webservice 'MyFirst' initialised...");
}
#Autowired
#Qualifier("studentService")
private StudentService service;
public StudentService getService() {
return service;
}
public void setService(StudentService service) {
this.service = service;
}
#RequestMapping(value="/hello",method=RequestMethod.GET,produces="application/json")
public ResponseEntity<String> sayHello() {
StringBuffer strb = new StringBuffer();
strb.append("{")
.append("\"message\"")
.append(":")
.append("\"Hello, this is my first message\"")
.append("}");
ResponseEntity<String> responseEntity = new ResponseEntity<String>(strb.toString(), HttpStatus.OK);
return responseEntity;
}
#RequestMapping(value="/students",method=RequestMethod.GET,produces="application/json")
public List<StudentVO> getAllStudents(){
List<StudentVO> list = null;
System.out.println(" Studeent list ");
try {
list = this.service.getAll();
}catch(Exception e) {
e.printStackTrace();
}
return list;
}
}
I am able to invoke
/spring/first/hello
But I am not able to invoke
/spring/first/students
The error it gives is:
HTTP Status 406 – Not Acceptable
Then I changed my code to,
#RequestMapping(value="/students",method=RequestMethod.GET,produces="application/json")
public ResponseEntity<List<StudentVO>> getAllStudents(){
List<StudentVO> list = null;
ResponseEntity<List<StudentVO>> responseEntity = null;
System.out.println(" Studeent list ");
try {
list = this.service.getAll();
for(StudentVO vo : list) {
System.out.println(vo);
}
responseEntity = new ResponseEntity<List<StudentVO>>(list,HttpStatus.OK);
}catch(Exception e) {
e.printStackTrace();
}
return responseEntity;
}
It's not working as well, although it prints all the vo's in console.
It gives the same error:
HTTP Status 406 – Not Acceptable
StudentVO.java
package com.pk.vo;
import java.io.Serializable;
public class StudentVO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 145L;
private Integer studentId;
private String studentName;
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
#Override
public int hashCode(){
int hash = 31;
int hashFromId = this.studentId.hashCode();
hash = (7 * hash) + hashFromId;
return hash;
}
#Override
public boolean equals(Object object) {
boolean flag = false;
StudentVO vo = (StudentVO) object;
if(vo != null && this.studentId.intValue() == vo.studentId.intValue()) {
flag = true;
}
return flag;
}
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("\nStudent-ID ").append(this.studentId).append(",\tStudent-Name ").append(this.studentName);
return strb.toString();
}
}
Can you please tell me where I am wrong?
Add the following dependencies to your pom.xml, you get the error because spring can not serialize your List to JSON, this is handled by JSON however with spring 4.1.1+ you have to add these dependencies yourself:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Related
I connected Spring 5.0.19.RELEASE and Hibernate 5.2.10.Final.
I'm getting an error: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active].
The same error is also obtained with other requests (for example "from News").
The work of the application reaches the DAO layer and executes a query from the database.
When I trying to get information from BD and display this list in the web app.
I'm a newbie in Java.
I tried the options below:
why-org-hibernate-hql-internal-ast-querysyntaxexception-customer-is-not-mapped
Hibernate error - QuerySyntaxException: users is not mapped [from
users]
but it doesn't work.
I hope to get help in my confused situation.
My DataBase in MySQL
CREATE TABLE `news` (
`idnews` int NOT NULL AUTO_INCREMENT,
`title` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`brief` varchar(500) COLLATE utf8_bin DEFAULT NULL,
`content` varchar(5000) COLLATE utf8_bin DEFAULT NULL,
`date` timestamp NULL DEFAULT NULL,
`status` varchar(45) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`idnews`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
Error:
Jun 22, 2021 9:10:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/spring-myproject] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3696)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3585)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:546)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:655)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:679)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
at myproject.dao.impl.SQLNewsDAO.all(SQLNewsDAO.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at jdk.proxy3/jdk.proxy3.$Proxy26.all(Unknown Source)
at myproject.service.impl.NewsServiceImpl.takeAll(NewsServiceImpl.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at jdk.proxy3/jdk.proxy3.$Proxy27.takeAll(Unknown Source)
at myproject.command.GoToMainIndexPage.execute(GoToMainIndexPage.java:27)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:799)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:873)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:831)
Entity:
package myproject.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="news")
public class News implements Serializable {
private static final long serialVersionUID = 5421029433949953632L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idnews")
private int idnews;
#Column(name="title")
private String title;
#Column(name="brief")
private String brief;
#Column(name="content")
private String content;
#Column(name="date")
private LocalDateTime date;
#Column(name="status")
private String status;
public News() {
}
public News(int idnews, String title, String brief) {
super();
this.setIdnews(idnews);
this.title = title;
this.setBrief(brief);
}
public News(int idnews, String title, String brief, String content, LocalDateTime date) {
super();
this.setIdnews(idnews);
this.title = title;
this.setBrief(brief);
this.setContent(content);
this.setDate(date);
}
public int getIdnews() {
return idnews;
}
public void setIdnews(int idnews) {
this.idnews = idnews;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBrief() {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
String formattedDateTime = date.format(newFormat);
return formattedDateTime;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((brief == null) ? 0 : brief.hashCode());
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + idnews;
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
News other = (News) obj;
if (brief == null) {
if (other.brief != null)
return false;
} else if (!brief.equals(other.brief))
return false;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (idnews != other.idnews)
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
#Override
public String toString() {
return "id: " + this.idnews + "\n" +
"title:" + this.title + "\n" +
"brief:" + this.brief + "\n" +
"content: " + this.content + "\n" +
"date: " + this.date + "\n" +
"status: " + this.status;
}
}
Controller layer
package myproject.command;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import myproject.entity.News;
import myproject.service.NewsService;
import myproject.service.ServiceException;
#Controller
#RequestMapping("/mainIndexPage")
public class GoToMainIndexPage {
#Autowired
private NewsService newsService;
#RequestMapping("/showMainPage")
public String execute(Model theModel) throws ServletException, IOException, ServiceException {
List<News> news = newsService.takeAll();
theModel.addAttribute("news", news);
return "main_index_page";
}
}
Service layer
package myproject.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import myproject.dao.DAOException;
import myproject.dao.NewsDAO;
import myproject.entity.News;
import myproject.service.NewsService;
import myproject.service.ServiceException;
#Service
public class NewsServiceImpl implements NewsService {
#Autowired
private NewsDAO newsDAO;
//#Override
#Transactional
public List<News> takeAll() throws ServiceException {
System.out.println(1);
List<News> news;
try {
news = newsDAO.all();
} catch (DAOException e) {
throw new ServiceException(e.getMessage(), e);
}
return news;
}
}
DAO layer
package myproject.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import myproject.dao.DAOException;
import myproject.dao.NewsDAO;
import myproject.entity.News;
#Repository
public class SQLNewsDAO implements NewsDAO {
// need to inject the session factory
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<News> all() throws DAOException {
System.out.println(2);
Session currentSession = sessionFactory.getCurrentSession();
Query<News> theQuery = currentSession.createQuery("from News where status =: active", News.class); /*"from News where status = 'active'"*/
List<News> news = theQuery.getResultList();
return news;
}
}
ApplicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="myproject" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 6 Add support for reading web resources: css, images, js, etc
... -->
<mvc:resources location="/resources/"
mapping="/resources/**" />
<bean
class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property value="resources/messages" name="basenames" />
</bean>
<!-- Step 7 Define Database DataSource / connection pool -->
<bean id="myDataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/news_management_spring_hibernate?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC" />
<property name="user" value="111" />
<property name="password" value="111" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 8 Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="src.main.java.myproject.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 9 Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 10 Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>by.htp.spring.main</groupId>
<artifactId>spring-myproject</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-myproject Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Generic properties -->
<maven.compiler.release>1.8</maven.compiler.release>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<!-- Spring -->
<spring-framework.version>5.0.19.RELEASE</spring-framework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- BD -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- Dependency Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Other -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
<!-- New depend -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.26.Final</version>
</dependency>
</dependencies>
<build>
<finalName>spring-myproject</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>tomcat-server</server>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>${project.build.sourceEncoding}</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
</project>
main_index_page.jsp (view)
<!--News-->
<div class="list_news">
<c:forEach var="AllNewsFromBD" items="${news}"> <!--requestScope.-->
<div class="list_news_block">
<div class="">
<h5 class="title_news">
<c:out value="${AllNewsFromBD.title}" />
</h5>
<p class="">
<c:out value="${AllNewsFromBD.brief}" />
</p>
<c:if test="${sessionScope.auth == true}">
<div class="">
<a href="Controller?command=go_to_one_news_page&idnews=<c:out value="${AllNewsFromBD.idnews}"/>">
<c:out value="${ReadMore}" /></a>
</div>
</c:if>
<br/>
</div>
</div>
</c:forEach>
</div>
There are lot of posts on stackoverflow in which addressing the same issue. But I was unable to find a definite solution for this.
Please help
You could try this:
Query<News> theQuery = currentSession.createQuery("select news from News news where news.status = :active", News.class);
theQuery.setParameter("status", active);
return theQuery.getResultList();
I'm implementing a JAX-RS that use Jersey, Hibernate, and DataSources, but after a lot of corrected errors, I faced one that I couldn't find a solution
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408:
Unsatisfied dependencies for type ServiceLocator with qualifiers
#Default at injection point [UnbackedAnnotatedField] #Inject private
org.glassfish.jersey.server.mvc.internal.ViewableMessageBodyWriter.serviceLocator
at
org.glassfish.jersey.server.mvc.internal.ViewableMessageBodyWriter.serviceLocator(ViewableMessageBodyWriter.java:0)
at
org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:362)
at
org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:284)
at
org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:137)
at
org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:158)
at
org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:501)
at
org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:61)
at
org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:59)
at
org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:62)
at
org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:55)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748) at
org.jboss.threads.JBossThread.run(JBossThread.java:320)
Controller
I tried withou Stateless, RequestScoped... But don't worked.
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
#Path("ejb/notificacao")
#Stateless
#LocalBean
#RequestScoped
public class NotificacaoControladorEJB {
SmartJava smartjava = new SmartJava();
#EJB
NotificacaoDAOEJB notificacaoDAO;
#GET
#Produces("application/json; charset=UTF-8")
#Path("/contador/{id}")
public Notificacao contadorGet(#PathParam("id") int id) {
long quantidade;
try {
quantidade = notificacaoDAO.contador(id);
return new Notificacao(quantidade);
} catch(Exception e) {
quantidade = 0;
System.err.println(smartjava.getFullStackTrace(e));
return new Notificacao(quantidade);
}
}
#GET
#Produces("application/json; charset=UTF-8")
#Path("/marcarcomolida/{id}")
public Notificacao marcarcomolida(#PathParam("id") int id) {
try {
Notificacao entidade = notificacaoDAO.GetNotificacao(id);
if(entidade != null) {
entidade.setVisualizado(true);
entidade.setDtvisualizado(new Timestamp(System.currentTimeMillis()));
notificacaoDAO.Alterar(entidade);
return new Notificacao(entidade.getNrseq());
} else {
return new Notificacao();
}
} catch(Exception e) {
System.err.println(smartjava.getFullStackTrace(e));
return null;
}
}
#GET
#Produces("application/json; charset=UTF-8")
#Path("/listar/{id}/{quantidade}")
public List<Notificacao> listar(#PathParam("id") int id, #PathParam("quantidade") int quantidade) {
List<Notificacao> notificacoes = new ArrayList<Notificacao>();
List<Notificacao> listaDeNotificacoes;
try {
if(quantidade < 1) {
listaDeNotificacoes = notificacaoDAO.listarTodosPorUsuarioNrseq(id);
} else {
listaDeNotificacoes = notificacaoDAO.listarQuantidadePorUsuarioNrseq(id, quantidade);
}
if(listaDeNotificacoes != null) {
for (Notificacao notificacao : listaDeNotificacoes) {
Usuario u = construtorUsuario(notificacao.getUseralvo());
notificacoes.add(new Notificacao(notificacao.getNrseq(), notificacao.getTitulo(), notificacao.getConteudo(),
notificacao.getImg(), notificacao.getLink(), notificacao.isAtivo(), notificacao.isVisualizado(),
notificacao.getDtcad(), notificacao.getDtvisualizado(), u));
}
}
return notificacoes;
} catch(Exception e) {
return new ArrayList<Notificacao>();
}
}
#POST
#Consumes("application/json; charset=UTF-8")
#Produces("application/json; charset=UTF-8")
#Path("/cadastrar/um")
public Notificacao cadastrarUm(Notificacao notificacao) {
try {
Notificacao entidade = notificacaoParaEntidade(notificacao, notificacao.getUseralvo());
notificacaoDAO.Salvar(entidade);
return new Notificacao(entidade.getNrseq());
} catch(Exception e) {
System.err.println(smartjava.getFullStackTrace(e));
return new Notificacao();
}
}
public Notificacao cadastrar(Notificacao notificacao) {
try {
Notificacao entidade = notificacaoParaEntidade(notificacao, notificacao.getUseralvo());
notificacaoDAO.Salvar(entidade);
return new Notificacao(entidade.getNrseq());
} catch(Exception e) {
System.err.println(smartjava.getFullStackTrace(e));
return new Notificacao();
}
}
public Notificacao notificacaoParaEntidade(Notificacao notificacao, Usuario usuario) {
Notificacao entidade = new Notificacao();
entidade.setTitulo(notificacao.getTitulo());
entidade.setConteudo(notificacao.getConteudo());
entidade.setImg(notificacao.getImg());
entidade.setDtcad(new Timestamp(System.currentTimeMillis()));
entidade.setUsercad(notificacao.getUsercad());
entidade.setLink(notificacao.getLink());
entidade.setAtivo(true);
entidade.setUseralvo(usuario);
return entidade;
}
private Usuario construtorUsuario(Usuario u) {
try {
return new Usuario(u.getNrseq(), u.getNome(), u.getEmail());
} catch (Exception e) {
return new Usuario();
}
}
}
DAO
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
#LocalBean
public class NotificacaoDAOEJB {
//private EntityManagerFactory entityManagerFactory;
#PersistenceContext
private EntityManager entityManager;
SmartJava sj = new SmartJava();
public Notificacao Salvar(Notificacao notificacao) {
try {
this.entityManager.getTransaction().begin();
this.entityManager.persist(notificacao);
this.entityManager.getTransaction().commit();
} catch (Exception e) {
System.out.println(sj.getFullStackTrace(e));
} finally {
//this.entityManager.close();
}
return notificacao;
}
public void Alterar(Notificacao notificacao){
this.entityManager.getTransaction().begin();
this.entityManager.merge(notificacao);
this.entityManager.getTransaction().commit();
//this.entityManager.close();
}
#SuppressWarnings("unchecked")
public List<Notificacao> Listar(){
return this.entityManager.createQuery("SELECT a FROM Notificacao a ORDER BY a.dtcad").getResultList();
}
public Notificacao GetNotificacao(int nrseq) {
return this.entityManager.find(Notificacao.class, nrseq);
}
#SuppressWarnings("unchecked")
public long contador(int nrsequsuario) {
try {
return (long) this.entityManager.createQuery("SELECT COUNT(a) FROM Notificacao a "
+ "WHERE a.visualizado = false AND a.useralvo.nrseq = :usuario ORDER BY a.dtcad")
.setParameter("usuario", nrsequsuario).getSingleResult();
} catch(Exception e) {
System.err.println(sj.getFullStackTrace(e));
return 0;
}
}
#SuppressWarnings("unchecked")
public List<Notificacao> listarTodosPorUsuarioNrseq(int id) {
try {
return this.entityManager.createQuery("SELECT a FROM Notificacao a "
+ "WHERE a.useralvo.nrseq = :usuario ORDER BY a.dtcad DESC")
.setParameter("usuario", id).getResultList();
} catch(Exception e) {
System.err.println(sj.getFullStackTrace(e));
return null;
}
}
#SuppressWarnings("unchecked")
public List<Notificacao> listarQuantidadePorUsuarioNrseq(int id, int quantidade) {
try {
return this.entityManager.createQuery("SELECT a FROM Notificacao a "
+ "WHERE a.useralvo.nrseq = :usuario ORDER BY a.dtcad DESC")
.setParameter("usuario", id).setMaxResults(quantidade).getResultList();
} catch(Exception e) {
System.err.println(sj.getFullStackTrace(e));
return null;
}
}
}
WEB.XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>br.com.souvizinho.controlador</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
<!--
<resource-ref>
<description>DB Connection</description>
<res-ref-name>java:/dbsouvizinho</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref> -->
<!-- COMENTAR AO GLASSFISH -->
<!--
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> -->
</web-app>
PERSISTENCE.XML
<!-- JBOS AS 7.11 E WildFly-->
<!-- --> <persistence-unit name="persistence_unit_souvizinho" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/dbsouvizinho</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
<!-- --> <!-- <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/dbsouvizinho"/> -->
<!-- -->
<!-- <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.2"/> -->
<!-- <property name="hibernate.classloading.use_current_tccl_as_parent" value="false" /> -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit> <!-- -->
POM.XML
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-mvc-jsp</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.grizzly/grizzly-http-server -->
<dependency>
<groupId>org.glassfish.grizzly</groupId>
<artifactId>grizzly-http-server</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<!-- TOMCAT -->
<!--
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.1.Final</version>
</dependency> -->
<!-- WILDFLY 11 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.10.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.1.10.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging -->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
</dependencies>
Worked for me:
Remove:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-mvc-jsp</artifactId>
</dependency>
And put the bellow tag on my persistence
<class>br.com.souvizinho.modelo.Notificacao</class>
Am struggling for last three days with the error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/demomongo/templateapp/login. (Reason: CORS header 'Access-Control-Allow-Origin' missing)."
Here is my code kindly help.
Login.html
<html ng-app="LoginApp">
<body>
<script src="angular.min.js"></script>
<script src="LoginApp.js"> </script>
<div ng-controller="loginController as login">
Username <input type="text" ng-model="username" /><br/>
Password <input type="text" ng-model="password" /><br/>
<button ng-click="validate()">Validate</button>
</div>
<br/> Register Me/New user
</body>
</html>
LoginApp.js
(function(){
var app;
app=angular.module('LoginApp',[]);
app.controller('loginController',function($scope,$http){
var dataObj = {
"name" : "Java Honk",
"password" : "NY"
};
$scope.validate = function() {
dataObj.name=$scope.username;
dataObj.password=$scope.password;
//if($scope.username=="sam" && $scope.password=="pwd")
// console.log("password match");
// else
//console.log("username/pwd not matching");
$http.post('http://localhost:8080/demomongo/templateapp/login', dataObj)
.success(function(responseData) {
$scope.responseData = responseData;
console.log(responseData);
}).error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
}
});
})();
CORSFilter:
CORSFilter.java
package com.demo.mongo.example.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;
public class CORSFilter extends OncePerRequestFilter {
private static final Log LOG = LogFactory.getLog(CORSFilter.class);
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
LOG.trace("Sending Header....");
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
// response.addHeader("Access-Control-Allow-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1");
}
filterChain.doFilter(request, response);
}
}
Template Controller.java
//templatecontroller.java
package com.demo.mongo.example.controller;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.demo.mongo.example.model.UserDetails;
#RestController
#RequestMapping("/templateapp")
public class TemplateController {
#CrossOrigin
#RequestMapping(value="/login", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String validateUser(#RequestBody UserDetails udata,UriComponentsBuilder ucBuilder) {
/*UserDetails obj=new UserDetails();
List<UserDetails> values=obj.UserDetails(udata.getName(),udata.getPassword());
if(values.size()>0){
return "welcome udata.getName";
}
else
{
return "please register using registration link";
}*/
if(udata.getName().equalsIgnoreCase("admin") && udata.getPassword().equalsIgnoreCase("admin"))
{
return "welcome admin";
}
else
{
return "password mismatch/not an admin";
}
}
#CrossOrigin
#RequestMapping(value="/addUser", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String addUser(#RequestBody UserDetails udata,UriComponentsBuilder ucBuilder) {
return " new user details: name "+ udata.getName() + " Email Id " + udata.getEmailid() ;
}
}
UserDetails.Java
package com.demo.mongo.example.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class UserDetails {
#Id
private String name;
private String password;
private String emailid;
private int contact;
public UserDetails(){}
public UserDetails(String name,String password,String emailid,int contact){
this.name=name;
this.password=password;
this.emailid=emailid;
this.contact=contact;
}
public void setName(String name){
this.name=name;
}
public void setPassword(String password){
this.password=password;
}
public void setEmailid(String emailid){
this.emailid=emailid;
}
public void setContact(int contact){
this.contact=contact;
}
public String getPassword(){
return this.password;
}
public String getName(){
return this.name;
}
public int getContact(){
return this.contact;
}
public String getEmailid(){
return this.emailid;
}
}
**dispatcher-servlet.xml**
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.demo.mongo.example" />
<mvc:annotation-driven />
<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
</bean>
<!-- MongoTemplate for connecting and querying the documents in the database -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="test" />
</bean>
<!-- Use this post processor to translate any MongoExceptions thrown in #Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<!-- Add this to your web.xml to enable "CORS" -->
<filter>
<filter-name>cors</filter-name>
<filter-class>com.demo.mongo.example.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.mongo.example</groupId>
<artifactId>demomongo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>demomongo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1-1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
</dependencies>
<build>
<finalName>demomongo</finalName>
</build>
</project>
please help to fix which i did wrong.
You set header "Access-Control-Allow-Origin" in filter. If the header is not appearing make sure it is chained. Debug or log it.
I am trying to validate if a String has a number associated with it, and rejecting the value if it has a number. It is my first time using Spring Validation, and I have struggled for days with getting it all set up properly. I want the string to print out if it doesn't contain a number, but be rejected by the validator if it does. I am also unsure about the paramater being the value of target. I am unsure of how all of that works. Here is what I have so far:
#Component
public class StringValidator implements Validator
{
public boolean supports(Class<?> clazz)
{
return Main.class.isAssignableFrom(clazz);
}
#Autowired
public void validate(Object target, Errors errors)
{
//the 2nd parameter in ValidationUtils needs to be the string the validator takes in, which should be a set value from Main...?
Main main = (Main) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, String.valueOf(main), AppConstants.NULL_ERROR_MSG);
if(!errors.hasErrors())
{
boolean containsNbr = false;
for(char c : String.valueOf(main).toCharArray())
{
if(Character.isDigit(c))
{
containsNbr = true;
break;
}
}
if(containsNbr)
{
errors.rejectValue(String.valueOf(main), AppConstants.NUMBERS_ERROR_MSG);
}
else
{
System.out.println(String.valueOf(main));
}
}
}
}
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.imports.validationexample"/>
<bean id="main" class="com.imports.validationexample.application" />
<bean id ="springValidator" class="com.imports.validationexample.validation.StringValidator" />
<bean id="main" class="com.imports.validationexample.application.main">
<property name="string" value="Forty8"/>
</bean>
<bean id="validate" class="org.springframework.validation.Validator">
<constructor-arg ref="Validator"/>
</bean>
</beans>
I can't seem to hook it up properly, and am unsure how to represent it in my Main class. Any help is appreciated!
Here's one approach (maybe it can be improved):
app-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="stringValidator" class="com.foo.bar.StringValidator" />
<bean id="myStringHoldingBean" class="com.foo.bar.MyStringHoldingBean">
<property name="string" value="Faulty m3ssage" />
</bean>
</beans>
Your main class:
package com.foo.bar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");
MyStringHoldingBean bean = (MyStringHoldingBean) ctx.getBean("myStringHoldingBean");
Errors errors = new BeanPropertyBindingResult(bean, "myStringHoldingBean");
Validator validator = (Validator)ctx.getBean("stringValidator");
ValidationUtils.invokeValidator(validator, bean, errors);
if (errors.hasErrors()) { System.out.println("ERRORS"); }
}
}
MyStringHoldingBean:
package com.foo.bar;
public class MyStringHoldingBean {
private String string;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}
StringValidator:
package com.foo.bar;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class StringValidator implements Validator {
public boolean supports(Class<?> clazz) {
return MyStringHoldingBean.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
MyStringHoldingBean main = (MyStringHoldingBean) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "string", "Not null string, please!");
if (!errors.hasErrors()) {
boolean containsNbr = false;
for (char c : main.getString().toCharArray()) {
if (Character.isDigit(c)) {
containsNbr = true;
break;
}
}
if (containsNbr) {
errors.rejectValue("string", "String contains numbers!");
}
else {
System.out.println(main.getString());
}
}
}
}
pom.xml
<properties>
<spring.framework.version>3.2.6.RELEASE</spring.framework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
</dependencies>
Spring Validation is about validating beans, so this is why I put that "string" inside a class (MyStringHoldingBean).
As the title states, I have setup a scheduler in a spring web app and it seems to run in a loop, random times, starting with 8 invocations and then randomly adding. I am using spring version 3.1.3.RELEASE. I am in no way expert on the subject but I have already done the same configuration for scheduling in the past,for about 5-6 other projects. I always add the spring task configuration, like a scheduler and the annotation-driven directive. Then a #Scheduled annotation on the method and that worked like a charm. I have also succeeded scheduling 1 month ago with the same version of Spring, so I believe its not a Spring version issue. I am giving the configuration and bean code below. Please don't hesitate to ask more info :)
Thanks for your time!
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fileExport</groupId>
<artifactId>FileExportDaemon</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>3.1.3.RELEASE</spring.version>
</properties>
<dependencies>
<!-- The SFL4J logging implementation you prefer -->
<!--
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
</dependency>
-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<!--
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.7.5</version>
</dependency>
-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<!-- JCR API -->
<dependency>
<groupId>javax.jcr</groupId>
<artifactId>jcr</artifactId>
<version>2.0</version>
</dependency>
<!-- All the Jackrabbit libraries needed for DavEx, plus JcrUtils -->
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>jackrabbit-jcr2dav</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>jackrabbit-api</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.19</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<build>
<finalName>fileExportDaemon</finalName>
<filters>
<filter>${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
The application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:configuration.properties</value>
</list>
</property>
<property name="fileEncoding" value="utf-8"/>
</bean>
<import resource="fileExportDaemon-service.xml"/>
<import resource="fileExportDaemon-servlet.xml"/>
<!-- Tasks Configuration -->
<task:annotation-driven scheduler="myScheduler" />
<task:scheduler id="myScheduler" pool-size="100" />
<!--
<util:properties id="applicationProps" location="classpath:configuration.properties" />
<context:property-placeholder properties-ref="applicationProps" />
<task:annotation-driven />
<task:scheduled-tasks>
<task:scheduled ref="fileExportService" method="cronExport" cron="#{applicationProps['exportDaemon.execution.cron']}"/>
</task:scheduled-tasks>
-->
<context:annotation-config />
<tx:annotation-driven />
<mvc:annotation-driven />
</beans>
fileExportDaemon-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.3.xsd">
<!-- Services -->
<bean id="fileExportService" class="com.fileExportDaemon.service.FileExportService" />
</beans>
fileExportDaemon-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.fileExportDaemon" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
</beans>
FileExportService.java
package com.fileExportDaemon.service;
public class FileExportService {
#Value("${exportDaemon.jcr.repository.url}")
private String jcrURL;
#Value("${exportDaemon.filesystem.separator}")
private String filesystemSeparator;
#Value("${exportDaemon.path.complete}")
private String pathComplete;
#Value("${exportDaemon.path.incomplete}")
private String pathIncomplete;
Log logger = LogFactory.getLog(FileExportService.class);
public void exportFilesWithRules(){
Session jcrSession = getJcrSession(jcrURL);
try {
Node root = jcrSession.getRootNode();
Node dsNode = root.getNode("DS");
Node applicationsNode= dsNode.getNode("applications");
NodeIterator applicationNodes = applicationsNode.getNodes();
while (applicationNodes.hasNext()) {
handleNode(applicationNodes.nextNode());
}
} catch (RepositoryException e) {
logger.error("Repository error", e);
}
logger.debug("done exporting with rules!");
}
public void exportFilesAll(){
logger.debug("done exporting without rules!");
}
private void handleNode(Node node) throws RepositoryException {
logger.debug(node.getPath());
Node attachments = node.getNode("attachments");
boolean isComplete = isCompleteFiling(attachments);
if(isComplete){
File completedEfiling = new File(pathComplete + filesystemSeparator + node.getName());
if (!completedEfiling.exists()){
exportNodeFiles(attachments,pathComplete);
}else{
logger.debug("File exists, go to next: " + node.getName());
return;
}
}else{
logger.debug("filing Incomplete!");
File incompletedEfilingDir = new File(pathIncomplete + filesystemSeparator + node.getName());
if(!incompletedEfilingDir.exists()){
exportNodeFiles(attachments, pathIncomplete);
}else if( attachments.getNodes().getSize() != incompletedEfilingDir.list().length ){
exportNodeFiles(attachments, pathIncomplete);
}else{
logger.debug("files found identical on:" + node.getName());
return;
}
}
// Skip the virtual (and large!) jcr:system subtree
if (node.getName().equals("jcr:system")) {
return;
}
}
private void exportNodeFiles (Node attachmentsNode, String destinationDir){
File directory = null;
try {
directory = new File(destinationDir + filesystemSeparator + attachmentsNode.getParent().getName());
} catch (AccessDeniedException e1) {
logger.error("Access denied error", e1);
} catch (ItemNotFoundException e1) {
logger.error("Item not found.", e1);
} catch (RepositoryException e1) {
logger.error("Repository error.", e1);
}
directory.mkdir();
NodeIterator nodeIter = null;
try {
nodeIter = attachmentsNode.getNodes();
} catch (RepositoryException e) {
logger.error("Repository error.", e);
}
while( nodeIter.hasNext()){
OutputStream outputStream = null;
InputStream is = null;
try {
Node nodeToStore = nodeIter.nextNode().getNode("file").getNodes().nextNode();
Node content = nodeToStore.getNodes().nextNode();
is = content.getProperty("jcr:data").getBinary().getStream() ;
String a = directory.getAbsolutePath() + filesystemSeparator +nodeToStore.getName();
outputStream = new FileOutputStream(new File( directory.getAbsolutePath() + filesystemSeparator + nodeToStore.getName() ));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (PathNotFoundException e) {
logger.error("Path not found.", e);
} catch (RepositoryException e) {
logger.error("Repository error.", e);
} catch (FileNotFoundException e) {
logger.error("File not found.", e);
} catch (IOException e) {
logger.error("IO error", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}//finally
}//while nodeIter has next
}
private boolean isCompleteFiling(Node node){
boolean result = false;
NodeIterator nodeIter = null;
try {
nodeIter = node.getNodes();
} catch (RepositoryException e) {
logger.error("Repository error", e);
}
while(nodeIter.hasNext()){
Node attachmentNode = nodeIter.nextNode();
try {
if(StringUtils.endsWith(attachmentNode.getName(), ".pdf")){
if ( StringUtils.equals("receipt.pdf", attachmentNode.getNode("file").getNodes().nextNode().getName() )){
result = true;
}
}else{
continue;
}
} catch (RepositoryException e) {
logger.error("Repository error", e);
}
}
return result;
}
private Session getJcrSession(String url){
Repository repository = null;
try {
repository = JcrUtils.getRepository(url);
} catch (RepositoryException e) {
logger.error("Repository error", e);
}
SimpleCredentials creds = new SimpleCredentials("admin","admin".toCharArray());
Session jcrSession = null;
try {
jcrSession = repository.login(creds, "default");
} catch (LoginException e) {
logger.error("could not log in to jcr", e);
} catch (NoSuchWorkspaceException e) {
logger.error("Could not find workspace", e);
} catch (RepositoryException e) {
logger.error("Repository error", e);
}
return jcrSession;
}
#Scheduled(cron="${exportDaemon.execution.cron}" )
public void cronExport(){
logger.debug("Starting cron export!");
exportFilesWithRules();
}
}
properties
exportDaemon.jcr.repository.url=http://192.168.3.3:10080/jackrabbit-webapp-2.6.2/server
exportDaemon.execution.cron=* */5 * * * *
exportDaemon.filesystem.separator=\\
exportDaemon.path.complete=C:\\files\\export\\complete
exportDaemon.path.incomplete=C:\\files\\export\\incomplete
exportDaemon.all.filings=false
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>fileExportDaemon</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>fileExportDaemon</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>fileExportDaemon</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Just for anyone facing the same issue. I haven't found any logical solution over the described behaviour, but I have found a good work around. As said in my problem description, I have used the annotation Scheduled many times and of course it works. For this time only, I used the spring-quartz configuration and it works perfectly. The changes are not very big and you will find many many tutorials on how to use quartz with Spring. Regarding the bug, it remains a mystery. At this time, I have in fron of me two apps working with Scheduled and one with quartz. Even now I can't figure out why this happens.