JAXRS / CXF why is this simple post example not working - cxf

I know my client works as I post to another website and it all works. I changed the client to post to url http://localhost:9000/enrollment/enroll and ran the following server...
#Path("/enrollment")
public class MockHpsRestApi {
private static final Logger log = LoggerFactory.getLogger(MockHpsRestApi.class);
public static void main(final String[] args) throws InterruptedException,
IOException, MuleException {
log.info("starting the server");
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(MockHpsRestApi.class);
sf.setResourceProvider(MockHpsRestApi.class, new SingletonResourceProvider(new MockHpsRestApi()));
sf.setAddress("http://0.0.0.0:9000/");
sf.create();
}
#POST
#Path("/enroll")
#Consumes("application/xml")
public String enrollment(MultipartBody body) throws IOException {
log.info("received request="+body);
Attachment att = body.getRootAttachment();
ByteArrayOutputStream str = new ByteArrayOutputStream(100);
InputStream in = att.getDataHandler().getInputStream();
try {
IOUtils.copy(in, str);
log.info("body payload received="+str);
String xml = "success";
return xml;
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(str);
}
}
}
My logs though say this when it receives the request...
2012-03-16 09:30:30,295 INFO 300 [main] c.i.e.s.i.MockHpsRestApi - starting the server
Mar 16, 2012 9:30:30 AM org.apache.cxf.endpoint.ServerImpl initDestination
INFO: Setting the server's publish address to be http://0.0.0.0:9000/
2012-03-16 09:30:30,769 INFO 774 [main] org.eclipse.jetty.server.Server - jetty-7.5.4.v20111024
2012-03-16 09:30:30,801 INFO 806 [main] o.e.jetty.server.AbstractConnector - Started SelectChannelConnector#0.0.0.0:9000 STARTING
2012-03-16 09:30:30,824 INFO 829 [main] o.e.j.server.handler.ContextHandler - started o.e.j.s.h.ContextHandler{,null}
Mar 16, 2012 9:30:37 AM org.apache.cxf.jaxrs.utils.JAXRSUtils readFromMessageBody
WARNING: No message body reader has been found for request class MultipartBody, ContentType : application/xml.
Mar 16, 2012 9:30:37 AM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: WebApplicationException has been caught : no cause is available
Why isn't this working?
hmmm, turning up the log levels, is this some kind of bug in CXF, though that would mean no one is really doing basic posts, so that doesn't seem right....(again, my client posts fine to another service today).
2012-03-16 09:51:01,414 DEBUG 10916 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Request path is: /enrollment/enroll
2012-03-16 09:51:01,414 DEBUG 10916 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Request HTTP method is: POST
2012-03-16 09:51:01,414 DEBUG 10916 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Request contentType is: application/xml
2012-03-16 09:51:01,415 DEBUG 10917 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Accept contentType is: */*
2012-03-16 09:51:01,415 DEBUG 10917 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Found operation: enrollment
2012-03-16 09:51:01,420 WARN 10922 [qtp669588045-18 - /enrollment/enroll] o.apache.cxf.jaxrs.utils.JAXRSUtils - No message body reader has been found for request class MultipartBody, ContentType : application/xml.
2012-03-16 09:51:01,423 WARN 10925 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.WebApplicationExceptionMapper - WebApplicationException has been caught : no cause is available
2012-03-16 09:51:01,428 DEBUG 10930 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.WebApplicationExceptionMapper - no cause is available
javax.ws.rs.WebApplicationException: null
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1052) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:616) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:580) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:238) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:89) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263) [cxf-api-2.5.2.jar:2.5.2]
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:123) [cxf-rt-core-2.5.2.jar:2.5.2]
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.serviceRequest(JettyHTTPDestination.java:323) [cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:289) [cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:72) [cxf-bundle-2.5.2.jar:2.5.2]
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:943) [jetty-server-7.5.4.v20111024.jar:7.5.4.v20111024]
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:879) [jetty-server-7.5.4.v20111024.jar:7.5.4.v20111024]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117) [jetty-server-7.5.4.v20111024.jar:7.5.4.v20111024]

When using #POST and #Consumes("application/xml"), it's normal for the (single un-annotated) argument type on the method to be a JAXB-annotated class that CXF will deserialize the XML into before handing it to you. Is there a particular reason for not going that well-travelled route?

After debugging the code, it turns out you can use the following types as parameters to the method above.
Source
XMLSource
Document
byte[]
InputStream
I ended up using InputStream.

Related

Apache Camel Azure queue: Message body is empty while sending message

I am trying to send a message to Azure Queue using Apache Camel, route code is:
from("direct:testMessage")
.process(exchange -> {
exchange.getIn().setBody("test message");
})
.to("azure-storage-queue://azureaccount/test-queue?operation=sendMessage");
The code to initiate Azure service client bean is:
#Bean
public QueueServiceClient queueServiceClient() {
StorageSharedKeyCredential credential = new StorageSharedKeyCredential(ACCOUNT, ACCESS_KEY);
return new QueueServiceClientBuilder().endpoint(QUEUE_URL).credential(credential).buildClient();
}
I am getting the below error:
com.azure.storage.queue.models.QueueStorageException: Status code 400, "<?xml version="1.0" encoding="utf-8"?><Error><Code>InvalidXmlDocument</Code><Message>XML specified is not syntactically valid.
RequestId:e3496af3-f003-001a-0d2e-a38636000000
Time:2020-10-15T20:08:26.5431469Z</Message><LineNumber>0</LineNumber><LinePosition>0</LinePosition><Reason /></Error>"
Tried enabling HTTP logs and looks like the Message body is empty:
2020-10-16 01:38:25 INFO c.a.s.q.i.M.enqueue - --> POST https://azureaccount.queue.core.windows.net/blob-backup-queue/messages
53-byte body:
<?xml version='1.0' encoding='UTF-8'?><QueueMessage/>
--> END POST
2020-10-16 01:38:25 INFO c.a.s.q.i.M.enqueue - <-- 400 https://azureaccount.queue.core.windows.net/blob-backup-queue/messages (163 ms, 294-byte body)
Response body:
<?xml version="1.0" encoding="utf-8"?><Error><Code>InvalidXmlDocument</Code><Message>XML specified is not syntactically valid.
RequestId:e3496af3-f003-001a-0d2e-a38636000000
Time:2020-10-15T20:08:26.5431469Z</Message><LineNumber>0</LineNumber><LinePosition>0</LinePosition><Reason /></Error>
<-- END HTTP
Going through the source code of camel-azure component, figured out the right way to send message is as follows:
exchange.getIn().getHeaders().put(QueueConstants.MESSAGE_TEXT, "test message");

com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </span>; expected </br>

I created the stub classes using CXF wsdl2java tool.
I am using Apache CXF library, with JCIFS. I validated the WSDL file itself through couple tools, it is good. Here is the code. It looks like some setting I must do.
//JCIFS Authentication related code
jcifs.Config.setProperty("jcifs.smb.client.domain", "NTS");
jcifs.Config.setProperty("jcifs.netbios.wins", "ecmchat.mark.gov");
jcifs.Config.setProperty("jcifs.smb.client.soTimeout", "300000"); // 5 minutes
jcifs.Config.setProperty("jcifs.netbios.cachePolicy", "1200"); // 20 minutes
jcifs.Config.setProperty("jcifs.smb.client.username", "user");
jcifs.Config.setProperty("jcifs.smb.client.password", "password");
//Register the jcifs URL handler to enable NTLM
jcifs.Config.registerSmbURLHandler();
//WSDL and Client settings
URL wsdlURL = BF.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
BF ss = new BF(wsdlURL, SERVICE_NAME);
BFSoap port = ss.getBFSoap12();
Client client = ClientProxy.getClient(port);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(32000);
http.setClient(httpClientPolicy);
// Calling the method
System.out.println("Invoking testMethod...");
String _testMethod__return = port.testMethod();
System.out.println("testMethod.result=" + _testMethod__return);
I am getting the following exception
Caused by: com.ctc.wstx.exc.WstxParsingException: Unexpected close tag </span>; expected </br>.
at [row,col,system-id]: [59,22,"https://ecmchat.mark.gov/BF/BF.asmx"]
at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.java:621)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:491)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:475)
at com.ctc.wstx.sr.BasicStreamReader.reportWrongEndElem(BasicStreamReader.java:3365)
at com.ctc.wstx.sr.BasicStreamReader.readEndElem(BasicStreamReader.java:3292)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2911)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1123)
at org.apache.cxf.staxutils.StaxUtils.readDocElements(StaxUtils.java:1361)
at org.apache.cxf.staxutils.StaxUtils.readDocElements(StaxUtils.java:1255)
at org.apache.cxf.staxutils.StaxUtils.read(StaxUtils.java:1183)
at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:235)
... 9 more
If I comment out the JCIFS NTLM authentication code, I get a HTTP 401 error. Therefore, I believe, at least it is passing some kind of authorization step.
And, if I use local WSDL in place of remote URL WSDL, then I get a different error like "method not implemented" on the call to the method. May be this is due to me not using the local WSDL correctly. I do not even know if we can use the local WSDL reference for remote service.
Then, I created a SoapUI dummy service with this WSDL, and the same code (but without the JCIFS authentication code) works good, and successfully calls the methods.
It appears to me that I must add some more appropriate settings in the configuration related code.
Am I right, and are you aware of any, for NTLM authentication and Apache CXF?
But parsing error is confusing???
I do not know if this is related.
My original WSDL URL that I gave was this.
https://ecmchat.mark.gov/BF/BF.asmx
I added a ?wsdl like below
https://ecmchat.mark.gov/BF/BF.asmx?wsdl
Then I am getting a different error.
I wonder why it is working if I access my local SoapUI version of the same WSDL service, but not for the remote one.
Invoking testMethod...
Jan 07, 2020 10:47:25 AM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {https://ecmchat.mark.gov}BF#{https://ecmchat.mark.gov}testMethod has thrown exception, unwinding now
java.lang.UnsupportedOperationException: Method not implemented.
at java.net.URLStreamHandler.openConnection(URLStreamHandler.java:96)
at java.net.URL.openConnection(URL.java:1028)
at org.apache.cxf.transport.https.HttpsURLConnectionFactory.createConnection(HttpsURLConnectionFactory.java:92)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.createConnection(URLConnectionHTTPConduit.java:121)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.setupConnection(URLConnectionHTTPConduit.java:125)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:505)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:47)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:530)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:441)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:356)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:314)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:140)
at com.sun.proxy.$Proxy33.testMethod(Unknown Source)
at edison.learn.BFSoap_BFSoap12_Client.main(BFSoap_BFSoap12_Client.java:90)
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Method not implemented.
at org.apache.cxf.jaxws.JaxWsClientProxy.mapException(JaxWsClientProxy.java:195)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:145)
at com.sun.proxy.$Proxy33.testMethod(Unknown Source)
at edison.learn.BFSoap_BFSoap12_Client.main(BFSoap_BFSoap12_Client.java:90)
Caused by: java.lang.UnsupportedOperationException: Method not implemented.
at java.net.URLStreamHandler.openConnection(URLStreamHandler.java:96)
at java.net.URL.openConnection(URL.java:1028)
at org.apache.cxf.transport.https.HttpsURLConnectionFactory.createConnection(HttpsURLConnectionFactory.java:92)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.createConnection(URLConnectionHTTPConduit.java:121)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.setupConnection(URLConnectionHTTPConduit.java:125)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:505)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:47)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:530)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:441)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:356)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:314)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:140)
... 2 more

Apache Camel upload email attachment to ftp

I'm using the following processor to fetch the first attachement of an email and upload it to a ftp-server.
Route configuration
<from uri="imaps://...
<to uri="ejb:java:global/Dms/MailProcessor"/>
<to uri="ftp://....
MailProcessor
#Named("MailProcessor")
#Stateless
public class MailProcessor implements Processor {
#Override
public void process(Exchange exchange) throws Exception {
exchange.getOut().setHeaders(exchange.getIn().getHeaders());
Map<String, DataHandler> attachments = exchange.getIn().getAttachments();
if (attachments.size() > 0) {
for (String name : attachments.keySet()) {
DataHandler dataHandler = attachments.get(name);
// SET ATTACHMENT FILENAME TO OUTPUT FILENAME HEADER
String filename = dataHandler.getName();
filename = MimeUtility.decodeText(filename);
exchange.getOut().setHeader("filename", filename);
// SET INPUT ATTACHMENT TO OUTPUT BODY
byte[] data = exchange.getContext().getTypeConverter().convertTo(byte[].class, dataHandler.getInputStream());
exchange.getOut().setBody(data);
// SET ONLY THE FIRST ATTACHMENT
break;
}
}else{
exchange.getOut().setBody(exchange.getIn().getBody());
}
}
This works in general, but it takes literally forever for "big" attachments. (half an hour for just a 5 mb attachment)
Log
TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) Changing directory: upload
TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) doStoreFile(ID-example-local-59752-1494841993139-21-11)
DEBUG [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) About to store file: ID-example-local-59752-1494841993139-21-11 using stream: com.sun.mail.util.BASE64DecoderStream#601a11dc
TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) Client storeFile: ID-example-local-59752-1494841993139-21-11
-- long pause --
I've also tried to convert the attachment like this:
byte[] data = exchange.getContext().getTypeConverter().convertTo( byte[].class, dataHandler.getInputStream() );
exchange.getOut().setBody(data);
but this gives me the following:
2017-05-15 11:23:20,968 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Converting org.apache.camel.Processor$$$view63 -> org.apache.camel.Processor with value: Proxy for view class: org.apache.camel.Processor of EJB: MailProcessor
2017-05-15 11:23:20,968 TRACE [org.apache.camel.component.bean.BeanProcessor] (Camel (example) thread #133 - imaps://mail.example.com) Using a custom adapter as bean invocation: Proxy for view class: org.apache.camel.Processor of EJB: MailProcessor
2017-05-15 11:23:20,990 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Converting com.sun.mail.util.BASE64DecoderStream -> byte[] with value: com.sun.mail.util.BASE64DecoderStream#28442828
2017-05-15 11:23:20,990 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Using converter: StaticMethodTypeConverter: public static byte[] org.apache.camel.converter.IOConverter.toBytes(java.io.InputStream) throws java.io.IOException to convert [class com.sun.mail.util.BASE64DecoderStream=>class [B]
2017-05-15 11:23:20,990 TRACE [org.apache.camel.util.IOHelper] (Camel (example) thread #133 - imaps://mail.example.com) Copying InputStream: java.io.BufferedInputStream#24b2cffb -> OutputStream: with buffer: 4096 and flush on each write false
-- long pause --
Uploading to the ftp server using Filezilla works like a charm. Also when I use camel-ftp in another route ( triggered by a file upload ) the upload to the ftp server works pretty fast.
So I have a feeling that it's the conversion of the attachment which slows things down.
Questions:
Is my assumption correct and how can I speed things up?
Solution was to use <from uri="imaps://...&mail.imaps.partialfetch=false.
https://community.oracle.com/thread/2604843?start=0&tstart=0

Solrj IOException occured when talking to server

I am using basic authentication. My solr version is 4.1. I can get query results but when I try to index documents I am getting the following error message:
org.apache.solr.client.solrj.SolrServerException: IOException occured when talking to server at: http://192.168.0.1:8983/solr/my_core
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:416)
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:181)
at org.apache.solr.client.solrj.request.AbstractUpdateRequest.process(AbstractUpdateRequest.java:117)
at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:116)
at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:102)
at warningletter.Process.run(Process.java:128)
at warningletter.WarningLetter.parseListPage(WarningLetter.java:81)
at warningletter.WarningLetter.init(WarningLetter.java:47)
at warningletter.WarningLetter.main(WarningLetter.java:21)
Caused by: org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:822)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:353)
... 8 more
Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:625)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:464)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
... 11 more
This is my code piece:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "password"));
HttpSolrServer server = new HttpSolrServer("http://192.168.0.1:8983/solr/warning_letter/", httpclient);
SolrInputDocument solrDoc = new SolrInputDocument();
solrDoc.addField("id", "id1");
solrDoc.addField("letter", "letter");
server.add(solrDoc);
server.commit();
What am I doing wrong?
The trick is to use the preemptive authentication so as to avoid the need to repeat the query after the "unauthorized" response is sent.
Here is the example
Preemptive Basic authentication with Apache HttpClient 4

OpenEJB 4.5.1: NameNotFoundException

Its the first time I used the OpenEJB container system. When I use the lockup-Method of the InitialContext, I get a NameNotFoundException. I've read lots of examples and tutorials and in every example the lookup method looks like:
initialContext.lookup("NameOfBean");
Now I've found another solution which uses the lookup like the following code snippet which works for me too.
initialContext.lookup("java:global/classpath.ear/ProjectName/NameofBean");
The question is why the first version doesn't work for me and what I've done wrong?
Excerpts of the OpenEJB log:
INFO - ********************************************************************************
INFO - OpenEJB http://openejb.apache.org/
INFO - Startup: Sat Dec 22 13:17:59 CET 2012
INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.
INFO - Version: 4.5.1
INFO - Build date: 20121209
INFO - Build time: 08:47
INFO - ********************************************************************************
INFO - openejb.home = D:\workspace\ProjectName
INFO - openejb.base = D:\workspace\ProjectName
INFO - Succeeded in installing singleton service
INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.
INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)
INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)
INFO - Using 'openejb.deployments.classpath.include=.*'
INFO - Found EjbModule in classpath: D:\workspace\ProjectName\build\classes
INFO - Searched 17 classpath urls in 2184 milliseconds. Average 128 milliseconds per url.
INFO - Beginning load: D:\workspace\ProjectName\build\classes
INFO - Configuring enterprise application: D:\workspace\ProjectName\classpath.ear
WARNUNG - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.
INFO - Auto-deploying ejb NameOfBean: EjbDeployment(deployment-id=NameOfBean)
[... AUTHORS'S NOTE: SOME MORE BEANS]
INFO - Assembling app: D:\workspace\ProjectName\classpath.ear
INFO - Hibernate Validator 4.2.0.Final
INFO - Ignoring XML configuration.
JAVA AGENT NOT INSTALLED. The JPA Persistence Provider requested installation of a ClassFileTransformer which requires a JavaAgent. See http://openejb.apache.org/3.0/javaagent.html
INFO - OpenJPA dynamically loaded a validation provider.
INFO - Jndi(name=NameOfBeanRemote) --> Ejb(deployment-id=NameofBean)
INFO - Jndi(name=global/classpath.ear/ProjectName/NameOfBean!de.mypath.stateless.NameOfBeanInterface) --> Ejb(deployment-id=NameofBean)
INFO - Jndi(name=global/classpath.ear/ProjectName/NameofBean) --> Ejb(deployment-id=NameOfBean)
[... AUTHORS'S NOTE: SOME FOR OTHER BEANS]
INFO - OpenWebBeans Container is starting...
INFO - Adding OpenWebBeansPlugin : [CdiPlugin]
INFO - All injection points are validated successfully.
INFO - OpenWebBeans Container has started, it took 250 ms.
INFO - Created Ejb(deployment-id=NameOfBean, ejb-name=NameOfBean, container=Default Stateless Container)
[... AUTHORS'S NOTE: SOME FOR OTHER BEANS]
INFO - Quartz scheduler 'OpenEJB-TimerService-Scheduler' initialized from an externally provided properties instance.
INFO - Quartz scheduler version: 2.1.6
INFO - Scheduler OpenEJB-TimerService-Scheduler_$_OpenEJB started.
INFO - Started Ejb(deployment-id=NameOfBean, ejb-name=NameOfBean, container=Default Stateless Container)
[... AUTHORS'S NOTE: SOME FOR OTHER BEANS]
This is my TestClass:
public class NamerOfBeanOpenEJBTest {
private static InitialContext initialContext;
#BeforeClass
public static void setUp() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
properties.setProperty("openejb.deployments.classpath.include", ".*");
initialContext = new InitialContext(properties);
}
#Test
public void testBean() throws NamingException{
Object object = initialContext.lookup("java:global/classpath.ear/ProjectName/NameOfBean");
assertNotNull(object);
assertTrue(object instanceof NameOfBean);
}
#AfterClass
public static void afterClass() throws Exception {
if (initialContext != null) {
initialContext.close();
}}
}
Does someone have tipps or solutions for me?
Thanks a lot.
Edit:
In JBoss AS 7.1 the lookup can places like this example:
new InitialContext().lookup("ejb:/ProjectName//NameOfBean!de." + "mypath.sessionbean.stateless.NameOfBeanInterface");
Isnt that possible in OpenEJB? Do I have to change every lookup call in every bean to have a local test with OpenEJB? That wouldn't be really effective and time-saving.
Problem solved!
The strukture of the lookup is {deploymentId}{interfaceType.annotationName}. Therefore in my case it must be
initialContext.lookup("NameOfBeanLocal");
or
initialContext.lookup("NameOfBeanRemote");
depending on the type of the interface.
To get the problem with JBoss solved you can switch from default lookup
new InitialContext().lookup("ejb:/ProjectName//NameOfBean!de." + "mypath.sessionbean.stateless.NameOfBeanInterface");
to something more flexible like Dependcy-Lookup or Dependency-Injection and use the #EJB annotation. Both ways are supportet by JBoss and OpenEJB.

Resources