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.
Related
Currently I have a RESTful service, and I am trying to deserialize a POST request body, that is XML, that is not working. I've tried all solutions out there, but none seem to work. JSON works perfectly with Spring MVC, but getting XML to work is such a pain..
I'm using Spring 5.1.5 version, and using Jaxb for the marshalling and unmarshalling.
The following is what I currently have:
This is my spring mvc configuration:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="my.project.controllers" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter">
<property name="objectMapper" ref="xmlMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true"
p:simpleDateFormat="yyyy-MM-dd"
p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule"/>
<bean id="xmlMapper" parent="objectMapper" p:createXmlMapper="true"/>
</beans>
These are my pom.xml dependencies:
<!-- Spring -->
<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-web</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.guice</groupId>
<artifactId>spring-guice</artifactId>
<version>${spring.guice.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${sl4j-log4j.version}</version>
</dependency>
<!-- Other dependencies -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax.annotation.version}</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>${guice.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
This is my RestController:
#RestController
#RequestMapping("issuance")
public class ProtocolController {
#Autowired
private IssuerManager issuerManager;
#PostMapping(value = "init", produces = "application/xml", consumes = "application/xml")
public IssuanceMessageAndBoolean initializeIssuance(#RequestBody final IssuancePolicyAndAttributes ipaa) throws CryptoEngineException {
IssuanceMessageAndBoolean imab = issuerManager.initializeIssuanceProtocol(ipaa);
return imab;
}
This is the object that I am trying to deserialize (IssuancePolicyAndAttributes):
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(
name = "IssuancePolicyAndAttributes",
namespace = "http://abc4trust.eu/wp2/abcschemav1.0",
propOrder = {"issuancePolicy", "attribute"}
)
#XmlRootElement(
name = "IssuancePolicyAndAttributes"
)
public class IssuancePolicyAndAttributes implements Serializable {
private static final long serialVersionUID = 6699648078303838561L;
#XmlElement(
name = "IssuancePolicy",
namespace = "http://abc4trust.eu/wp2/abcschemav1.0",
required = true
)
protected IssuancePolicy issuancePolicy;
#XmlElement(
name = "Attribute",
namespace = "http://abc4trust.eu/wp2/abcschemav1.0"
)
protected List<Attribute> attribute;
public IssuancePolicyAndAttributes() {
}
public IssuancePolicy getIssuancePolicy() {
return this.issuancePolicy;
}
public void setIssuancePolicy(IssuancePolicy value) {
this.issuancePolicy = value;
}
public List<Attribute> getAttribute() {
if (this.attribute == null) {
this.attribute = new ArrayList();
}
return this.attribute;
}
}
And this is my XML that I am sending as the request body:
<abc:IssuancePolicyAndAttributes
xmlns:abc="http://abc4trust.eu/wp2/abcschemav1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://abc4trust.eu/wp2/abcschemav1.0 ../../../../../../../../abc4trust-xml/src/main/resources/xsd/schema.xsd">
<abc:IssuancePolicy Version="1.0">
<abc:PresentationPolicy PolicyUID="http://ticketcompany.com/tickets/issuance/policy">
<abc:Pseudonym Exclusive="true" Scope="http://ticketcompany.com/tickets/vip" Established="false"
Alias="#nym"/>
<abc:Message>
<abc:Nonce>KNsRu9cGzkaeabogeRVV</abc:Nonce>
<abc:ApplicationData>
<abc:TestApplicationData>
<abc:Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xsi:type="xs:string">Some data
</abc:Data>
</abc:TestApplicationData>
</abc:ApplicationData>
</abc:Message>
</abc:PresentationPolicy>
<abc:CredentialTemplate SameKeyBindingAs="#nym">
<abc:CredentialSpecUID>http://MyFavoriteSoccerTeam/tickets/vip</abc:CredentialSpecUID>
<abc:IssuerParametersUID>http://ticketcompany/MyFavoriteSoccerTeam/issuance:idemix</abc:IssuerParametersUID>
<abc:UnknownAttributes/>
</abc:CredentialTemplate>
</abc:IssuancePolicy>
<abc:Attribute>
<abc:AttributeUID>-5027215341191833963</abc:AttributeUID>
<abc:AttributeDescription DataType="xs:string" Encoding="urn:abc4trust:1.0:encoding:string:sha-256"
Type="FirstName">
<abc:FriendlyAttributeName lang="en">first name</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">fornavn</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">John
</abc:AttributeValue>
</abc:Attribute>
<abc:Attribute>
<abc:AttributeUID>-2715953330829768453</abc:AttributeUID>
<abc:AttributeDescription DataType="xs:string" Encoding="urn:abc4trust:1.0:encoding:string:sha-256"
Type="LastName">
<abc:FriendlyAttributeName lang="en">last name</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">efternavn</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Dow
</abc:AttributeValue>
</abc:Attribute>
<abc:Attribute>
<abc:AttributeUID>-2231744817504418816</abc:AttributeUID>
<abc:AttributeDescription DataType="xs:date" Encoding="urn:abc4trust:1.0:encoding:date:unix:signed"
Type="Birthday">
<abc:FriendlyAttributeName lang="en">birthday</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">fødselsdag</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1985-05-05Z
</abc:AttributeValue>
</abc:Attribute>
<abc:Attribute>
<abc:AttributeUID>-2231744817504418826</abc:AttributeUID>
<abc:AttributeDescription DataType="xs:date" Encoding="urn:abc4trust:1.0:encoding:date:unix:signed"
Type="Matchday">
<abc:FriendlyAttributeName lang="en">Match day</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">Kamp dag</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2013-08-07Z
</abc:AttributeValue>
</abc:Attribute>
<abc:Attribute>
<abc:AttributeUID>-1231744817504418817</abc:AttributeUID>
<abc:AttributeDescription Type="MemberNumber" DataType="xs:integer"
Encoding="urn:abc4trust:1.0:encoding:integer:unsigned">
<abc:FriendlyAttributeName lang="en">VIP member id</abc:FriendlyAttributeName>
<abc:FriendlyAttributeName lang="da">VIP medlems nummer</abc:FriendlyAttributeName>
</abc:AttributeDescription>
<abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:integer">23784638726
</abc:AttributeValue>
</abc:Attribute>
</abc:IssuancePolicyAndAttributes>
When I debug and check the value of the variable ipaa of the RestController, the variable itself is instantiated but all of its members are null, which indicates the unmarshalling is not occurring correctly.
What am I doing wrong?
change the name of xml element
#XmlElement(name = "abc:IssuancePolicy", namespace = "http://abc4trust.eu/wp2/abcschemav1.0", required = true)
protected IssuancePolicy issuancePolicy;
#XmlElement(name = "abc:Attribute", namespace = "http://abc4trust.eu/wp2/abcschemav1.0")
protected List<Attribute> attribute;
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>
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 have defined an aspect which should be executed when the method getFirstName() is called on the User object. But it does not happen.
My Aspect class:
#Component
#Aspect
public class JpaGetFirstNameAspect {
#Pointcut("execution(* de.playground.model.User.getFirstName(..))")
public void pointCutSetFirstName() {
}
#Before("pointCutGetFirstName()")
public void beforeGetFirstName(JoinPoint joinPoint) {
System.out.println(">>>> Before retrieving first name ... " + joinPoint.getSignature().getName());
}
#After("pointCutGetFirstName()")
public void afterGetFirstName() {
System.out.println(">>>> After execution of getFirstName method ... ");
}
#AfterReturning(pointcut = "pointCutGetFirstName()", returning = "firstName")
public void afterReturningGetFirstName(JoinPoint joinPoint, String firstName) {
System.out.println("<<<< " + joinPoint.getSignature().getName());
System.out.println("<<<< returned first name of user " + firstName);
}
#AfterThrowing(pointcut = "pointCutGetFirstName()", throwing = "exc")
public void afterThrowingGetFirstName(Exception exc) {
System.out.println("|||| Retrieved Exception from getFirstName method ... " + exc.toString());
}
}
My application-context.xml:
<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:aop="http://www.springframework.org/schema/aop"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
">
<context:annotation-config />
<context:load-time-weaver />
<context:component-scan base-package="de.playground.service" />
</beans>
My testclass:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/test/resources/META-INF/spring/application-context.xml" })
public class AspectIntegrationTest {
#Autowired
private GenericApplicationContext context;
private ClassPathXmlApplicationContext ctx;
public AspectIntegrationTest() {
}
#AfterClass
public static void tearDownClass() {
}
#BeforeClass
public static void setUpClass() {
}
#Before
public void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext();
}
#After
public void tearDown() {
}
#Test
public void testHijackingUser() {
User user1 = new User();
user1.setCreatedOn(new Date());
user1.setLastModified(new Date());
user1.setFirstName("Max");
user1.setLastName("Mustermann");
user1.setUsername("max.mustermann");
user1.setPassword("start123");
System.out.println(">user 1 = " + user1.getFirstName());
assertNotNull(user1);
}
}
My aop.xml:
<!DOCTYPE aspectj PUBLIC
"-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver options="-Xset:weaveJavaxPackages=true -verbose -showWeaveInfo">
<!-- only weave classes in this package -->
<include within="de.playground.service.*" />
</weaver>
<aspects>
<!-- use only this aspect for weaving -->
<aspect name="de.playground.aspect.JpaGetFirstNameAspect" />
</aspects>
</aspectj>
My 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>
<parent>
<groupId>de.playground.platform</groupId>
<artifactId>playground-dev</artifactId>
<version>0.0.2-SNAPSHOT</version>
</parent>
<artifactId>playground-script</artifactId>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${version.aspectj}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${version.aspectj}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<version.aspectj>1.8.5</version.aspectj>
<version.spring>4.1.6.RELEASE</version.spring>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>once</forkMode>
<argLine>-javaagent:"${settings.localRepository}/org/springframework/spring-instrument/${version.spring}/spring-instrument-${version.spring}.jar"</argLine>
<useSystemClassloader>true</useSystemClassloader>
</configuration>
</plugin>
</plugins>
</build>
</project>
Got it working. My updated pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>once</forkMode>
<argLine>-javaagent:"${settings.localRepository}/org/springframework/spring-instrument/${version.spring}/spring-instrument-${version.spring}.jar"</argLine>
<useSystemClassloader>true</useSystemClassloader>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<showWeaveInfo>true</showWeaveInfo>
<source>1.7</source>
<target>1.7</target>
<Xlint>ignore</Xlint>
<complianceLevel>1.7</complianceLevel>
<encoding>UTF-8</encoding>
<verbose>false</verbose>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${version.aspectj}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${version.aspectj}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>