Hot questions for Using Enterprise JavaBeans in ear

Question:

I have deployed an ear file named abc.ear to weblogic 10.3.6.

Inside the ear file, there are several class files. The main Java class file is abc.class

Here I would like to ask if there is a way to tell the JVM to run a java method if I am undeploying / delete the abc.ear file from weblogic?

I want to unbind some JNDI in that Java method.

Thanks


Answer:

You can attach an ApplicationLifeCycleListener . See link: http://docs.oracle.com/cd/E13222_01/wls/docs92/programming/lifecycle.html#wp1049765

Question:

I have an EJB project which contains a Rest Web Service EJB. I package this EJB.jar project into an EAR file along with a WAR project. What would be the absolute path of my Rest Web Service then?


Answer:

My problem seems to be due to the fact that the EJB JAR file containing the EJB REST Web Service is packaged in an EAR file alongside a WAR file. I've read that you can use JAX-RS within an EJB JAR file but what I wasn't aware of was that this JAR file has to then be packaged within the WEB-INF/lib folder in a Dynamic Web Project (WAR file). According to this link, it is not supported for JAX-RS EJB's to be included in an EAR file.

Question:

I access a EJB dao in an ejb container from a backing sessionscoped cdi bean. The dao execute a JQL query with join fetch and retrieve a entity with a @OneToMany reference. The @OneToMany collections are filled and I can use them inside EJB, but in the CDI backing bean, the collections are empty and cleared. My entities look like this:

@Entity
@NamedQuery(name = "order.with.items", 
           query = "select o from Order o inner join fetch o.item i where o.id=:orderNo")
public class Order implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Version
    @Column(name = "version")
    private int version;

    @Column
    private String name;

    @OneToMany(mappedBy = "order")
    private Set<Item> item = new HashSet<>();;

    ... getters setters
}

and the referenced item's:

@Entity
public class Item implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Version
    @Column(name = "version")
    private int version;

    @Column
    private String name;

    @ManyToOne
    @JoinColumn(name = "order_id", referencedColumnName = "id")
    private Order order;

    //... getters setters

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass()) // UPDATE: don't do it 
            return false;                 // with getClass - use instanceof 
        Item other = (Item) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (order == null) {
            if (other.order != null)
                return false;
        } else if (!order.equals(other.order))
            return false;
        return true;
    }

}

and the dao:

@Stateless
@LocalBean
public class OrderDao {

    @PersistenceContext(unitName = "jpa-persistence-unit")
    protected EntityManager entityManager;

    public Order getOrderWhithItems(Long orderId) {
        Order order = entityManager.createNamedQuery("order.with.items",Order.class).setParameter("orderId", orderId).getSingleResult();

        // Here is the size greater than zero
        System.out.println("# of items: " + order.getItem().size());
        return order;
    }
}

and the backing bean:

@Named
@SessionScoped
public class BackingBean {

    @EJB
    private OrderDao orderDao;


    public BackingBean() {
        Order order = orderDao.getOrderWhithItems( 4L);

        Set<Item> items = order.getItem();
        // This will ouputs 0
        System.out.println("# of items " + items.size());
    }

}

The problem is, that the order contain all items in the method of the dao, but when the backing bean receive the order, the items are ripped and the set is empty. I wrote also an arquillian junit test to test the dao in it and it work perfectly and the order contain the items in the test. But not in the CDI session bean. When I extract the set in the dao like a DTO (data transfer object) I can receive the items in the backing bean.

The dao bean is in an ejb jar, in an ear enterprise archive. The CDI backing bean is in a war archive in the same ear. I simplified our problem case to the order item example. I could not find any resources of this stupid behavior. I use a wildfly 13 appserver and use the hibernate jpa orm.


Answer:

The cause of that problem is a overwritten equals method. Hibernate us a big caching and proxiing mechanism and every Entity Class is handled by a proxy. The problem are the following test in the equals method:

    if (getClass() != obj.getClass()) // This wouldn't work in JPA!!!
         return false;

In the case of an entity these lines always return false, because obj has the type of the proxy class and not of the entity. The obj is stored in a set and the set is accessed by the proxy, while caching and so on.

Use never getClass in a equals method of an entity, use always the instanceof operator. In my case, this wrong implementation causes unpredictable behaviour while the instance of the entity travels from the dao to the backing bean.

The equals method should looks like:

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Item)) {
            return false;
        }
        Item other = (Item) obj;
        if (id != null) {
            if (!id.equals(other.id)) {
                return false;
            }
        }
        return true;
    }

Question:

I'm dealing with some weird stuff regarding a legacy application, weblogic and ejb's. I have some code that is deployed in weblogic 10 as an EAR without any errors but now, I'm testing it against 12 version. Unfortunately, it doesn't deploy successfully.

I have a singleton class called "Monitor", with this constructor:

 private Monitor(){
    if(MonitorProperties.getInstance().getEnabled()){
        try{                
            Context objContext = new InitialContext();
            monitorJmsGatewayRemote = (MonitorJmsGatewayRemote)objContext.lookup(MonitorProperties.getInstance().getJndiEjbGatewayProperty());
            active = true;
            if(tracer.isInfoEnabled()){
                tracer.info("'"+FrameworkApplicationContext.getInstance().getApplicationId()+"' Framework monitor is initialize");
            }           
        }catch(Exception excep){
            tracer.warn("'"+FrameworkApplicationContext.getInstance().getApplicationId()+"' It's not possible to initialize the framework monitor. "+ excep.getMessage());
            active = false;
        }       

        init();
    }else{
        active = false;
    }
}    

So, at runtime, the monitor might be enabled or disabled.

On the other hand, I have the MonitorJMSGateway ejb:

@Stateless(name="FwkMonitorJmsGatewayBean")
@Remote(MonitorJmsGatewayRemote.class)  
public class MonitorJmsGateway implements MonitorJmsGatewayRemote {

private static Tracer tracer = null;

static{//Inicializamos el log4j
    PropertyConfigurator.configure(Thread.currentThread().getContextClassLoader().getResourceAsStream(MonitorJmsGatewayConstants.LOG4J_PROPERTIES_FILE));
    tracer = Tracer.getTracer(MonitorJmsGateway.class);
}

The problem is that I'm getting a nullpointer because the log4.properties file doesn't exists. That's fine, ok. But the weird stuff is that this app deploys right in weblogic 10, but not in 12. It sounds like like lazy initialization stuff in 10 (due to the fact that custom monitoring is disabled, the ejb is not initialized, the exception is not raised and the application is successfully deployed)

The log error traces are the following

####<18-sep-2017, 8:42:29,43 AM CEST> <Error> <Deployer> <CASER-5041> <AdminServer> <[ACTIVE] ExecuteThread: '4' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <a7a2e7ff-e3ef-4cf9-8686-75d7d0d27689-00000013> <1505716949043> <[severity-value: 8] [rid: 0] [partition-id: 0] [partition-name: DOMAIN] > <BEA-149265> <Failure occurred in the execution of deployment request with ID "2686211063156" for task "0" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: java.lang.NoClassDefFoundError: Could not initialize class es.caser.archit.monitor.jmsgateway.FwkMonitorJmsGatewayBean_nrwnbe_Impl"
weblogic.application.ModuleException: java.lang.NoClassDefFoundError: Could not initialize class es.caser.archit.monitor.jmsgateway.FwkMonitorJmsGatewayBean_nrwnbe_Impl
    at weblogic.application.internal.ExtensibleModuleWrapper.prepare(ExtensibleModuleWrapper.java:114)
    at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100)
    at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:192)
    at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:187)
    at weblogic.application.utils.StateMachineDriver$ParallelChange.run(StateMachineDriver.java:83)
    at weblogic.work.ContextWrap.run(ContextWrap.java:46)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
    at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
    at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
    at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
    at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
Caused By: java.lang.NoClassDefFoundError: Could not initialize class es.caser.archit.monitor.jmsgateway.FwkMonitorJmsGatewayBean_nrwnbe_Impl
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at weblogic.utils.classloaders.GenericClassLoader.defineCodeGenClass(GenericClassLoader.java:1357)
    at weblogic.ejb.container.ejbc.bytecodegen.GeneratorFactory.generateClass(GeneratorFactory.java:100)
    at weblogic.ejb.container.ejbc.bytecodegen.GeneratorFactory.generate(GeneratorFactory.java:51)
    at weblogic.ejb.container.ejbc.EJBCompiler.generate(EJBCompiler.java:606)
    at weblogic.ejb.container.ejbc.EJBCompiler.doCompile(EJBCompiler.java:201)
    at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:345)
    at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:313)
    at weblogic.ejb.container.deployer.EJBDeployer.compileEjbs(EJBDeployer.java:420)
    at weblogic.ejb.container.deployer.EJBDeployer.compileIfNecessary(EJBDeployer.java:351)
    at weblogic.ejb.container.deployer.EJBDeployer.prepare(EJBDeployer.java:716)
    at weblogic.ejb.container.deployer.EjbModuleExtension.postPrepare(EjbModuleExtension.java:97)
    at weblogic.application.internal.ExtensibleModuleWrapper$PrepareStateChange.next(ExtensibleModuleWrapper.java:297)
    at weblogic.application.internal.ExtensibleModuleWrapper$PrepareStateChange.next(ExtensibleModuleWrapper.java:285)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.ExtensibleModuleWrapper.prepare(ExtensibleModuleWrapper.java:109)
    at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100)
    at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:192)
    at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:187)
    at weblogic.application.utils.StateMachineDriver$ParallelChange.run(StateMachineDriver.java:83)
    at weblogic.work.ContextWrap.run(ContextWrap.java:46)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
    at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
    at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
    at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
    at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
> 
####<18-sep-2017, 8:42:29,43 AM CEST> <Error> <Deployer> <CASER-5041> <AdminServer> <[ACTIVE] ExecuteThread: '7' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <a7a2e7ff-e3ef-4cf9-8686-75d7d0d27689-00000012> <1505716949043> <[severity-value: 8] [rid: 0] [partition-id: 0] [partition-name: DOMAIN] > <BEA-149265> <Failure occurred in the execution of deployment request with ID "2686211063156" for task "weblogic.deploy.configChangeTask.0" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: java.lang.NullPointerException"
weblogic.application.ModuleException: java.lang.NullPointerException
    at weblogic.application.internal.ExtensibleModuleWrapper.prepare(ExtensibleModuleWrapper.java:114)
    at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100)
    at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:192)
    at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:187)
    at weblogic.application.utils.StateMachineDriver$ParallelChange.run(StateMachineDriver.java:83)
    at weblogic.work.ContextWrap.run(ContextWrap.java:46)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
    at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
    at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
    at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
    at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
Caused By: java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:532)
    at org.apache.log4j.PropertyConfigurator.configure(PropertyConfigurator.java:427)
    at es.caser.archit.monitor.jmsgateway.MonitorJmsGateway.<clinit>(MonitorJmsGateway.java:23)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at weblogic.utils.classloaders.GenericClassLoader.defineCodeGenClass(GenericClassLoader.java:1357)
    at weblogic.ejb.container.ejbc.bytecodegen.GeneratorFactory.generateClass(GeneratorFactory.java:100)
    at weblogic.ejb.container.ejbc.bytecodegen.GeneratorFactory.generate(GeneratorFactory.java:51)
    at weblogic.ejb.container.ejbc.EJBCompiler.generate(EJBCompiler.java:606)
    at weblogic.ejb.container.ejbc.EJBCompiler.doCompile(EJBCompiler.java:201)
    at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:345)
    at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:313)
    at weblogic.ejb.container.deployer.EJBDeployer.compileEjbs(EJBDeployer.java:420)
    at weblogic.ejb.container.deployer.EJBDeployer.compileIfNecessary(EJBDeployer.java:351)
    at weblogic.ejb.container.deployer.EJBDeployer.prepare(EJBDeployer.java:716)
    at weblogic.ejb.container.deployer.EjbModuleExtension.postPrepare(EjbModuleExtension.java:97)
    at weblogic.application.internal.ExtensibleModuleWrapper$PrepareStateChange.next(ExtensibleModuleWrapper.java:297)
    at weblogic.application.internal.ExtensibleModuleWrapper$PrepareStateChange.next(ExtensibleModuleWrapper.java:285)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.ExtensibleModuleWrapper.prepare(ExtensibleModuleWrapper.java:109)
    at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100)
    at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:192)
    at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:187)
    at weblogic.application.utils.StateMachineDriver$ParallelChange.run(StateMachineDriver.java:83)
    at weblogic.work.ContextWrap.run(ContextWrap.java:46)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
    at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
    at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
    at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
    at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)

The error log is pointing to the fact that there is no log4j properties file in the classpath. The funny thing is that error doens't appear in weblogic 10.


Answer:

I think i've found the answer. When the ear is deployed, weblogic 10.3 expects a ejb-descriptor and weblogic 12 uses annotations. That's why weblogic 10 runs "well"

Question:

I have an EAR project, deployed on WildFly 10.1.0.Final This EAR consist of some jars and wars. I have a WebService in my jar file.

I can't understand clearly how to configurate my project. I spend a lot of time in google and debugger... so i need help )

My AIM: Set default AuthType/Security-domain for my EJB WebService in JAR on ear/server level.

For Security-domain i found configuration in:

  • Standalone.xml -> subsystem xmlns="urn:jboss:domain:ejb3:4.0 (server level, HIGHT priority) tag: subsystem xmlns="urn:jboss:domain:ejb3:4.0 scope: All EJB

  • Standalone.xml -> subsystem xmlns="urn:jboss:domain:undertow:3.0" (server level, Only for Undertow, HIGHT priority) attribute: default-security-domain (server level, medium priority) scope: All WebServices

  • In jboss-app.xml (Medium priority!) in EAR META-INF Example: https://developer.jboss.org/thread/177666 Scope: All EJB

  • XML file jboss-ejb3.xml in EAR child jar project (low priority) http://wildscribe.github.io/Wildfly/8.1.0.Final/subsystem/ejb3/index.html Scope: All EJB

  • Security domain annotation on WebService Class: Annotation: org.jboss.security.SecurityDomain Scope: Single WebService

Also, how can i understand - ejb properties more priority for ejb beans webservices than webservices properties

But how can i set default auth metod BASIC? Without annotation on the class. I cant find ( WEB-INF/web.xml and jboss-web.xml don't affect on my webservice.


Answer:

is using maven?

In this repository https://github.com/wildfly/quickstart you can find lot of examples of projects for deploy in wildfly. Specifically for web service using ejb this example is usefull https://github.com/wildfly/quickstart/tree/10.x/jaxws-ejb. Note that in this project is necesary indicate the context root on jboss-web.xml:

<jboss-web>
    <context-root>/yourpath</context-root>
</jboss-web>

And the configuration for web service is performed with annotations.

/**
* @author rsearls@redhat@com
*/
@Stateless
@Remote(EJB3RemoteInterface.class)
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class EJB3Bean01 implements EJB3RemoteInterface {
    @WebMethod
    public String echo(String input) {
        return "EJB3Bean01 returning: " + input;
    }

}

Question:

I have an ear application that consists of an ejb.jar and a web application (war). The ejb.jar contains all my EJBs (beans and interfaces) and my war contains REST web services. I want to access the EJBs from the war module, is that possible? Injecting the EJBs doesn't work, I get null pointer exception.

I know that this has been asked many times but I can't seem to get this working...

I am using Glassfish v2.1.1 (I know I should upgrade, but right now it is difficult...)

Here is the code fragment that returns nullPointerException: (I know I am not supposed to validate a user through GET, but this is just an example code I am trying just to check if I can access the ejb)

@Path("/user")
public class UserWS
{
    @EJB
    SB_usrRemote sb_usrRemote;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String checkLoginAttempt(String username, String password)
    {
        return sb_usrRemote.checkLoginAttempt(username, password).toString();
    }
}

I didn't mention that this code only works when I include the ejb.jar in the ear application's lib folder where the war module can "see" it. Is there any other way I can access the EJB classes? Also I am using Intellij, the application is a java EE Application that includes a web module (for the war).

EDIT

I couldn't avoid the glassfish upgrade from v2 to v4. It was the best decision I made as all my problems went away. All the ejb injection in my code worked like a charm!

Thank you both for your suggestions! I am accepting hugh 's answer because JNDI probably would have worked, but upgrading glassfish seemed like a more appropriate solution in the long run.

EDIT 2

I finally managed to do a proper ejb injection using this code:

@Path("/user")
public class UserWS
{
    @EJB (lookup = "java:global/<ear-name>/<ejb-jar-name>/SB_usrRemote")
    SB_usrRemote sb_usrRemote;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String checkLoginAttempt(String username, String password)
    {
        return sb_usrRemote.checkLoginAttempt(username, password).toString();
    }
}

I found the proper lookup path in the glassfish log when I deployed my ear file.


Answer:

Per the JAX-RS specification, injection is not enabled by default in JAX-RS classes. You either need to use a CDI bean deployment archive (add WEB-INF/beans.xml for CDI 1.0), make the JAX-RS class be a managed bean (add the @ManagedBean annotation to the class)., or make the JAX-RS class be an EJB (e.g., add the @Stateless annotation to the class).

Question:

In an application-managed scenario, an entity manager has to be manually cleared if it will be active for some time, otherwise entities will pile up and potentially eat up tons of memory. But in the for a container-managed application, when is a persistence context cleared or closed? I see one claim here that it's always cleared when a transaction ends:

https://en.wikibooks.org/wiki/Java_Persistence/Persisting#Clear

"For JTA managed EntityManagers the persistence context is automatically cleared across each JTA transaction boundary."

...but I'm not able to find a source for this claim.


Answer:

If you want to see the source of the claim, the JPA specification is the best source you can get. Here it is stated:

After the JTA transaction has completed (either by transaction commit or rollback), the container closes the entity manager by calling EntityManager.close.

It is Page 357, under section "Container Responsibilities".

Question:

Just started working with EJB (already developed project).

Imported the project from git and converted it to Maven project. However the project looks like a normal folder structure unlike regular java project. I cannot have any eclipse Java capabilities in side those files. Though they are Java files they look like class files to me with different symbol (can see that in image).

It won't compile unless I do maven build. Eclipse not showing any errors for those files even there are compile errors.

Running each time maven kills time and its irritating too.

Any help will be greatly appreciated. How to make that a normal Java project with eclipse compiler capabilities.

What configuration I have to do achieve this ?


Answer:

Try running the command mvn eclipse:eclipse from the root folder of the project. It will create eclipse configuration files after which the project can be imported in Eclipse.

Question:

I have an enterprise Web Application, let's call it AppOne, containing multiple WARs and one EJB, that uses JPA 2 to perform CRUD operations on a set of Entities.

Now I need to build another enterprise Web Application, let's call it AppTwo, with a similar structure (EAR containing n WARS + EJB) that will need to share the same entities and database of AppOne.

Both AppOne and AppTwo will reside on the same application server.

I'm using JBoss 7, Hibernate 4 as JPA 2 provider, my entities are auto scanned.

My persistence.xml is very small:

<?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="FoobarService"  transaction-type="JTA">
      <jta-data-source>java:jboss/datasources/foobarDS</jta-data-source>      
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
         <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
         <property name="hibernate.show_sql"    value="true" />
         <property name="format_sql"            value="true" />
         <property name="use_sql_comments"      value="true" />      
         <!-- when using type="yes_no" for booleans, the line below allows booleans in HQL expressions: -->
         <property name="hibernate.query.substitutions" value="true 'Y', false 'N'"/>
      </properties>
   </persistence-unit>
</persistence>

I was thinking to "clone" (read: copy&paste) the part of AppOne's EJB containing the Entities and the relevant DAO parts into AppTwo's EJB, but since I've never done this with JPA, I'm wondering if this is possible/advisable (or which are the alternatives, considering that AppOne is already deployed in production so I can't take its EJB out to make it a shared one), and specifically if:

  1. Can both AppOne and AppTwo Persistence Units cohexist ? (I've read of problems but I'm not sure if they're related to this or if they've been resolved meanwhile)
  2. How will the transactions be handled ? I mean, if two different PU from two different EJBs are trying to update the same entity at the same time, what happens ?
  3. Can you think of any problem with this approach ? Apart from the obvious redundancy that would force me to update twice the files in case of future entities/database modifications.

Answer:

I never tried it, but I think it should be no (big) problem.

  1. Yes, they can coexist. E.g if for every deployment a separated ClassLoader is used.
  2. Transactions from each application will NOT know of each other. It will be the same as two users would click one after another on the same button.
  3. I personally don't see any problems. If your server is strange configured, you will have to configure JBoss to isolate every application.

Question:

I have a singleton class that perform an task in some time interval. When the application starts its all fine, the task is run in right period and that interval is enough suck that any task isn't overlap.

The class is show bellow:

@Singleton
@Startup
public class BOTAnalisaSituacao {
    public BOTAnalisaSituacao() throws FileNotFoundException {
    }

    @Schedule(second = "0", minute = "*/1", hour = "*")
    public void analisar() throws Exception {
        System.out.println("Starting");
        System.out.println("DONE");
    }
 }

The web container used is Wildfly 10.

The problem is, when the application is started after one hour down, for example, the task is executed sequentially, in this case all 60 calls, after that the 1 minute period is restored by itself. Do I have to clear any cache to avoid suck behavior?


Answer:

Timers are persistent by default. If the server is shut down or crashes, persistent timers are saved and will become active again when the server is restarted, If a persistent timer expires while the server is down all lost timers will be called. Non-persistent programmatic timers are created by calling adding persistent=false to annotation:

@Schedule(second = "0", minute = "*/1", hour = "*",persistent=false)
    public void analisar() throws Exception {
        System.out.println("Starting");
        System.out.println("DONE");
    }

source: http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html#bnbpa

Question:

I'm working on session bean (EJB3.0) and I need to make search method (in tables) for client.

I have 2 tables (TB1, TB2) with some columns (id, col2, col3)

For search I'm using such construct:

public TB1 findTB1( TB1 tb1 ) throws Exception{
    if (tb1.getId() == null ){
        _entityManager.persist(tb1);
         }
         else{


            return (tb1);
         }
    }
}

Is it right?


Answer:

Doesn't quite work.

Firstly, I'd think about the persist part. When using find method I do not usually expect my entity to get persisted into DB.

Secondly, returning the object you have might not work (probably will not). That's because you have no guarantee that tb1, even if it's id is filled, is a managed bean at the moment. Also, I would expect find method to give me up-to-date row from DB and not the argument I passed.

The correct way is simply using the find method:

return _entityManager.find(TB1.class, tb1.getId());

And handling the case with id==null on a higher level. When you may not have a primary key to search with you do not search.