GlassFish exception - netbeans

Im quite new to all this stuff. I try to launch a webservice via GlassFish. When i try to build this project i get an error.
ant -f /home/philipp/NetBeansProjects/sks3 -DforceRedeploy=false -Ddirectory.deployment.supported=true -Dnb.wait.for.caches=true run
init:
deps-module-jar:
deps-ear-jar:
deps-jar:
check-rest-config-props:
generate-rest-config:
library-inclusion-in-archive:
library-inclusion-in-manifest:
compile:
compile-jsps:
In-place deployment at /home/philipp/NetBeansProjects/sks3/build/web
Initializing...
deploy?DEFAULT=/home/philipp/NetBeansProjects/sks3/build/web&name=sks3&contextroot=/sks3&force=true failed on GlassFish Server 3.1.2
Error occurred during deployment: Exception while deploying the app [sks3] : Invalid TYPE-level #EJB with name() = [] and beanInterface = [class java.lang.Object] in class Webservice.MeasurementResources. Each TYPE-level #EJB must specify both name() and beanInterface().at org.glassfish.apf.AnnotationInfo#3b63118a. Please see server.log for more details.
/home/philipp/NetBeansProjects/sks3/nbproject/build-impl.xml:1028: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 6 seconds)
I dont have a clue what is going wrong but according to the message it has to be in the file MeasurementResurces.java ...
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Webservice;
import Exception.DALException;
import dal.MeasurementDao;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.Path;
import repo.Measurement;
/**
*
* #author philipp
*/
//#Stateless
//#inject
#EJB
//#LocalBean
#Named
#Path("Measurement")
public class MeasurementResources {
#Inject
MeasurementDao mDao;
public void add(Measurement arg) throws DALException{
mDao.save(arg);
}
/* public void getAll(Measurement arg) throws DALException{
mDao.getAll();
}
*/
}
Someone has at least a hint whats the problem?

You are using a Type-Level EJB without declaring name and beanInterface.
/**
*
* #author philipp
*/
//#Stateless
//#inject
#EJB(name="MyEjb", beanInterface=RemoteEjb.class)
//#LocalBean
#Named
#Path("Measurement")
public class MeasurementResources {
#Inject
MeasurementDao mDao;
public void add(Measurement arg) throws DALException{
mDao.save(arg);
}
}
#Remote
public interface RemoteEjb {
public void doSomething();
}
#Stateless
public class MyEjb implements RemoteEjb {
...
}
name is the name of the EJB you trying to inject. beanInterface is the Local or Remote interface. It's not a real injection. It is a way to use annotation as a replacement of deployment descriptor ejb-ref element. You should use a JNDI lookup in order to inject the ejb.
I don't know what are you trying to do but the common way to inject an ejb is the following:
#Named
#Path("Measurement")
public class MeasurementResources {
#EJB
private MyEjb myejb;
#Inject
MeasurementDao mDao;
public void add(Measurement arg) throws DALException{
mDao.save(arg);
}
...
}

Related

Injection of #PersistenceContext in CDI-Unit

Here is the unit testing code. When we run unit test code (SampleServiceTest2); EntityManager injected in AbstractDao is always null! How can we inject em during unit test.
*** SampleServiceTest2.java
import javax.inject.Inject;
import org.jglue.cdiunit.CdiRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(CdiRunner.class)
public class SampleServiceTest2 {
#Inject SampleService greeter;
#Test
public void testGreeter() throws Exception {
System.out.println("before2");
greeter.addSampleData(new SampleDataDto(), new KullaniciDto());
System.out.println("after2");
}
}
*** SampleService.java
import javax.ejb.Stateless;
import javax.inject.Inject;
....
#Stateless
#SecuredBean
public class SampleService {
#Inject
SampleLogic sampleLogic;
#Yetki(tag="perm_add_sample_data")
public void addSampleData(SampleDataDto data, KullaniciDto aktifKullaniciDto){
SampleDataHelper sampleDataHelper = new SampleDataHelper();
SampleData sampleData = sampleDataHelper.getEntity(data);
KullaniciHelper kullaniciHelper = new KullaniciHelper();
Kullanici kullanici = kullaniciHelper.getEntity(aktifKullaniciDto);
sampleLogic.addData(sampleData, kullanici);
}
}
**** SampleLogic.java
import javax.inject.Inject;
....
public class SampleLogic {
#Inject
SampleDataDao sampleDataDao;
public void addData(SampleData data, Kullanici kullanici) {
addData1(data,kullanici);
System.out.println("SampleLogic : addData() called!");
}
public void addData1(SampleData data, Kullanici kullanici) {
sampleDataDao.create(data, kullanici);
}
}
**** SampleDataDao.java
public class SampleDataDao extends AbstractDao<SampleData> {
private static final long serialVersionUID = 1L;
}
**** AbstractDao.java
public abstract class AbstractDao<T extends BaseEntity> implements Serializable {
private static final long serialVersionUID = 1L;
#PersistenceContext(unitName="meopdb")
private EntityManager em;
protected EntityManager getEm() {
return em;
}
#SuppressWarnings("rawtypes")
private Class entityClass;
#SuppressWarnings("rawtypes")
private Class getEntityClass() {
if (entityClass == null) {
entityClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
return entityClass;
}
public T create(T t, Kullanici kullanici) {
if (t.getId() != null) {
throw new IllegalStateException("Create Operation: Oid should be null");
}
t.setId(getSeqNextValue(t));
t.setEklemeZamani(new Timestamp(Calendar.getInstance().getTimeInMillis()));
t.setEkleyenKullaniciId(kullanici.getId());
t.setDurumId(EnumDurum.AKTIF.getValue());
t = em.merge(t);
em.flush();
return t;
}
}
If you test with CDIUnit, the only thing you get is CDI injections, not the full power of Java EE. Injecting entityManager using #PersistenceContext into AbstractDAO is not part of standalone CDI, it is only supported when application is running within a Java EE application server.
The solution is to inject EntityManager using CDI mechanism and create a producer. The producer could be then switched for an alternative in unit tests to provide test entityManager. However, setting up JPA in a standalone unit test is not so straightforward, as you need to specify connection properties directly in persistence.xml file. Also, do not forget to add dependencies on a JPA implementation (hibernate, eclipselink) into your test dependencies.
However, if you do not want to adapt your application's code or you need more than CDI in your tests, you should have a look at Arquillian Java EE test framework.
Here is an example for CDIUnit:
public abstract class AbstractDao<T extends BaseEntity> implements Serializable {
...
#Inject
#Named("meopdb")
private EntityManager em;
...
}
// producer in application - just a wraper over `#PersisteneContext`
public class EntityManagerProducer {
#Produces
#PersistenceContext(unitName="meopdb")
#Named("meopdb")
private EntityManager em;
}
/* producer in your test sources - it creates entityManager via API calls instead of injecting via `#PersistenceContext`. Also, a different persistence unit is used so that it does not clash with main persistence unit, which requires datasource from app server
*/
public TestEntityManagerProducer {
#Produces
#ProducesAlternative // CDIUnit annotation to turn this on as an alternative automatically
#Named("meopdb")
public EntityManager getEm() {
return Persistence
.createEntityManagerFactory("meopdb-test")
.createEntityManager();
}
}
And it is not yet enough. You need to create a new persistence.xml in your test resources with the test persistence unit named "meopdb-test". For this unit you need to specify RESOURCE_LOCAL transaction-type, and specify connection information. And last thing not to forget - you need to list all your entities in the persistence.xml, or in external orm file. This is because your tests run outside of application server. Inside app server, JPA can find entities automatically.
As #OndroMih said, in CDI-Unit, the only thing you get is CDI injections. So you have to cheat a little.
You can use extension do add javax.inject.Inject annnotation to all #PersistenceContext injections
import java.util.Set;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.*;
import javax.inject.Inject;
import javax.persistence.PersistenceContext;
import org.apache.deltaspike.core.util.metadata.AnnotationInstanceProvider;
import org.apache.deltaspike.core.util.metadata.builder.AnnotatedTypeBuilder;
public class AddInjectToPersistenceContextInjectionsCdiExtension implements Extension {
<T> void processAnnotatedType(#Observes ProcessAnnotatedType<T> pat) {
Set<AnnotatedField<? super T>> fields = pat.getAnnotatedType().getFields();
for (AnnotatedField<? super T> field : fields) {
if (shouldInjectionAnnotationBeAddedToField(field)) {
AnnotatedType<T> at = pat.getAnnotatedType();
AnnotatedTypeBuilder<T> builder = new AnnotatedTypeBuilder<T>().readFromType(at);
Inject injectAnnotation = AnnotationInstanceProvider.of(Inject.class);
builder.addToField(field, injectAnnotation);
pat.setAnnotatedType(builder.create());
}
}
}
private <X> boolean shouldInjectionAnnotationBeAddedToField(AnnotatedField<? super X> field) {
return !field.isAnnotationPresent(Inject.class) &&
field.isAnnotationPresent(PersistenceContext.class);
}
}
and produce suitable EntityManager in test class
#RunWith(CdiRunner.class)
#AdditionalClasses(AddInjectToPersistenceContextInjectionsCdiExtension.class)
public class SampleServiceTest2 {
#Inject SampleService greeter;
EntityManagerFactory emf;
#PostConstruct
void init() {
emf = Persistence.createEntityManagerFactory("integration");
}
#Produces
EntityManager createEntityManager() {
return emf.createEntityManager();
}
#Test
public void testGreeter() throws Exception {
}
}
It's not exactly equivalent of what Java EE container does, but it's close enough more often than not.

null pointer exception error when revoking EJB method

I am new in creating Java modules, currently I'm trying to call method which inserts data into database. I have an 1) interface TestSEI. 2) The webservice called TestWS, implements TestSEI. 3) Class TestBean which implements methods which I call from TestWS. In this class I added new method DocPay, which have to call method from another EJB Module (named PayTestmodule) from class TestDB. I added PayTestmodule in dependency in my project.
In Netbeans I am succesfully build and deploy EAR file on Jobss, but when I revoke method DocPay in class TestBean I get error - Null pointer exception. I spend all day to fing out possible solution, but no success. Here some snippets:
1.TestSEI
#WebService(name="TestWS")
#SOAPBinding(style=SOAPBinding.Style Document)
public interface TestSEI {
......
2.TestWS
#WebService
public class TestWS implements TestSEI {
#Inject
private TestBean domain
....
domain.DocPay(Object RQU)
...
3.TestBean
#stateless
#Localbean
public class TestBean {
....
Public DocPay(Object request)
PayDB dbapi=new PayDB();
String id=dbapi.insertdata(Stringparams)
....
4.PayDB class(defined in another EJB module)
#Stateless
public class PayDB implements PayDBLocal
......
Publis String insertdata(Stringparams) throws ....
5.PayDBLocal
#Local
public interface PayDBLocal
.......
Please, help me to understand what I am doing wrong?
Did you mean "when I revoke method DocPay in class TestBean" or its in TestWS??
Use this in TestWS
#EJB
private TestBean domain

EJB 3.x deployment on JBOSS AS 7.1.1

I'm trying to create an ejb timer and successful to do so but however unable to deploy it successfully. I'm using ejb timer first time so I might not be doing it right. so kindly if someone guides me in the right direction. Thank you
followed the tutorial from
http://www.adam-bien.com/roller/abien/entry/simplest_possible_ejb_3_16
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ejb.Timer;
#Stateless
public class ScheduleRoutine {
/**
* Default constructor.
*/
public ScheduleRoutine() {
// TODO Auto-generated constructor stub
}
#Schedule(second="*/1", minute="*",hour="*", persistent=false)
public void scheduledTimeout(final Timer t) {
System.out.println("#Schedule called at: " + new java.util.Date());
}
}
This is the code I'm using I think there's no problem with it. I'm using JBoss AS 7.1.1 with eclipse and all I'm doing is 'run on server' it runs but it's unable to display the output as it is supposed to.
EDIT :(Solution)
It didn't work when i tried to run it from eclipse but then i tried exporting the jar manually then it was deployed successfully.
I had the same problem with jboss 7.1. To solve the problem I added a stub method to my ejb and annotated it with #Timeout
#Timeout
public void stub(){
// NOOP
}
Also changed #Stateless to #Singleton and #Startup so your code would look like the following:
import javax.ejb.Schedule;
import javax.ejb.Startup;
import javax.ejb.Timer;
import javax.ejb.Timeout;
#Singleton
#Startup
public class ScheduleRoutine {
/**
* Default constructor.
*/
public ScheduleRoutine() {
// TODO Auto-generated constructor stub
}
#Timeout
public void stub() {
// NOOP
}
#Schedule(second="*/1", minute="*",hour="*", persistent=false)
public void scheduledTimeout(final Timer t) {
System.out.println("#Schedule called at: " + new java.util.Date());
}
}

This class does not define a public default constructor, or the constructor raised an exception. Internal Exception: java.lang.InstantiationException

Hi everyone I have problems with my JPA project.
Fichier.java end Application.java implements an interface "FileSystemElement.java"
Those are my classes
Application.java
package com.bfi.webtop.model;
import java.io.Serializable;
import java.util.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
/** #pdOid d477195f-149e-4336-8586-19d6a09ee2d4 */
#Entity
#Table(name="application_")
public abstract class Application implements FileSystemElement, Serializable {
// public Application() {
// super();
// }
public Application(int id_app, String url) {
super();
this.id_app = id_app;
this.url = url;
}
public Application() {
super();
// TODO Auto-generated constructor stub
}
private int id_app;
private java.lang.String url;
/**
* #return the url
*/
public java.lang.String getUrl() {
return url;
}
/**
* #param url the url to set
*/
public void setUrl(java.lang.String url) {
this.url = url;
}
/**
* #return the id_app
*/
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getId_app() {
return id_app;
}
/**
* #param id_app the id_app to set
*/
public void setId_app(int id_app) {
this.id_app = id_app;
}
}
Fichier.java
package com.bfi.webtop.model;
/***********************************************************************
* Module: Fichier.java
* Author: Marwa
* Purpose: Defines the Class Fichier
***********************************************************************/
import java.util.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public abstract class Fichier implements FileSystemElement {
private int id_fichier;
private java.lang.String extension;
private java.lang.Boolean supprim;
/**
* #return the extension
*/
public java.lang.String getExtension() {
return extension;
}
/**
* #param extension the extension to set
*/
public void setExtension(java.lang.String extension) {
this.extension = extension;
}
/**
* #return the supprim
*/
public java.lang.Boolean getSupprim() {
return supprim;
}
/**
* #param supprim the supprim to set
*/
public void setSupprim(java.lang.Boolean supprim) {
this.supprim = supprim;
}
/**
* #return the id_fichier
*/
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getId_fichier() {
return id_fichier;
}
/**
* #param id_fichier the id_fichier to set
*/
public void setId_fichier(int id_fichier) {
this.id_fichier = id_fichier;
}
public Fichier() {
super();
}
}
FileSystemElement.java
package com.bfi.webtop.model;
import javax.annotation.Generated;
import javax.persistence.metamodel.StaticMetamodel;
#Generated(value="Dali", date="2013-01-28T10:33:26.416+0100")
#StaticMetamodel(FileSystemElement.class)
public class FileSystemElement_ {
}
The other classes have the same structures
When I try to do: jpa tooles> generate tables from entities I have the following mistakes
Exception in thread "main" javax.persistence.PersistenceException: Exception >[EclipseLink-28019] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [webtop] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
Exception [EclipseLink-34] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: This class does not define a public default constructor, or the constructor raised an exception.
Internal Exception: java.lang.InstantiationException
Descriptor: RelationalDescriptor(com.bfi.webtop.model.Application --> [DatabaseTable(application_)])
Exception [EclipseLink-34] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: This class does not define a public default constructor, or the constructor raised an exception.
Internal Exception: java.lang.InstantiationException
Descriptor: RelationalDescriptor(com.bfi.webtop.model.Fichier --> [DatabaseTable(FICHIER)])
Exception [EclipseLink-34] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: This class does not define a public default constructor, or the constructor raised an exception.
Internal Exception: java.lang.InstantiationException
Descriptor: RelationalDescriptor(com.bfi.webtop.model.Raccourci --> [DatabaseTable(RACCOURCI)])
Runtime Exceptions:
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:616)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:596)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:186)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:278)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:304)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:282)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.perform(Main.java:85)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.execute(Main.java:76)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.main(Main.java:63)
Caused by: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [webtop] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.IntegrityException
I am using Eclipse Juno
Any help please?
}
You've defined your class Fichier as abstract:
public abstract class Fichier
Remove abstract and it'll work. The error message in this case is somewhat confusing.
As the error states, you need to provide a default (no argument) constructor for you Application class.
The constructor can be private if you do not want to expose it to your app.
Consider create no-arg constructor in your class, then clean you project and try.
I had the same problem and using lombok I fixed it

How to inject dependencies into resources with Jersey?

I'm having the following code:
#Path("stores")
class StoreResources {
private ServerConfig config;
#GET
public String getAll() {
//do some stuff with ServerConfig
}
}
And I need the ServerConfig object to be injected into this class from outside and use it inside the getAll() method.
What are the possible ways to achieve it? Should I use a DI framework like Guice or Spring?
This is a good blog about Spring injection under Jersey http://javaswamy.blogspot.com/2010/01/making-jersey-work-with-spring.html
The upshot is you use annotations to flag fields that are to be injected, an example resource being
package com.km.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.sun.jersey.spi.inject.Inject;
import com.km.spring.SimpleBean;
#Path("/hello")
#Component
#Scope("request")
public class HelloResource {
#Inject private SimpleBean simpleBean;
#GET
#Produces("text/plain")
public String getMessage() {
return simpleBean.sayHello();
}
}
For my purposes the configuration was excessively difficult so I used a static spring resolver factory to resolve the bean. eg.
private SimpleBean simpleBean = SpringBeanFactory.getBean("mySimpleBean");
You don't need Spring or Guice to inject a ServletConfig. Jersey does through its own injection mechanism. Refer to the simple-servlet example that comes with Jersey samples distribution. Here is the sample code that injects a HttpServletRequest and a ServletConfig onto a resource:
#Path("/resource1")
public class ResourceBean1 {
#Context
HttpServletRequest servletRequest;
#Context
ServletConfig servletConfig;
#GET
#Produces("text/plain")
public String describe() {
return "Hello World from resource 1 in servlet: '" +
servletConfig.getServletName() +
"', path: '" +
servletRequest.getServletPath() +
"'";
}
}
When deploying an JAX-RS application using Servlet then ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse are available for injection using #Context.