I am trying to test an Stateless bean with JUnit in netbeans. This bean uses an EntityManager.
#Stateless
public class myEjb{
#PersistenceContext
private EntityManager em;
public MyResult getResult(){
return em.find(...);
}
}
Then I write a test class.
public class myTest{
private static EJBContainer ec;
private static Context ctx;
#BeforeClass
public static void setUpClass(){
ec = EJBContainer.createEJBContainer();
ctx = ec.getContext();
}
....
}
When I run the test, it does not work. I obtain the following message:
Invalid resource : mydb__pm
The error occurs when this line is executed:
ec = EJBContainer.createEJBContainer();
If a change my bean by removing the entity manager, it works. So, it seems that I have a problem with the entity manager.
My persistence.xml file is simple:
<persistence version="2.0" ...>
<persistence-unit name="MetisDemoPU" transaction-type="JTA">
<jta-data-source>MyDb</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
Finally, I create a JSF managed bean that called my EJB (which uses the entity manager) and it works.
#ManagedBean
#RequestScoped
public class myManagedBean{
#EJB
private OfferEjb offerEjb;
...
}
Any help would be appreciated!
Ok, I find a solution to my problem. I am now able to use JUnit to test my session bean with a persistence context.
I am not a specialist, so my explanation will probably not be complete.
With netbeans 7.2, there is an embedded glassfish server which is used for the test. It is necessary to configure the jdbc parameters in the domain.xml file and then for me it works.
On my computer, this file is under
C:\Program Files\glassfish-3.1.2.2\glassfish\domains\domain\
I just add a jdbc connection pool and a jdvc jndi.
This article contains more details.
Related
I have created a Spring SOAP based webservice which retrives data from my DB , I am able to test the service through SOAP UI , but now I am trying to add few functionalites for the service and I want to add some Junits for the service , Please find my Endpoint and Junit details below.
My End Point Class
#Endpoint
public class CountryEndPoint {
private static final String NAMESPACE_URI = "http://tutorialspoint/schemas";
#Autowired
CountryRepository countryRepository;
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
#ResponsePayload
public GetCountryResponse getCountry(#RequestPayload GetCountryRequest request) throws JDOMException {
Country country = countryRepository.findCountry(request.getName());
GetCountryResponse response = new GetCountryResponse();
response.setCountry(country);
return response;
}
}
Spring-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:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.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.0.xsd">
<context:component-scan
base-package="com.tutorialspoint" />
<sws:annotation-driven />
<bean id="schema"
class="org.springframework.core.io.ClassPathResource">
<constructor-arg index="0" value="*.xsd" />
</bean>
</beans>
Junit-Test calss
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "/spring-context.xml")
public class CustomerEndPointTest {
#Autowired
private ApplicationContext applicationContext;
#Autowired
private ResourceLoader resourceLoader;
private MockWebServiceClient mockClient;
private Resource schema = new ClassPathResource("countries.xsd");
#Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);
GenericApplicationContext ctx = (GenericApplicationContext) applicationContext;
final XmlBeanDefinitionReader definitionReader = new XmlBeanDefinitionReader(ctx);
definitionReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
definitionReader.setNamespaceAware(true);
}
#Test
public void testCountryEndpoint() throws Exception {
Resource request = resourceLoader.getResource("request.xml");
Resource response = resourceLoader.getResource("response.xml");
mockClient.sendRequest(withPayload(request)).
andExpect(payload(response)).
andExpect(validPayload(schema));
}
}
I am able to run the test case with out any issue but my problem is I am not able to mock my service class (CountryRepository) mock the the code below.
Country country = countryRepository.findCountry(request.getName());
Does any one have any suggessions on this?
From your test case, I suppose your are trying to mock the CrudRepository object from inside a webservice call: That would be called integration testing. You need to make a choice for unit testing:
Test the request, and assert its response http status code (for example),
Or test the getCountry method inside your CountryEndPoint class. Doing both options at the same time would be considered an integration test.
I will try to answer considering the unit test case, using option 2. I think it will give you better insights for the future.
You are injecting the dependency of the CountryRepository on your CountryEndPoint class. You need to do the same on your testing class. For example, a basic setup would be:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "/spring-context.xml")
public class CustomerEndPointTest {
#InjectMocks
private CountryEndPoint countryEndPoint;
#Mock
private CountryRepository countryRepository;
#Test
public void testCountryEndpoint() throws Exception {
Mockito.when(countryRepository //...
countryEndPoint.getCountry(request //build a request object and pass it here.
//assertions...
}
}
Then, whenever a method from CountryRepository is invoked, it will be invoked from the mock instead. This is only possibly because of the injection of the mock via annotations.
If you actually send a request, using a HTTP client (like you intended), you cannot mock the methods being invoked inside your controller class, because you are not manipulating and assigning the instances yourself, and thus are not able to determine what is a mock, and what is not.
My web app is not getting the datasource which was configured in server.xml. I have added the sqlconnector jar (mysql-connector-java-8.0.12) under the folder C:\wlp\usr\shared\resources\mysql
server.xml
<!-- Enable features -->
<featureManager>
<feature>cdi-1.2</feature>
<feature>jaxrs-2.0</feature>
<feature>jdbc-4.0</feature>
<feature>jndi-1.0</feature>
<feature>jpa-2.0</feature>
<feature>localConnector-1.0</feature>
<feature>servlet-3.1</feature>
</featureManager>
<!-- Declare the jar files for MySQL access through JDBC. -->
<library id="MySQLLib">
<fileset dir="${shared.resource.dir}/mysql" includes="mysql-connector-java-8.0.12.jar"/>
</library>
<!-- Declare the runtime database -->
<dataSource jndiName="AdminWeb/jdbc/AdminDS" transactional="false">
<jdbcDriver libraryRef="MySQLLib"/>
<properties databaseName="admin" password="****" portNumber="3306" serverName="localhost" user="root"/>
</dataSource>
DAO
#Resource(name = "AdminWeb/jdbc/AdminDS",lookup="AdminWeb/jdbc/AdminDS")
DataSource dataSource;
public UserEntity getAllUsers() {
UserEntity user = new UserEntity();
Connection connection = null;
try {
System.out.println("****************1");
connection = dataSource.getConnection();
System.out.println("2");
While invoking the webapp, the getconnection method throws
[ERROR ] SRVE0777E: Exception thrown by application class 'com.fist.tools.admin.dao.UserDAO.getAllUsers:25'
java.lang.NullPointerException
Could anyone please help me on this?
The dataSource/server configuration itself looks fine. #Resource can only be injected into web components/ejb components. Does the class you are injecting into fit that description?
I am adding JSONP support to a REST Service in SPRING4 + JDK 8 + STS 3.6.4
Versions:
Spring 4.1.6.RELEASE
My implementation is based on these links:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-jsonp
The REST service returns ResponseEntity or ResponseBody and use case is to return data in JSONP format.
Added a ControllerAdvice
#ControllerAdvice
public class JsonpCallbackAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpCallbackAdvice(){
super("Callback");
}
}
Here is the Controller of the REST Service
#Controller
public class AcctController {
...
#RequestMapping(value = "/act/{actNum}", method = RequestMethod.GET)
public ResponseEntity<Account> getAccount(#PathVariable("actNum") Integer accountNum) throws Exception {
...
return new ResponseEntity<account>();
}
Here is the relevant web application context configuration
...
<context:component-scan base-package="com.controllers" />
<bean name="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
...
The controller and ControllerAdvice are in same package.
When deployment of the project is initiated following exception is observed
Caused by: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
at org.springframework.context.annotation.AnnotationBeanNameGenerator.determineBeanNameFromAnnotation(AnnotationBeanNameGenerator.java:91)
at org.springframework.context.annotation.AnnotationBeanNameGenerator.generateBeanName(AnnotationBeanNameGenerator.java:69)
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:246)
at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:84)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:74)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1427)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1417)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:174)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:144)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:100)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:510)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
This exception was not happening before the ControllerAdvice was added.
Also, it does not happens when #ControllerAdvice annotation is removed
or
the component scan excludes scanning package of the ControllerAdvice class
I tried with Spring version 4.2.0.RC1, and the exception still happens.
Kindly help with resolution of this exception, since not much help is available online.
It seems like a bug in SPRING 4, however am not sure.
I'm not sure whether this is a misconfiguration on my part, a misunderstanding of what can be accomplished via #ModelAttribute and automatic JSON content conversion, or a bug in either Spring or Jackson. If it turns out to be the latter, of course, I'll file an issue with the appropriate folks.
I've encountered a problem with adding a #ModelAttribute to a controller's handler method. The intent of the method is to expose a bean that's been populated from a form or previous submission, but I can reproduce the issue without actually submitting data into the bean.
I'm using the Spring mvc-showcase sample. It's currently using Spring 3.1, but I first encountered, and am able to reproduce, this issue on my 3.0.5 setup. The mvc-showcase sample uses a pretty standard servlet-context.xml:
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven conversion-service="conversionService">
<argument-resolvers>
<beans:bean class="org.springframework.samples.mvc.data.custom.CustomArgumentResolver"/>
</argument-resolvers>
</annotation-driven>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Imports user-defined #Controller beans that process client requests -->
<beans:import resource="controllers.xml" />
<!-- Only needed because we install custom converters to support the examples in the org.springframewok.samples.mvc.convert package -->
<beans:bean id="conversionService" class="org.springframework.samples.mvc.convert.CustomConversionServiceFactoryBean" />
<!-- Only needed because we require fileupload in the org.springframework.samples.mvc.fileupload package -->
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans:beans>
The controllers.xml referenced in the file simply sets up the relevant component-scan and view-controller for the root path. The relevant snippet is below.
controllers.xml
<!-- Maps '/' requests to the 'home' view -->
<mvc:view-controller path="/" view-name="home"/>
<context:component-scan base-package="org.springframework.samples.mvc" />
The test bean which I am attempting to deliver is a dead-simple POJO.
TestBean.java
package org.springframework.samples.mvc.test;
public class TestBean {
private String testField = "test#example.com";
public String getTestField() {
return testField;
}
public void setTestField(String testField) {
this.testField = testField;
}
}
And finally, the controller, which is also simple.
TestController.java
package org.springframework.samples.mvc.test;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("test/*")
public class TestController {
#ModelAttribute("testBean")
public TestBean getTestBean() {
return new TestBean();
}
#RequestMapping(value = "beanOnly", method = RequestMethod.POST)
public #ResponseBody
TestBean testBean(#ModelAttribute("testBean") TestBean bean) {
return bean;
}
#RequestMapping(value = "withoutModel", method = RequestMethod.POST)
public #ResponseBody
Model testWithoutModel(Model model) {
model.addAttribute("result", "success");
return model;
}
#RequestMapping(value = "withModel", method = RequestMethod.POST)
public #ResponseBody
Model testWithModel(Model model, #ModelAttribute("testBean") TestBean bean) {
bean.setTestField("This is the new value of testField");
model.addAttribute("result", "success");
return model;
}
}
If I call the controller via the mapped path /mvc-showcase/test/beanOnly, I get a JSON representation of the bean, as expected. Calling the withoutModel handler delivers a JSON representation of the Spring Model object associated with the call. It includes the implicit #ModelAttribute from the initial declaration in the return value, but the bean is unavailable to the method. If I wish to process the results of a form submission, for example, and return a JSON response message, then I need that attribute.
The last method adds the #ModelAttribute, and this is where the trouble comes up. Calling /mvc-showcase/test/withModel causes an exception.
In my 3.0.5 installation, I get a JsonMappingException caused by a lack of serializer for FormattingConversionService. In the 3.1.0 sample, the exception is caused by lack of serializer for DefaultConversionService. I'll include the 3.1 exception here; it seems to have the same root cause, even if the path is a bit different.
3.1 org.codehaus.jackson.map.JsonMappingException
org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.springframework.format.support.DefaultFormattingConversionService and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.validation.support.BindingAwareModelMap["org.springframework.validation.BindingResult.testBean"]->org.springframework.validation.BeanPropertyBindingResult["propertyAccessor"]->org.springframework.beans.BeanWrapperImpl["conversionService"])
at org.codehaus.jackson.map.ser.StdSerializerProvider$1.failForEmpty(StdSerializerProvider.java:89)
at org.codehaus.jackson.map.ser.StdSerializerProvider$1.serialize(StdSerializerProvider.java:62)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:272)
at org.codehaus.jackson.map.ser.BeanSerializer.serializeFields(BeanSerializer.java:175)
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:147)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:272)
at org.codehaus.jackson.map.ser.BeanSerializer.serializeFields(BeanSerializer.java:175)
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:147)
at org.codehaus.jackson.map.ser.MapSerializer.serializeFields(MapSerializer.java:207)
at org.codehaus.jackson.map.ser.MapSerializer.serialize(MapSerializer.java:140)
at org.codehaus.jackson.map.ser.MapSerializer.serialize(MapSerializer.java:22)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:315)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:242)
at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1030)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.writeInternal(MappingJacksonHttpMessageConverter.java:153)
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:181)
at org.springframework.web.servlet.mvc.method.annotation.support.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:121)
at org.springframework.web.servlet.mvc.method.annotation.support.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)
at org.springframework.web.servlet.mvc.method.annotation.support.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:81)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:64)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMethodAdapter.invokeHandlerMethod(RequestMappingHandlerMethodAdapter.java:505)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMethodAdapter.handleInternal(RequestMappingHandlerMethodAdapter.java:468)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at
...
So, is there some configuration I am missing that should allow the Jackson converter to properly handle a response derived from a handler with #ModelAttribute in the method signature? If not, any thoughts as to whether this is more likely a Spring bug or a Jackson bug? I'm leaning toward Spring, at this point.
It looks like a Spring config problem, when serializing to JSON the DefaultFormattingConversionService is empty and Jackson (by default) will throw an exception if a bean is empty see FAIL_ON_EMPTY_BEANS in the features documentation. But I am not clear why the bean is empty.
It should work if you set FAIL_ON_EMPTY_BEANS to false, but still doesn't really explain why it is happening in the first place.
DefaultFormattingConversionService is new to 3.1 - it extends the FormattingConversionService which explains the different exceptions between 3.0.5 and 3.1.
I do not think it is a Jackson problem, although a new version of Jackson (1.8.0) was released only 3 days ago so you could try that also.
I will try to reproduce this locally.
I am using Eclipse Galileo and I wanted to deploy a simple application, using JPA, GlassFish 2.1 and MySQL 5. Unfortunately, I could not find any tutorials for GlassFish 2.1 (just for 3.0, but I cannot use it).
I created a JPA project, added a MySQL5 connection and generated an Entity from the database.
The generate JPA class is:
package model;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="customer_id")
private int customerId;
private String email;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
public Customer() {
}
public int getCustomerId() {
return this.customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
And the persistence.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="JPAProject2">
<class>model.Customer</class>
</persistence-unit>
</persistence>
I created a Dynamic Web Project, and added a new Servlet class, which looks like this:
package servlet;
import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import model.Customer;
public class JpaDemoServlet2 extends HttpServlet
{
private static final long serialVersionUID = 1L;
#PersistenceUnit
private EntityManagerFactory entityManagerFactory;
#Resource
private UserTransaction userTransaction;
public JpaDemoServlet2()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
EntityManager entityManager =
entityManagerFactory.createEntityManager();
Customer customer = new Customer();
customer.setCustomerId(3);
customer.setFirstName("Smith");
customer.setLastName("John");
customer.setEmail("john.smith#email.com");
try
{
userTransaction.begin();
entityManager.persist(customer);
userTransaction.commit();
}
catch(Exception ex)
{
response.sendError(1, ex.getMessage());
}
}
}
I added in the servlet project's properties Project References and Module Dependencies for the JPA project. Are there any other configuration setting that must be done?
So far I was able to publish the Servlet, but unfortunately, I cannot run it. http://localhost:4848/ServletProject2, I get the 'Hello, World!' message, but if I want to access http://localhost:4848/ServletProject2/JpaDemoServlet2 I get this exception:
Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.1 (Build b60e-fcs (12/23/2008))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Error Code: 0
Is there something I am missing?
There are a number of issues I think.
First, the persistence.xml looks a bit odd, I would have expected something like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="JPAProject2" transaction-type="JTA">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<jta-data-source>jdbc/sample</jta-data-source>
<class>model.Customer</class>
</persistence-unit>
</persistence>
That is, a provider field, and the necessary fields to indicate that you're running in a server (jta-data-source). Of course, jta-data-source has to refer to a datasource that you configured in Glassfish.
Next, I think it's quite odd that your application runs on ports 4848, normally that's the administrative listener for Glassfish, and I'd expect only the admin console to run there. Did you reconfigure your Glassfish's ports?
One thing that puzzles me is how you got this far with such a configuration: it looks like Toplink thinks it has to contact a Derby running on localhost (port 1527 is standard for Derby) so maybe there's still some other persistence.xml floating around? Please check that.
About tutorials: I use Glassfish a lot, but always with NetBeans. Here are a couple of links to tutorials from the Netbeans site, they might help you.
http://www.netbeans.org/kb/docs/web/customer-book.html
http://www.netbeans.org/kb/61/javaee/persistence.html
It may be easiest to just install Netbeans, follow the tutorials and have a look at all the files that get generated, Netbeans automates the creation of a lot of this stuff and I have no idea what degree of assistance Eclipse gives you with these files.
Here is a rather complete tutorial based on Eclipse: http://wiki.eclipse.org/EclipseLink/Examples/JPA/GlassFishV2_Web_Tutorial
A last one: a tutorial for GF3 should get you going on GF2 as well, at least for these technologies (servlet and JPA). OK, GF3 comes with Eclipselink instead of Toplink Essentials, but these two are not that different at all.
Edit: when I saw TLE trying to connect to a Derby on localhost I forgot the part about MySQL. This has been corrected now - references to how you should start Derby have been removed.