I've been researching similar topics to this, but none of the solutions have worked. I'm trying to map a simple HttpServlet in a Web Application using Eclipse, but have been getting the following error when the form is submitted from the html page that calls get on the servlet.
HTTP Status 500 - Error instantiating servlet class java.UserScoresServlet
type Exception report
message Error instantiating servlet class java.UserScoresServlet
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class java.UserScoresServlet
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.lang.Thread.run(Thread.java:748)
root cause
java.lang.ClassNotFoundException: java.UserScoresServlet
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.lang.Thread.run(Thread.java:748)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.
I've tried mapping both with the #WebServlet annotation as well as the Web.xml file to no avail. I was trying to use one or the other, not both at the same time. When using JSP's and HTML pages my mapping works correctly. My XML file mapping is as follows, and is located in the WEB-INF directory.
<display-name>GetUserScores</display-name>
<servlet>
<servlet-name>GetUserScores</servlet-name>
<servlet-class>java.UserScoresServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetUserScores</servlet-name>
<url-pattern>/GetUserScores</url-pattern>
</servlet-mapping>
</web-app>
The server class is as follows. As I mentioned above, I've been doing either the annotation, or the web.xml, not both. Both throw the same exception.
package java;
import java.io.IOException;
import java.score.jpa.Score;
import java.score.jpa.ScoreService;
import java.user.jpa.User;
import java.user.jpa.UserService;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class UserScoresServlet
*/
#WebServlet(name = "GetUserScores", urlPatterns = "/GetUserScores")
public class UserScoresServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserService userService;
private ScoreService scoreService;
/**
* #see HttpServlet#HttpServlet()
*/
public UserScoresServlet() {
super();
userService = new UserService();
scoreService = new ScoreService();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = (String)request.getParameter("firstName");
String lastName = (String)request.getParameter("firstName");
User user = userService.findUserByFirstAndLastName(firstName, lastName);
if (user != null){
List<Score> scoreList = scoreService.findAllScoresByUser(user);
request.setAttribute("scoreList", scoreList);
}
gotoPage("/scores", request, response);
}
private void gotoPage(String address, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
See photo for the file structure: File Structure Image
Any help anyone could provide would be a big help. I've searched this site thoroughly and tried every suggestion of similar issues to no avail. Appreciate the help.
As stated in the JLS, you should not use java as name for your development packages:
Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier java; package names that start with the identifier java are reserved for package of the Java SE platform
Noted here in your code:
package java;
import java.io.IOException;
import java.score.jpa.Score;
import java.score.jpa.ScoreService;
import java.user.jpa.User;
import java.user.jpa.UserService;
import java.util.List;
//rest of code...
Change the name of your package to something else.
I must to test this web app, but when I try to deploy on JBoss 7 EAP this is the error, maybe I forgot something?
This is the exception that the application throws:
Cannot upload deployment: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL" =>
"org.jboss.msc.service.StartException in service jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL: WFLYSRV0153:
Failed to process phase INSTALL of deployment \"WebAppGuestbooks.war\" Caused by:
org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0041: Component class it.matteo.nesea.ejb.GuestDao for
component GuestDao has errors:
WFLYJPA0033: Can't find a persistence unit named null in deployment
\"WebAppGuestbooks.war\""},"WFLYCTL0180: Services with missing/unavailable dependencies" =>
["jboss.deployment.unit.\"WebAppGuestbooks.war\".weld.weldClassIntrospector is missing
[jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]","jboss.deployment.unit.\"WebAppGuestbooks.war\".batch.environment
is missing [jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]"]}
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="GuestbookPU" transaction-type="JTA">
<class>it.matteo.nesea.dao.jpa</class>
<properties>
<property name="javax.persistence.jdbc.url" value="$objectdb/db/guests.odb"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
this is the Ejb GuestDAO:
package it.matteo.nesea.ejb;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import it.matteo.nesea.dao.jpa.Guest;
#Stateless
public class GuestDao {
// Injected database connection:
#PersistenceContext private EntityManager em;
// Stores a new guest:
public void persist(Guest guest) {
em.persist(guest);
}
// Retrieves all the guests:
public List<Guest> getAllGuests() {
TypedQuery<Guest> query = em.createQuery(
"SELECT g FROM Guest g ORDER BY g.id", Guest.class);
return query.getResultList();
}
}
this is Jpa POJO Class Guest:
package it.matteo.nesea.dao.jpa;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Guest implements Serializable {
private static final long serialVersionUID = 1L;
// Persistent Fields:
#Id
#GeneratedValue
Long id;
private String name;
private Date signingDate;
// Constructors:
public Guest() {
}
public Guest(String name) {
this.name = name;
this.signingDate = new Date(System.currentTimeMillis());
}
// String Representation:
#Override
public String toString() {
return name + " (signed on " + signingDate + ")";
}
}
This is a Servlet GuestServlet:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.matteo.nesea.dao.jpa.Guest;
import it.matteo.nesea.ejb.GuestDao;
#WebServlet(name="GuestServlet", urlPatterns={"/guest"})
public class GuestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Injected DAO EJB:
#EJB GuestDao guestDao;
#Override
protected void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Display the list of guests:
request.setAttribute("guests", guestDao.getAllGuests());
request.getRequestDispatcher("/guest.jsp").forward(request, response);
}
#Override
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle a new guest:
String name = request.getParameter("name");
if (name != null)
guestDao.persist(new Guest(name));
// Display the list of guests:
doGet(request, response);
}
}
This is a JSP Page:
<%#page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#page import="java.util.*,it.matteo.nesea.dao.jpa.Guest"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JPA Guest Book Web Application</title>
</head>
<body>
<form method="POST" action="guest">
Name: <input type="text" name="name" />
<input type="submit" value="Add" />
</form>
<hr><ol> <%
#SuppressWarnings("unchecked")
List<Guest> guests = (List<Guest>)request.getAttribute("guests");
if (guests != null) {
for (Guest guest : guests) { %>
<li> <%= guest %> </li> <%
}
} %>
</ol></hr>
</body>
This is the path of Project
Your persistence.xml file is in the wrong place. The JPA uses a convention to find your persistence.xml so you have put the file in the right place.
According to the Oracle docs:
The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit.
If you package the persistent unit as a set of classes in an EJB JAR file, persistence.xml should be put in the EJB JAR’s META-INF directory.
If you package the persistence unit as a set of classes in a WAR file, persistence.xml should be located in the WAR file’s WEB-INF/classes/META-INF directory.
In your case when the persistence.xml file is in src/META-INF/ (if you use MAVEN the path is src/resources/META-INF) its going to be packaged in your war in the WEB-INF/classes/META-INF folder, funcioning as the root of the persistence unit.
I'm using JPA 2.0, eclipselink 2.x and maven. This is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="certifications" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/com/ni/ds_edata_soa_nontx</jta-data-source>
<class>com.ni.apps.engineering.certification.entities.NicdsCliCertificationStg</class>
<class>com.ni.apps.engineering.certification.entities.NicdsCliCertificationStgPK</class>
<class>com.ni.apps.engineering.certification.entities.NicdsCliUpMapping</class>
<properties>
<property name="javax.persistence.jdbc.password" value="ni"/>
<!--property name="javax.persistence.jdbc.user" value="NI"/-->
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
I have this AbstractFacade
public abstract class AbstractFacade {
#PersistenceUnit(unitName = "certifications")
private static EntityManagerFactory emf;
private EntityManager em;
/**
* Gets the entity manager
* #return
*/
protected EntityManager getEntityManager(){
if(emf == null){
emf = Persistence.createEntityManagerFactory("certifications");
}
if(em == null){
em = emf.createEntityManager();
}
return em;
}
}
And this is how I implement it
public class CertificationFacade extends AbstractFacade{
/**
* Gets the certifications for the paramenter upId
* #param upId the upId
* #return the certifications
* #throws CertificationException
*/
public List<NicdsCliCertificationStg> getCertificationsByUpId(String upId)
throws CertificationException {
String stringQuery = new StringBuilder(
"select c from NicdsCliCertificationStg c, NicdsCliUpMapping d where c.id.contactsId = d.contactsId and d.profileId =")
.append(upId).toString();
try {
TypedQuery<NicdsCliCertificationStg> query = getEntityManager().createQuery(stringQuery,
NicdsCliCertificationStg.class);
return query.getResultList();
} catch (Exception e) {
throw new CertificationException(
CertificationConstants.INTERNAL_ERROR_MESSAGE, e);
}
}
}
This is the DAO
public final class CertificationDAO {
private CertificationDAO(){}
/**
**Gets the certifications for the requested upId
* #param upId the upId
* #return the certifications
* #throws CertificationException
*/
public static Certifications getCertificationByUpId(String upId) throws CertificationException{
Certifications response = new Certifications();
List<NicdsCliCertificationStg> certifications = new CertificationFacade().getCertificationsByUpId(upId);
CertificationType newCertification = new CertificationType();
for(NicdsCliCertificationStg cert : certifications){
newCertification.setAlternateEmail(cert.getAlternateEmail());
newCertification.setCertificationName(cert.getId().getCertName());
newCertification.setContactId((int)cert.getId().getContactsId());
newCertification.setFirstName(cert.getFirstName());
newCertification.setLastName(cert.getLastName());
newCertification.setPrimaryEmail(cert.getPrimaryEmail());
newCertification.setStatus(cert.getCertStatus());
response.getCertification().add(newCertification);
}
return response;
}
}
The exception is caused when I try to iterate through the list. I get a ClassCastException. I've been reading, and this is caused by 2 possible reasons: 1) the class is duplicated in the classpath (which is not so in my case) and 2) there are 2 different classloaders at the same time. This exception also happens when I redeploy the app to my weblogic. It seems that the garbage collector doesn't recycle the old classloader fast enough, and when I run the app, I'm dealing with two classloaders at the same time, causing the classcast exception. What I don't understand is that since I'm using JTA transaction type in my persistence.xml, the lifecycle of the EntityManagerFactory should be handled automatically. One option would be to close the factory myself, but I'm more interested in learning why isn't the JTA handling this for me. Thanks!
--EDIT--
Stacktrace
java.lang.ClassCastException: com.ni.apps.engineering.certification.entities.NicdsCliCertificationStg
at com.ni.apps.engineering.certification.dao.CertificationDAO.getCertificationByUpId(CertificationDAO.java:25)
at com.ni.apps.engineering.certification.rest.implementation.CertificationService.getCertificationByUpId(CertificationService.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1382)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:717)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:821)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:57)
at com.ni.apps.engineering.certification.filter.ConfigurableRepRestServletFilter.doFilter(ConfigurableRepRestServletFilter.java:139)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:57)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3730)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
So, this is how I fixed it.
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.ni.apps.engineering.certification.controller.AbstractFacade;
public class ApplicationListener implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent arg0) {
AbstractFacade.closeFactory();
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
}
}
That way, everytime I redeploy the app, I make sure that the factory that I've created is closed.
-Edit-
Just to make it clear, after creating that Listener class, I have to add the listener to the web.xml like this
<listener>
<listener-class>com.ni.apps.engineering.certification.filter.ApplicationListener</listener-class>
</listener>
The closeFactory() simply does emf.close() after verifying that emf is not null.
My develop environment is: netbeas7.01 + mysql5 + spring3 + struts2 + jpa2(hibernate3.6;
When I Refactoring a old project,I got some trouble:there is a random “null point” error when I run the project,could any one give me some suggestion,thanks.
full project download:http://www.oschina.net/action/code/download?code=6526&id=10445
build log:
Running com.itcast.service.product.BrandServiceTest
001com.itcast.service.product.BrandServiceImpl#10d0eae
entityManager=save()===Shared EntityManager proxy for target factory [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#120b2da]
002922defe1-38d4-48f5-8fa5-b43027f897d9
2011-10-11 18:02:50 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
2011-10-11 18:02:51 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext#1e893df: startup date [Tue Oct 11 18:02:51 CST 2011]; root of context hierarchy
2011-10-11 18:02:51 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
信息: Loading properties file from class path resource [jdbc.properties]
2011-10-11 18:02:51 org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
信息: Bean 'dataSource' of type [class org.apache.commons.dbcp.BasicDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2011-10-11 18:02:51 org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
信息: Bean 'org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver#145c859' of type [class org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2011-10-11 18:02:51 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
信息: Building JPA container EntityManagerFactory for persistence unit 'itcast'
2011-10-11 18:02:54 org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
信息: Bean 'entityManagerFactory' of type [class org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2011-10-11 18:02:54 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1ffc686: defining beans [brandServiceImpl,typeServiceImpl,uploadFileServiceImpl,/control/product/allbrandsfinder,/control/product/alltypesfinder,/control/product/branddeleter,/control/product/brandfinder,/control/product/brandsaver,/control/product/brandupdater,/control/product/typedeleter,/control/product/typefinder,/control/product/typesaver,/control/product/typeupdater,/control/upload/uploadfilesaver,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,entityManagerFactory,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor]; root of factory hierarchy
003测试Find()方法!
004null
Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.868 sec <<< FAILURE!
Results :
Tests in error:
testfind(com.itcast.service.product.BrandServiceTest)
Tests run: 7, Failures: 0, Errors: 1, Skipped: 0
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 10.939s
Finished at: Tue Oct 11 18:02:56 CST 2011
Final Memory: 4M/254M
error log:
-------------------------------------------------------------------------------
Test set: com.itcast.service.product.BrandServiceTest
-------------------------------------------------------------------------------
Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.868 sec <<< FAILURE!
testfind(com.itcast.service.product.BrandServiceTest) Time elapsed: 0.008 sec <<< ERROR!
java.lang.NullPointerException
at com.itcast.service.product.BrandServiceTest.testfind(BrandServiceTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.apache.maven.surefire.junitcore.ConfigurableParallelComputer$AsynchronousRunner$1.call(ConfigurableParallelComputer.java:186)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
junit class:
/*
* Copyright 2011 待到道成日,纵横天地间.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itcast.service.product;
import com.itcast.model.product.Brand;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
* #author Kang.Cunhua
*/
#ContextConfiguration(locations = {"classpath:beans.xml"})
#RunWith(SpringJUnit4ClassRunner.class)
public class BrandServiceTest {
private static final Logger logger = Logger.getLogger(BrandServiceTest.class.getName());
#Resource(name = "brandServiceImpl")
private BrandService brandService;//= new BrandServiceImpl();
#Test
public void testSave() {
Brand brand = new Brand("远阳瑜伽", "/image/brand/2011/10/04/yuanyangyujia.png");
System.err.println("001" + brandService);
brandService.save(brand);
System.err.println("002" + brand.getCode());
}
#Test
public void testfind() {
System.out.println("003" + "测试Find()方法!");
System.err.println("004" + brandService);
Brand brand = (Brand) brandService.find(Brand.class, "55fba033-b4a7-4d61-89c0-2564b020731c");
System.err.println("005" + brand.getCode());
logger.log(Level.INFO, "获取id为\"55fba033-b4a7-4d61-89c0-2564b020731c\"的记录! {0}", brand);
}
}
some exact code about testclass
*BrandServiceImpl.java*
/*
* Copyright 2011 待到道成日,纵横天地间.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itcast.service.product;
import com.itcast.model.product.Brand;
import java.util.UUID;
import com.itcast.service.dao.DaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* #author Kang.Cunhua
*/
#Service //标注为Spring的Servicebean,供自动扫描机制加载该bean,就不用再beans.xml中声明了
#Transactional
public class BrandServiceImpl extends DaoSupport implements BrandService {
public BrandServiceImpl() {
}
#Override
public void save(Object entity) {
((Brand) entity).setCode(UUID.randomUUID().toString());
super.save(entity);
}
}
DaoSupport.java
package com.itcast.service.dao;
import com.itcast.model.QueryResult;
import java.util.LinkedHashMap;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
*
* #author kang.cunhua
*/
#Transactional // 后面的方法都会具有默认的事务行为
public abstract class DaoSupport implements Dao {
/**
*
*/
#PersistenceContext
protected EntityManager em; // 允许子类访问,不用再在子类中注入
#Override
public void save(Object entity) {
//System.out.println("entityManager====" + em + "caller========" + Reflection.getCallerClass(2));
em.persist(entity);
}
#Override
public void update(Object entity) {
em.merge(entity);
}
#Override
public <T> void delete(Class<T> entityClass, Object entityid) {
delete(entityClass, new Object[]{entityid});
}
#Override
public <T> void delete(Class<T> entityClass, Object[] entityids) {
for (Object id : entityids) {
em.remove(em.getReference(entityClass, id));
}
}
#Override
#Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public <T> T find(Class<T> entityClass, Object entityId) {
//System.out.println("entityManager====" + em);
return em.find(entityClass, entityId);
}
#Override
#Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex,
int maxresult, String wherejpql, Object[] queryParams, LinkedHashMap<String, String> orderby) {
QueryResult qr = new QueryResult<T>();
String entityname = getEntityName(entityClass);
Query query = em.createQuery("select o from " + entityname + " o " + (wherejpql == null ? "" : "where " + wherejpql) + buildOrderby(orderby));
setQueryParams(query, queryParams);
if (firstindex != -1 && maxresult != -1) {
query.setFirstResult(firstindex);
query.setMaxResults(maxresult);
//这两句也可以简写为:query.setFirstResult(firstindex).setMaxResults(maxresult);
}
qr.setResultlist(query.getResultList());
query = em.createQuery("select count(o) from " + entityname + " o " + (wherejpql == null ? "" : "where " + wherejpql));
setQueryParams(query, queryParams);
qr.setTotalrecord((Long) query.getSingleResult());
return qr;
}
/**
*
* #param <T>
* #param entityClass
* #param firstindex
* #param maxresult
* #param orderby
* #return
*/
#Override
#Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult, LinkedHashMap<String, String> orderby) {
return getScrollData(entityClass, firstindex, maxresult, null, null, orderby);
}
/**
*
* #param <T>
* #param entityClass
* #param firstindex
* #param maxresult
* #param wherejpql
* #param queryParams
* #return
*/
#Override
#Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult, String wherejpql, Object[] queryParams) {
return getScrollData(entityClass, firstindex, maxresult, wherejpql, queryParams, null);
}
/**
*
* #param <T>
* #param entityClass
* #param firstindex
* #param maxresult
* #return
*/
#Override
#Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult) {
return getScrollData(entityClass, firstindex, maxresult, null, null, null);
}
/**
*
* #param <T>
* #param entityClass
* #return
*/
#Override
#Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public <T> QueryResult<T> getScrollData(Class<T> entityClass) {
return getScrollData(entityClass, -1, -1);
}
/**
*
* #param query
* #param queryParams
*/
protected void setQueryParams(Query query, Object[] queryParams) {
if (queryParams != null && queryParams.length > 0) {
for (int i = 0; i < queryParams.length; i++) {
query.setParameter(i + 1, queryParams[i]);
}
}
}
/**
* 组装order by 语句
* #param orderby
* #return
*/
protected String buildOrderby(LinkedHashMap<String, String> orderby) {
StringBuilder orderbyql = new StringBuilder();
if (orderby != null && orderby.size() > 0) {
orderbyql.append(" order by ");
// order by o.key desc,o.key2 asc
for (String key : orderby.keySet()) {
orderbyql.append("o.").append(key).append(" ").append(orderby.get(key)).append(",");
}
orderbyql.deleteCharAt(orderbyql.length() - 1);
}
return orderbyql.toString();
}
/**
* 利用反射技术得到要传递到分页方法中的实体类的名字,简单名字还是自定义名字
* #param <T>
* #param entityClass
* #return
*/
protected <T> String getEntityName(Class<T> entityClass) {
String entityname = entityClass.getSimpleName();
Entity entity = entityClass.getAnnotation(Entity.class);
if (entity.name() != null && !"".equals(entity.name())) {
entityname = entity.name();
}
return entityname;
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : beans.xml
Created on : 2010年12月13日, 下午5:07
Author : kang.cunhua
Description: Spring3.05+JPA(Hibernate3.6)集成.
-->
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:component-scan base-package="com.itcast"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}" />
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 最小空闲值,当空闲的连接数少于阀值时,连接池就会去申请一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}" />
</bean>
<!-- This will ensure that hibernate or jpa exceptions are automatically translated into
Spring's generic DataAccessException hierarchy for those classes annotated with Repository
For example see PersonDaoJpa-->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<!-- 类工厂由spring管理 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/><!-- 注入数据源bean到实体管理工厂bean -->
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="loadTimeWeaver"><!-- 运行时植入 -->
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<!-- bean post-processor for JPA annotations -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- 事务由spring管理 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/><!-- 注入实体管理工厂bean到事务管理bean -->
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/><!-- 事务声明方式是注解 -->
</beans>
Your brandservice is null. See output
004null
EDIT: after inspecting your full sources:
remove:
<configuration>
<parallel>methods</parallel>
<threadCount>1</threadCount>
</configuration>
from your surefire config in super-pom:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<parallel>methods</parallel>
<threadCount>1</threadCount>
</configuration>
</plugin>
will make it work. It seems if the tests are executed in parallel, it fails.
I believe you should use this for the brandService, to get an instance of it:
#Autowired
#Qualifier("brandServiceImpl")
private BrandService brandService;
Is there any solution to have something like <cms:include type="OpenCmsString" element="text1" /> ? Because the output from my <cms:include element="text1"> always give me data with <p> tag.
Any kind help is appreciated.
I've once created my own tag for that (StripPTag). You would compile that class and wrap it in a jar file, then deploy that to your opencms webapp lib folder.
package com.opencmsserver.taglib;
import org.opencms.flex.CmsFlexController;
import org.opencms.jsp.Messages;
import org.opencms.main.CmsLog;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.logging.Log;
/**
* Removes the <p> tag from the surrounded content,
* because FCKEditor always add <p> tag to content at
* the beginning and end when using the html editor component
*
* #author Mathias Lin
*
* #version $Revision: 0.1 $
*
* #since 0.4
*/
public class StripPTag extends BodyTagSupport {
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = -2361021288258405388L;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(StripPTag.class);
/**
* #see javax.servlet.jsp.tagext.Tag#doEndTag()
* #return EVAL_PAGE
* #throws JspException in case soemthing goes wrong
*/
public int doEndTag() throws JspException {
ServletRequest req = pageContext.getRequest();
// This will always be true if the page is called through OpenCms
if (CmsFlexController.isCmsRequest(req)) {
try {
// Get link-string from the body and reset body
String content = getBodyContent().getString();
content = content.replaceAll("<p>", "");
content = content.replaceAll("</p>", "");
getBodyContent().clear();
getBodyContent().print(content);
getBodyContent().writeOut(pageContext.getOut());
} catch (Exception ex) {
if (LOG.isErrorEnabled()) {
LOG.error("Failed using StripPTag. ", ex);
}
throw new JspException(ex);
}
}
return EVAL_PAGE;
}
}
and my own opencmsserver.tld:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>0.1</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>opencmsserver</short-name>
<uri>http://www.opencmsserver.com/taglib/cms</uri>
<display-name>OpenCms JSP standard taglib</display-name>
<description>
Additional OpenCms Tags
Developed by SYSVISION Ltd. / Mathias Lin (info#opencmsserver.com)
</description>
<tag>
<name>stripPTag</name>
<tag-class>com.opencmsserver.taglib.StripPTag</tag-class>
<body-content>JSP</body-content>
<description>
This tag stripts the p-tag from the surrounded content.
</description>
</tag>
</taglib>
which I then reference in my web.xml:
<!-- Begin: Custom SYSVISION OpenCmsServer lib -->
<taglib>
<taglib-uri>http://www.opencmsserver.com/taglib/opencmsserver</taglib-uri>
<taglib-location>/WEB-INF/opencmsserver.tld</taglib-location>
</taglib>
In your jsp, you just surround it then with:
<opencmsserver:stripPTag>Some content<p>with a paragraph</opencmsserver:stripPTag>
(and don't forget to reference to this tag lib in the jsp header section).