RESTful web-service not found when I deploy app in eclipse - eclipse

So, I have a Spring Maven web-app with a handful of RESTful web-services. For testing, this project is in Spring (4.1.4.RELEASE). I am using the latest STS (Spring-Eclipse) tool, and I am using Tomcat 8 for the server.
My UserController is designed as follows:
#Controller
#RequestMapping("/users")
public class UserController {
private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
#Autowired
private IUserService service;
#RequestMapping(value = "", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody
ArrayList<UserEntity> getUserList()
{
System.out.println("UserController: getUserList: START");
ArrayList<UserEntity> userEntityList = (ArrayList) service.getAllUsers();
return userEntityList;
}
#RequestMapping(value = "/", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody
ArrayList<UserEntity> getAllUsers()
{
System.out.println("UserController: getAllUsers: START");
ArrayList<UserEntity> userEntityList = (ArrayList) service.getAllUsers();
return userEntityList;
}
I have a test which runs when I build the app with maven, and this works great:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations =
{ "classpath:/spring/angular-context.xml", "file:src/main/webapp/WEB-INF/springmvc-servlet.xml" })
#Transactional
public class BaseControllerTests extends TestCase {
#Test
public void testMockGetUserList1() throws Exception
{
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/users/");
this.mockMvc.perform(requestBuilder).andDo(print()).andExpect(status().isOk());
}
#Test
public void testMockGetUserList2() throws Exception
{
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/users");
this.mockMvc.perform(requestBuilder).andDo(print()).andExpect(status().isOk());
}
}
The web-xml file looks like:
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/angular-context.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/logging/log4j-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Servlets -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>jUnitHostImpl</servlet-name>
<servlet-class>com.google.gwt.junit.server.JUnitHostImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>jUnitHostImpl</servlet-name>
<url-pattern>/SoccerApp/junithost/*</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
And the angular-context.xml file looks like:
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.tomholmes.angularjs.phonebook" />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/phonebook</value>
</property>
<property name="username">
<value>myusername</value>
</property>
<property name="password">
<value>mypassword</value>
</property>
</bean>
<!-- JNDI DataSource for Java EE environments -->
<!-- <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/MyDatabase"/> -->
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="com.tomholmes.angularjs.phonebook.domain" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
</props>
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.tomholmes.net" />
<property name="port" value="587" />
<property name="username" value="myusername" />
<property name="password" value="mypassword" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<!--
<bean id="sendMailService" class="com.tomholmes.angularjs.phonebook.shared.util.SendEmailService">
<property name="mailSender" ref="mailSender" />
</bean>
-->
<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name = "sessionFactory" ref = "sessionFactory" />
</bean>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
So, this project compiles under maven just fine. Under eclipse (STS) with the Tomcat 8 engine, it runs fine, and I can go to my app:
http://localhost:8080/angularjs-phone-book/
and I can see the index.html just fine, so I know the app is out there.
If I go to:
http://localhost:8080/angularjs-phone-book/users
http://localhost:8080/angularjs-phone-book/users/
http://localhost:8080/angularjs-phone-book/rest/users
http://localhost:8080/angularjs-phone-book/rest/users/
Nothing works, and I get a 404 error that this web-service is not found.
But like I said, I know the test works, but I can't see what the exact URL has to be to get there.
I tried deploying the WAR on Tomcat 8 directly, but this web-app won't even start there, supposedly because of logging problems.
If I can provide any more information, please let me know. Any help in finding this would be great. Ultimately I want to have an AngularJS UI on the front-end tied to web-services, and I have to get the web-services working first.
Thanks!

You probably miss the Spring config reference from your web.xml. The unit test runs because you give the reference to the XML directly there, but not in web.xml, so Spring will not scan your controller for annotations.
Use an <init-param> inside <servlet>!
And the correct URL will be the last one, that is, with .../rest/users/, and .../rest/users is also allowed by the help of the browser, I guess.

Related

How to solve Java EE EJB Glassfish error javax.naming.NamingException: Invocation exception: Got null ComponentInvocation?

I have a problem with creating a simple databse with EJB. I created a Web Project in Netbeans with Maven. I am using Glassfish 5 however the problem also occurs with glassfish 4.
Here are my classes.
Ui_model.java:
#Named("model")
#Stateless
public class Ui_model implements Serializable{
#Inject
PizzaRepository pizzas;
public Ui_model() {
}
#PostConstruct
public void init(){
Pizza one = new Pizza(1, "Pizza Margaritta", 4.5);
Pizza two = new Pizza(2, "Pizza Napoli", 5);
Pizza three = new Pizza(3, "Pizza Calzone", 6);
pizzas.createDB(one);
pizzas.createDB(two);
pizzas.createDB(three);
}
}
PizzaRepository.java:
#Named
#ApplicationScoped
public class PizzaRepository implements Serializable{
#PersistenceContext(unitName="Unit")
protected EntityManager em;
public void createDB(Pizza pizza){
try{
em.persist(pizza);
}catch(RollbackException e){
System.out.println(e.getMessage());
}
}
}
Pizza.java:
#Entity
public class Pizza implements Serializable{
#Id
int number;
String name;
double price;
public Pizza(int number, String name, double price) {
this.number = number;
this.name = name;
this.price = price;
}
public Pizza(){
}
}
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Unit" transaction-type="JTA">
<jta-data-source>java:app/jdbc/testdb</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!-- database connection -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
</properties>
</persistence-unit>
</persistence>
This is my glassfish-resources.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false"
associate-with-thread="false"
connection-creation-retry-attempts="0"
connection-creation-retry-interval-in-seconds="10"
connection-leak-reclaim="false"
connection-leak-timeout-in-seconds="0"
connection-validation-method="auto-commit"
datasource-classname="org.apache.derby.jdbc.ClientDataSource"
fail-all-connections="false" idle-timeout-in-seconds="300"
is-connection-validation-required="false"
is-isolation-level-guaranteed="true"
lazy-connection-association="false"
lazy-connection-enlistment="false"
match-connections="false"
max-connection-usage-count="0"
max-pool-size="32"
max-wait-time-in-millis="60000"
name="derby_net_testdb_usernamePool"
non-transactional-connections="false"
pool-resize-quantity="2"
res-type="javax.sql.DataSource"
statement-timeout-in-seconds="-1"
steady-pool-size="8"
validate-atmost-once-period-in-seconds="0"
wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="1527"/>
<property name="databaseName" value="testdb"/>
<property name="User" value="username"/>
<property name="Password" value="123456"/>
<property name="URL" value="jdbc:derby://localhost:1527/testdb"/>
<property name="driverClass" value="org.apache.derby.jdbc.ClientDriver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true"
jndi-name="java:app/jdbc/testdb"
object-type="user"
pool-name="java:app/derby_net_testdb_usernamePool"/>
</resources>
My project structure:
When I run this I get the following error:
The strange thing is that this still creates an empty table named Pizza in the testdb but with no entries. So it doesn't mean that the program is not finding the DB itself. I really don't know what to make of that error. The project was much bigger originally but I broke it down to get to the base problem and it doesn't get much easier than this. Still it doesn't work. I would appreciate any advice on how to fix it.
Edit:
asadmin list-jndi-entries prompts:
java:global: com.sun.enterprise.naming.impl.TransientContext
UserTransaction: com.sun.enterprise.transaction.startup.TransactionLifecycleService$2
__internal_java_app_for_app_client__testdb__java:app: com.sun.enterprise.naming.impl.TransientContext
concurrent: com.sun.enterprise.naming.impl.TransientContext
com.sun.enterprise.container.common.spi.util.InjectionManager: com.sun.enterprise.container.common.impl.util.InjectionManagerImpl
jms: com.sun.enterprise.naming.impl.TransientContext
ejb: com.sun.enterprise.naming.impl.TransientContext
jdbc: com.sun.enterprise.naming.impl.TransientContext
Command list-jndi-entries executed successfully.
asadmin list-jndi-entries --context jdbc prompts:
__default: org.glassfish.resourcebase.resources.api.ResourceProxy
__TimerPool: org.glassfish.resourcebase.resources.api.ResourceProxy
sample: org.glassfish.resourcebase.resources.api.ResourceProxy
Command list-jndi-entries executed successfully.
I think the problem is that the jdbc-resource pool-name and the jdbc-connection-pool name do not match. The first has java:app/ prefixed. Try to remove that.
See here for a minimal example: https://github.com/payara/Payara-Examples/blob/master/payara-micro/database-ping/src/main/webapp/WEB-INF/glassfish-resources.xml
I was able to solve the problem by putting the glassfish.xml into an setup file in src. I also got help from a friend who gave me his files.
glassfish.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.apache.derby.jdbc.ClientDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="derby_net_testdb_pizzaPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="1527"/>
<property name="databaseName" value="testdb"/>
<property name="User" value="username"/>
<property name="Password" value="123456"/>
<property name="connectionAttributes" value=";create=true" />
<property name="URL" value="jdbc:derby://localhost:1527/testdb;create=true"/>
<property name="driverClass" value="org.apache.derby.jdbc.ClientDriver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="jdbc/testdb" object-type="user" pool-name="derby_net_testdb_pizzaPool"/>
</resources>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Unit" transaction-type="JTA">
<jta-data-source>jdbc/testdb</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!--<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/ModulDB"/>
<property name="javax.persistence.jdbc.user" value="pizza"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.password" value="123456"/>-->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
However I then got an error Could not create stateless EJB because of the persist call. That I could resolve by not calling createDB() in the PostConstruct init(). I don't know why but it just didn't work with post construct. Now everything works properly so far. Thank you all very much.

org.quartz-scheduler nullify the reference of repository in the executeInternal(JobExecutionContext executionContext) why?

Its an observation and would like to share the information to know why executeInternal() nullify the reference of customerRepository? I was developing Spring + Quartz + Spring Data JPA example. In this example I was looking to run the multiple jobs at the same time by providing implementation of JobDetailFactoryBean. In jobA.java class I experience an issue....
JobA.java
#Service
public class JobA extends QuartzJobBean {
private CustomerRepository customerRepository = null;
#Autowired
public JobA(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public JobA() { }
#Override
protected void executeInternal(JobExecutionContext executionContext) throws JobExecutionException {
System.out.println("~~~~~~~ Job A is runing ~~~~~~~~");
Trigger trigger = executionContext.getTrigger();
System.out.println(trigger.getPreviousFireTime());
System.out.println(trigger.getNextFireTime());
getCustomerList();
}
private List<Customer> getCustomerList(){
List<Customer> customers = customerRepository.findAll();
for (Customer customer : customers) {
System.out.println("------------------------------");
System.out.println("ID : "+customer.getId());
System.out.println("NAME : "+customer.getName());
System.out.println("STATUS : "+customer.getStatus());
}
return customers;
}
}
I can't use the customerRepository instance in the executeInternal() why ? If I getCustomerList() from public JobA(CustomerRepository customerRepository) { it works fine there, but if I use from executeInternal(), it nullify the reference of customerRepository why ?
Spring-Quartz.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xmlns:context="http://www.springframework.org/schema/context"
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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd">
<import resource="classpath:dataSourceContext.xml"/>
<jpa:repositories base-package="com.mkyong.repository" />
<context:component-scan base-package="com.mkyong.*" />
<context:annotation-config />
<bean id="jobA" class="com.mkyong.job.JobA" />
<bean id="jobB" class="com.mkyong.job.JobB" />
<bean id="jobC" class="com.mkyong.job.JobC" />
<!-- ~~~~~~~~~ Quartz Job ~~~~~~~~~~ -->
<bean name="JobA" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobA" />
</bean>
<bean name="JobB" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobB" />
</bean>
<bean name="JobC" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobC" />
</bean>
<!-- ~~~~~~~~~~~ Cron Trigger, run every 5 seconds ~~~~~~~~~~~~~ -->
<bean id="cronTriggerJobA" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobA" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean id="cronTriggerJobB" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobB" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean id="cronTriggerJobC" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobC" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<!-- ~~~~~~~~~~~~~~~~ Scheduler bean Factory ~~~~~~~~~~~~~~~~ -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTriggerJobA" />
<!-- <ref bean="cronTriggerJobB" />
<ref bean="cronTriggerJobC" /> -->
</list>
</property>
</bean>
</beans>
dataSourceContext.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
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://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:property-placeholder location="classpath:database.properties"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.driver.class.name}" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="${database.vendor}"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="com.mkyong.*"/>
</bean>
</beans>
App.java
public class App {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Quartz.xml");
}
}
Where are you define the customerRepository bean? you should define it in the xml file, or add #Repository annonation in the class.

Tomcat + Eclipse Link + Vaadin, NoClassDefFoundError javax/persistence/Persistence

I'm using Vaadin and Eclipse Link for my web application based on MySQL database.
I have a following class to manage db operations:
public class DatabaseManager {
private static final String PERSISTENCE_UNIT_NAME = "students";
private static EntityManagerFactory factory;
private static EntityManager em;
public DatabaseManager() {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = factory.createEntityManager();
}
public void addEntry(Student student) {
em.getTransaction().begin();
em.persist(student);
em.getTransaction().commit();
}
}
and the following persistence.xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="students" transaction-type="RESOURCE_LOCAL">
<class>com.example.simplegradebook.Student</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:C:\\Users\\Ja\\workspace\\SimpleDB;create=true" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />
<!-- EclipseLink should create the database schema automatically -->
<!-- <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> -->
<property name="eclipselink.ddl-generation.output-mode" value="both" />
</properties>
I also have a DBTest class in which I test DatabaseManager in console and everything seems to be okay. But when I put for example:
DatabaseManager dbm = new DatabaseManager();
dbm.addEntry(new Student(/*some stuff here*/));
in my VaadinUI class, I get errors like that:
com.vaadin.server.ServiceException: java.lang.NoClassDefFoundError: javax/persistence/Persistence
com.vaadin.server.VaadinService.handleExceptionDuringRequest(VaadinService.java:1463)
com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1417)
com.vaadin.server.VaadinServlet.service(VaadinServlet.java:237)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
java.lang.NoClassDefFoundError: javax/persistence/Persistence
com.example.simplegradebook.DatabaseManager.<init>(DatabaseManager.java:19)
com.example.simplegradebook.SimplegradebookUI.init(SimplegradebookUI.java:44)
com.vaadin.ui.UI.doInit(UI.java:641)
com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:222)
com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1405)
com.vaadin.server.VaadinServlet.service(VaadinServlet.java:237)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
I have these libraries included in my project:
javax.persistence_2.1.0.v201304241213.jar
javax.persistence.source_2.1.0.v201304241213.jar
Any ideas what may cause the problem?

Spring #Autowired annotation giving null for dozer mapping

Here is my class I am trying to use this annotation and I am getting null for dozerBeanMapper. I also get null for other beans I am trying to use like Jaxb2Mapper, etc
#Service("Transformer")
#Scope("prototype")
public class Transformer {
#Autowired
private Mapper dozerBeanMapper;
public Object testMethod(Object wlpData) throws TransformerException {
MbrReq destObject = null;
destObject = dozerBeanMapper.map(request, MbrReq.class);
return destObject;
}
Here is my configuration:
<?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:sws="http://www.springframework.org/schema/web-services"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<sws:annotation-driven />
<context:component-scan base-package="com.xxxxx.xxxx.srvc.membership,com.xxxxx.xxxx.interact.membership.request,com.xxxxx.membership.ws,com.xxxxxx.srvc.membership.generated,com.xxxxx.xxxx.service.transform" />
<!-- WSDL Exposed as memberService -->
<bean id="searchMemDemographics" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">
<constructor-arg value="/WEB-INF/schema/MemSvc_Binding_HTTP_V0100.wsdl"/>
</bean>
<bean class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles">
<list>
<value>classpath:mapping/dozer-global-configuration.xml</value>
<value>classpath:mapping/dozer-bean-mappings.xml</value>
</list>
</property>
</bean>
<oxm:jaxb2-marshaller id="marshaller" contextPath="com.xxxxx.srvc.membership" />
<oxm:jaxb2-marshaller id="reqMarshaller" contextPath="com.xxxxxx.membership.request" />
<oxm:jaxb2-marshaller id="respMarshaller" contextPath="com.xxxxxx.membership.response" />
In web.xml I have this
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/membershipApplicationContext.xml
</param-value>
</context-param>
Anything else I am missing ?
Try adding an id to the bean.
<bean id="dozerBeanMapper" class="org.dozer.spring.DozerBeanMapperFactoryBean">

Velocity email is not working

I use Velocity and Java mail sender but I get a NullPointerException and I don't know why. And I tried a lot but can't solve the problem, to be honest I don't have any idea about what the problem can depends on.
Here are the sample codes I use.
Thanks full for any help.
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/guard_weblayer] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at se.guards.mail.VelocityEmailService.sendLostPasswordEmail(VelocityEmailService.java:49)
at se.guards.lostpassword.LostPasswordController.processSubmit(LostPasswordController.java:71)
public interface VelocityMailRepository
{
public void sendLostPasswordEmail(final User user, final String action);
}
public class VelocityEmailService implements VelocityMailRepository
{
private static final Logger logger= LoggerFactory.getLogger(VelocityEmailService.class);
#Autowired
private VelocityEngine velocity;
#Autowired
private JavaMailSenderImpl javaMailSenderImpl;
#Autowired
private JavaMailSender sender;
public void sendLostPasswordEmail(final User user, final String action)
{
logger.debug("Sending lost password email to: {}", user.getUsername());
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(user.getEmail());
message.setFrom("no-reply#sziebert.net");
message.setSubject("Your Password");
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", user);
model.put("url", action);
String text = mergeTemplateIntoString(velocity, "email/lost-password.vm","password", model);
message.setText(text, true);
}
};
this.sender.send(preparator);
}
public class LostPasswordFormValidator implements Validator {
private static final Logger logger = LoggerFactory.getLogger(LostPasswordFormValidator.class);
public boolean supports(Class clazz) {
return LostPasswordForm.class.equals(clazz);
}
public void validate(Object obj, Errors errors) {
logger.debug("Validating lost password form.");
LostPasswordForm form = (LostPasswordForm) obj;
// Insure that a value with specified.
rejectIfEmptyOrWhitespace(errors, "username", "error.username.empty");
// Insure the inputs don't contain any illegal characters.
if (!isAlphanumeric(form.getUsername()))
errors.rejectValue("username", "error.username.illegal.chars");
if (isNotBlank(form.getUsername()) && form.getUsername().length() < 4)
errors.rejectValue("username", "error.username.too.short");
}
}
#Controller
public class LostPasswordController
{
private static final Logger logger = LoggerFactory.getLogger(LostPasswordController.class);
VelocityEmailService sender= new VelocityEmailService();
UserService service= new UserService();
#InitBinder
public void initBinder(WebDataBinder binder)
{
binder.setAllowedFields(new String[] { "captcha", "username" });
}
#ModelAttribute("form")
public LostPasswordForm populateForm()
{
return new LostPasswordForm();
}
#RequestMapping(value = "/lostPassword", method = RequestMethod.GET)
public String lostPassword()
{
logger.debug("Rendering lost password form.");
return "lostPassword";
}
#RequestMapping(value = "/lostPassword", method = RequestMethod.POST)
public String processSubmit(#ModelAttribute("form") LostPasswordForm form,HttpServletResponse response, BindingResult result)
{
logger.debug("Processing lost password form.");
new LostPasswordFormValidator().validate(form, result);
if (!result.hasErrors())
{
User user = service.findUserByUsername(form.getUsername());
System.out.println(user);
if (user != null)
{
String frob = BCrypt.hashpw(user.getUsername() + "3m4il", BCrypt.gensalt());
String link = createLostPasswordLink(user, frob);
sender.sendLostPasswordEmail(user, link);
response.addCookie(persistFrob(frob));
return "lost-password-success";
}
result.rejectValue("username", "error.username.invalid");
}
return "lostPassword";
}
private String createLostPasswordLink(final User user, final String frob)
{
StringBuilder link = new StringBuilder();
link.append("http://localhost:8080/password/reset.do?frob=");
link.append(frob);
link.append("&username=");
link.append(user.getUsername());
return link.toString();
}
private Cookie persistFrob(final String frob)
{
Cookie cookie = new Cookie("frob", frob);
cookie.setMaxAge(60 * 60); // 1 hour
return cookie;
}
}
<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:p="http://www.springframework.org/schema/p"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package=".........weblayer" />
<mvc:annotation-driven />
<context:annotation-config />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:property-placeholder location="classpath*:*.properties" />
<bean id="messageTemplate" class="org.springframework.mail.SimpleMailMessage"
scope="prototype">
<property name="from" value="myemailaddress" />
</bean>
<!-- - This bean resolves specific types of exceptions to corresponding
logical - view names for error views. The default behaviour of DispatcherServlet
- is to propagate all exceptions to the servlet container: this will happen
- here with all other types of exceptions. -->
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.servlet.PageNotFound">pageNotFound</prop>
<prop key="org.springframework.dao.DataAccessException">dataAccessFailure</prop>
<prop key="org.springframework.transaction.TransactionException">dataAccessFailure</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/users/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="mymessages"></property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="50242880" />
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
</beans>
<?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"
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">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="port" value="${mail.port}" />
<property name="protocol" value="smtp" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.connectiontimeout">5000</prop>
<prop key="mail.smtp.sendpartial">${mail.smtp.sendpartial}</prop>
<prop key="mail.smtp.userset">${mail.smtp.userset}</prop>
<prop key="mail.mime.charset">UTF-8</prop>
<prop key="mail.smtp.isSecure">${mail.smtp.isSecure}</prop>
<prop key="mail.smtp.requiresAuthentication">${mail.smtp.requiresAuthentication}</prop>
<prop key="mail.smtps.auth">${mail.smtps.auth}</prop>
<prop key="mail.smtp.port">${mail.port}</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.fallback">${mail.smtp.socketFactory.fallback}</prop>
<prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
<prop key="mail.debug">${mail.debug}</prop>
</props>
</property>
</bean>
<bean id="messageTemplate" class="org.springframework.mail.SimpleMailMessage"
scope="prototype">
<property name="from" value="${mail.username}" />
</bean>
<!-- Mail sender configured for using Gmail -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
p:host="smtp.gmail.com" p:username="${mail.username}" p:password="${mail.password}">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<props>
<prop key="resource.loader">class</prop>
<prop key="class.resource.loader.class">org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</prop>
</props>
</property>
</bean>
</beans>
Solved
Just change
VelocityEmailService sender= new VelocityEmailService();
UserService service= new UserService();
to
VelocityEmailService sender;
UserService service;
There is no any need of initiation.
And the emailConfig.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"
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">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="port" value="${mail.port}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.debug">true</prop>
</props>
</property>
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
</bean>
</beans>