Hot questions for Using Enterprise JavaBeans in ant

Question:

I'm trying to setup the Jboss server "client" (version 5.1.0) to use remote EJBs from another Jboss server (10.90.0.91), but I can't do this using a jndi.properties file on the Jboss client.

I can get the remote EJB using this simple code on my client:

        InitialContext ctx = null;
        try {
            Hashtable<String, String> jndiProps = new Hashtable<String, String>();
            jndiProps.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
            jndiProps.put(InitialContext.PROVIDER_URL, "jnp://10.90.0.91:1099");
            ctx = new InitialContext(jndiProps);
            return ctx.lookup(jndiName);
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }

This works fine.

Now I would like to setup the Jboss client with this properties. But if I edit the existent jndi.properties file localized on server/{application}/conf/ from:

# DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING
#
java.naming.factory.initial=org.jboss.iiop.naming.ORBInitialContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

To:

# DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING
#
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=jnp://10.90.0.91:1099

I receive some errors when I start the Jboss client (apparently, I don't know what I'm doing :)):

2016-08-19 10:17:41,645 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController] (main) Error installing to Start: name=HASessionStateService state=Create
javax.naming.NameAlreadyBoundException: Default
    at org.jnp.server.NamingServer.bind(NamingServer.java:209)
    at org.jnp.server.NamingServer.bind(NamingServer.java:167)
[...]

2016-08-19 10:17:42,767 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController] (main) Error installing to Start: name=ProfileServiceProxyFactory state=Create
javax.naming.NameAlreadyBoundException: ProfileService
    at org.jnp.server.NamingServer.bind(NamingServer.java:209)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[...]

2016-08-19 10:17:44,778 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController] (main) Error installing to Start: name=jboss:service=ClientUserTransaction state=Create mode=Manual requiredState=Installed
javax.naming.NameAlreadyBoundException: UserTransaction
    at org.jnp.server.NamingServer.bind(NamingServer.java:209)
    at sun.reflect.GeneratedMethodAccessor487.invoke(Unknown Source)
[...]

And in the final:

2016-08-19 10:17:51,993 ERROR [org.jboss.system.server.profileservice.ProfileServiceBootstrap] (main) Failed to load profile: Summary of incomplete deployments (SEE PREVIOUS ERRORS FOR DETAILS):

DEPLOYMENTS MISSING DEPENDENCIES:
  Deployment "ProfileServiceInvocationHandler" is missing the following dependencies:
    Dependency "ProfileServiceProxyFactory" (should be in state "Configured", but is actually in state "**ERROR**")
    Dependency "ProfileServiceProxyFactory" (should be in state "Configured", but is actually in state "**ERROR**")

DEPLOYMENTS IN ERROR:
  Deployment "jboss:service=ClientUserTransaction" is in error due to the following reason(s): javax.naming.NameAlreadyBoundException: UserTransaction
  Deployment "HASessionStateService" is in error due to the following reason(s): javax.naming.NameAlreadyBoundException: Default
  Deployment "ProfileServiceProxyFactory" is in error due to the following reason(s): javax.naming.NameAlreadyBoundException: ProfileService, **ERROR**

So, I think I can't touch in already existent JNDI properties on that file.

If the jndi.properties file can not be changed because it is used by JBoss itself, in which location puts my JNDI lookup settings to the remote EJBs within the Jboss 5? How can I configure a jndi.properties file to be available in the application classpath without put the jndi.properties file inside of my WAR file?

Thanks!


Answer:

An alternative way to do this is to configure a org.jboss.naming.ExternalContext MBean in your jboss-service.xml file:

<mbean code="org.jboss.naming.ExternalContext" 
       name="jboss.jndi:service=ExternalContext,jndiName=external/server2">
    <attribute name="JndiName">external/server2</attribute>
    <attribute name="Properties">
        java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
        java.naming.provider.url=jnp://10.90.0.91:1099
        <!-- other properties as needed -->
    </attribute>
    <attribute name="InitialContext"> javax.naming.IntialContext </attribute>
    <attribute name="RemoteAccess">false</attribute>
</mbean>

Your java code to perform the lookup then becomes:

 Context initialContext = new InitialContext();
 return initialContext.lookup("external/server2/" + jndiName);

You can even navigate the remote JNDI tree using JNDIView in the local management console when you set this up.

More information can be found in org.jboss.naming.ExternalContext MBean.

Question:

I am using NetBeans 8.0.2, jdk 1.8 and Glassfish 4. I have also used another config, with NB 7.3.1, jdk 1.7 and GF 3.1.2 and the same result.

I am creating a new Java EE project, only with an EJB module. When i try to deploy the EJB module, i get this error:

java3c7e4\java3c7e4-ejb\nbproject\build-impl.xml:938: The module has not been deployed.
See the server log for details.

And this is the server log:

Launching GlassFish on Felix platform
Jan 07, 2015 10:42:33 PM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner createBundleProvisioner
INFO: Create bundle provisioner class = class com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner.
Jan 07, 2015 10:42:33 PM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner$DefaultCustomizer getLocations
WARNING: Skipping entry  because it is not an absolute URI.
Jan 07, 2015 10:42:33 PM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner$DefaultCustomizer getLocations
WARNING: Skipping entry  because it is not an absolute URI.
Registered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishRuntime@2f2c26f0 in service registry.
Found populator: com.sun.enterprise.v3.server.GFDomainXml
Info:   Running GlassFish Version: GlassFish Server Open Source Edition  4.1  (build 13)
Info:   Server log file is using Formatter class: com.sun.enterprise.server.logging.ODLLogFormatter
Info:   Realm [admin-realm] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.
Info:   Realm [file] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.
Info:   Realm [certificate] of classtype [com.sun.enterprise.security.auth.realm.certificate.CertificateRealm] successfully created.
Info:   Authorization Service has successfully initialized.
Info:   Registered org.glassfish.ha.store.adapter.cache.ShoalBackingStoreProxy for persistence-type = replicated in BackingStoreFactoryRegistry
Info:   visiting unvisited references
Info:   Java security manager is disabled.
Info:   Entering Security Startup Service.
Info:   Loading policy provider com.sun.enterprise.security.provider.PolicyWrapper.
Info:   Security Service(s) started successfully.
Info:   Grizzly Framework 2.3.15 started in: 212ms - bound to [/0.0.0.0:8080]
Info:   Grizzly Framework 2.3.15 started in: 0ms - bound to [/0.0.0.0:8181]
Info:   Grizzly Framework 2.3.15 started in: 20ms - bound to [/0.0.0.0:4848]
Info:   Grizzly Framework 2.3.15 started in: 17ms - bound to [/0.0.0.0:3700]
Info:   Created HTTP listener http-listener-1 on host/port 0.0.0.0:8080
Info:   Created HTTP listener http-listener-2 on host/port 0.0.0.0:8181
Info:   Created HTTP listener admin-listener on host/port 0.0.0.0:4848
Info:   Created virtual server server
Info:   Created virtual server __asadmin
Info:   Setting JAAS app name glassfish-web
Info:   Virtual server server loaded default web module 
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   Initializing Mojarra 2.2.7 ( 20140610-1547 https://svn.java.net/svn/mojarra~svn/tags/2.2.7@13362) for context '/java3c7e2-web'
Info:   HV000001: Hibernate Validator 5.0.0.Final
Info:   Monitoring jndi:/server/java3c7e2-web/WEB-INF/faces-config.xml for modifications
Info:   Loading application [java3c7e2-web] at [/java3c7e2-web]
Info:   Loading application java3c7e2-web done in 5,862 ms
Info:   GlassFish Server Open Source Edition  4.1  (13) startup time : Felix (6,341ms), startup services(7,526ms), total(13,867ms)
Info:   Grizzly Framework 2.3.15 started in: 3ms - bound to [/0.0.0.0:7676]
Info:   Registered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl@42fcc7e6 as OSGi service registration: org.apache.felix.framework.ServiceRegistrationImpl@de88ac6.
Info:   JMXStartupService has started JMXConnector on JMXService URL service:jmx:rmi://Eddie-PC:8686/jndi/rmi://Eddie-PC:8686/jmxrmi
Info:   Created HTTP listener http-listener-2 on host/port 0.0.0.0:8181
Info:   Grizzly Framework 2.3.15 started in: 0ms - bound to [/0.0.0.0:8181]
Info:   visiting unvisited references
Severe:   Exception while deploying the app [java3c7e4-ejb]
Severe:   Exception during lifecycle processing
java.lang.IllegalArgumentException: Specified library jar java3c7e4-lib.jar does not exist: D:\Facultate\JAVA%203\Modul%207\java3c7e4-lib\dist\java3c7e4-lib.jar
    at org.glassfish.deployment.common.DeploymentContextImpl.getAppLibs(DeploymentContextImpl.java:458)
    at org.glassfish.deployment.common.DeploymentContextImpl.createClassLoader(DeploymentContextImpl.java:244)
    at org.glassfish.deployment.common.DeploymentContextImpl.createDeploymentClassLoader(DeploymentContextImpl.java:229)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:365)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)

Severe:   Exception while deploying the app [java3c7e4-ejb] : Specified library jar java3c7e4-lib.jar does not exist: D:\Facultate\JAVA%203\Modul%207\java3c7e4-lib\dist\java3c7e4-lib.jar
Info:   Created HTTP listener http-listener-1 on host/port 0.0.0.0:8080
Info:   Grizzly Framework 2.3.15 started in: 30ms - bound to [/0.0.0.0:8080]
Info:   Domain Pinged: release.glassfish.org
Info:   visiting unvisited references
Severe:   Exception while deploying the app [java3c7e4-ejb]
Severe:   Exception during lifecycle processing
java.lang.IllegalArgumentException: Specified library jar java3c7e4-lib.jar does not exist: D:\Facultate\JAVA%203\Modul%207\java3c7e4-lib\dist\java3c7e4-lib.jar
    at org.glassfish.deployment.common.DeploymentContextImpl.getAppLibs(DeploymentContextImpl.java:458)
    at org.glassfish.deployment.common.DeploymentContextImpl.createClassLoader(DeploymentContextImpl.java:244)
    at org.glassfish.deployment.common.DeploymentContextImpl.createDeploymentClassLoader(DeploymentContextImpl.java:229)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:365)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)

Severe:   Exception while deploying the app [java3c7e4-ejb] : Specified library jar java3c7e4-lib.jar does not exist: D:\Facultate\JAVA%203\Modul%207\java3c7e4-lib\dist\java3c7e4-lib.jar

I have verified and this .jar exists. I have searched everywhere and i didn't find anything similar. What can i do? Is there a problem with Netbeans, Java or Glassfish? Or with my configuration of the project?

Also, this is the line of the build-impl.xml file(line 938):

<nbdeploy debugmode="false" forceRedeploy="${forceRedeploy}"/>

Thank you!


Answer:

I had the same problem. My computer's user-name contains a space (Ngoc Chien) so when deploying the EJB, the Glassfish found the jar library in C:\Users\Ngoc%20Chien\NetbeanProject... , it was a wrong path , I guessed.

So I copied my NetbeanProject to D:\Data\NetbeanProject (or anywhere you want that have no space and special character in path) and removed the library jar in the project , then added it again with new path. It worked.

In your case , D:\Facultate\JAVA%203\Modul%207.the problem is at %203 %207 , which may be some special UTF-8 characters or spaces .

Question:

This is a follow-up to User context for @Startup EJB on websphere

I have the following scenario:

EJB 1:

@WebService( ... )
@Local(SomeLocalServiceType.class)
@Stateless
@RolesAllowed("SomeRole")
public class SomeServiceBean implements SomeLocalServiceType {

    ...

    @Override
    public void someMethodInSomeLocalServiceType() { ... }

    ...
}

EJB 2:

@Startup
@Singleton
@RunAs("SomeRole")
public class PIRSingletonEJB {

        @EJB
        private SomeLocalServiceType service; 

        ...

        @PostContruct
        public void performStartupAction() { 
            service.someMethodInSomeLocalServiceType();
        }

}

In short: I have one EJB requiring a role "SomeRole", and a startup EJB using @RunAs to use that role.

As far I as understand @RunAs this should work.

However, I get the following Exception (class and role names changed to match my example):

javax.ejb.NoSuchEJBException: An error occurred during initialization of singleton session bean MY_Appl#myappl-ejb.jar#PIRSingletonEJB, resulting in the discarding of the singleton instance.; nested exception is: javax.ejb.EJBAccessException: SECJ0053E: Authorization failed for wasldaphost:389/SOMEUSER while invoking (Bean)MY_Appl#myappl-ejb.jar#SomeServiceBean someMethodInSomeLocalServiceType::3  is not granted any of the required roles: SomeRole
Caused by: javax.ejb.EJBAccessException: SECJ0053E: Authorization failed for wasldaphost:389/SOMEUSER while invoking (Bean)MY_Appl#myappl-ejb.jar#SomeServiceBean someMethodInSomeLocalServiceType::3  is not granted any of the required roles: SomeRole

Is this just a misunderstanding on my part of how this should work?

I am using WebSphere 8.0.0.9


Answer:

You have to do two things:

  • In the admin console, in the Security role to user mapping you have to add your SOMEUSER to SomeRole
  • Then in RunAs role mapping you have to specify one particular user from the SomeRole (in your case SOMEUSER) and provide password for him.

Both settings are required, because container must have userid and password for the RunAs, and also that user must be valid user for the role that should be used. (You cannot run just as role, it must be a specific user that has that role).

PS. I don't have console at hand, so links might be called a bit differently in the console, but you should get the idea.

For more details check Assigning users to RunAs roles

Question:

I´m developping a Java Web Application.

I have this class:

@Stateless
public class A {

void makeSomething();

}

Now I call this class in another class (I have two approaches):

@Stateless
public class B {

Method 1:

A a =new A();
a.makeSomething();

Method 2:

A a =new A();
a.makeSomething();

or


@EJB 
A a;

Method 1:

a.makeSomething();

Method 2:

a.makeSomething();

 }

My Web Application has a lot of requests. In a concurrency world what´s the best way to Instantiate class A?


Answer:

The best way is using @EJB annotation. The container will inject and manage your instances. The container will create a pool of instances, and manage between requests, its a good practice! it not will create a new instance for each request )

Question:

I am working in a JavaEE Project and i use an interface to implement method but when i want to use an EJB it say that my EJB is null Interface.java

public interface Interface {  public void methodTest ();  }

SubInterface.java

public class SubInterface implements Interface {
@EJB
private myEJB myejb
@Override
public void methodTest(){
if( myejb == null ){
System.out.println("He is null");
}
} 
}

myEJB.java

@Stateless
public class myEJB extends SomeAbstractFacade {
@PersistanceContext
private EntityManager em ; 

....

}

UserController.java

@ManagedBean
@ViewScoped
public class UserController extends SomeAbstractController implements         Seializable{
private interface myInterface ;

public void method (){
myInterface  = new SubInterface();
myInterface.methodTest();

}

}

when i execute methodTest we can read in the output he is null. thank you


Answer:

You will need to inject your interface instance. When you use 'new' all the annotations (@EJB etc.) will be ignored as the dependency manager won't know about the creation of that instance.

So in your managed bean annotate the private interface field and the ejb will be injected for you.

@ManagedBean
@ViewScoped
public class UserController extends SomeAbstractController implements         Seializable{

   @Inject
   private interface myInterface ;

   public void method (){
      myInterface.methodTest();

   }

}

Question:

Is there any big advantage on this approach:

@Entity
public class A {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "ID_B")
    private B b;
}

@Entity
public class B {
    @OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
    private List<A> aList;
}

...instead of this?...

@Entity
public class A {
    @Column(name = "ID_B")
    private Long idB;
}

@Entity
public class B {
    //no reference to A
}

I thing the second one is better for encapsulation (as I have A and B classes in different projects, and the second don't need to reference the fist).


Answer:

One advantage is that using proper JPA relationships allow you to fetch A from the database, and use a simple getter on A to get B: myA.getB()

Whereas if you use a long, you will need to always manually query the database again when you want to fetch some B.

Note that you are not obligated to declare the relationship both ways. Something like this is perfectly valid:

@Entity
public class A {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "ID_B")
    private B b;
}

@Entity
public class B {
    //no reference to A
}

Of course, it all depends on what you are trying to achieve!

Question:

We're building a Java web application. We're using EJB containers and JPA with Wildfly 9.2.

Now we want to integrate a permission system in which a user has a certain role, but this role is only granted in combination with a certain entity. I'll name this access resource Department.

So we would have a list of permission for the user stored in such a table:

| User ID | Department | Role    |
| ------- | ---------- | ------- |
| 1       | A          | MANAGER |
| 1       | B          | ADMIN   |
| 2       | B          | MANAGER |

In addition we have global roles. A user has a set of global roles that will be applied should there not be an entry in the table above with the deparment in question.

| User ID | Role    |
| ------- | ------- |
| 1       | VIEWER  |
| 3       | MANAGER |

How can we easily check if a user is in a certain role, given a department?

By just using the annotation @RolesAllowed we can check for a certain role, but not restricted to a department.


Answer:

Remember that enterprise java security roles are about authorization.

So, you could model the department as a role in your security system as well. It's quite OK for a user to be assigned more than one security role.

Therefore, given a manager in department B:

@RolesAllowed({"manager", "B"}
public void someBusinessMethod(...) {
     ...
}

Only users who are managers and in department B are authorized to invoke this method.

Question:

I'm new to EJB and I've wrote a very small ejb component for demonstration purposes. All It's supposed to do is print "hello ". Currently struggling to configure the InitialContext of the remote client correctly. The container I use is JBoss 7.0. I use JaveEE7.0 with ejb3.2.

The Interface of the ejb:

package hello;

public interface Hello {

    public String sayHello(String name);
}

The bean itself:

package hello;

import javax.ejb.Remote;
import javax.ejb.Stateless;

@Stateless(name="HelloEJB")
@Remote(Hello.class)
public class HelloBean implements Hello {

    @Override
    public String sayHello(String name) {
        return "Hello, " + name;
    }

}

And the remote client that I placed inside the EJB project but I run as a java application:

package client;

import hello.Hello; 

import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

public class Test {

    public static void main(String[] args) {

        Hello statelessHello = null;
        try {
            statelessHello = lookupStatelessHello(); // the method that throws exception
        } catch (NamingException e) {
            System.out.println("Bean Loading Failed");
            e.printStackTrace();
            Thread.currentThread().stop();
        }       
        Hello stub=(Hello)PortableRemoteObject.narrow(statelessHello, Hello.class);
        System.out.println("obtained a remote stateless hello for invocation");
        System.out.println(stub.sayHello(args[0]));
    }



    private static Hello lookupStatelessHello() throws NamingException {
    // the problematic code:
            Properties jndiProperties = new Properties();
            jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
            jndiProperties.put(Context.PROVIDER_URL,"remote://localhost:4447"); // tried to change ports.
            jndiProperties.put("jboss.naming.client.ejb.context", true);
            Context context = new InitialContext(jndiProperties); // exception happens here
            return (Hello) context.lookup("stateless1/HelloEJB!hello.Hello");
        }
    }

When I run JBoss, I manage to deploy my ejb project without problems:

13:37:20,141 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-6) JNDI bindings for session bean named HelloEJB in deployment unit deployment "stateless1.jar" are as follows:

java:global/stateless1/HelloEJB!hello.Hello java:app/stateless1/HelloEJB!hello.Hello java:module/HelloEJB!hello.Hello java:global/stateless1/HelloEJB java:app/stateless1/HelloEJB java:module/HelloEJB

13:37:20,255 INFO [org.jboss.as.server.controller] (DeploymentScanner-threads - 2) Deployed "stateless1.jar"

but when I try to call the ejb from remote client I get:

Bean Loading Failed javax.naming.NoInitialContextException: Cannot instantiate class: org.jboss.naming.remote.client.InitialContextFactory [Root exception is java.lang.ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory] at javax.naming.spi.NamingManager.getInitialContext(Unknown Source) at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source) at javax.naming.InitialContext.init(Unknown Source) at javax.naming.InitialContext.(Unknown Source) at client.Test.lookupStatelessHello(Test.java:34) at client.Test.main(Test.java:18) Caused by: java.lang.ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method)

I've tried to change ports, tried to add security credentials but I can't understand how to add a user, tried to read guides but frankly because i'm new to this It's pretty hard for me. Also, I'm pretty sure that the way I lookup my bean is wrong, but It's not the issue right now.

I hope you'll be able to help me find the thing that I do wrong here. If you need more info on the setup, just ask.


Answer:

As stated above you need to required jboss-client.jar along with your code , in order this to work. The specific jar can be found at

JBOSS_HOME/bin/client/jboss-client-7.1.0.Final.jar.

Also please have a look on the official documentation and wiki that comes along with a full example. See here.

Question:

I am building a restful webservice using Jax-RS and EJB3 running on wildfly 8. The system is splited into two parts. A rest module and a persistence module. The rest module consists of a rest servlet with a method, reacheable under "mycontext/rest/do". This method calls the method "do()" of a stateless bean which represents the interface of the persistence module. "do()" calls "persistEntity(Entity e)" of another stateless bean which represents a facade (kind of an interface pattern) of a entity class. The entity I want to persist has a few constraints. If they get violated an exception like "ConstraintViolationException" gets thrown (by the EJB container I think). I try to catch the exception in one of the two stateless beans in the persistence module but this is not working. That means that the code in the catch block is not executed. But catching the exception in the servlet works.

Rest servlet (catching exception works here):

@Path("/rest")
public class AccountRestService {
    @Inject
    private Service service;
    @POST
    public void do(Entity entity) {
        service.do(entity);
    }
}

Bean representing interface of the persistence module (catching exception is ignored):

 @Stateless
 @LocalBean
 public class Service {
     @Inject
     private EntityFacade facade;
     public void do(Entity entity) {
         facade.persist(entity);
     }
 }

Entity Facade (catching exception is ignored):

@Stateless
public class EntityFacade{
    @PersistenceContext(unitName = "primary")
    private EntityManager em;
    public void create(Entity entity){
        em.persist(entity); // this line throws exception like ConstraintViolationException
    }
}

Answer:

That's expected. The exception is thrown at flush time. The flush happens at transaction-commit time. And the commit happens after the EJB method has returned successfully.

So, contrary to what you say, it's not the persist() method which throws the exception (the stack trace would confirm that), but the method of the transactional proxy which wraps your EJB and commits the transaction.

There is really nothing you can do with such an exception except

  • show an error message to the user. In that case, catching the exception in the rest service, or letting a generic exception handler handle it is the right thing to do
  • retry the transaction. In that case, you should have an intermediate layer (or method) between the rest service method and the EJB, which calls the transactional EJB, catches the exception and retries.

Question:

I have a method Meth1 witch will call a Meth2 from another class. I want the Meth2 NOT to be executed if the Meth1 fails.

Both of them have REQUIRED attribute. With this code, if the Meth1 fails while persisting (after Meth2 was executed succesfully), the Meth2 changes will remain.

I want all the code to be executed as a whole transaction, all or nothing.

Ex.:

@TransactionAttribute(TransactionAttributeType.REQUIRED)
void meth1(){
    // ...some code
    otherClass.meth2();
    // ... some persistance that may fail
}

@TransactionAttribute(TransactionAttributeType.REQUIRED)
void meth2(){
    // some persistance
}

Thanks!


Answer:

In this case both methods will be executed in the same transaction.

EJB specification 3.0 tells about REQUIRED:

The container must invoke an enterprise bean method whose transaction attribute is set to the REQUIRED value with a valid transaction context.

If a client invokes the enterprise bean’s method while the client is associated with a transaction context, the container invokes the enterprise bean’s method in the client’s transaction context.

If the client invokes the enterprise bean’s method while the client is not associated with a transaction context, the container automatically starts a new transaction before delegating a method call to the enterprise bean business method. The container automatically enlists all the resource managers accessed by the business method with the transaction. If the business method invokes other enterprise beans, the container passes the transaction context with the invocation. The container attempts to commit the transaction when the business method has completed. The container performs the commit protocol before the method result is sent to the client.

Question:

I need some assist, I've tried to run it since this morning, I've 2 projects,

  • EJB project (StudentManajementEJB)
  • Dynamic web project (StudentManajementWeb)

web server :

jboss-as-7.1.1.Final

The StudentManajementEJB has been succesfully deployed (Table gets created in the db), as a proof :

Now I go link the StudentManajementWeb to StudentManajementEJB.

Now I right click- run on server the StudentManajementWeb , I keep getting :

Persistence.xml:


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="StudentMgtPU"
        transaction-type="JTA">
        <jta-data-source>java:/StudentMgtDS</jta-data-source>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.hbm2ddl.auto" value="create" />
        </properties>
    </persistence-unit>
</persistence>

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>StudentManagementWeb</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <description></description>
        <display-name>ManageStudentServlet</display-name>
        <servlet-name>ManageStudentServlet</servlet-name>
        <servlet-class>com.sameera.controller.ManageStudentServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ManageStudentServlet</servlet-name>
        <url-pattern>/ManageStudentServlet</url-pattern>
    </servlet-mapping>
</web-app>

Here's the failure's log:

13:58:43,295 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.deployment.unit."StudentManagementWeb.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."StudentManagementWeb.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "StudentManagementWeb.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_60]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_60]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_60]
Caused by: java.lang.RuntimeException: Error getting reflective information for class com.sameera.controller.ManageStudentServlet with ClassLoader ModuleClassLoader for Module "deployment.StudentManagementWeb.war:main" from Service Module Loader
    at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex(DeploymentReflectionIndex.java:70) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.ee.metadata.MethodAnnotationAggregator.runtimeAnnotationInformation(MethodAnnotationAggregator.java:58)
    at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.handleAnnotations(InterceptorAnnotationProcessor.java:85)
    at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.processComponentConfig(InterceptorAnnotationProcessor.java:70)
    at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.deploy(InterceptorAnnotationProcessor.java:55)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    ... 5 more
Caused by: java.lang.NoClassDefFoundError: Lcom/sameera/session/ManageStudentSessionBeanLocal;
    at java.lang.Class.getDeclaredFields0(Native Method) [rt.jar:1.7.0_60]
    at java.lang.Class.privateGetDeclaredFields(Class.java:2436) [rt.jar:1.7.0_60]
    at java.lang.Class.getDeclaredFields(Class.java:1806) [rt.jar:1.7.0_60]
    at org.jboss.as.server.deployment.reflect.ClassReflectionIndex.<init>(ClassReflectionIndex.java:57) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex(DeploymentReflectionIndex.java:66) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    ... 10 more
Caused by: java.lang.ClassNotFoundException: com.sameera.session.ManageStudentSessionBeanLocal from [Module "deployment.StudentManagementWeb.war:main" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
    ... 15 more

Answer:

Having the class in the build path is good for build time, but for the deployment the container needs access to the dependencies. Try to include your jar file in your war file.

Question:

I have the next problem while trying to develope a REST app using JPA and EJB's.

I have 3 projects in NetBeans (same workspace, just projects, not EAR or that weird stuff):

  • One of them is a Java Application in which I created some entity classes from a database. Inside of the same project, I created other package containing the controller classes from the entities. I tested the project creating a java main class and using the controllers.

  • The other project is a EJB module, it as simple as a package and the next class inside of it:

    package com.studentejb;
    import java.util.List;
    import javax.ejb.LocalBean;
    import javax.ejb.Stateless;
    import studentdao.StudentTO;
    import studentdao.StudentJpaController;
    
    @Stateless
    @LocalBean
    public class StudentEJB {
    
        private StudentJpaController studentDao = new StudentJpaController();
    
        public List<StudentTO> findStudents() {
            return studentDao.findStudentTO();
        }
    }
    

As you can see, I imported the previous JAR project (the one with the entity's controllers). I also tested this EJB project with a java main class and it worked.

  • The last project is a web application, as you can imagine I want to use the EJB modules of the previous project but I get the following errors while trying to enter to the resource http://localhost:8080/studentWeb/student/:

    12:00:12,384 ERROR [io.undertow.request] (default task-2) UT005023:    Exception handling request to /studentWeb/student/hola:     com.google.common.util.concurrent.ExecutionError:     java.lang.ExceptionInInitializerError
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2201)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824)
    at org.jboss.weld.util.cache.LoadingCacheUtils.getCacheValue(LoadingCacheUtils.java:49)
    .
    .
    .
    
    at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.ExceptionInInitializerError
    at studentdao.StudentJpaController.<init>(StudentJpaController.java:40)
    at com.studentejb.StudentEJB.<init>(StudentEJB.java:23)
    at com.studentweb.Resources.<init>(Resources.java:52)
    at com.studentweb.Resources$Proxy$_$$_WeldClientProxy.<init>(Unknown Source)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    .
    .
    .
    
    ... 58 more
    Caused by: javax.persistence.PersistenceException: Unable to locate persistence units 
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:99)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:86)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:67)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at studentdao.EntityProvider.<clinit>(EntityProvider.java:20)
    ... 80 more
    
    Caused by: javax.persistence.PersistenceException: Invalid persistence.xml.
    Error parsing XML [line : -1, column : -1] : cvc-elt.1.a: Cannot find the     declaration of element 'persistence'.
    
    at org.hibernate.jpa.boot.internal.PersistenceXmlParser.validate(PersistenceXmlParser.java:377)
    at org.hibernate.jpa.boot.internal.PersistenceXmlParser.loadUrl(PersistenceXmlParser.java:310)
    at org.hibernate.jpa.boot.internal.PersistenceXmlParser.parsePersistenceXml(PersistenceXmlParser.java:114)
    at org.hibernate.jpa.boot.internal.PersistenceXmlParser.doResolve(PersistenceXmlParser.java:104)
    at org.hibernate.jpa.boot.internal.PersistenceXmlParser.locatePersistenceUnits(PersistenceXmlParser.java:86)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:95)
    ... 85 more
    

Here is the code of the web app (Resources.java):

@Path("/student")
public class Resources {
    @EJB
    private StudentEJB studentEjb;

    @Context
    private UriInfo context;

    public Resources() throws FileNotFoundException, IOException, NamingException {
        studentEjb = new StudentEJB();
    }

    @GET
    @Path("/")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getJson() {
        return Response.ok(studentEjb.findStudents()).build();
    }
}

So I am using 2 JARs for the web project, the one with the EJB modules and the other with the entities and controllers..

Here is the persistence.xml generated by the JPA project:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://xmlns.jcp.org/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="studentJPAPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <!-- <provider>org.hibernate.ejb.HibernatePersistence</provider> -->
    <class>studentjpa.Address</class>
    <class>studentjpa.Phone</class>
    <class>studentjpa.Student</class>
    <class>studentjpa.Email</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:1433;databaseName=tca_student_db;integratedSecurity=true"/>
      <property name="javax.persistence.jdbc.user" value="xxxx"/>
      <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
      <property name="javax.persistence.jdbc.password" value="xxxx"/>
    </properties>
  </persistence-unit>
</persistence>

Thank you!


Answer:

Caused by: javax.persistence.PersistenceException: Invalid persistence.xml. Error parsing XML [line : -1, column : -1] : cvc-elt.1.a: Cannot find the declaration of element 'persistence'.

Here :

<persistence version="2.0" xmlns="http://xmlns.jcp.org/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">

xmlns :http://xmlns.jcp.org/xml/ns/persistence doesn't match with the namespace in xsischemaLocation which is http://java.sun.com/xml/ns/persistence

Try to use the same in both :

<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">

Question:

I am trying to set up an automatic build system with Jenkins CI for a NetBeans multitiered web application project. This NetBeans project contains an EJB-project (for the business layer of the web application) and a WAR-project (for the web layer of the application). I'm currently stuck on getting Ant to compile the project.

I am using Windows 8 to develop in NetBeans IDE 8.0. Jenkins also runs on Windows 8.

I'm currently looking for someone who understands how to build EJB-projects with Jenkins and Ant.

What I've done so far:

  • I've set up a NetBeans project (as described above)
  • I've set up a git repository for the project
  • I've set up Jenkins CI
  • I am able to get the project from the git repository with Jenkins CI
  • I am able to make Jenkins use Ant to clean the project it retrieved from the git repository

Where I get stuck:

After being succesful to execute the clean command with Ant I want to make the debug command work. For this the project needs to be compiled. Here is where it goes wrong.

I entered the following properties in the Properties field for the Ant Invoke in Jenkins:

libs.CopyLibs.classpath=C:/Program Files/NetBeans 8.0/java/ant/extra/org-netbeans-modules-java-j2seproject-copylibstask.jar
j2ee.server.home=C:/Program Files/wildfly-8.1.0.Final

In the output of my Jenkins build I see the following command:

[PGB Webapp] $ cmd.exe /C '""C:\Program Files (x86)\Jenkins\tools\hudson.tasks.Ant_AntInstallation\Apache_Ant\bin\ant.bat" "-Dlibs.CopyLibs.classpath=C:/Program Files/NetBeans 8.0/java/ant/extra/org-netbeans-modules-java-j2seproject-copylibstask.jar" "-Dj2ee.server.home=C:/Program Files/wildfly-8.1.0.Final" clean debug && exit %%ERRORLEVEL%%"'

And this is the last part of my output: (the part that seems most important to me)

init:

-init-cos:

-deps-module-jar:

-deps-ear-jar:

deps-jar:

-pre-pre-compile:
    [mkdir] Created dir: C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\pgb-ejb\build\classes

-pre-compile:

-copy-meta-inf:
     [copy] Copying 2 files to C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\pgb-ejb\build\classes\META-INF

-do-compile:
    [mkdir] Created dir: C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\pgb-ejb\build\empty
    [mkdir] Created dir: C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\pgb-ejb\build\generated-sources\ap-source-output
    [javac] Compiling 5 source files to C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\pgb-ejb\build\classes

-post-compile:

compile:

-pre-dist:

library-inclusion-in-manifest:

BUILD FAILED
C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\nbproject\build-impl.xml:204: The following error occurred while executing this line:
C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\pgb-ejb\nbproject\build-impl.xml:806: Warning: Could not find file C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\pgb-ejb\${libs.MySQLDriver.classpath} to copy.

Total time: 1 second
Build step 'Start Ant' marked build as failure
Finished: FAILURE

So in this output I see the following warning:

Warning: Could not find file C:\Program Files (x86)\Jenkins\workspace\PGB Webapp\pgb-ejb\${libs.MySQLDriver.classpath} to copy.

Now, to me this seems to be a rare issue as I can find almost nothing about it on the internet (or am I using the wrong search term?) I've searched on Google, here on SO, and DuckDuckGo, and I could only find the following (pretty useless) clues to my problem: (pretty useless because the warning I get is mentioned there, but the context is different..)

https://netbeans.org/bugzilla/show_bug.cgi?id=128505 and Error with database in javafx DataApp demo

Any help is appreciated as I am still pretty new to continuous integration systems, developing web applications and build tools.

Also, I haven't looked much into Maven or Gradle yet as alternatives. So maybe the solution to the problem might as well be to switch to another build tool..?


Answer:

It seems to me as if the property libs.MySQLDriver.classpath is not defined. When Ant cannot resolve a property, it uses the property name in the output.

Try to define

libs.MySQLDriver.classpath

in the properties field in Jenkins where you also defined the other two properties.

You need to point it to your MySQL JDBC driver.

Question:

I'm deploying an application making use of EJB. I'have wrote an EJB and a java standalone client to connect to. Everything works correctly in Netbeans, but when i try to start in command line I got exceptions. The JavaFX Application contains the following code :

    String chemin = IRemoteInterface.class.getName();
    Properties vEnv = new Properties();
    vEnv.put("org.omg.CORBA.ORBInitialHost", "localhost");
    vEnv.put("org.omg.CORBA.ORBInitialPort", "3700");

    try {
        Context ctx = new InitialContext(vEnv);
        leProxy = (IRemoteInterface) ctx.lookup(chemin);
        System.out.println("proxy OK");
    } catch (NamingException ex) {
        System.out.println("erreur proxy");
        Logger.getLogger(CDM.class.getName()).log(Level.SEVERE, null, ex);
    }

I have tried the following :

java -jar CDM.jar

And the error I get is :

javax.naming.NoInitialContextException: Cannot instantiate class: com.sun.enterprise.naming.impl.SerialInitContextFactory [Root exception is java.lang.NullPointerException]
    at java.naming/javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
    at java.naming/javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
    at java.naming/javax.naming.InitialContext.init(Unknown Source)
    at java.naming/javax.naming.InitialContext.<init>(Unknown Source)
    at cdm.CDM.main(CDM.java:77)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.NullPointerException
    at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.initializeServiceLocator(AbstractModulesRegistryImpl.java:152)
    at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.newServiceLocator(AbstractModulesRegistryImpl.java:144)
    at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:218)
    at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:224)
    at com.sun.enterprise.module.single.StaticModulesRegistry.createServiceLocator(StaticModulesRegistry.java:88)
    at org.glassfish.internal.api.Globals.getStaticHabitat(Globals.java:102)
    at com.sun.enterprise.naming.impl.SerialInitContextFactory.<init>(SerialInitContextFactory.java:130)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.base/java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.base/java.lang.Class.newInstance(Unknown Source)
    ... 16 more

I really don't know how to fix it.

Many thanks for your help in advance !


Answer:

EDIT :

When I use the following it works

java -cp "C:\Program Files\glassfish5\glassfish\lib\appserv-rt.jar;C:\Program Files\glassfish5\glassfish\lib\javaee.jar;C:\Program Files\glassfish5\glassfish\lib\gf-client.jar;CDM.jar" cdm.CDM

Question:

I have the following code:

@ConcurrencyManagement(BEAN)
@Startup
@Singleton
public class MySingletonBean {

    private Object threadSafeObject;

    @PostConstruct
    private void init() {
        threadSafeObject = nonTrivialInitialization();
    }

    private void nonTrivialInitialization() {
        // something with other beans or container resources
    }

    public void accessObject() {
        threadSafeObject.performSomeThreadSafeOperation();
    }

}

The circumstances are as follows:

  • threadSafeObject is accessed concurrently (obviously)
  • threadSafeObject takes care internally of its own synchronization
  • threadSafeObject initialization is not trivial, i.e. it accesses other beans or resources, so it needs to be performed inside container managed code aka @PostConstruct method, not as field initialization at object instantiation
  • bean managed concurrency is required because actual business code behind the singleton bean can be executed from both a JEE environment and a non-managed environment. Because of this, uniform handling of synchronization is preferred, thus, bean managed concurrency

Direct question: do I need to synchronize the initialization of threadSafeObject and therefore all other accesses to it to prevent possible visibility issues, e.g. thread A processes the initialization of the bean, but, afterwards, thread B doesn't see a correct view of threadSafeObject?

More elaborate question: When putting a singleton session bean into service, in case of bean managed concurrency, does the container offer any guarantees with regards to the safe publishing of the state of the singleton session bean? The EJB spec [part that I read] didn't quite give any hints towards this.

More rants from my part: For container managed concurrency, the container synchronizes all access to the singleton session bean, therefore we have the guarantee that all threads see the most recent consistent state of the bean. For bean managed concurrency, I keep reading that all synchronization is left to the implementor of the bean and the story ends there. Nothing more. So, even though, the container doesn't perform synchronization per se, bean initialization and feeding requests to the bean is still container managed, I'd still expect that the container somehow performs a write barrier when putting the bean into service. The JVM offers this guarantee for instance initialization for example and the metaphor goes that a JEE container is a JVM on steroids with ripped abs, right? :D


Answer:

Great question! I think this is the relevant part of the spec (taken from here):

Independent of the bean’s concurrency management type, the container must ensure that no concurrent access to the Singleton bean instance occurs until after the instance has successfully completed its initialization sequence, including any @PostConstruct lifecycle callback method(s). The container must temporarily block any Singleton access attempts that arrive while the Singleton is still initializing.

(section 4.8.5, p109)

My understanding of "no concurrent access" would be that some container synchronization is required after @PostConstruct completes. Hope that helps?

Question:

Currently I am developing an application composed of basically three modules: 1 ejb and two web apps. Using ant I am exporting this as a single ear.

My client asked to run multiple instances of the same ear on the same server. I was able to change application names and context path so they do not clash, however there is a problem with EJBs. Apache Geronimo can't startup EBJs with the same name event if they live on different ear/jar, etç.

Is there any way to make the EJB deployment specific for each "installation", or isn't possible and therefore I need to strip EJBs Jar from the web apps enclosed on the EAR ?

I would appreciate any help/hint.

Regards, Ivan Frias


Answer:

If it will be enough to have the many copies of web applications with one EJB.

Then you can separate EJB module and web modules and then load one EJB and N copies of web applications in the application server.

But it may cause some errors because of one EJB for many web applications. Otherwise you have to run three instances of the application server because you will not be able to use equal EJB even separated by different jars/packages.

Question:

I am in the middle of building continuous integration using apache ant to execute the build.

Currently we are facing some weird ant warning. I already point the ant task to generate EJBGen to EJB file called DnAOperationEJB.java

Herewith the ant build file:

<ejbgen source="1.6" outputDir="${staging.dir}" descriptorDir="ejbModule\META-INF" forceGeneration="true"
            ejbSuffix = "."
            localSuffix = "Local"
            localHomeSuffix = "LocalHome">
            <fileset dir="ejbModule/sample/oss/dna/ejb">
                    <contains text="@Session"/>
                    <contains text="@LocalMethod"/>
            </fileset>
</ejbgen>

After compiling, the result of the build was SUCCESSFUL as shown below

   [ejbgen] Invoking EJBGen with the following command line:
   [ejbgen]   -d
   [ejbgen]   C:\Users\Jenkins Project\Sample\DnA_Ejb\staging
   [ejbgen]   -forceGeneration
   [ejbgen]   -source
   [ejbgen]   1.6
   [ejbgen]   -ejbSuffix
   [ejbgen]   .
   [ejbgen]   -localSuffix
   [ejbgen]   Local
   [ejbgen]   -localHomeSuffix
   [ejbgen]   LocalHome
   [ejbgen]   -descriptorDir
   [ejbgen]   C:\Users\Jenkins Project\Sample\DnA_Ejb\ejbModule\META-INF
   [ejbgen]   C:\Users\Jenkins Project\Sample\DnA_Ejb\ejbModule\sample\oss\dna\ejb\DnAOperationEJB.java
   [ejbgen] EJBGen WebLogic Server 10.3.6.0  Tue Nov 15 08:52:36 PST 2011 1441050
   [ejbgen]  Warning:  No EJBGen file found!

BUILD SUCCESSFUL
Total time: 1 second

But the generated file from EJB Gen is not shown up in target folder. I think this is due to Ant cannot find the EJBGen file, as shown in the Warning: No EJBGen file found!

The source code of DnAOperationEJB.java as below:

/*
 * GenericSessionBean subclass automatically generated by OEPE.
 *
 * Please complete the ejbCreate method as needed to properly initialize new instances of your bean and add
 * all required business methods. Also, review the Session, JndiName and FileGeneration annotations 
 * to ensure the settings match the bean's intended use.
 */
@Session(ejbName = "DnAOperationEJB", initialBeansInFreePool = "5", maxBeansInFreePool = "20", transactionType = SessionTransactionType.CONTAINER, defaultTransaction = TransactionAttribute.SUPPORTS)
@JndiName(local = "ejb.DnAOperationEJBLocalHome")
@FileGeneration(remoteClass = Constants.Bool.FALSE, remoteHome = Constants.Bool.FALSE, localClass = Constants.Bool.TRUE, localHome = Constants.Bool.TRUE)
public class DnAOperationEJB extends GenericSessionBean implements SessionBean {

    private static final long serialVersionUID = 1L;
    private static String className = DnAOperationEJB.class.getName();
    /*
     * (non-Javadoc)
     * 
     * @see weblogic.ejb.GenericSessionBean#ejbCreate()
     */
    public void ejbCreate() 
    {
        // IMPORTANT: Add your code here
    }


//  @LocalMethod()
    @LocalMethod(transactionAttribute =  TransactionAttribute.NOT_SUPPORTED)
    public Context createContext(String xmlIn, String tID)
    {
        Log.debug("Executing createContext", className, tID);

        try
        {
            Context ctx = new Context();
            ctx.setTransactionID(tID);
            ctx.setRequest(xmlIn);

            return ctx;
        }
        catch (Exception e) 
        {
            throw new RuntimeException(e);
        }
        finally
        {
            Log.debug("createContext executed", className, tID);
        }       
    }

//  @LocalMethod()
    @LocalMethod(transactionAttribute =  TransactionAttribute.REQUIRES_NEW)
    public void executeOperation(Context ctx) throws Exception 
    {
        Log.debug("Executing executeOperation", className, ctx.getTransactionID());
        Operation operation = null;
        try
        {
            operation = OSSFactory.newOperation(ctx);
            Log.debug("OperationBegin: " + ctx.getRequest().toString(), className, ctx.getTransactionID());
            operation.execute();
        }
        catch(Exception e)
        {
            Log.exception(e, className, ctx.getTransactionID());
            e.printStackTrace();
            getSessionContext().setRollbackOnly();
            Log.debug("Transaction rolled back",  className, ctx.getTransactionID());
            throw e;
        }
        finally
        {
            if(operation != null)
                operation.terminate(false);
            Log.debug("executeOperation executed", className, ctx.getTransactionID());
        }
    }

    @LocalMethod(transactionAttribute =  TransactionAttribute.NOT_SUPPORTED)
    public String generateResponse(Context ctx)  throws Exception 
    {
        Log.debug("Executing generateResponse", className, ctx.getTransactionID());

        Operation operation = null;             
        try
        {
            operation = OSSFactory.newOperation(ctx);
            return operation.generateResponse(null);
        }
        finally
        {
            if(operation != null)
                operation.terminate(false);
            Log.debug("generateResponse executed", className, ctx.getTransactionID());
        }
    }

    @LocalMethod(transactionAttribute =  TransactionAttribute.NOT_SUPPORTED)
    public String generateErrorResponse(Context ctx, Exception exception) 
    {
        Log.debug("Executing generateErrorResponse", className, ctx.getTransactionID());

        Operation operation = null;             

        try
        {
            operation = OSSFactory.newOperation(ctx);
            return operation.generateResponse(exception);
        }
        catch(Exception e)
        {
            Log.exception(e, className, ctx.getTransactionID());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        finally
        {
            if(operation != null)
                operation.terminate(false);
            Log.debug("generateErrorResponse executed", className, ctx.getTransactionID());
        }
    }

//  @LocalMethod()
    @LocalMethod(transactionAttribute =  TransactionAttribute.REQUIRES_NEW)
    public void terminate (Context ctx)
    {
        Log.debug("Executing terminate", className, ctx.getTransactionID());

        Operation operation = null;
        try
        {
            operation = OSSFactory.newOperation(ctx);
            operation.terminate(true);
        }
        catch(Exception e)
        {
            Log.exception(e, className, ctx.getTransactionID());
            e.printStackTrace();
        }
    }
}

But i already put the EJB file to ant task.

Any ideas, help and/or comments?


Answer:

After finding a best solution, there is SOLUTION for this kind of error.

First: verbose your EJBGEN function.

<ejbgen source="1.6" outputDir="${staging.dir}" descriptorDir="ejbModule\META-INF" forceGeneration="true" 
verbose="true"
            ejbSuffix = "."
            localSuffix = "Local"
            localHomeSuffix = "LocalHome">
            <fileset dir="ejbModule/sample/oss/dna/ejb">
                    <contains text="@Session"/>
                    <contains text="@LocalMethod"/>
            </fileset>
</ejbgen>

Then second, change the source from 1.6 to 1.5

In my case, there are another error thrown if i put 1.6 in the source. Exception in thread "main" com.bea.wls.ejbgen.EJBGenException: ejbName is a required attribute

answer this error here how to generate deployment descriptor using ejbGen for weblogic?

Then third, put the -lib parameter in your ant task. This is optional parameter if you not specify libraries that are not in your classpath. example:

ant build -lib ../lib -v > build.log