An EJB is in a JAR but is not found by the WAR next to in in an EAR - jboss7.x

I have the structure described below, but I cannot make it so MyWebService has its member myService not null. The code of MyWebService is properly executed when I call the webservice. When I look at the JBoss logs, I keep seeing that MyServiceBean has several JNDI bindings allocated to it.
So how do I bind MyServiceBean to MyWebService?
Thanks!
my-ejb.jar:
#Local
public interface MyServiceBeanLocal {
...
}
#Stateless
public class MyServiceBean implements MyServiceBeanLocal {
...
}
my-web.war:
#Webservice(...)
public class MyWebService {
#EJB
MyServiceBeanLocal myService;
...
}
my-ear.ear:
* my-ear.ear
|-* my-web.war
|-* my-ejb.jar

Have you tried using MyServiceBeanLocal as a Remote interface ? You are trying to use dependency injection from a Web module and for a Local Interface .This is not actually suggested. Anyway, At first try to make the interface #Remote . If still it doesn't work try to use`Remote Look up from the Web module for your Remote interface link

I use CXF. CXF is not an EJB container, hence the issues I got.
I had to manually bind the EJBs, using their full name.

Related

start application (from jar) on Weblogic startup

I'm using Weblogic 12c, I need to run app before/with the web app starts.
the app should fetch information and write it to db.
I read that in previous versions of WL programmers used to work with ApplicationLifecycleListener, but it is deprecated now.
I'm compiling the project to ear file.
I also tried to use ejb3.2 eager singleton, but it didn't worked.
Is there any working alternative?
I solved the issue by creating EJB as the following:
#Singleton
#Startup
public class StartupBean {
#PostConstruct
private void startup() { ... }
#PreDestroy
private void shutdown() { ... }
...
}
Creating the EJB Singleton instances is one of the Weblogic life cycle init calls, I put my java code under startup() method.

#inject does not work with stateless EJB

Hi I have a very simple example. I created a resource in javaee 7 as follows:
#Path("greetings")
public class GreetingsResource {
#Inject
Sample s;
#GET
public JsonObject greetings(){
return Json.createObjectBuilder().add("first","1")
.add("second","2")
.add("third","3")
.add("fourth","4")
.add("helloworld", s.helloWorld())
.build();
}
}
Sample is the following simple EJB:
#Stateless
public class Sample {
public String helloWorld(){
return "Hello World";
}
}
Finally the resource Application class:
#ApplicationPath("resources")
public class RestConfiguration extends Application {
}
I can access the URL: "localhost:8081/jasonandjaxrs/resources/greetings"
The problem is that #Inject gives the following error:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=sample,parent=GreetingsResource,qualifiers={}),position=-1,optional=false
But #EJB seems to work. I am trying to understand why #Inject does not work? Thank you.
You can't use CDI (means #Inject) with this setup. CDI only works with beans managed by the container which is not the case for JAX-RS resource classes (your GreetingsResource).
JAX-RS 2.0 does not support injection of EJBs into JAX-RS components
(providers, resources).
If you use #Inject in your case the injection is provided by the HK2 dependency injection framework which isn't aware of normal CDI beans. It even shouldn't work if you use #EJB, I don't know why it works, maybe this has to do with Java EE 7.
As it works for you there should be no problem in using #EJB here, but there are also some alternative approaches in my response to this question.
See also:
Inject a EJB into JAX-RS (RESTfull service)
JERSEY-2040 Add support for injection of EJBs into Jersey-managed providers and resources

EJB Injection failure on deploy

I've got a problem exxh EJB's.
First of all, my setup: I am using GlassFish & JEE6. I have got a REST-Service packaged as a WAR and a bean packaged as an EJB-Jar. They are not inside an EAR.
The EJB should be used from the REST-WAR via #EJB, but when I try to deploy the WAR, GlassFish shows this error:
Error occurred during deployment:
Exception while deploying the app [exx-upload-1.0] : Cannot resolve reference Local ejb-ref name=com.ex.exx.model.FileUpload/ocr,Local 3.x interface =com.ex.exx.api.IOCRService,ejb-link=null,lookup=,mappedName=,jndi-name=,refType=Session. Please see server.log for more details.
(The EJB was deployed before without any erros).
I have no clue why. Here is the EJB Code:
Interface:
#Local
public interface IOCRService {
public String performOCRonImage(BufferedImage input);
}
and Implementation:
#Stateless
#LocalBean
public class OCRScanner implements IOCRService {
private Logger logger = Logger.getLogger(this.getClass().getName());
private final static String NOT_RECOGNIZED = "Can not regocnize text";
/**
* Default constructor.
*/
public OCRScanner() {
logger.log(Level.INFO, "### OCR SCANNER BUILD" + this);
}
public String performOCRonImage(BufferedImage input) {
logger.log(Level.INFO, "### OCR SCANNER CALLED" + this);
}
...
And here is the important part in the WAR:
public class FileUpload {
private final File PROPERTIES_FILE = new File(
"fileUploadProperties.properties");
private final String PARAMETER_NAME = "file";
private final Logger logger = Logger.getLogger(this.getClass().getName());
#EJB
private IOCRService ocr;
public Response uploadFile(...) {
// do some stuff
logger.log(Level.INFO, "### EJB" + ocr.toString())
}
Anny suggestions? I can not find my failure here.
Solved this, by replaceing #Local with #Remote.
This works, however, I am not satisfied as I do not understand why.
Basically, given the specs (eg. explained in the tutorial), an application can only access other application's EJB, if they are decorated with #Remote.
Thus, you have 3 options:
decorate your EJB with #Remote (what you have done),
package both together inside an ear (as they would reside in the
same application then). But if you intent to deploy them in seperate
applications or even seperate servers, use 1.)
use CDI with #Inject, but this will still only discover the EJB if
either in the same application, or decorated as #Remote if not.
HTH,
Alex
You should not use #EJB if the target is not an EJB. I guess this is your case because you are trying to inject into a class in your WAR.
Instead use:
#Inject
private IOCRService ocr;
Basically, #Inject is better in most cases, because:
it is more typesafe,
it supports #Alternatives
it is aware of the scope of the injected object.
Another solution it's to add #Stateless(name=""), this worked form

How to share fluent configuration in a Castle Windsor IOC container

I am trying to create an IOC container in Castle Windsor that's configuration is shared across assemblies.
(What follows is an example of how this works in Unity. What I want to do is to make it work the same way using Castle Windsor)
I have the following project configuration...
TestCompany.Services.Host
(Web project hosting a number of .svc files)
PrintService.svc
Web.Config
Unity.Config
TestCompany.Services.PrintService
IPrintService.cs
PrintService.cs
The actual implementation of my "PrintService" is not implemented inside my Services.Host but in the TestCompany.Services.PrintService assembly.
As part of my shared project code (not shown) I have a container helper which is responsible for loading the unity configuration...
public static IUnityContainer GetContainer()
{
// Checks for existance of container (_container == null) ommitted.
var section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
section.Configure(_container, name);
...
...
}
This method loads the unity configuration section from the Unity.Config and uses it to configure the container.
The advantage of this method is that one Unity.Config loaded inside (I presume) the AppDomain can service a number of assemblies. Simply calling GetContainer() from any of the assemblies consumed by my service host will return a container populated with the same type resolution's etc.
I really want to use the fluent configuration in Castle Windsor but I dont see how without this "shared" configuration file that can be acheived. PrintService and any future services will all need to resolve the same dependencies and I dont want to have to repeat my fluent configuration between these services.
Ideally I need some sort of container configured in the service host app that can "flow" into all of the assemblies that it makes use of.
Thanks.
I think I may not be understanding your question but I think I understand your scenario and here is how I do something similar, if it helps at all...
My Philosophy:
Each part of the application should be in charge of registering what
it knows about and nothing more, so there is no need for a single
central configuration file and things that are shared between
components are registered in one place and their interfaces are
available everywhere via a common library.
So let's take an example...
First of all, let us just say (for the purposes of my example) that IPrintService is something that you want to register an implementation of once and use throughout the application and that we have some other component that needs to be implemented by some external module from the main application. We, therefore, create an assembly called Common like so:
Common
public interface IPrintService
{
void Print();
}
public interface IMyService
{
void DoSomething();
}
Now let us think about the main part of the application (maybe it is an ASP .NET application, maybe justa console application, does not really matter). Here we construct the container and ask it to find all the possible components. We can do that like so:
Main Application
// Could be the Global.asax code behind but for simplicity this is
// just a console application
class Program
{
private static readonly IWindsorContainer Mycontainer
= BootstrapContainer();
// Allow access to the raw container - this is probably a bad idea but
// in the rare case that you need it you can get it from here
public static IWindsorContainer Container { get { return Mycontainer; } }
private static IWindsorContainer BootstrapContainer()
{
// Here we will just install every IWindsorInstaller found in any
// assembly in the same folder as the application (so no need for
// references or anything).
var c = new WindsorContainer();
string folder = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
c.Install(FromAssembly.InDirectory(new AssemblyFilter(folder)));
return c;
}
}
// Here is the print service implementation
public class MyPrintService : IPrintService
{
public void Print()
{
// Print!
}
}
// This is the installer for the main module - here we are saying exactly
// what is implementing the interface
public class MainApplicationInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container,
IConfigurationStore store)
{
container
.Register(Component
.For<IPrintService>()
.ImplementedBy<MyPrintService>());
}
}
So now we have a common library with our shared inetrfaces and a main application that will register an implementation for our shared interface and also load up any other modules in the system.
The only thing, therefore, left to do is to consume that print service and use it. We can do this anywhere that is using the container so let's create a third assembly that references only Common (we will call it test module.
Test Module
// This installer installs just the things inside this module since that
// is all it knows about but those things can use things that are
// registered in the container by anybody.
public class TestModuleInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container,
IConfigurationStore store)
{
container
.Register(Component
.For<IMyService>()
.ImplementedBy<MyServiceThatDoesSomething>());
}
}
public class MyServiceThatDoesSomething : IMyService
{
private readonly IPrintService _printService;
public MyServiceThatDoesSomething(IPrintService printService)
{
_printService = printService;
}
public void DoSomething()
{
// Use the print service!
_printService.Print();
}
}
Finally compile everything and copy the test module to the same folder as the main application and then from the main you can do this:
Container.Resolve<IMyService>().DoSomething();
And then the magic happens! Well, some code runs and you find that the print service is called by the class from the module even though it knows nothing about it.
Anyway, maybe that helps a little bit, maybe not, good luck!

Getting Microsoft test framework to use Spring.Net to create test classes

I have a project using .Net 4.0, VS 2010 and Spring 1.3. Before and after each of my Integration tests run, I want to be able setup and clean up some data for the test. I was thinking of using custom attributes to do this.
[TestClass]
public class UnitTest1
{
[TestMethod]
[PreTestSqlExecute(SqlScript="SetUpDataForMethod1.sql")]
public virtual void TestMethod1()
{
.
To do this, I have created the custom attribute and the Around Method Interceptor
public class PreTestSqlExecuteAdvice : IMethodInterceptor
{
public object Invoke(IMethodInvocation invocation)
{
.
Basically, the problem now is how to get the Test framework in Microsoft to use Spring to create the "UnitTest1" class rather than creating a concrete class directly. For example, I can use a dummy console app with appropriate configuration to do something like this
static void Main(string[] args)
{
IApplicationContext ctx = ContextRegistry.GetContext();
var ut = (UnitTest1)ctx["mySqlTest"];
ut.TestMethod1();
This works fine. But when I run the tests directly using visual studio and clicking "Run All Tests In Solution" for example, it does not call the interceptor and execute the before and after code, just goes directly to the test method.
I have tried using AttributeAutoProxyCreator in the config as shown below
<object type="Spring.Aop.Framework.AutoProxy.AttributeAutoProxyCreator, Spring.Aop">
<property name="AttributeTypes" value="SpringTests.ClassInstanceAttribute"/>
<!-- Interceptor names can be either of the type IAdvice, IAdvisor, or IAdvisors -->
<property name="InterceptorNames" value="aroundAdvisor"/>
</object>
with the appropriate attribute on the class
[TestClass]
[ClassInstance]
public class UnitTest1
{
or inheriting from the AbstractDependencyInjectionSpringContextTests
public class UnitTest1 : AbstractDependencyInjectionSpringContextTests
But none of these seems to work. My method interceptor is not being called. So how do I get the Microsoft test framework in Visual Studio to either use spring context to create the Test Classes. Or alternately, get Spring to intercept the concrete constructions of these test classes and inject the Proxy class instead.
Thanks in advance for the help.
Found my own solution, as detailed here - http://www.chaitanyaonline.net/2011/09/25/improving-integration-tests-in-net-by-using-attributes-to-execute-sql-scripts/
Basically I inherit my unit tests from "ContextBoundObjects", this lets me inject my own code and do AOP like stuff. I created my own custom attributes so that I can run the pre and post processing Sql scripts.