***** UPDATED *****
I have the following method in a Stateless Session Bean, deployed in an EAR on JBoss WildFly 12.0.0.Final which is called when the database is updated.
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
#Inject
private BeanManager beanManager;
public void onFoodsCosmeticsMedicinesChange(FoodsCosmeticsMedicines foodsCosmeticsMedicines) {
logger.info(">>>>> onFoodsCosmeticsMedicinesChange beanManager = {}", beanManager);
logger.info(">>>>> onFoodsCosmeticsMedicinesChange getBrand = {}", foodsCosmeticsMedicines.getBrand());
beanManager.fireEvent(new PushEvent(foodsCosmeticsMedicines.getBrand()));
}
PushBean is a POJO, contained in the WAR:
import org.omnifaces.cdi.Push;
import org.omnifaces.cdi.PushContext;
import javax.inject.Inject;
#Named
#ApplicationScoped
public class PushBean {
/**
*
*/
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
*
*/
#Inject
#Push(channel = "testChannel")
private PushContext testChannel;
/**
*
*/
public PushBean() {
}
/**
*
* #param pushEvent PushEvent
*/
public void onPush(#Observes PushEvent pushEvent) {
logger.info("***** onPersist pushEvent getMessage = {}", pushEvent.getMessage());
logger.info("***** pushContext = {}", testChannel);
testChannel.send(pushEvent.getMessage());
}
}
PushEvent:
public final class PushEvent {
private final String message;
public PushEvent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
The OmniFaces 3.1 JAR is only in the WAR.
When the method 'onFoodsCosmeticsMedicinesChange' is called the console log shows:
INFO [com.notifywell.ejb.FoodsCosmeticsMedicinesEJB] (default task-4)
onFoodsCosmeticsMedicinesChange beanManager = Weld BeanManager for
NOTiFYwell.ear/NOTiFYwellJAR.jar/ [bean count=38]
INFO[com.notifywell.ejb.FoodsCosmeticsMedicinesEJB] (default task-4)
onFoodsCosmeticsMedicinesChange getBrand = BONNE MAMAN
But the following statement:
beanManager.fireEvent(new PushEvent(foodsCosmeticsMedicines.getBrand()));
Doesn't appear to be executed as I do not see the PushBean method 'onPersist' in PushBean being executed:
public void onPush(#Observes PushEvent pushEvent) {
Deployed on WildFly 12.0.0.Final on MacOS using EE8.
Any idea what I'm doing wrong?
The above code works. 'Schoolboy error', I had a typo in my build and the 'PushBean.class' was being put in the wrong place in my WAR.
It should have been in:
WEB-INF/classes/PushBean.class
I now see my event being fired in the 'onPush' method of PushBean:
13:18:30,598 INFO [com.notifywell.push.PushBean] (default task-1)
***** onPush pushEvent getMessage = BONNE MAMAN
Related
I have Spring Boot application, everything works fine until I implement spring security in front of my application. This is a RESTful api that has a token based authentication. What's even more weird it works (!) intermittently - by intermittently I mean restarting the application will return the right responses such as 401/403 if unauthenticated and other codes if user is authorized to access them. This is being deployed into WebLogic.
2017-01-05 14:12:51.164 WARN 11252 --- [ (self-tuning)'] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/user] in DispatcherServlet with name 'dispatcherServlet'
WebApplication.java
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class WebApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
Object[] sources = new Object[2];
sources[0] = WebConfiguration.class;
sources[1] = WebSecurityConfiguration.class;
SpringApplication.run(sources, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(WebApplication.class);
}
}
WebConfiguration.java
#Configuration
#ComponentScan(basePackages = { "com.controller", "com.service", "com.dao"})
#EnableAutoConfiguration(exclude = {
DataSourceAutoConfiguration.class })
public class WebConfiguration extends WebMvcConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(WebConfiguration.class);
/**
* Setup a simple strategy: use all the defaults and return XML by default
* when not sure.
*/
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON).mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML);
}
#Bean(name = "entityManagerFactory")
public EntityManagerFactory getQmsEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName(Config.PERSISTENCE_UNIT_NAME);
em.setPersistenceXmlLocation("META-INF/persistence.xml");
em.setDataSource(getDataSource());
em.setJpaVendorAdapter(getJpaHibernateVendorAdapter());
em.afterPropertiesSet();
return em.getObject();
}
#Bean
public HibernateJpaVendorAdapter getJpaHibernateVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(true);
// adapter.setDatabase("ORACLE");
adapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect");
return adapter;
}
#Bean(name="dataSource", destroyMethod = "")
//http://stackoverflow.com/questions/19158837/weblogic-datasource-disappears-from-jndi-tree
#Qualifier("dataSource")
#Profile("weblogic")
public DataSource dataSource() {
DataSource dataSource = null;
JndiTemplate jndi = new JndiTemplate();
try {
dataSource = (DataSource) jndi.lookup("jdbc/datasource");
} catch (NamingException e) {
logger.error("NamingException for jdbc/datasource", e);
}
return dataSource;
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*");
}
};
}
}
WebSecurityConfiguration.java
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
#ComponentScan({
"com.subject",
"com.custom"
})
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private StatelessAuthenticationFilter statelessAuthenticationFilter;
#Autowired
private RestAuthenticationEntryPoint unauthorizedHandler;
#Autowired
private CusAuthenticationProvider cusAuthenticationProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(cusAuthenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.securityContext()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.addFilterBefore(statelessAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
}
}
StatelessAuthenticationFilter.java
#Component
public class StatelessAuthenticationFilter extends OncePerRequestFilter {
#Inject
private SubjectLookupService subjectLookupService;
#Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(authenticateUser(request));
filterChain.doFilter(request, response);
}
private Authentication authenticateUser(HttpServletRequest request) {
try {
String application = StringUtils.defaultString(request.getParameter("application"));
UserInfo me = subjectLookupService.getUserInfo();
List<GrantedAuthority> roles = me.getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName())).collect(Collectors.toList());
UserDetails user = new User(me.getUsername(), "", roles);
Authentication authentication = new UserAuthentication(user);
return authentication;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Controller.java
#RestController
public class Controller {
#Autowired
private QService qService;
#PreAuthorize("hasAnyRole('view', 'admin')")
#RequestMapping(value = "/q/{year}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public ResponseEntity<?> listQuotas(#PathVariable Integer year) {
return new ResponseEntity<>(qService.listQs(year), HttpStatus.OK);
}
#RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public ResponseEntity<?> user(HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return new ResponseEntity<>( auth.getPrincipal(), HttpStatus.OK);
}
#PreAuthorize("hasRole('shouldntauthorize')")
#RequestMapping(value = "/unauthorized/{year}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public ResponseEntity<?> unauthorized(#PathVariable Integer year) {
return new ResponseEntity<>(qService.listQs(year), HttpStatus.OK);
}
}
When it works - I am able to hit any of the above methods using HTTP gets and I am getting correct responses. When it's not working, I am constantly getting:
2017-01-05 14:18:47.506 WARN 11252 --- [ (self-tuning)'] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/user] in DispatcherServlet with name 'dispatcherServlet'
I can verify in the logs that when Spring Boot initializes the application is also sets the correct mapping URL.
Any ideas what could be the problem here?
when you say "intermittently" I tend to think that the problem is with Spring startup configuration.
So, I'd be weary on the fact that you have #ComponentScan twice, and with different packages.
Could you try removing
#ComponentScan(basePackages = { "com.controller", "com.service", "com.dao"})
from class WebConfiguration.java and
#ComponentScan({ "com.subject", "com.custom" })
from class WebSecurityConfiguration.java, and replace them with a single
#ComponentScan(basePackages = { "com.controller", "com.service", "com.dao", "com.subject", "com.custom"})
in the main SpringBoot class?
I am building a Java application on the Equinox OSGi framework and I have been using DS (declarative services) to declare referenced and provided services. So far all the service consumers I have implemented happened to be service providers as well, so it was natural for me to make them stateless (so that they can be reused by multiple consumers, rather than being attached to one consumer) and let them be instantiated by the framework (default constructor, invoked nowhere in my code).
Now I have a different situation: I have a class MyClass that references a service MyService but is not itself a service provider. I need to be able to instantiate MyClass myself, rather than letting the OSGi framework instantiate it. I would then want the framework to pass the existing MyService instance to the MyClass instance(s). Something like this:
public class MyClass {
private String myString;
private int myInt;
private MyService myService;
public MyClass(String myString, int myInt) {
this.myString = myString;
this.myInt= myInt;
}
// bind
private void setMyService(MyService myService) {
this.myService = myService;
}
// unbind
private void unsetMyService(MyService myService) {
this.myService = null;
}
public void doStuff() {
if (myService != null) {
myService.doTheStuff();
} else {
// Some fallback mechanism
}
}
}
public class AnotherClass {
public void doSomething(String myString, int myInt) {
MyClass myClass = new MyClass(myString, myInt);
// At this point I would want the OSGi framework to invoke
// the setMyService method of myClass with an instance of
// MyService, if available.
myClass.doStuff();
}
}
My first attempt was to use DS to create a component definition for MyClass and reference MyService from there:
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="My Class">
<implementation class="my.package.MyClass"/>
<reference bind="setMyService" cardinality="0..1" interface="my.other.package.MyService" name="MyService" policy="static" unbind="unsetMyService"/>
</scr:component>
However, MyClass is not really a component, since I don't want its lifecycle to be managed -- I want to take care of instantiation myself. As Neil Bartlett points out here:
For example you could say that your component "depends on" a
particular service, in which case the component will only be created
and activated when that service is available -- and also it will be
destroyed when the service becomes unavailable.
This is not what I want. I want the binding without the lifecycle management.
[Note: Even if I set the cardinality to 0..1 (optional and unary), the framework will still try instantiate MyClass (and fail because of the lack of no-args constructor)]
So, my question: is there a way to use DS to have this "binding-only, no lifecycle management" functionality I'm looking for? If this is not possible with DS, what are the alternatives, and what would you recommend?
Update: use ServiceTracker (suggested by Neil Bartlett)
IMPORTANT: I've posted an improved version of this below as an answer. I'm just keeping this here for "historic" purposes.
I'm not sure how to apply ServiceTracker in this case. Would you use a static registry as shown below?
public class Activator implements BundleActivator {
private ServiceTracker<MyService, MyService> tracker;
#Override
public void start(BundleContext bundleContext) throws Exception {
MyServiceTrackerCustomizer customizer = new MyServiceTrackerCustomizer(bundleContext);
tracker = new ServiceTracker<MyService, MyService>(bundleContext, MyService.class, customizer);
tracker.open();
}
#Override
public void stop(BundleContext bundleContext) throws Exception {
tracker.close();
}
}
public class MyServiceTrackerCustomizer implements ServiceTrackerCustomizer<MyService, MyService> {
private BundleContext bundleContext;
public MyServiceTrackerCustomizer(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
#Override
public MyService addingService(ServiceReference<MyService> reference) {
MyService myService = bundleContext.getService(reference);
MyServiceRegistry.register(myService); // any better suggestion?
return myService;
}
#Override
public void modifiedService(ServiceReference<MyService> reference, MyService service) {
}
#Override
public void removedService(ServiceReference<MyService> reference, MyService service) {
bundleContext.ungetService(reference);
MyServiceRegistry.unregister(service); // any better suggestion?
}
}
public class MyServiceRegistry {
// I'm not sure about using a Set here... What if the MyService instances
// don't have proper equals and hashCode methods? But I need some way to
// compare services in isActive(MyService). Should I just express this
// need to implement equals and hashCode in the javadoc of the MyService
// interface? And if MyService is not defined by me, but is 3rd-party?
private static Set<MyService> myServices = new HashSet<MyService>();
public static void register(MyService service) {
myServices.add(service);
}
public static void unregister(MyService service) {
myServices.remove(service);
}
public static MyService getService() {
// Return whatever service the iterator returns first.
for (MyService service : myServices) {
return service;
}
return null;
}
public static boolean isActive(MyService service) {
return myServices.contains(service);
}
}
public class MyClass {
private String myString;
private int myInt;
private MyService myService;
public MyClass(String myString, int myInt) {
this.myString = myString;
this.myInt= myInt;
}
public void doStuff() {
// There's a race condition here: what if the service becomes
// inactive after I get it?
MyService myService = getMyService();
if (myService != null) {
myService.doTheStuff();
} else {
// Some fallback mechanism
}
}
protected MyService getMyService() {
if (myService != null && !MyServiceRegistry.isActive(myService)) {
myService = null;
}
if (myService == null) {
myService = MyServiceRegistry.getService();
}
return myService;
}
}
Is this how you would do it?
And could you comment on the questions I wrote in the comments above? That is:
Problems with Set if the service implementations don't properly implement equals and hashCode.
Race condition: the service may become inactive after my isActive check.
No this falls outside the scope of DS. If you want to directly instantiate the class yourself then you will have to use OSGi APIs like ServiceTracker to obtain the service references.
Update:
See the following suggested code. Obviously there are a lot of different ways to do this, depending on what you actually want to achieve.
public interface MyServiceProvider {
MyService getService();
}
...
public class MyClass {
private final MyServiceProvider serviceProvider;
public MyClass(MyServiceProvider serviceProvider) {
this.serviceProvider = serviceProvider;
}
void doStuff() {
MyService service = serviceProvider.getService();
if (service != null) {
// do stuff with service
}
}
}
...
public class ExampleActivator implements BundleActivator {
private MyServiceTracker tracker;
static class MyServiceTracker extends ServiceTracker<MyService,MyService> implements MyServiceProvider {
public MyServiceTracker(BundleContext context) {
super(context, MyService.class, null);
}
};
#Override
public void start(BundleContext context) throws Exception {
tracker = new MyServiceTracker(context);
tracker.open();
MyClass myClass = new MyClass(tracker);
// whatever you wanted to do with myClass
}
#Override
public void stop(BundleContext context) throws Exception {
tracker.close();
}
}
Solution: use ServiceTracker (as suggested by Neil Bartlett)
Note: if you want to see the reason for the downvote please see Neil's answer and our back-and-forth in its comments.
In the end I've solved it using ServiceTracker and a static registry (MyServiceRegistry), as shown below.
public class Activator implements BundleActivator {
private ServiceTracker<MyService, MyService> tracker;
#Override
public void start(BundleContext bundleContext) throws Exception {
MyServiceTrackerCustomizer customizer = new MyServiceTrackerCustomizer(bundleContext);
tracker = new ServiceTracker<MyService, MyService>(bundleContext, MyService.class, customizer);
tracker.open();
}
#Override
public void stop(BundleContext bundleContext) throws Exception {
tracker.close();
}
}
public class MyServiceTrackerCustomizer implements ServiceTrackerCustomizer<MyService, MyService> {
private BundleContext bundleContext;
public MyServiceTrackerCustomizer(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
#Override
public MyService addingService(ServiceReference<MyService> reference) {
MyService myService = bundleContext.getService(reference);
MyServiceRegistry.getInstance().register(myService);
return myService;
}
#Override
public void modifiedService(ServiceReference<MyService> reference, MyService service) {
}
#Override
public void removedService(ServiceReference<MyService> reference, MyService service) {
bundleContext.ungetService(reference);
MyServiceRegistry.getInstance().unregister(service);
}
}
/**
* A registry for services of type {#code <S>}.
*
* #param <S> Type of the services registered in this {#code ServiceRegistry}.<br>
* <strong>Important:</strong> implementations of {#code <S>} must implement
* {#link #equals(Object)} and {#link #hashCode()}
*/
public interface ServiceRegistry<S> {
/**
* Register service {#code service}.<br>
* If the service is already registered this method has no effect.
*
* #param service the service to register
*/
void register(S service);
/**
* Unregister service {#code service}.<br>
* If the service is not currently registered this method has no effect.
*
* #param service the service to unregister
*/
void unregister(S service);
/**
* Get an arbitrary service registered in the registry, or {#code null} if none are available.
* <p/>
* <strong>Important:</strong> note that a service may become inactive <i>after</i> it has been retrieved
* from the registry. To check whether a service is still active, use {#link #isActive(Object)}. Better
* still, if possible don't store a reference to the service but rather ask for a new one every time you
* need to use the service. Of course, the service may still become inactive between its retrieval from
* the registry and its use, but the likelihood of this is reduced and this way we also avoid holding
* references to inactive services, which would prevent them from being garbage-collected.
*
* #return an arbitrary service registered in the registry, or {#code null} if none are available.
*/
S getService();
/**
* Is {#code service} currently active (i.e., running, available for use)?
* <p/>
* <strong>Important:</strong> it is recommended <em>not</em> to store references to services, but rather
* to get a new one from the registry every time the service is needed -- please read more details in
* {#link #getService()}.
*
* #param service the service to check
* #return {#code true} if {#code service} is currently active; {#code false} otherwise
*/
boolean isActive(S service);
}
/**
* Implementation of {#link ServiceRegistry}.
*/
public class ServiceRegistryImpl<S> implements ServiceRegistry<S> {
/**
* Services that are currently registered.<br>
* <strong>Important:</strong> as noted in {#link ServiceRegistry}, implementations of {#code <S>} must
* implement {#link #equals(Object)} and {#link #hashCode()}; otherwise the {#link Set} will not work
* properly.
*/
private Set<S> myServices = new HashSet<S>();
#Override
public void register(S service) {
myServices.add(service);
}
#Override
public void unregister(S service) {
myServices.remove(service);
}
#Override
public S getService() {
// Return whatever service the iterator returns first.
for (S service : myServices) {
return service;
}
return null;
}
#Override
public boolean isActive(S service) {
return myServices.contains(service);
}
}
public class MyServiceRegistry extends ServiceRegistryImpl<MyService> {
private static final MyServiceRegistry instance = new MyServiceRegistry();
private MyServiceRegistry() {
// Singleton
}
public static MyServiceRegistry getInstance() {
return instance;
}
}
public class MyClass {
private String myString;
private int myInt;
public MyClass(String myString, int myInt) {
this.myString = myString;
this.myInt= myInt;
}
public void doStuff() {
MyService myService = MyServiceRegistry.getInstance().getService();
if (myService != null) {
myService.doTheStuff();
} else {
// Some fallback mechanism
}
}
}
If anyone wants to use this code for whatever purpose, go ahead.
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
Log output of my RemoteServiceServlet (GWT) is not shown in Logfiles or Stdout when using getServletContext().log("anything");
For dependency injection I use Google Guice. For my own log output I use slf4j-jdk14. I tried this in Tomcat 6 as well as in Jetty (GWT devmode).
To make it clear, my Servlet:
#Singleton
public class MyServiceServlet extends RemoteServiceServlet implements MyService {
private static final Logger log = LoggerFactory.getLogger(MyServiceServlet.class);
private final ADependency dep;
#Inject
public MyServiceServlet(ADependency dep) {
getServletContext().log("THIS IS NOT SHOWN IN MY LOGS");
log.error("THIS IS SHOWN IN MY LOGS");
this.dep = dep;
}
}
So, where can I find the missing log output or where can I configure the ServletContext-Log?
The ServletContext.log method behavior is container specific. The method I have used to make it consistent is to wrap the ServletConfig passed in through init() in order to create a wrapped ServletContext which uses our own provided logger (Slf4j in this case).
public class Slf4jServletConfigWrapper implements ServletConfig {
private final ServletConfig config;
private final Logger log;
public Slf4jServletConfigWrapper(Logger log, ServletConfig config) {
this.log = log;
this.config = config;
}
public ServletContext getServletContext() {
return new ServletContext() {
public void log(String message, Throwable throwable) {
log.info(message, throwable);
}
public void log(Exception exception, String msg) {
log.info(msg, exception);
}
public void log(String msg) {
log.info(msg);
}
...
Full Slf4jServletConfigWrapper.java code
In your Servlet override the init() method to use the ServletConfig wrapper
public void init(final ServletConfig config) throws ServletException {
super.init(new Slf4jServletConfigWrapper(log, config));
}
I was reading the tutorial on this page:
http://edocs.bea.com/docs/cd/E13222_01/wls/docs81/medrec_tutorials/ejbgen.html#858279
And I have the following file BankAccountEJB.java
import javax.ejb.CreateException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
public abstract class BankAccountEJB implements EntityBean {
private EntityContext context;
public void setEntityContext(EntityContext aContext) {
context = aContext;
}
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void ejbRemove() {
}
public void unsetEntityContext() {
context = null;
}
public void ejbLoad() {
}
public void ejbStore() {
}
public abstract String getName();
public abstract void setName(String name);
public abstract Float getBalance();
public abstract void setBalance(Float balance);
public java.lang.Long ejbCreate(String name, Float balance) throws CreateException {
if (name == null) {
throw new CreateException("The field \"key\" must not be null");
}
// TODO add additional validation code, throw CreateException if data is not valid
setName(name);
setBalance(balance);
return null;
}
public void ejbPostCreate(java.lang.Long key) {
// TODO populate relationships here if appropriate
}
}
and I run java weblogic.tools.ejbgen.EJBGen -ddOnlyGen BankAccountEJB.java which produces the following error:
Exception in thread "main" com.bea.wls.ejbgen.EJBGenException: ejbName is a required attribute
at com.bea.wls.ejbgen.Bean.createBeanSpecificTags(Bean.java:202)
at com.bea.wls.ejbgen.Bean.(Bean.java:127)
at com.bea.wls.ejbgen.EntityBean.(EntityBean.java:76)
at com.bea.wls.ejbgen.EJBFactory.createBean(EJBFactory.java:135)
at com.bea.wls.ejbgen.EJBFactory.createBean(EJBFactory.java:99)
at com.bea.wls.ejbgen.EJBGenSGen.initModule(EJBGenSGen.java:106)
at com.bea.sgen.SGen.run(SGen.java:205)
at com.bea.wls.ejbgen.EJBGen.main(EJBGen.java:212)
at com.bea.wls.ejbgen.EJBGen.main(EJBGen.java:238)
at weblogic.tools.ejbgen.EJBGen.main(EJBGen.java:21)
Any input will be greatly appreciated~!
Note: Are you still running Weblogic 8.1 - it's already reached end of life. Also ejbgen works with EJB 2.x and over the last 2 years, development has moved on to EJB 3, so i'd advise you to catch up on those.
Now to your specific problem.
Your code does not seem to have the required annotations for ejbgen to work.
Annotations like this which are used in generation of the descriptors.
* #ejbgen:entity
* ejb-name = containerManaged
* table-name = ejbAccounts
* data-source-name = examples-dataSource-demoPool
* prim-key-class = AccountPK
* invalidation-target = ServiceDesignEJB
As your URL says the code in the tutorial has the right data as a sample - make sure you replicate those correctly in your own code.
EJBGen uses annotations in the bean
file to generate the deployment
descriptor files and the EJB Java
source files. EJB files in the MedRec
application are already annotated for
EJBGen.
For another version of ejbgen, see http://www.beust.com/ejbgen/