Java: JNDI Lookup fails when ran inside a Thread - java

I'm facing a rather strange behaviour regarding JNDI lookup using Wildfly 18. I have one simple EJB:
package com.getronics.ejb;
import javax.ejb.Remote;
import javax.ejb.Local;
import javax.ejb.Stateless;
#Stateless
#Local(ICalculadoraLocal.class)
public class CalculadoraBean implements ICalculadoraLocal {
public int suma(int a, int b){
return a+b;
}
}
With a simple interface:
package com.getronics.ejb;
public interface ICalculadoraLocal{
int suma(int a, int b);
}
And a simple JSP page to check it out:
<html>
<body>
<%# page import="java.util.Hashtable,javax.naming.*,com.getronics.ejb.*" %>
request: <%= request.getRequestURI()%><br>
<%
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES,"org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
ICalculadoraLocal calculadora = (ICalculadoraLocal)context.lookup("java:app/ejb-0.0.0.0.0.1/CalculadoraBean!com.getronics.ejb.ICalculadoraLocal");
int suma = calculadora.suma(2,2);
%>
context: <%= context%></br>
2+2= <%=suma%>
</body>
</html>
This works fine:
request: /ejb/index.jsp
context: javax.naming.InitialContext#3e532295
2+2= 4
However, when I try to use a Thread, like this:
<html>
<body>
<%# page import="java.util.Hashtable,javax.naming.*,com.getronics.ejb.*" %>
request: <%= request.getRequestURI()%><br>
<%
new Thread() {
public void run() {
try {
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES,"org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
ICalculadoraLocal calculadora = (ICalculadoraLocal)context.lookup("java:app/ejb-0.0.0.0.0.1/CalculadoraBean!com.getronics.ejb.ICalculadoraLocal");
int suma = calculadora.suma(2,2);
System.out.println("suma: " + suma);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
%>
</body>
</html>
It throws a NameNotFoundException:
javax.naming.NameNotFoundException: java:app/ejb-0.0.0.0.0.1/CalculadoraBean!com.getronics.ejb.ICalculadoraLocal
Any ideas on why can this happen?

It seems that using "global" instead of "app" makes it work:
ICalculadoraLocal calculadora = (ICalculadoraLocal)context.lookup("java:global/ear-0.0.0.0.0.1/ejb-0.0.0.0.0.1/CalculadoraBean!com.getronics.ejb.ICalculadoraLocal");
The reason seems to be that JNDI lookup of "app", "module" and "comp" won't work in those threads as for specification.
You can check these links for more info:
jndi lookup fails in user-thread
[jboss-as7-dev] Issue with access to java:comp/UserTransaction from non EE threads

Related

JSP/Java/HTML | JSP out.println(); prints to console when in method

I'm working a dynamic website with jsp.
Now my problem: when I use <%, to write my java, everything works perfectly fine.
<%
out.println("<p>test</p>");
%>
But when i use the <%! like this:
<%!
private void test() {
out.println("<p>test</p>");
}
%>
My output will get displayed in my code editors console and not on my website as expected.
As import I used <%# page import="static java.lang.System.out" %>. Is this the correct import or is the problem somewhere else?
If more information is needed please comment! :)
As you probably know, JSPs are turned into servlets on-the-fly by the Java EE container. In a <% ... %> block, out is a local variable in the generated _jspService (or similar) method in the generated servlet. It's a JspWriter for writing to the output for the page.
In a <%! ... %> block, you're outside that generated _jspService (or similar) method, and so your static import means your out reference is to System.out, which isn't where the page output should be sent.
If you want to define methods in your JSP in <%! ... %> blocks, you'll have to pass out into them:
<%!
private void test(JspWriter out) throws IOException {
out.println("<p>test</p>");
}
%>
About that JSP -> servlet thing, say we have this JSP:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<%
out.println("The current date/time is " + new java.util.Date());
this.test(out, "Hi, Mom!");
%>
<%!
private void test(JspWriter out, String msg) throws java.io.IOException {
out.println(msg);
}
%>
</body>
</html>
Note that it has a <%...%> block and a <%! ... %> block.
The Java EE container turns that into something somewhat like the following. Note where our test method ended up, and where the code in our <%...%> block ended up (along with our raw JSP text/markup):
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class test_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private void test(JspWriter out, String msg) throws java.io.IOException {
out.println(msg);
}
/* ...lots of setup stuff omitted... */
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<!doctype html>\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<meta charset=\"utf-8\">\n");
out.write("<title>Example</title>\n");
out.write("</head>\n");
out.write("<body>\n");
out.println("The current date/time is " + new java.util.Date());
this.test(out, "Hi, Mom!");
out.write("\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else log(t.getMessage(), t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}

How to retrieve Arraylist object in javascript/jsp?

I am developing one sample web application using JSP and Servlets, in this application i have set some object in the Servlets, i can retrieve that value in JSP by using request.getAttribute("Object"). Here i want to iterate that array of value in JSP. How can i achieve this any one help me.
My servlet code:
ArrayList<Performer> Performerobj=new ArrayList<Performer>();
ResultSet rst = stm1.executeQuery("some query");
while (rst.next())
{
Performer obj=new Performer();
obj.setProject(projectname);
obj.setCount(rst.getString("COUNT"));
obj.setDate(rst.getString("DATE"));
obj.setEmpid(rst.getString("empid"));
Performerobj.add(obj);
}
request.setAttribute("Performer", Performerobj);
Performer.java
public class Performer {
private String project;
private String empid;
private String date;
private String count;
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
/*setter and getter...... for all*/
Perform.jsp
<% List<Performer>obj1=List<Performer>)request.getAttribute("Performerobj"); %>
<script>
var obj=<%=obj1%>
for(obj object : list)
{
/*IS it correct way or how can i iterate*/
}
</script>
You can do that if you transform the ArrayList object into a JSON using a library like Jackson:
<% List<Performer>obj1 = (List<Performer>) request.getAttribute("Performerobj"); %>
<script>
var obj=<%=new ObjectMapper().writeValueAsString(obj1)%>;
for(obj object : list)
{
/*IS it correct way or how can i iterate*/
}
</script>
Another option is to use JSTL:
<c:forEach var="performer" items="${Performerobj}">
<c:out value="${performer.project}"/>
</c:forEach>

use deployJava.js to call java methods in javascript

I want to call java methods in javascript and Andrew Thompson suggested to use the deployJava.js library for this. I followed these instructions:
http://docs.oracle.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html
Here is explained how to use the java class in javascript, but I would like to call the java methods from within the javascript. (This is because I want to import a .owl file in java en export the information in json-format to my code written in javascript.)
Does anybody know how to do this with the deployJava library?
This is my code to import the java file:
<noscript>A browser with JavaScript enabled is required for this page to operate properly.</noscript>
<h1>Sending Messages to Other Applets</h1>
<script>
function sendMsgToIncrementCounter() {
receiver.incrementCounter();
}
</script>
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'Sender.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'../Receiver.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
and this is are the sender and receiver java files:
import javax.swing.*;
public class Receiver extends JApplet {
private int ctr = 0;
private JLabel ctrLbl = null;
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
ctrLbl = new JLabel("");
add(ctrLbl);
}
});
} catch (Exception e) {
System.err.println("Could not create applet's GUI");
}
}
public void incrementCounter() {
ctr++;
String text = " Current Value Of Counter: " + (new Integer(ctr)).toString();
ctrLbl.setText(text);
}
}
import javax.swing.*;
import java.awt.event.;
import netscape.javascript.;
public class Sender extends JApplet implements ActionListener {
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
final ActionListener al = this;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JButton btn = new JButton("Click To Increment Counter");
add(btn);
btn.addActionListener(al);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
public void actionPerformed(ActionEvent e) {
try {
JSObject window = JSObject.getWindow(this);
window.eval("sendMsgToIncrementCounter()");
} catch (JSException jse) {
jse.printStackTrace();
}
}
}
I just copy-paste this from the example given on this site:
http://docs.oracle.com/javase/tutorial/deployment/applet/iac.html
This example works perfect in my browser, so the way it is done is correct, but I suspect that I don't import the javafiles correct, since this are the errors from je java-console:
load: class Sender.class not found.
java.lang.ClassNotFoundException: Sender.class
at sun.plugin2.applet.Applet2ClassLoader.findClass(Applet2ClassLoader.java:195)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:249)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:179)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:160)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Plugin2ClassLoader.java:690)
at sun.plugin2.applet.Plugin2Manager.createApplet(Plugin2Manager.java:3045)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Plugin2Manager.java:1497)
at java.lang.Thread.run(Thread.java:680)
Exception: java.lang.ClassNotFoundException: Sender.class
Combining your original method, with the new JS snippet, and part of the accepted answer on your last question (tweaked), gives..
<html>
<head>
<script>
// dangerous to have a 0x0 applet! Some security plug-ins regard it
// as suspicious & automatically remove the element. Better to set it
// not visible using styles
var attributes = {
codebase:'../sesame',
code:'applet_test',
width:10,
height:10
};
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
function test() {
var app = document.applet_test;
alert("Screen Dimension\r\n width:" + app.getScreenWidth()
+ " height:" + app.getScreenHeight());
}
</script>
<body>
<FORM>
<INPUT
type="button"
value="call JAVA"
onClick = "test()">
</FORM>
<script>
deployJava.runApplet(attributes, parameters, version);
</script>
</body>
</html>
But I just wrote that up off the top of my head. Don't trust me, trust a validation service. ;)
I would advise setting up a simple webservice that your javascript code can use. It doesn't need to be very involved, personally I'd use a simple REST layout with JAX-RS (jersey is really nice to work with), especially if you want something simple with JSON support built-in (with the right plugin).
Trying to actually communicate with the applet on the page might be possible, but very browser dependent and IMHO not worth the hassle. If you're working on the web, might as well use a web service.
There was a problem with the directory of the .class files given in the attributes. Here is the correct code:
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'sesame/Sender.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'sesame/Receiver.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>

Can't get resource files in my template files (using Restlet and Freemarker)

I'm trying to develop a webapp with Restlet and I have a little problem for access to my /public/css/* and /public/js/*.
I have messages like this in the console :
INFO: 2012-03-10 23:52:59 127.0.0.1 - - 8182 GET /public/css/bootstrap-responsive.min.css - 404 439 0 0 http://localhost:8182 Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Ubuntu/11.10 Chromium/17.0.963.65 Chrome/17.0.963.65 Safari/535.11 http://localhost:8182/hello
I currently only have a HelloWorld using a HTML template :
public class RestletServerTest extends ServerResource {
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
component.getDefaultHost().attach("/hello", new HelloWorldApplication());
component.start();
}
}
public class HelloWorldApplication extends Application {
private Configuration configuration;
#Override
public synchronized Restlet createInboundRoot() {
configuration = new Configuration();
try {
configuration.setDirectoryForTemplateLoading(new File("src/main/webapp/WEB-INF/template"));
configuration.setObjectWrapper(new BeansWrapper());
} catch (IOException e) {
e.printStackTrace();
}
Router router = new Router(getContext());
router.attach("", HelloWorldResource.class);
return router;
}
public Configuration getConfiguration() {
return configuration;
}
}
public class HelloWorldResource extends ServerResource {
#Get
public Representation get() {
TemplateRepresentation templateRepresentation = new TemplateRepresentation("hello.ftl", getApplication()
.getConfiguration(), MediaType.TEXT_HTML);
return templateRepresentation;
}
#Override
public HelloWorldApplication getApplication() {
return (HelloWorldApplication) super.getApplication();
}
}
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="/public/css/bootstrap-responsive.min.css" />
<link rel="stylesheet" href="/public/css/bootstrap.min.css" />
<script type="text/javascript" src="/public/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
CSS and JS files are in "/src/main/webapp/public" folder.
I forgot something?
Thank you.
Florian.
Perhaps can you try to use one of following classes: ClassTemplateLoader or WebappTemplateLoader.
For example, you can the ClassTemplateLoader class as described below:
Configuration configuration = new Configuration();
configuration.setTemplateLoader(
new ClassTemplateLoader(ClassInTheClasspath.class,
"/rootpath/under/classpath/");
configuration.setObjectWrapper(new DefaultObjectWrapper());
(...)
This allows finding your templates in the classpath under the path /rootpath/under/classpath/. In this context, the first / is the root of your classpath.
Hope it helps you.
Thierry
I found the solution :
#Override
public synchronized Restlet createInboundRoot() {
Directory directory = new Directory(getContext(), LocalReference.createFileReference("/home/florian/dev/wkspace/myproject/src/main/webapp/public"));
directory.setListingAllowed(true);
Router router = new Router(getContext());
router.attachDefault(new HomeApplication());
router.attach("/static", directory);
router.attach("/hello", new HelloWorldApplication());
return router;
}
But I would like to make a relative path.
I prefere to use relative path instead of absolute FileReference. This is used in the method represent(), which return the representation of that resource:
Representation indexFtl = new ClientResource(LocalReference.createClapReference(getClass().getPackage()) + "/templates/index.ftl.html").get();
fixing
733 firstDotIndex = fullEntryName.indexOf('.');
to
733 firstDotIndex = fullEntryName.lastIndexOf('.');
in DirectoryServerResource did the job for me.

JSP Custom Taglib: Nested Evaluation

Say I have my custom taglib:
<%# taglib uri="http://foo.bar/mytaglib" prefix="mytaglib"%>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<mytaglib:doSomething>
Test
</mytaglib:doSomething>
Inside the taglib class I need to process a template and tell the JSP to re-evaluate its output, so for example if I have this:
public class MyTaglib extends SimpleTagSupport {
#Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("<c:out value=\"My enclosed tag\"/>");
getJspBody().invoke(null);
}
}
The output I have is:
<c:out value="My enclosed tag"/>
Test
When I actually need to output this:
My enclosed tag
Test
Is this feasible? How?
Thanks.
Tiago, I do not know how to solve your exact problem but you can interpret the JSP code from a file. Just create a RequestDispatcher and include the JSP:
public int doStartTag() throws JspException {
ServletRequest request = pageContext.getRequest();
ServletResponse response = pageContext.getResponse();
RequestDispatcher disp = request.getRequestDispatcher("/test.jsp");
try {
disp.include(request, response);
} catch (ServletException e) {
throw new JspException(e);
} catch (IOException e) {
throw new JspException(e);
}
return super.doStartTag();
}
I tested this code in a Liferay portlet, but I believe it should work in other contexts anyway. If it don't, I would like to know :)
HTH
what you really need to have is this:
<mytaglib:doSomething>
<c:out value="My enclosed tag"/>
Test
</mytaglib:doSomething>
and change your doTag to something like this
#Override public void doTag() throws JspException, IOException {
try {
BodyContent bc = getBodyContent();
String body = bc.getString();
// do something to the body here.
JspWriter out = bc.getEnclosingWriter();
if(body != null) {
out.print(buff.toString());
}
} catch(IOException ioe) {
throw new JspException("Error: "+ioe.getMessage());
}
}
make sure the jsp body content is set to jsp in the tld:
<bodycontent>JSP</bodycontent>
Why do you write a JSTL tag inside your doTag method?
The println is directly going into the compiled JSP (read: servlet) When this gets rendered in the browser it will be printed as it is since teh browser doesn't understand JSTL tags.
public class MyTaglib extends SimpleTagSupport {
#Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("My enclosed tag");
getJspBody().invoke(null);
}
}
You can optionally add HTML tags to the string.

Categories