Req.getParameter Security
If you are using req.getParameter() in a servlet to gather data from a form... What methods could you use to guarantee that the data is coming from that form and not a malicious user who is typing the parameters in the url (ie. www.something.com/servletname?importantparameter=something)
Sorry for the double post... First time using this and I can't figure out how to delete.
Set the method of your form to POST and override the doPost(...) method in your Servlet. This by no means guarantees security per se.
Similar Messages
-
Req.getParameter("codiop") hangs
I have developed a web site that has thousands of visits a day (and thousands of invocations to servlet).
My problem is, sometimes it hangs (and so, I have to restart tomcat). It hangs in a syncrhonized method, call by doPost.
The place inside the syncronized method it hangs is the next:
String elCodiOp = req.getParameter("codiop");
I have both System.out.prinln before and after this statement and another in the catch(Exception e), but only the first System.out is executed, but the second ones are never executed (restart time!).
It happens once or twice a week, with the same invocations, with the same parameters it usually works.
Has anyone experienced the same problem? Is it normal getParameter() hangs?The problem sounds like the way in which you are synchronizing rather than with getParameter().
If your doPost() code looks like this...
public void doPost(HttpServletRequest request,...) {
accessSharedResource(request);
And you have a method in the servlet like this...
public synchronized void accessSharedResource(HttpServletRequest request) {
System.out.println("here1");
String c = request.getParameter("codi");
// do something
System.out.println("here2");
You can rewrite the method like this...
public void accessSharedResource(HttpServletRequest request) {
synchronized(this) {
System.out.println("here1");
String c = request.getParameter("codi");
// do something
System.out.println("here2");
Your putting a lock on the whole servlet, preventing it from reading any more input. This is the hanging.
The quickest way to fix this is to remove the 'synchronized' and have the servlet implement the SingleThreadedModel interface.
Another way is to use a lock dedicated to the shared resource.
Object sharedResourceLock = new Object();
public void accessSharedResource(HttpServletRequest request)
synchronized(sharedResourceLock) {
System.out.println("here1");
String code = request.getParameter("code");
System.out.println("here2");
Or better yet, leave the request object alone (HttpServletRequest) and just pass in the parameters.
public void doPost(...) {
String code = request.getParameter(code);
accessSharedResoruce(code);
I hope this helps. -
How can i deal with java.security.AccessControlException?
Hi all, I need to implement JavaMail using Servlet and deploy throught J2EE deployment tool. But when i test out the servlet i will always encounter this exception thrown. How can i solve this?
java.security.AccessControlException: access denied (java.util.PropertyPermission * read,write)
This is the servlet i am testing. Please advise. Thanks in advance!
* @(#)JavaMailServlet.java 1.3 99/12/06
* Copyright 1998, 1999 Sun Microsystems, Inc. All Rights Reserved.
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
import java.io.*;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
* This is a servlet that demonstrates the use of JavaMail APIs
* in a 3-tier application. It allows the user to login to an
* IMAP store, list all the messages in the INBOX folder, view
* selected messages, compose and send a message, and logout.
* <p>
* Please note: This is NOT an example of how to write servlets!
* This is simply to show that JavaMail can be used in a servlet.
* <p>
* For more information on this servlet, see the
* JavaMailServlet.README.txt file.
* <p>
* For more information on servlets, see
* * http://java.sun.com/products/java-server/servlets/index.html
* @author Max Spivak
public class JavaMailServlet extends HttpServlet implements SingleThreadModel {
String protocol = "POP3";
String mbox = "INBOX";
* This method handles the "POST" submission from two forms: the
* login form and the message compose form. The login form has the
* following parameters: <code>hostname</code>, <code>username</code>,
* and <code>password</code>. The <code>send</code> parameter denotes
* that the method is processing the compose form submission.
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// get the session
HttpSession ssn = req.getSession(true);
String send = req.getParameter("send");
String host = req.getParameter("hostname");
String user = req.getParameter("username");
String passwd = req.getParameter("password");
URLName url = new URLName(protocol, host, -1, mbox, user, passwd);
ServletOutputStream out = res.getOutputStream();
res.setContentType("text/html");
out.println("<html><body bgcolor=\"#CCCCFF\">");
if (send != null) {
// process message sending
send(req, res, out, ssn);
} else {
// initial login
// create
MailUserData mud = new MailUserData(url);
ssn.putValue("javamailservlet", mud);
try {
Properties props = System.getProperties();
System.out.println("url");
props.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
Store store = session.getStore(url);
store.connect();
Folder folder = store.getDefaultFolder();
if (folder == null)
throw new MessagingException("No default folder");
folder = folder.getFolder(mbox);
if (folder == null)
throw new MessagingException("Invalid folder");
folder.open(Folder.READ_WRITE);
int totalMessages = folder.getMessageCount();
Message[] msgs = folder.getMessages();
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
// track who logged in
System.out.println("Login from: " + store.getURLName());
// save stuff into MUD
mud.setSession(session);
mud.setStore(store);
mud.setFolder(folder);
// splash
out.print("<center>");
out.print("<font face=\"Arial,Helvetica\" font size=+3>");
out.println("<b>Welcome to JavaMail!</b></font></center><p>");
// folder table
out.println("<table width=\"50%\" border=0 align=center>");
// folder name column header
out.print("<tr><td width=\"75%\" bgcolor=\"#ffffcc\">");
out.print("<font face=\"Arial,Helvetica\" font size=-1>");
out.println("<b>FolderName</b></font></td><br>");
// msg count column header
out.print("<td width=\"25%\" bgcolor=\"#ffffcc\">");
out.print("<font face=\"Arial,Helvetica\" font size=-1>");
out.println("<b>Messages</b></font></td><br>");
out.println("</tr>");
// folder name
out.print("<tr><td width=\"75%\" bgcolor=\"#ffffff\">");
out.print("<a href=\"" + HttpUtils.getRequestURL(req) + "\">" +
"Inbox" + "</a></td><br>");
// msg count
out.println("<td width=\"25%\" bgcolor=\"#ffffff\">" +
totalMessages + "</td>");
out.println("</tr>");
out.println("</table");
} catch (Exception ex) {
out.println(ex.toString());
} finally {
out.println("</body></html>");
out.close();
* This method handles the GET requests for the client.
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession ses = req.getSession(false); // before we write to out
ServletOutputStream out = res.getOutputStream();
MailUserData mud = getMUD(ses);
if (mud == null) {
res.setContentType("text/html");
out.println("<html><body>Please Login (no session)</body></html>");
out.close();
return;
if (!mud.getStore().isConnected()) {
res.setContentType("text/html");
out.println("<html><body>Not Connected To Store</body></html>");
out.close();
return;
// mux that takes a GET request, based on parameters figures
// out what it should do, and routes it to the
// appropriate method
// get url parameters
String msgStr = req.getParameter("message");
String logout = req.getParameter("logout");
String compose = req.getParameter("compose");
String part = req.getParameter("part");
int msgNum = -1;
int partNum = -1;
// process url params
if (msgStr != null) {
// operate on message "msgStr"
msgNum = Integer.parseInt(msgStr);
if (part == null) {
// display message "msgStr"
res.setContentType("text/html");
displayMessage(mud, req, out, msgNum);
} else if (part != null) {
// display part "part" in message "msgStr"
partNum = Integer.parseInt(part);
displayPart(mud, msgNum, partNum, out, res);
} else if (compose != null) {
// display compose form
compose(mud, res, out);
} else if (logout != null) {
// process logout
try {
mud.getFolder().close(false);
mud.getStore().close();
ses.invalidate();
out.println("<html><body>Logged out OK</body></html>");
} catch (MessagingException mex) {
out.println(mex.toString());
} else {
// display headers
displayHeaders(mud, req, out);
/* main method to display messages */
private void displayMessage(MailUserData mud, HttpServletRequest req,
ServletOutputStream out, int msgNum)
throws IOException {
out.println("<html>");
out.println("<HEAD><TITLE>JavaMail Servlet</TITLE></HEAD>");
out.println("<BODY bgcolor=\"#ccccff\">");
out.print("<center><font face=\"Arial,Helvetica\" ");
out.println("font size=\"+3\"><b>");
out.println("Message " + (msgNum+1) + " in folder " +
mud.getStore().getURLName() +
"/INBOX</b></font></center><p>");
try {
Message msg = mud.getFolder().getMessage(msgNum);
// first, display this message's headers
displayMessageHeaders(mud, msg, out);
// and now, handle the content
Object o = msg.getContent();
//if (o instanceof String) {
if (msg.isMimeType("text/plain")) {
out.println("<pre>");
out.println((String)o);
out.println("</pre>");
//} else if (o instanceof Multipart){
} else if (msg.isMimeType("multipart/*")) {
Multipart mp = (Multipart)o;
int cnt = mp.getCount();
for (int i = 0; i < cnt; i++) {
displayPart(mud, msgNum, mp.getBodyPart(i), i, req, out);
} else {
out.println(msg.getContentType());
} catch (MessagingException mex) {
out.println(mex.toString());
out.println("</BODY></html>");
out.close();
* This method displays a message part. <code>text/plain</code>
* content parts are displayed inline. For all other parts,
* a URL is generated and displayed; clicking on the URL
* brings up the part in a separate page.
private void displayPart(MailUserData mud, int msgNum, Part part,
int partNum, HttpServletRequest req,
ServletOutputStream out)
throws IOException {
if (partNum != 0)
out.println("<p><hr>");
try {
String sct = part.getContentType();
if (sct == null) {
out.println("invalid part");
return;
ContentType ct = new ContentType(sct);
if (partNum != 0)
out.println("<b>Attachment Type:</b> " +
ct.getBaseType() + "<br>");
if (ct.match("text/plain")) {
// display text/plain inline
out.println("<pre>");
out.println((String)part.getContent());
out.println("</pre>");
} else {
// generate a url for this part
String s;
if ((s = part.getFileName()) != null)
out.println("<b>Filename:</b> " + s + "<br>");
s = null;
if ((s = part.getDescription()) != null)
out.println("<b>Description:</b> " + s + "<br>");
out.println("<a href=\"" +
HttpUtils.getRequestURL(req) +
"?message=" +
msgNum + "&part=" +
partNum + "\">Display Attachment</a>");
} catch (MessagingException mex) {
out.println(mex.toString());
* This method gets the stream from for a given msg part and
* pushes it out to the browser with the correct content type.
* Used to display attachments and relies on the browser's
* content handling capabilities.
private void displayPart(MailUserData mud, int msgNum,
int partNum, ServletOutputStream out,
HttpServletResponse res)
throws IOException {
Part part = null;
try {
Message msg = mud.getFolder().getMessage(msgNum);
Multipart mp = (Multipart)msg.getContent();
part = mp.getBodyPart(partNum);
String sct = part.getContentType();
if (sct == null) {
out.println("invalid part");
return;
ContentType ct = new ContentType(sct);
res.setContentType(ct.getBaseType());
InputStream is = part.getInputStream();
int i;
while ((i = is.read()) != -1)
out.write(i);
out.flush();
out.close();
} catch (MessagingException mex) {
out.println(mex.toString());
* This is a utility message that pretty-prints the message
* headers for message that is being displayed.
private void displayMessageHeaders(MailUserData mud, Message msg,
ServletOutputStream out)
throws IOException {
try {
out.println("<b>Date:</b> " + msg.getSentDate() + "<br>");
Address[] fr = msg.getFrom();
if (fr != null) {
boolean tf = true;
out.print("<b>From:</b> ");
for (int i = 0; i < fr.length; i++) {
out.print(((tf) ? " " : ", ") + getDisplayAddress(fr));
tf = false;
out.println("<br>");
Address[] to = msg.getRecipients(Message.RecipientType.TO);
if (to != null) {
boolean tf = true;
out.print("<b>To:</b> ");
for (int i = 0; i < to.length; i++) {
out.print(((tf) ? " " : ", ") + getDisplayAddress(to[i]));
tf = false;
out.println("<br>");
Address[] cc = msg.getRecipients(Message.RecipientType.CC);
if (cc != null) {
boolean cf = true;
out.print("<b>CC:</b> ");
for (int i = 0; i < cc.length; i++) {
out.print(((cf) ? " " : ", ") + getDisplayAddress(cc[i]));
cf = false;
out.println("<br>");
out.print("<b>Subject:</b> " +
((msg.getSubject() !=null) ? msg.getSubject() : "") +
"<br>");
} catch (MessagingException mex) {
out.println(msg.toString());
* This method displays the URL's for the available commands and the
* INBOX headerlist
private void displayHeaders(MailUserData mud,
HttpServletRequest req,
ServletOutputStream out)
throws IOException {
SimpleDateFormat df = new SimpleDateFormat("EE M/d/yy");
out.println("<html>");
out.println("<HEAD><TITLE>JavaMail Servlet</TITLE></HEAD>");
out.println("<BODY bgcolor=\"#ccccff\"><hr>");
out.print("<center><font face=\"Arial,Helvetica\" font size=\"+3\">");
out.println("<b>Folder " + mud.getStore().getURLName() +
"/INBOX</b></font></center><p>");
// URL's for the commands that are available
out.println("<font face=\"Arial,Helvetica\" font size=\"+3\"><b>");
out.println("<a href=\"" +
HttpUtils.getRequestURL(req) +
"?logout=true\">Logout</a>");
out.println("<a href=\"" +
HttpUtils.getRequestURL(req) +
"?compose=true\" target=\"compose\">Compose</a>");
out.println("</b></font>");
out.println("<hr>");
// List headers in a table
out.print("<table cellpadding=1 cellspacing=1 "); // table
out.println("width=\"100%\" border=1>"); // settings
// sender column header
out.println("<tr><td width=\"25%\" bgcolor=\"ffffcc\">");
out.println("<font face=\"Arial,Helvetica\" font size=\"+1\">");
out.println("<b>Sender</b></font></td>");
// date column header
out.println("<td width=\"15%\" bgcolor=\"ffffcc\">");
out.println("<font face=\"Arial,Helvetica\" font size=\"+1\">");
out.println("<b>Date</b></font></td>");
// subject column header
out.println("<td bgcolor=\"ffffcc\">");
out.println("<font face=\"Arial,Helvetica\" font size=\"+1\">");
out.println("<b>Subject</b></font></td></tr>");
try {
Folder f = mud.getFolder();
int msgCount = f.getMessageCount();
Message m = null;
// for each message, show its headers
for (int i = 1; i <= msgCount; i++) {
m = f.getMessage(i);
// if message has the DELETED flag set, don't display it
if (m.isSet(Flags.Flag.DELETED))
continue;
// from
out.println("<tr valigh=middle>");
out.print("<td width=\"25%\" bgcolor=\"ffffff\">");
out.println("<font face=\"Arial,Helvetica\">" +
((m.getFrom() != null) ?
m.getFrom()[0].toString() :
"" ) +
"</font></td>");
// date
out.print("<td nowrap width=\"15%\" bgcolor=\"ffffff\">");
out.println("<font face=\"Arial,Helvetica\">" +
df.format((m.getSentDate()!=null) ?
m.getSentDate() : m.getReceivedDate()) +
"</font></td>");
// subject & link
out.print("<td bgcolor=\"ffffff\">");
out.println("<font face=\"Arial,Helvetica\">" +
"<a href=\"" +
HttpUtils.getRequestURL(req) +
"?message=" +
i + "\">" +
((m.getSubject() != null) ?
m.getSubject() :
"<i>No Subject</i>") +
"</a>" +
"</font></td>");
out.println("</tr>");
} catch (MessagingException mex) {
out.println("<tr><td>" + mex.toString() + "</td></tr>");
mex.printStackTrace();
out.println("</table>");
out.println("</BODY></html>");
out.flush();
out.close();
* This method handles the request when the user hits the
* <i>Compose</i> link. It send the compose form to the browser.
private void compose(MailUserData mud, HttpServletResponse res,
ServletOutputStream out)
throws IOException {
res.setContentType("text/html");
out.println(composeForm);
out.close();
* This method processes the send request from the compose form
private void send(HttpServletRequest req, HttpServletResponse res,
ServletOutputStream out, HttpSession ssn)
throws IOException {
String to = req.getParameter("to");
String cc = req.getParameter("cc");
String subj = req.getParameter("subject");
String text = req.getParameter("text");
try {
MailUserData mud = getMUD(ssn);
if (mud == null)
throw new Exception("trying to send, but not logged in");
Message msg = new MimeMessage(mud.getSession());
InternetAddress[] toAddrs = null, ccAddrs = null;
if (to != null) {
toAddrs = InternetAddress.parse(to, false);
msg.setRecipients(Message.RecipientType.TO, toAddrs);
} else
throw new MessagingException("No \"To\" address specified");
if (cc != null) {
ccAddrs = InternetAddress.parse(cc, false);
msg.setRecipients(Message.RecipientType.CC, ccAddrs);
if (subj != null)
msg.setSubject(subj);
URLName u = mud.getURLName();
msg.setFrom(new InternetAddress(u.getUsername() + "@" +
u.getHost()));
if (text != null)
msg.setText(text);
Transport.send(msg);
out.println("<h1>Message sent successfully</h1></body></html>");
out.close();
} catch (Exception mex) {
out.println("<h1>Error sending message.</h1>");
out.println(mex.toString());
out.println("<br></body></html>");
// utility method; returns a string suitable for msg header display
private String getDisplayAddress(Address a) {
String pers = null;
String addr = null;
if (a instanceof InternetAddress &&
((pers = ((InternetAddress)a).getPersonal()) != null)) {
addr = pers + " "+"<"+((InternetAddress)a).getAddress()+">";
} else
addr = a.toString();
return addr;
// utility method; retrieve the MailUserData
// from the HttpSession and return it
private MailUserData getMUD(HttpSession ses) throws IOException {
MailUserData mud = null;
if (ses == null) {
return null;
} else {
if ((mud = (MailUserData)ses.getValue("javamailservlet")) == null){
return null;
return mud;
public String getServletInfo() {
return "A mail reader servlet";
* This is the HTML code for the compose form. Another option would
* have been to use a separate html page.
private static String composeForm = "<HTML><HEAD><TITLE>JavaMail Compose</TITLE></HEAD><BODY BGCOLOR=\"#CCCCFF\"><FORM ACTION=\"/servlet/JavaMailServlet\" METHOD=\"POST\"><input type=\"hidden\" name=\"send\" value=\"send\"><P ALIGN=\"CENTER\"><B><FONT SIZE=\"4\" FACE=\"Verdana, Arial, Helvetica\">JavaMail Compose Message</FONT></B><P><TABLE BORDER=\"0\" WIDTH=\"100%\"><TR><TD WIDTH=\"16%\" HEIGHT=\"22\"> <P ALIGN=\"RIGHT\"><B><FONT FACE=\"Verdana, Arial, Helvetica\">To:</FONT></B></TD><TD WIDTH=\"84%\" HEIGHT=\"22\"><INPUT TYPE=\"TEXT\" NAME=\"to\" SIZE=\"30\"> <FONT SIZE=\"1\" FACE=\"Verdana, Arial, Helvetica\"> (separate addresses with commas)</FONT></TD></TR><TR><TD WIDTH=\"16%\"><P ALIGN=\"RIGHT\"><B><FONT FACE=\"Verdana, Arial, Helvetica\">CC:</FONT></B></TD><TD WIDTH=\"84%\"><INPUT TYPE=\"TEXT\" NAME=\"cc\" SIZE=\"30\"> <FONT SIZE=\"1\" FACE=\"Verdana, Arial, Helvetica\"> (separate addresses with commas)</FONT></TD></TR><TR><TD WIDTH=\"16%\"><P ALIGN=\"RIGHT\"><B><FONT FACE=\"Verdana, Arial, Helvetica\">Subject:</FONT></B></TD><TD WIDTH=\"84%\"><INPUT TYPE=\"TEXT\" NAME=\"subject\" SIZE=\"55\"></TD></TR><TR><TD WIDTH=\"16%\"> </TD><TD WIDTH=\"84%\"><TEXTAREA NAME=\"text\" ROWS=\"15\" COLS=\"53\"></TEXTAREA></TD></TR><TR><TD WIDTH=\"16%\" HEIGHT=\"32\"> </TD><TD WIDTH=\"84%\" HEIGHT=\"32\"><INPUT TYPE=\"SUBMIT\" NAME=\"Send\" VALUE=\"Send\"><INPUT TYPE=\"RESET\" NAME=\"Reset\" VALUE=\"Reset\"></TD></TR></TABLE></FORM></BODY></HTML>";
* This class is used to store session data for each user's session. It
* is stored in the HttpSession.
class MailUserData {
URLName url;
Session session;
Store store;
Folder folder;
public MailUserData(URLName urlname) {
url = urlname;
public URLName getURLName() {
return url;
public Session getSession() {
return session;
public void setSession(Session s) {
session = s;
public Store getStore() {
return store;
public void setStore(Store s) {
store = s;
public Folder getFolder() {
return folder;
public void setFolder(Folder f) {
folder = f;You posted a thousand lines of badly-formatted code and didn't have the sense to say which one had the exception.
My guess is that it was this one:Session session = Session.getDefaultInstance(props, null);because that happened to me. I fixed it by calling getInstance instead of getDefaultInstance.
However if that isn't the problem, how about spending a few seconds to post a less useless question? -
JMS Wrappers can't cache JNDI lookups when using secured queues
Hi All!
We are working on a jms client, inside a webapp(servlets), using Weblogic 9.2 and Weblogic 10.3.
As we want to use secured queues and keep being efficient we tryed to use Weblogic JMS Wrappers, that should work according to the docs:
Enhanced Support for Using WebLogic JMS with EJBs and Servlets
http://download.oracle.com/docs/cd/E12840_01/wls/docs103/jms/j2ee.html
But we are facing a problem:
When we define a JMS Wrapper and try to cache JNDI lookups for the QueueConnectionFactory and Queue, as the docs recommend for efficiency, the connection to the queue is ignoring the user/pwd.
The JMS Wrapper is using <res-auth>Application</res-auth>.
We are creating the connection using createQueueConnection(user, pwd) from QueueConnectionFactory and after several tests it seems that the user and password are ingored unless a jndi lookup is made in the same thread, as if when there are not any thread credentials present user and password are ignored for the connection...
so the question is:
That behaviour goes against Weblogic JMS Wrapper documentation, doesn't it?
Is there then any other way to access efficiently secured queues using a servlet as a client? (iit's not an option for us to use mdbs, or ejbs).
If it helps, this seems related to this still opened spring-weblogic issue: SPR-2941 --> http://jira.springframework.org/browse/SPR-2941 and SPR-4720 --> http://jira.springframework.org/browse/SPR-4720
Thanxs
And here goes our DDs and code to reproduce:
First in pretty format:
web.xml --> http://pastebin.com/f5f85e8d4
weblogic.xml --> http://pastebin.com/f2fbe10cc
Client code --> http://pastebin.com/f586d32d9
And now emmebded in the msg:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app
xmlns="http://www.bea.com/ns/weblogic/90"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/90
http://www.bea.com/ns/weblogic/90/weblogic-web-app.xsd">
<description>WebLogic Descriptor</description>
<resource-description>
<res-ref-name>jms/QCF</res-ref-name>
<jndi-name>weblogic.jms.ConnectionFactory</jndi-name>
</resource-description>
</weblogic-web-app>weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name> QCFWrapperCredentialsTest </display-name>
<description> QCFWrapperCredentialsTest </description>
<servlet id="Servlet_1">
<servlet-name>QCFWrapperCredentialsTest</servlet-name>
<servlet-class>QCFWrapperCredentialsTest</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping id="ServletMapping_1">
<servlet-name>QCFWrapperCredentialsTest</servlet-name>
<url-pattern>/Test</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>jms/QCF</res-ref-name>
<res-type>javax.jms.QueueConnectionFactory</res-type>
<res-auth>Application</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</web-app>And our test client:
import java.io.*;
import java.util.Properties;
import javax.jms.*;
import javax.naming.*;
import javax.servlet.http.*;
public class QCFWrapperCredentialsTest extends HttpServlet {
QueueConnectionFactory factory = null;
Queue queue = null;
String jndiName = "java:comp/env/jms/QCF";
String queueName= "jms/ColaEntradaConsultas";
String user = "usuarioColas";
String pwd = "12345678";
String userjndi = "usuarioColas";
String pwdjndi = "12345678";
String serverT3URL="t3://127.0.0.1:7007";
public void init() {
setupJNDIResources();
private void setupJNDIResources(){
try {
Properties props = new Properties();
props.put("java.naming.factory.initial",
"weblogic.jndi.WLInitialContextFactory");
props.put("java.naming.provider.url",serverT3URL );
props.put("java.naming.security.principal", userjndi);// usr
props.put("java.naming.security.credentials", pwdjndi);// pwd
InitialContext ic = new InitialContext(props);
factory = (QueueConnectionFactory) ic.lookup(jndiName);
queue = (Queue) ic.lookup(queueName);
} catch (NamingException e) {
e.printStackTrace();
public void service(HttpServletRequest req, HttpServletResponse res) {
res.setContentType("text/html");
Writer wr = null;
try {
wr = res.getWriter();
//Comment this out, do a lookup for each request and it will work
//setupJNDIResources();
String user = this.user;
String pwd = this.pwd;
//read users and passwords from the request in case they are present
if (req.getParameter("user") != null) {
user = req.getParameter("user");
if (req.getParameter("pwd") != null) {
pwd = req.getParameter("pwd");
wr.write("JNDI User: *" + userjndi + "* y pwd: *" + pwdjndi + "*<p>");
wr.write("Queue User: *" + user + "* y pwd: *" + pwd + "*<p>");
//Obtain a connection using user/pwd
QueueConnection conn = factory.createQueueConnection(user, pwd);
QueueSession ses = conn.createQueueSession(true,
Session.SESSION_TRANSACTED);
QueueSender sender = ses.createSender(queue);
TextMessage msg = ses.createTextMessage();
msg.setText("Hi there!");
conn.start();
sender.send(msg);
ses.commit();
sender.close();
ses.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
try {
wr.write(e.toString());
} catch (Exception e2) {
e2.printStackTrace();
finally{
try {
wr.close();
} catch (IOException e) {
e.printStackTrace();
}Edited by: user2525402 on Feb 9, 2010 7:14 PMThanks Tom,
Quite a useful response .-)
Leaving aside the fact that weblogic behaviour with jms wrappers and secured queues seems to not be working as the docs says...
Talking about workarounds:
Both workarounds you suggest works, but as you already noted, creating a new JNDI context just to inject credentials into the threads is overkill when high performance is needed.
I also found more information about the same issue here: http://sleeplessinslc.blogspot.com/2009/04/weblogic-jms-standalone-multi-threaded.html
And he suggest the same workaround, injecting credentials
So I tried the second approach, successfully, injecting credentials into the thread using the security API.
This way, using JMS wrappers and injecting credentials into the thread we get the best performance available, caching resource using wrappers and using credentials in a somewhat efficient way.
Now the test snippet looks like this:
import java.io.*;
import java.security.PrivilegedAction;
import java.util.Properties;
import javax.jms.*;
import javax.naming.*;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginException;
import javax.servlet.http.*;
import weblogic.jndi.Environment;
import weblogic.security.auth.Authenticate;
public class JMSWrapperCredentialsTest extends HttpServlet {
QueueConnectionFactory factory = null;
Queue queue = null;
String jndiName = "java:comp/env/jms/QCF";
String queueName= "jms/ColaEntradaConsultas";
String user = "usuarioColas";
String pwd = "12345678";
String userjndi = "usuarioColas";
String pwdjndi = "12345678";
String serverT3URL="t3://127.0.0.1:7007";
public void init() {
setupJNDIResources();
private void setupJNDIResources(){
try {
Properties props = new Properties();
props.put("java.naming.factory.initial",
"weblogic.jndi.WLInitialContextFactory");
props.put("java.naming.provider.url",serverT3URL );
props.put("java.naming.security.principal", userjndi);// usr
props.put("java.naming.security.credentials", pwdjndi);// pwd
InitialContext ic = new InitialContext(props);
factory = (QueueConnectionFactory) ic.lookup(jndiName);
queue = (Queue) ic.lookup(queueName);
} catch (NamingException e) {
e.printStackTrace();
public void service(HttpServletRequest req, HttpServletResponse res) {
final HttpServletRequest fReq=req;
final HttpServletResponse fRes=res;
PrivilegedAction action = new java.security.PrivilegedAction() {
public java.lang.Object run() {
performRequest(fReq,fRes);
return null;
try {
Subject subject=createSingleSubject(serverT3URL,user,pwd);
weblogic.security.Security.runAs(subject, action);
} catch (Exception e) {
e.printStackTrace();
public void performRequest(HttpServletRequest req, HttpServletResponse res) {
res.setContentType("text/html");
Writer wr = null;
try {
wr = res.getWriter();
//Comment this out, do a lookup for each request and it will work
//setupJNDIResources();
String user = this.user;
String pwd = this.pwd;
//read users and passwords from the request in case they are present
if (req.getParameter("user") != null) {
user = req.getParameter("user");
if (req.getParameter("pwd") != null) {
pwd = req.getParameter("pwd");
wr.write("JNDI User: *" + userjndi + "* y pwd: *" + pwdjndi + "*<p>");
wr.write("Queue User: *" + user + "* y pwd: *" + pwd + "*<p>");
//Obtain a connection using user/pwd
QueueConnection conn = factory.createQueueConnection(user, pwd);
QueueSession ses = conn.createQueueSession(true,
Session.SESSION_TRANSACTED);
QueueSender sender = ses.createSender(queue);
TextMessage msg = ses.createTextMessage();
msg.setText("Hi there!");
conn.start();
sender.send(msg);
ses.commit();
sender.close();
ses.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
try {
wr.write(e.toString());
} catch (Exception e2) {
e2.printStackTrace();
finally{
try {
wr.close();
} catch (IOException e) {
e.printStackTrace();
private Subject createSingleSubject(String providerUrl, String userName, String password) {
Subject subject = new Subject();
// Weblogic env class
Environment env = new Environment();
if(providerUrl!=null)
env.setProviderUrl(providerUrl);
env.setSecurityPrincipal(userName);
env.setSecurityCredentials(password);
try {
// Weblogic Authenticate class will populate and Seal the subject
Authenticate.authenticate(env, subject);
return subject;
catch (LoginException e) {
throw new RuntimeException("Unable to Authenticate User", e);
catch (Exception e) {
throw new RuntimeException("Error authenticating user", e);
}Thanks a lot for the help -
GetParameter, setAttribute and session values
I am having a problem forwarding values to a jsp from my servlet.
This problem only occurs when multiple users are accessing the same pages to make a payment.
The value is passed from the page to the servlet.
The servlet gets the value using a getParameter.
//Get the value from the previous page
String DocTotal = request.getParameter("DocTotal");
logger.debug("DocTotal: " + DocTotal);
//set the value to pass to next page
request.setAttribute("payAmount", DocTotal);
displayTemplate(CREDITCARDPAYMENT);
displayTemplate code follows.
RequestDispatcher rd = getServletContext().getRequestDispatcher(template);
rd.forward(req, res);
I then set the value in the request object to pass to the next page.
This all seems to work fine for a single user but when I I have more than one user, one user will get a null for value being passed on the next page and the other user will not get the page displayed.
It is like my session values are getting stomped on by the other user.The changes that you have suggested seem to work, but I still have a problem.
One user seems to be able to get the data passed successfully to the next jsp, but the other just gets a blank screen. If the user with the blank screen refreshes they get the screen with the data. It is as if the servlet hangs up when calling the page. I am not sure.
Here is the code that is being accessed with formatting.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
req = request;
res = response;
HttpSession session = req.getSession(true);
logger.debug("Made it to the doPost method of DownloadUtilServlet!");
logger.debug("session: " + session);
String cmd = req.getParameter("cmd");
logger.debug("cmd equals: " + cmd);
if ((cmd != null) && cmd.equalsIgnoreCase("forwardPaymentInfo")){
XCBillerCenterItem bci = null;
try{
logger.debug("XCConfig.CCUSER: " + XCConfig.CCUSER);
bci = new XCBillerCenterItem(XCConfig.CCUSER);
catch(Exception e) {
logger.debug("XCBillerCenterItem Create: " + e);
String ccList = bci.getCCTypes();
req.setAttribute("ccList", ccList);
logger.debug("cmd equals: " + cmd);
String DocTotal = req.getParameter("DocTotal");
logger.debug("DocTotal: " + DocTotal);
req.setAttribute("payAmount", DocTotal);
displayTemplate(CREDITCARDPAYMENT);
}//User has paid, proceed to download
else if ((cmd != null) && cmd.equalsIgnoreCase("downloadreportfilter")){
displayTemplate(DOWNLOADREPORTFILTER);
else{
GetParameters(req, res, session);
public void displayTemplate(String template)
try
RequestDispatcher rd = getServletContext().getRequestDispatcher(template);
rd.forward(req, res);
catch(Exception e)
e.printStackTrace(); -
Why does getParameter("uri") returns null ???
Hi !
JAVA can be rather frustrating and I have run of of dukes. How about IOU ?
Unfortunately none of the previous questions in the db shed light on my problem.
I am trying to get at the "uri" and I have the following code fragment :
package com.developer;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class proptest extends HttpServlet
public void doGet( HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
PrintWriter out = resp.getWriter();
out.println("Parameter Name: " + req.getParameter("uri"));
public void init() throws ServletException
// initialie the servlet here. Use ServletConfig object to get
// initialization parameters...
ServletConfig config = getServletConfig();
// ... more stuff ...
}Hi!
In case anyone stumbles upon this in the database, I worked aroung it by using req.getRequestURI().
However I still do not know why getParameter() returns null. It would be useful e.g. if you want to display a list of all request params e.g.:
// stub code follows...
java.util.Enumeration enum = rea.getParameterNames();
while (enum.hasMoreElements())
String name = (String) enum.nextElement();
System.out.println("Parameter "+name + " " + req.getParameter(name))
...For me, nope, all nulls. If it works for you , do tell me.
Also if you look at the "bugs db" there seems to be a number of issues concerning getParameter(). -
Trying to call Jasper iReport through portlet & getting error
Hi,
I have written the following code which is linked to a button in my portlet.
package com.ext.portlet.drpdwn.action;
import com.liferay.portal.struts.PortletAction;
import com.liferay.portal.util.Constants;
import javax.portlet.WindowState;
import javax.servlet.jsp.PageContext;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.sql.*;
import javax.portlet.PortletException;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.engine.export.*;
public class QualityReportAction extends PortletAction
public void processAction(ActionMapping mapping, ActionForm form,PortletConfig config,ActionRequest req, ActionResponse res)
throws Exception
String typeofreport_val = req.getParameter("types_of_reports").trim();
System.out.println("Report Name is:" +typeofreport_val);
JasperReport jasperReport;
JasperPrint jasperPrint;
JasperDesign jasperDesign;
Connection connection = null;
if ( null == typeofreport_val || "".equals("typeofreport_val"))
setForward(req,"portlet.ext.drpdwn.error");
else
try
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://10.10.33.39:5432/globus_db?user=postgres&password=marines@123";
connection = DriverManager.getConnection(url);
// load JasperDesign from XML and compile it into JasperReport
jasperDesign = JRXmlLoader.load("C:/testRep/CCQR.jrxml");
jasperReport = JasperCompileManager.compileReport(jasperDesign);
// fill JasperPrint using fillReport() method
jasperPrint = JasperFillManager.fillReport(jasperReport,null,connection);
JasperExportManager.exportReportToPdfFile(jasperPrint,"C:/testRep/ccqr.pdf");
catch (SQLException ex)
setForward(req,"portlet.ext.drpdwn.error");
System.out.println("-------------------------------------------");
while (ex != null)
ex.printStackTrace();
ex = ex.getNextException();
System.out.println("-------------------------------------------");
catch(Exception e)
System.out.println("-------------------------------------------");
System.out.println("Exception is --> "+e);
System.out.println("-------------------------------------------");
setForward(req,"portlet.ext.drpdwn.success");
public ActionForward render(ActionMapping mapping,ActionForm form,PortletConfig config, RenderRequest req,RenderResponse res) throws Exception
if (getForward(req) != null && !getForward(req).equals(""))
return mapping.findForward(getForward(req));
else
return
mapping.findForward("portlet.ext.drpdwn.view");
}When I try to run this code I get the following error:
exception javax.servlet.ServletException: Servlet execution threw an exception
com.liferay.filters.secure.SecureFilter.doFilter(SecureFilter.java:144)
com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter.doFilter(VirtualHostFilter.java:136)
com.liferay.portal.servlet.FriendlyURLServlet.service(FriendlyURLServlet.java:126)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
com.liferay.filters.strip.StripFilter.doFilter(StripFilter.java:95)
com.liferay.filters.secure.SecureFilter.doFilter(SecureFilter.java:144)
com.liferay.filters.compression.CompressionFilter.doFilter(CompressionFilter.java:116)
com.liferay.filters.doubleclick.DoubleClickFilter.doFilter(DoubleClickFilter.java:138)
com.liferay.portal.servlet.filters.layoutcache.LayoutCacheFilter.doFilter(LayoutCacheFilter.java:170)
com.liferay.portal.servlet.filters.autologin.AutoLoginFilter.doFilter(AutoLoginFilter.java:106)
com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter.doFilter(VirtualHostFilter.java:136)
root cause java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/xml/JRXmlLoader com.ext.portlet.drpdwn.action.QualityReportAction.processAction(QualityReportAction.java:59)I have the following necessary files in my class path:
itext-1.3.1.jar
iReport.jar
commons-logging-1.0.2.jar
commons-javaflow-20060411.jar
commons-digester-1.7.jar
commons-collections-2.1.jar
commons-beanutils-1.7.jar
jasperreports-2.0.2.jar
jdt-compiler-3.1.1.jar
log4j-1.2.15.jar
xercesImpl.jar Please suggest me where I am going wrong.
Thanks & Regards
Saurabh.
Edited by: Saurabh.J on Nov 27, 2007 2:33 PMDisable your anti-virus, install the update, turn you anti-virus back on
-
How to Use Weblogic6.1 JAAS Sample in Servlet???
Hi there,
I am now developing JAAS security service based on weblogic. Here is the problem I met with:
1. There is no problem when invoking JAAS sample from application.
But Subject.doAs() is denied when moving the application to servlet.
2. It is said that when invoking JAAS from servlet,
an authenticated subject will be returned using:
Subject subjectTest = loginContext.getSubject();
How can I store the subject into the session and be called later?
3. getUserPrincipal(), isUserInRole() are two important
methods in authenticaion on web services.
How is the user principal and role stored in the session?
4. Where can I find some tutorials on invoking JAAS service from servlet?
Thanks.
============================================================
This is my source code
package examples.security.jaas;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.io.*;
import java.util.*;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.TextInputCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.AccountExpiredException;
import javax.security.auth.login.CredentialExpiredException;
public class SampleServlet extends HttpServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
doPost(req, res);
System.out.println("1\n");
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
HttpSession session = req.getSession(true);
res.setContentType("text/html");
PrintWriter out = res.getWriter();
System.out.println("2\n");
String username = req.getParameter("username");
String password = req.getParameter("password");
String url = req.getParameter("url");
LoginContext loginContext = null;
Context ctx = null;
try
// Set server url for SampleLoginModule
Properties property = new Properties(System.getProperties());
property.put("weblogic.security.jaas.ServerURL", "http://localhost:7001");
System.setProperties(property);
property = new Properties(System.getProperties());
property.put("weblogic.security.SSL.ignoredHostnameVerification", "TRUE");
System.setProperties(property);
// Set configuration class name to load SampleConfiguration
property = new Properties(System.getProperties());
property.put("weblogic.security.jaas.Configuration", "examples.security.jaas.SampleConfig");
System.setProperties(property);
// Set configuration file name to load sample configuration policy file
property = new Properties(System.getProperties());
property.put("weblogic.security.jaas.Policy", "Sample.policy");
System.setProperties(property);
// Create LoginContext; specify username/password login module
loginContext = new LoginContext("SamplePolicy", new MyCallbackHandler());
catch(SecurityException se)
se.printStackTrace();
System.exit(-1);
catch(LoginException le)
le.printStackTrace();
System.exit(-1);
System.out.println("SampleServlet:" + username + "\n");
// Attempt authentication
try
// If we return without an exception, authentication succeeded
loginContext.login();
catch(FailedLoginException fle)
out.println("Authentication Failed, " + fle.getMessage());
System.exit(-1);
catch(AccountExpiredException aee)
out.println("Authentication Failed: Account Expired");
System.exit(-1);
catch(CredentialExpiredException cee)
out.println("Authentication Failed: Credentials Expired");
System.exit(-1);
catch(Exception e)
out.println("Authentication Failed: Unexpected Exception, " + e.getMessage());
e.printStackTrace();
System.exit(-1);
// Retrieve authenticated subject, perform SampleAction as Subject
out.println("Authentication succeeded " );
System.out.println("===============start to trace333\n");
Subject subject = loginContext.getSubject();
System.out.println("Subject:"+subject.toString()+"\n");
System.out.println("Subject.getclass:" + subject.getClass().getName());
SampleAction sampleAction = new SampleAction();
Subject.doAs(subject, sampleAction);
System.out.println("4\n");
// System.exit(0);
========================================================
void doPost(
HttpServletRequest req,
HttpServletResponse resp) {
Principal p =
req.getUserPrincipal();
auditCall(p.getName());
if (req.isUserInRole(
"ManagersRole")) {
// Do some Manager stuff
} else if
(ctx.isUserInRole(
"SalesRole")) {
// Do some Sales stuff
I'll describe where JAAS fits in to the web app model but please note that some of this should be automatically handled by your Servlet container.
Servlet engine (or your MVC servlet controller) receives a request for a protected resource.
It then checks for the existence of an "authenticated" token in the HttpSession.
If that token doesn't exist then it forwards the user to the login page.
The user fills in the form, and the login servlet receives the username and password at which point the JAAS Login Module is called with two callback objects: one that returns the username and one that returns the password.
The JAAS Module checks to see if the credentials are valid, if not, it throws an authentication exception.
Once control is returned to the Login Servlet, the Login Servlet would add the authenticated "Subject" to the HttpSession and if necessary, an authentication "token".
So, JAAS is really only called ONCE, not for every web request, and it's called
by the "logical" Login Servlet AFTER the user submits their login information.
JAAS is not used to check for whether the user is authenticated already or not.
the weblogic 6.1 server side exception
username: joeuser
password: joepass
<May 25, 2002 11:05:20 PM PDT> <Error> <HTTP> <[WebAppServletContext(2169486,exa
mplesWebApp,/examplesWebApp)] Servlet failed with Exception
java.lang.SecurityException: Attempting Privileged Action With Unauthenticated S
ubject
at javax.security.auth.Subject.doAs(Subject.java:74)
at examples.security.jaas.SampleClient.startWeb(SampleClient.java:200)
at jsp_servlet.__poc1._jspService(__poc1.java:92)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
pl.java:265)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
pl.java:200)
at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
rvletContext.java:2495)
at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
pl.java:2204)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
>If anyone of you, has got any answers related to the above mentioned problem, Post it here, Will folks from SUN respond to this at any time.
Regards
Jayendran -
Problem calling a method in a servlet witch returns remote ejb
Hi, I have a problem combining servlets ands ejbs, I expose my problem :
What I have :
1 . I have a User table into a SGBD with two attributes login and pass.
2 . I have a UserBean linked to User table with a remote interface
3 . I have a stateless UserSessionBean with a remote interface
4 . I have a UserServlet linked to a jsp page which allows me to add users
5 . I use Jboss
What is working ?
1 - I have a method newUser implemented in my UserSessionBean :
public class UserSessionBean implements SessionBean {
private SessionContext sessionContext;
private UserRemoteHome userRemoteHome;
public void ejbCreate() throws CreateException {
// Initialize UserRemoteHome
// Method to add a new user
public UserRemote newUser(String login, String password) {
UserRemote newUser = null;
try {
newUser = userRemoteHome.create(login, password);
} catch (RemoteException ex) {
System.err.println("Error: " + ex);
} catch (CreateException ex) {
System.err.println("Error: " + ex);
return newUser;
}2 - When I test this method with a simple client it works perfectly :
public class TestEJB {
public static void main(String[] args) {
Context initialCtx;
try {
// Create JNDI context
// Context initialization
// Narrow UserSessionHome
// Create UserSession
UserSession session = sessionHome.create();
// Test create
UserRemote newUser = session.newUser("pierre", "hemici");
if (newUser != null) {
System.out.println(newUser.printMe());
} catch (Exception e) {
System.err.println("Error: " + e);
e.printStackTrace();
Result : I got the newUser printed on STDOUT and I check in the User table (in the SGBD) if the new user has been created.
What I want ?
I want to call the newUser method from the UserServlet and use the RemoteUser returned by the method.
What I do ?
The jsp :
1 - I have a jsp page where a get information about the new user to create
2 - I put the login parameter and the password parameter into the request
3 - I call the UserServlet when the button "add" is pressed on the jsp page.
The Servlet :
1 - I have a method doInsert which call the newUser method :
public class UserServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
// EJB Context
InitialContext ejbCtx;
// Session bean
UserSession userSession;
public void init() throws ServletException {
try {
// Open JNDI context (the same as TestClient context)
// Get UserSession Home
// Create UserSession
userSession = userSessionHome.create();
} catch (NamingException ex) {
System.out.println("Error: " + ex);
} catch (RemoteException ex) {
System.out.println("Error: " + ex);
} catch (CreateException ex) {
System.out.println("Error: " + ex);
protected void service(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
* Does insertion of the new user in the database.
public void doInsert(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
try {
// Get parameters to create the newUser
String login = req.getParameter("login");
String password = req.getParameter("password");
// Create the newUser
System.out.println("Calling newUser before");
UserRemote user = userSession.newUser(login, password);
System.out.println("Calling newUser after");
} catch (Exception e) {
// Clean up resources
public void destroy() {
Result :
When I run my jsp page and click on the "add" button, I got the message "Calling newUser before" printed in STDOUT and the error message :
ERROR [[userservlet]] Servlet.service() for servlet userservlet threw exception
javax.servlet.ServletException: loader constraints violated when linking javax/ejb/Handle class
at noumea.user.UserServlet.service(UserServlet.java:112)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:153)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
at java.lang.Thread.run(Thread.java:534)
Constat :
I checked into my SGBD and the new user has been created.
The error appears only when the method return Remote ejbs, if I return simples objects (Strings, int..) it works.
What can I do to resolve this problem ?
Thank you."Why do you want to servlet to gain access to another EJB through the stateless session bean. Why cant the servlet call it directly ?"
Because I want to access to the informations included in the entity bean UserBean (which is remote).
You said that it is a bad design, but how can I access to my UserBean ejbs from the session bean if I don't do that ?
For example I want a List of all users to be seen in a jsp page :
1 - I call the method getUserList which returnsan ArrayList of UserRemote.
2 - I iterate over the ArrayList to get the users parameters to be seen.
As the other example (newUser), when I do
ArrayList users = (ArrayList) userSession.getUserList(); with the simple client it works, but in the servlet I got the same error.
But, if I call directly the findAll method (as you'are saying) in the servlet
ArrayList users = (ArrayList) userRemoteHome.findAll(); it works...
I think that if my servlet calls directly entity ejbs, I don't need UserSession bean anymore. Is that right ?
I precise that my design is this :
jsp -> servlet -> session bean -> entity bean -> sgbd
Is that a bad design ? Do I need the session bean anymore ?
Thank you. -
I am currently storing values from a database into an array
im my servlet. I have a JSP page and I'm trying to set
the datafields on this page to the values held in the array.
I need to send the array from the servlet to the JSP page
and then figure out how I retrieve it at the other end.
Can anyone help????????Here's the code I'm using for my Sevlet:
package SASSSpkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import javax.swing.*;
public class UserLogin extends HttpServlet{
private Connection connection;
private ResultSet resultSet;
private Statement statement;
public String getusername, getpassword, getdatabase;
private String customerId;
private String title;
private String firstName;
private String secondName;
private String surname;
private String residentialAddress;
private String dateOfBirth;
private String correspondenceName;
private String maritalStatus;
private String gender;
private String securityId;
private String postCode;
private String dateOfFirstContact;
private String homeTel;
private String businessTel;
private String currentAddressEntryDate;
private String nationalInsuranceNumber;
private String dateLastUpdated;
public ArrayList values = new ArrayList();
public void init(ServletConfig config) throws ServletException
super.init(config);
public UserLogin()
public void ConnectToDatabase() throws Exception
String url = "jdbc:odbc:SASSS";
String username = getusername;
String password = getpassword;
// Load the driver to allow connection to the database
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection( url, username,
password);
catch (ClassNotFoundException cnfex)
throw new Exception("cannot connect to database");
catch (SQLException sqlex)
throw new Exception("cannot connect to database");
public void getResultSetData()
try
String query = "SELECT DISTINCT CUSTOMER_ID, TITLE, FORENAME1, FORENAME2, SURNAME, DATE_OF_BIRTH, CUSTOMER_SALUTATN, MARITAL_STATUS, GENDER, SECURITY_NAME, FIRST_CONTACT_DATE,POSTCODE, TELEX, DATE_AT_ADDRESS, NATIONAL_INS_NUM, ADDRESS.LAST_UPDATED, ADDRESS.TELEPHONE FROM CUSTOMER, ADDRESS, CUSTOMER_ADDRESS WHERE CUSTOMER.CUSTOMER_CODE = CUSTOMER_ADDRESS.CUSTOMER_CODE AND CUSTOMER_ADDRESS.ADDRESS_ID = ADDRESS.ADDRESS_ID";
statement = connection.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
resultSet = statement.executeQuery(query);
resultSet.first();
for (int i = 0; i <= 16; i ++)
values.add(resultSet.getString(i + 1));
statement.close();
catch(SQLException sqlex)
sqlex.printStackTrace();
public void doPost(HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException
try{
boolean dbConnection;
// Get username and password from fields on web
page
getusername = req.getParameter("UserName");
getpassword = req.getParameter("Password");
getdatabase = req.getParameter("Database");
PrintWriter output = res.getWriter();
res.setContentType("text/html");
if(getusername.equals("") || getpassword.equals
res.sendRedirect
("http://localhost:9080/SASSS/ErrorPage.jsp");
return;
else
ConnectToDatabase();
getResultSetData();
res.sendRedirect
("http://localhost:9080/SASSS/EmployeeDetails.jsp");
catch(Exception ex) {
res.sendRedirect
("http://localhost:9080/SASSS/ErrorPage.jsp");
public void doGet(HttpServletRequest req, HttpServletResponse
resp)
throws ServletException, IOException
req.setAttribute("myArrayList", values);
public String getCustomerId()
return customerId;
public void setCustomerId(String Id)
customerId = Id;
public String getTitle()
return title;
public void setTitle(String theTitle)
title = theTitle;;
public String getFirstName()
return firstName;
public void setFirstName(String theFirstName)
firstName = theFirstName;
public String getSecondName()
return secondName;
public void setSecondName(String theSecondName)
secondName = theSecondName;
public String getSurname()
return surname;
public void setSurname(String theSurname)
surname = theSurname;
public String getResidentialAddress()
return residentialAddress;
public void setResidentialAddress(String theResidentialAddress)
residentialAddress = theResidentialAddress;
public String getDob()
return dateOfBirth;
public void setDob(String theDOB)
dateOfBirth = theDOB;
public String getCorrespondenceName()
return correspondenceName;
public void setCorrespondenceName(String theCorrespondenceName)
correspondenceName = theCorrespondenceName;
public String getMaritalStatus()
return maritalStatus;
public void setMaritalStatus(String theMaritalStatus)
maritalStatus = theMaritalStatus;
public String getGender()
return gender;
public void setGender(String theGender)
gender = theGender;
public String getSecurityId()
return securityId;
public void setSecurityId(String theSecurityId)
securityId = theSecurityId;
public String getPostCode()
return postCode;
public void setPostCode(String thePostCode)
postCode = thePostCode;
public String getDateOfFirstContact()
return dateOfFirstContact;
public void setDateOfFirstContact(String theDateOfFirstContact)
dateOfFirstContact = theDateOfFirstContact;
public String getHomeTel()
return homeTel;
public void setHomeTel(String theHomeTel)
homeTel = theHomeTel;
public String getBusinessTel()
return businessTel;
public void setBusinessTel(String theBusinessTel)
businessTel = theBusinessTel;
public String getCurrentAddressEntryDate()
return currentAddressEntryDate;
public void setCurrentAddressEntryDate(String
theCurrentAddressEntryDate)
currentAddressEntryDate = theCurrentAddressEntryDate;
public String getNationalInsuranceNumber()
return nationalInsuranceNumber;
public void setNationalInsuranceNumber(String
theNationalInsuranceNumber)
nationalInsuranceNumber = theNationalInsuranceNumber;
public String getDateLastUpdated()
return dateLastUpdated;
public void setDateLastUpdated(String theDateLastUpdated)
dateLastUpdated = theDateLastUpdated;
Here's the code I'm using for my JSP:
<HEAD><SCRIPT type="text/javascript">
<!--
var _sstmrID = null;
var _sstmrON = false;
var _sspos = 80;
function _ScrollStatus(msg, delay)
if (_sstmrON)
window.clearTimeout(_sstmrID);
_sstmrON = false;
var statmsg = "";
if (_sspos >= 0)
for (s = 0; s < _sspos; s++)
statmsg += " ";
statmsg += msg;
else
statmsg = msg.substring(-_sspos, msg.length);
window.status = statmsg;
sspos = (-sspos > msg.length) ? 80 : _sspos - 1;
fname = "_ScrollStatus('" + msg + "', " + delay + ")";
_sstmrID = window.setTimeout(fname, delay);
_sstmrON = true;
//-->
</SCRIPT><SCRIPT type="text/javascript">
<!--
function _ShowObj(lId)
var ob;ob=new Array;
var appVer=parseInt(navigator.appVersion);
var isNC=false,isN6=false,isIE=false;
if (document.all && appVer >= 4) isIE=true; else
if (document.getElementById && appVer > 4) isN6=true; else
if (document.layers && appVer >= 4) isNC=true;
if (isNC)
w_str = "document." + lId;ob[lId] = eval(w_str);
if (!ob[lId]) ob[lId] = _FindHiddenObj(document, lId);
if (ob[lId]) ob[lId].visibility = "show";
if (isN6)
ob[lId] = document.getElementById(lId);
ob[lId].style.visibility = "visible";
if (isIE)
w_str = "document.all.item(\"" + lId + "\").style";ob[lId] = eval(w_str);
ob[lId].visibility = "visible";
function _FindHiddenObj(doc, lId)
for (var i=0; i < doc.layers.length; i++)
var w_str = "doc.layers.document." + lId;
var obj;obj=new Array;
obj[lId] = eval(w_str);
if (!obj[lId]) obj[lId] = _FindHiddenObj(doc.layers[i], lId);
if (obj[lId]) return obj[lId];
return null;
//-->
</SCRIPT></HEAD>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html>
<HEAD>
<%@ page
language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="ErrorPage.jsp"
%>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="style.css" rel="stylesheet" type="text/css">
<h2>
<%@page import="SASSSpkg.UserLogin"%>
<%@page import="java.util.*"%>
<%@page import="javax.servlet.*"%>
<%@page import="javax.servlet.http.*"%>
<% UserLogin ul = new UserLogin(); %>
<TITLE>SASSS Employee Details</TITLE>
</HEAD>
<BODY bgcolor="#c0c0c0"><FORM action="servlet/SASSSpkg.UserLogin" method="get">
<%
if (request.getAttribute("myArrayList") != null) {
ArrayList Alist = (ArrayList)request.getAttribute("myArrayList");
ul.setCustomerId(Alist.get(0).toString());
else {
response.sendRedirect("http://localhost:9080/SASSS/ErrorPage.jsp");
%>
<TABLE border="0" width="792" height="359">
<TBODY>
<TR>
<TD colspan="6" valign="middle" align="center" height="58"><B>Customer
Id</B> <INPUT type="text" name="customerId" size="20" maxlength="10"
disabled value='<%= ul.getCustomerId() %>'></TD>
</TR>
<TR>
<TD align="center" height="57" width="160"><SPAN
style="font-weight: bold"><B>Title</B><BR>
<SELECT name="title" size="1">
<OPTION><%= ul.getTitle()%></OPTION>
<OPTION>Mr</OPTION>
<OPTION>Mrs</OPTION>
<OPTION>Miss</OPTION>
</SELECT></SPAN></TD>
<TD align="left" height="57" width="171"><SPAN
style="font-weight: bold"><B><STRONG>First Name</STRONG></B><BR>
<SCRIPT type="text/javascript">
<!--
_ScrollStatus("How cool is this", 2);
//-->
</SCRIPT><INPUT type="text" name="firstName" size="20" maxlength="25" value = '<%= ul.getFirstName() %>' ></SPAN></TD>
<TD align="left" height="57" colspan="2"><SPAN
style="font-weight: bold"><B>Second Name</B><BR>
<INPUT type="text" name="secondName" size="20" maxlength="25" value='<%= ul.getSecondName() %>'></SPAN></TD>
<TD align="left" height="57" colspan="2"><SPAN
style="font-weight: bold">Surname<BR>
<INPUT type="text" name="surname" size="20" maxlength="25" value='<%= ul.getSurname() %>'> </SPAN></TD>
</TR>
<TR>
<TD colspan="2" align="center" rowspan="3"><B>Residential Address</B><BR>
<TEXTAREA rows="7" cols="31" name="residentialAddress" ><%= ul.getResidentialAddress() %></TEXTAREA></TD>
<TD align="left" height="66" colspan="2"><B>Date of Birth</B><BR>
<INPUT type="text" name="dateOfBirth" size="20" maxlength="10" value='<%= ul.getDob() %>'></TD>
<TD align="left" colspan="2"><B>Correspondence Name<BR>
<INPUT type="text" name="correspondenceName" size="20" maxlength="25" value='<%= ul.getCorrespondenceName() %>'>
</B></TD>
</TR>
<TR>
<TD align="left" height="42" colspan="2"><B>Marital Status </B> <SELECT
name="maritalStatus" style="">
<OPTION selected><%= ul.getMaritalStatus()%></OPTION>
<OPTION>Divorced</OPTION>
<OPTION>Married</OPTION>
<OPTION>Seperated</OPTION>
<OPTION>Single</OPTION>
<OPTION>Widowed</OPTION>
</SELECT></TD>
<TD align="left" colspan="2"><B>Gender</B> <SELECT name="gender">
<OPTION><%= ul.getGender()%></OPTION>
<OPTION>Female</OPTION>
<OPTION>Male</OPTION>
</SELECT></TD>
</TR>
<TR>
<TD colspan="4" height="56"><B>Security
Id </B><INPUT type="text" name="securityId"
size="20" maxlength="20" value='<%= ul.getSecurityId() %>'></TD>
</TR>
<TR>
<TD height="55" align="left" colspan="2" nowrap><B>
Post Code </B> <INPUT type="text"
size="15" maxlength="8" value='<%= ul.getPostCode() %>' name="postCode"></TD>
<TD height="55" align="left" colspan="2"><B>Date of First Contact</B><BR>
<INPUT type="text" name="dateOfFirstContact" size="10" maxlength="10" value='<%= ul.getDateOfFirstContact() %>'>
</TD>
<TD height="55" rowspan="5" align="center" colspan="2"><SELECT
size="9" name="aditionalDetailForms">
<OPTION value="">Products Held</OPTION>
<OPTION>Employment</OPTION>
<OPTION>Dependants</OPTION>
<OPTION>Residential Details</OPTION>
<OPTION>Assets/Liabilities</OPTION>
<OPTION>Income/Commitments</OPTION>
<OPTION>Banks/Building Societies</OPTION>
<OPTION>Credit Cards</OPTION>
<OPTION>Leads and Follow ups</OPTION>
<OPTION value=""></OPTION>
</SELECT></TD>
</TR>
<TR>
<TD height="41" align="left" colspan="2" nowrap><B> Home
Tel </B>
<INPUT type="text" name="homeTel" size="18" maxlength="14" value='<%= ul.getHomeTel() %>'></TD>
<TD height="41" align="left" colspan="2"><INPUT type="button"
name="lastAddress" value="Last Address"></TD>
</TR>
<TR>
<TD height="49" align="left" colspan="2" nowrap><B> Business
Tel </B>
<INPUT type="text" name="businessTel" size="18" maxlength="14" value='<%= ul.getBusinessTel() %>'></TD>
<TD height="49" align="left" valign="bottom" colspan="2"><B>N.I.
Number</B></TD>
</TR>
<TR>
<TD height="42" colspan="2" nowrap><B> Current
Address Entry Date </B> <INPUT
type="text" name="currentAddressEntryDate" size="10" maxlength="10" value='<%= ul.getCurrentAddressEntryDate() %>'></TD>
<TD height="42" colspan="2"><INPUT type="text"
name="nationalInsuranceNumber" size="20" maxlength="9" value='<%= ul.getNationalInsuranceNumber() %>'></TD>
</TR>
<TR>
<TD height="44" colspan="2" nowrap><B> Date Last
Updated </B>
<INPUT type="text" name="dateLastUpdated" size="10" maxlength="15" value='<%= ul.getDateLastUpdated() %>'></TD>
<TD height="44" align="left" colspan="2"><INPUT type="button"
name="directMailExclusions" value="Mail Exclu"> <INPUT
type="button" name="telephoneExclusions" value="Tel Exclu"></TD>
</TR>
<TR>
<TD height="44" align="left" colspan="6" nowrap> <INPUT
type="submit" name="ok" value=" OK "> <INPUT
type="button" name="forward" value=" >> "> <INPUT
type="button" name="exit" value=" Exit "> <INPUT
type="button" name="delete" value=" Delete "> <INPUT
type="reset" name="refresh" value=" Refresh "> <INPUT
type="button" name="help" value=" Help "></TD></TR>
</TABLE></FORM>
</BODY>
</html:html>
The problem is, I'm trying to store String values into an array,
or a result set and then store them in the data fields on my jsp page.
When I use my set method such as setCustomerId(values.get(0));
it sets the variable customerId to the value I want but when I try to
call the get method in the JSP page to assign it to the data field it
will not retrieve it.
Can anyone solve this, I've been at it for days now???? -
How do you display xml file with xlst sheet in jsp
I have an xml file with accompanying xslt file (and several images that are used in a single directory. If I doubleclick on the xml file, it displays perfectly in my browser - Formatting, images and all!
The 100 dollar question - How do I duplicate this behavior in a JSP page in WebLogic 8.1 using the code in the xml and the accompanying xslt (formatting) file? I tried simple embedding the xml code in the jsp, but that didn't seem to work. What is the secret?
Okay, I need to add a bit more information here. I understand that it is really easy to just redirect to the XML file. The issue is really security. I want the XML to be inside a jsp that will only allow validated users to view it.
Another way to look at the problem would be, can I add a jsp security tag to the xml file? Or how to I add the xml code inside a jsp and keep the path references to the xslt and graphics.
Hope the added information helps
Thanks,
Ken
Message was edited by: KLee - 20050609 10:25 MST
[email protected]This proved out to be the answer. Thanks for the direction!
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XML_XSLT_Servlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String xmlfile = req.getParameter("xmlfile"); if (xmlfile==null) xmlfile = "test.xml";
String xsltfile = req.getParameter("xsltfile"); if (xsltfile==null) xsltfile = "test.xslt";
/* Test if file exists!, or use default file */
File f1 = new File(getServletContext().getRealPath("WEB-INF/displayfiles/"), xmlfile);
File f2 = new File(getServletContext().getRealPath("WEB-INF/displayfiles/"), xsltfile);
if (f1.exists() && f2.exists()) {
// System.out.println("Files Found");
} else {
System.out.println("XML and XSLT Files NOT Found");
System.out.println(f1.getPath());
System.out.println(f1.getName());
xmlfile = "test.xml";
xsltfile = "test.xslt";
InputStream fileXML = getServletContext().getResourceAsStream("WEB-INF/displayfiles/" + xmlfile);
InputStream fileXSLT = getServletContext().getResourceAsStream("WEB-INF/displayfiles/" + xsltfile);
OutputStream os = res.getOutputStream();
TransformerFactory xFactory = TransformerFactory.newInstance();
StreamSource stylesheet = new StreamSource(fileXSLT);
Transformer xformer = null;
try {
xformer = xFactory.newTransformer(stylesheet);
} catch (TransformerConfigurationException tfce) {
tfce.printStackTrace();
StreamSource input = new StreamSource(fileXML);
StreamResult output = null;
try {
output = new StreamResult(os);
} catch (Exception e) {
e.printStackTrace();
try {
xformer.transform(input, output);
} catch (TransformerException xfe) {
xfe.printStackTrace();
<pre></pre><pre></pre> -
Error Message when Generating SOAP in JDeveloper
I have been looking into this for a while now and have no idea where else to go. When creating and sending a SOAP message in JDeveloper 10g (OC4J) I continue to get this error message. Any ideas/suggestions would be much appreciated.
XSL-1101: (Fatal Error) DOMSource node as this type not supported.
javax.xml.transform.TransformerException: XSL-1101: (Fatal Error) DOMSource node as this type not supported.
at oracle.xml.jaxp.JXTransformer.reportException(JXTransformer.java:732)
at oracle.xml.jaxp.JXTransformer.transform(JXTransformer.java:198)
at com.sun.xml.messaging.saaj.soap.impl.EnvelopeImpl.output(EnvelopeImpl.java:237)
at com.sun.xml.messaging.saaj.soap.SOAPPartImpl.getContentAsStream(SOAPPartImpl.java:202)
at com.sun.xml.messaging.saaj.soap.MessageImpl.getHeaderBytes(MessageImpl.java:461)
at com.sun.xml.messaging.saaj.soap.MessageImpl.saveChanges(MessageImpl.java:538)
at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:223)
at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection$PriviledgedPost.run(HttpSOAPConnection.java:151)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:121)
at mypackage1.SoapTest.doGet(SoapTest.java:49)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:356)
at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:614)
at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:317)
at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:784)
at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)
at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
at java.lang.Thread.run(Thread.java:536)Thanks in advance.Hi,
under "project properties -> Libraries" add a new J2SE version (I use 1.4.1.2) by choosing the java.exe file.
I provide you my code sample.
Note: I use this just for test purposes, so be carefully, I haven't removed rubbish. I use a XML file attachment that is stored in local file.
import java.net.*;
import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.*;
import javax.xml.soap.*;
import javax.activation.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.apache.log4j.*;
import org.apache.log4j.xml.*;
import org.apache.commons.logging.*;
import javax.xml.parsers.DocumentBuilder;
public class TripplanSender extends HttpServlet
static Logger logger = Logger.getLogger(TripplanSender.class);
String toURL;
String data;
ServletContext servletContext;
private SOAPConnection con;
public TripplanSender()
data = null;
public void init(ServletConfig servletConfig)
throws ServletException
super.init(servletConfig);
servletContext = servletConfig.getServletContext();
try
String resource = "/WEB-INF/xml/loggingConfig.xml";
URL configFileResource = servletConfig.getServletContext().getResource(resource);
DOMConfigurator.configure(configFileResource.getFile());
logger.debug("Logger initialisiert. Initialisiere Config Manager");
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
con = scf.createConnection();
toURL = servletConfig.getInitParameter("SendToURL");
catch(Exception e)
//logger.error("Unable to open a SOAPConnection", e);
java.io.InputStream in = servletContext.getResourceAsStream("/WEB-INF/address.properties");
if(in != null)
Properties props = new Properties();
try
props.load(in);
//toURL = props.getProperty("to");
data = props.getProperty("data");
catch(IOException ex) { }
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException
String retval = "<html> <H4>";
try
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
SOAPPart sp = msg.getSOAPPart();
SOAPEnvelope envelope = sp.getEnvelope();
SOAPHeader header = msg.getSOAPHeader();
javax.xml.soap.Name tripplan = envelope.createName("Tripplan", "b", "http://de.tui.aergo.sample/Tripplan");
SOAPHeaderElement tripplanHeaderElem = header.addHeaderElement(tripplan);
tripplanHeaderElem.setActor("http://de.tui.aergo.sample/receiver");
tripplanHeaderElem.setMustUnderstand(true);
javax.xml.soap.Name tripplan_action = envelope.createName("tripplan_action", "b", "http://de.tui.aergo.sample/Tripplan");
SOAPElement tripplan_actionElem = tripplanHeaderElem.addChildElement(tripplan_action);
tripplan_actionElem.addTextNode("CREATE");
SOAPFactory soapFactory = SOAPFactory.newInstance();
SOAPBody body = msg.getSOAPBody();
StringBuffer urlSB = new StringBuffer("http://");
urlSB.append(req.getServerName());
urlSB.append(":").append(req.getServerPort());
urlSB.append(req.getContextPath());
String reqBase = urlSB.toString();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
String msgFilename = req.getParameter("ACTION");
data = reqBase + "/" +msgFilename;
//data = reqBase + "/191_create_requisitn_001.xml";
URL url = new URL(data);
AttachmentPart ap = msg.createAttachmentPart(new DataHandler(url));
ap.setContentType("text/xml");
msg.addAttachmentPart(ap);
URL urlEndpoint = new URL(toURL);
SOAPMessage reply = con.call(msg, urlEndpoint);
if(reply != null)
System.err.println("Reply logged in \"reply.msg\"");
retval = retval + " received reply (check \"reply.msg\").</H4> </html>";
} else
System.err.println("No reply");
retval = retval + " no reply was received. </H4> </html>";
catch(Throwable e)
e.printStackTrace();
//logger.error("Error in constructing or sending message " + e.getMessage());
retval = retval + " There was an error in constructing or sending message. </H4> </html>";
try
OutputStream os = resp.getOutputStream();
os.write(retval.getBytes());
os.flush();
os.close();
catch(IOException e)
e.printStackTrace();
//logger.error("Error in outputting servlet response " + e.getMessage());
} -
Params in queries with Jdev 10g
I had a working UIX App and used the null event to setting parameters for my query but using 10g doesn't work. I tried setWhereClause in my application module class, calling it from the data action, but i get an error (index out of bounds). If I try "setWhereClause", it works fine but it's veeeeery slow (I think the query first fechs all rows). I need something that before getting rows, initialize the query (my view object is defined with an empty where clause, because the queries will be defined in runtime via a Emp_ID). Of course, there is and index on emp_id. Help me, please...
Andy, excuse me for the repost.
If I try the way you explain, it worked fine, but the problem is that I'm also convertint to struts. In the data action, I have overriden this:
protected void initializeRequestParameters(DataActionContext actionContext)
There I try to set the params:
// TODO: Override this oracle.adf.controller.struts.actions.DataAction method
//super.initializeRequestParameters(actionContext);
HttpServletRequest
// If I uncomment the line super..., the result is the same.
req=actionContext.getHttpServletRequest();
String evento=req.getParameter("event");
DatosUsuario dat = DatosUsuario.getDatosUsuario(req);
String exp=dat.sId_Expediente;
BindingContext bc=actionContext.getBindingContext();
DCDataControl dc= bc.getContext(req).getDefaultDataControl();
Object misdatos=dc.getDataProvider();
Elendil am=(Elendil)misdatos;
am.ParamAnotacionExp(exp);
In my viewobject, I have this where clause:
anotacionexp.id_expediente = :1
Then, in my ApplicationModule class:
public void ParamAnotacionExp(String idexpediente)
AnotacionExpViewImpl vo=getAnotacionExpView1();
vo.setWhereClauseParam(1,idexpediente);
//vo.setWhereClauseParam(0,idexpediente); With 0, the result is the same.
vo.executeQuery();
And when I run, I get this:
oracle.jbo.JboException: JBO-29000: Unexpected exception caught: java.lang.ArrayIndexOutOfBoundsException, msg=0
at oracle.jbo.JboException.<init>(JboException.java:343)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.dispatchMethod(AbstractRemoteApplicationModuleImpl.java:4658)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.executeMethod(AbstractRemoteApplicationModuleImpl.java:4854)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.processSvcMsgRequest(AbstractRemoteApplicationModuleImpl.java:3449)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.processSvcMsgEntries(AbstractRemoteApplicationModuleImpl.java:3630)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.readServiceMessage(AbstractRemoteApplicationModuleImpl.java:2975)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.processMessage(AbstractRemoteApplicationModuleImpl.java:1639)
at oracle.jbo.server.ApplicationModuleImpl.doMessage(ApplicationModuleImpl.java:5986)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.sync(AbstractRemoteApplicationModuleImpl.java:1608)
at oracle.jbo.server.remote.colo.ServerApplicationModuleImpl.doMessage(ServerApplicationModuleImpl.java:245)
at oracle.jbo.common.colo.ColoApplicationModuleImpl.doMessage(ColoApplicationModuleImpl.java:102)
at oracle.jbo.client.remote.ApplicationModuleImpl.doMessage(ApplicationModuleImpl.java:5233)
at oracle.jbo.client.remote.PooledRequestHandler.doMessage(PooledRequestHandler.java:70)
at oracle.jbo.client.remote.ApplicationModuleImpl.doMessage(ApplicationModuleImpl.java:5233)
at oracle.jbo.client.remote.ApplicationModuleImpl.sendServiceMessage(ApplicationModuleImpl.java:998)
at oracle.jbo.client.remote.ApplicationModuleImpl.sendServiceMessage(ApplicationModuleImpl.java:1012)
at oracle.jbo.client.remote.ApplicationModuleImpl.sendWorkingSetRequests(ApplicationModuleImpl.java:3049)
at oracle.jbo.client.remote.ApplicationModuleImpl.sendRequest(ApplicationModuleImpl.java:1041)
at oracle.jbo.client.remote.ApplicationModuleImpl.riInvokeExportedMethod(ApplicationModuleImpl.java:5255)
at galadriel.client.ElendilClient.ParamAnotacionExp(ElendilClient.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java)
at oracle.jbo.common.ws.WSProxy.invokeMethod(WSProxy.java:120)
at oracle.jbo.common.ws.WSProxy.invoke(WSProxy.java:90)
at $Proxy3.ParamAnotacionExp(Unknown Source)
at controller.AnotacionesDataAction.initializeRequestParameters(AnotacionesDataAction.java:63)
at oracle.adf.controller.struts.actions.DataAction.executeImpl(DataAction.java:104)
at oracle.adf.controller.struts.actions.DataAction.execute(DataAction.java:69)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1485)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:509)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:356)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:16)
at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:148)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:20)
at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:148)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:610)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:317)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:784)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:186)
at java.lang.Thread.run(Thread.java:536)
## Detail 0 ##
java.lang.ArrayIndexOutOfBoundsException: 0
at oracle.jdbc.dbaccess.DBDataSetImpl._getDBItem(DBDataSetImpl.java:323)
at oracle.jdbc.dbaccess.DBDataSetImpl._createOrGetDBItem(DBDataSetImpl.java:566)
at oracle.jdbc.dbaccess.DBDataSetImpl.setNullBindItem(DBDataSetImpl.java:1878)
at oracle.jdbc.driver.OraclePreparedStatement.setNull(OraclePreparedStatement.java:1190)
at oracle.jbo.server.ViewRowSetImpl.bindParameters(ViewRowSetImpl.java:1436)
at oracle.jbo.server.QueryCollection.executeQuery(QueryCollection.java:576)
at oracle.jbo.server.ViewObjectImpl.executeQueryForCollection(ViewObjectImpl.java:2946)
at oracle.jbo.server.ViewRowSetImpl.execute(ViewRowSetImpl.java:553)
at oracle.jbo.server.ViewRowSetImpl.executeQueryForMasters(ViewRowSetImpl.java:612)
at oracle.jbo.server.ViewRowSetImpl.executeQuery(ViewRowSetImpl.java:594)
at oracle.jbo.server.ViewObjectImpl.executeQuery(ViewObjectImpl.java:2890)
at galadriel.ElendilImpl.ParamAnotacionExp(ElendilImpl.java:111)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.dispatchMethod(AbstractRemoteApplicationModuleImpl.java:4636)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.executeMethod(AbstractRemoteApplicationModuleImpl.java:4854)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.processSvcMsgRequest(AbstractRemoteApplicationModuleImpl.java:3449)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.processSvcMsgEntries(AbstractRemoteApplicationModuleImpl.java:3630)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.readServiceMessage(AbstractRemoteApplicationModuleImpl.java:2975)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.processMessage(AbstractRemoteApplicationModuleImpl.java:1639)
at oracle.jbo.server.ApplicationModuleImpl.doMessage(ApplicationModuleImpl.java:5986)
at oracle.jbo.server.remote.AbstractRemoteApplicationModuleImpl.sync(AbstractRemoteApplicationModuleImpl.java:1608)
at oracle.jbo.server.remote.colo.ServerApplicationModuleImpl.doMessage(ServerApplicationModuleImpl.java:245)
at oracle.jbo.common.colo.ColoApplicationModuleImpl.doMessage(ColoApplicationModuleImpl.java:102)
at oracle.jbo.client.remote.ApplicationModuleImpl.doMessage(ApplicationModuleImpl.java:5233)
at oracle.jbo.client.remote.PooledRequestHandler.doMessage(PooledRequestHandler.java:70)
at oracle.jbo.client.remote.ApplicationModuleImpl.doMessage(ApplicationModuleImpl.java:5233)
at oracle.jbo.client.remote.ApplicationModuleImpl.sendServiceMessage(ApplicationModuleImpl.java:998)
at oracle.jbo.client.remote.ApplicationModuleImpl.sendServiceMessage(ApplicationModuleImpl.java:1012)
at oracle.jbo.client.remote.ApplicationModuleImpl.sendWorkingSetRequests(ApplicationModuleImpl.java:3049)
at oracle.jbo.client.remote.ApplicationModuleImpl.sendRequest(ApplicationModuleImpl.java:1041)
at oracle.jbo.client.remote.ApplicationModuleImpl.riInvokeExportedMethod(ApplicationModuleImpl.java:5255)
at galadriel.client.ElendilClient.ParamAnotacionExp(ElendilClient.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java)
at oracle.jbo.common.ws.WSProxy.invokeMethod(WSProxy.java:120)
at oracle.jbo.common.ws.WSProxy.invoke(WSProxy.java:90)
at $Proxy3.ParamAnotacionExp(Unknown Source)
at controller.AnotacionesDataAction.initializeRequestParameters(AnotacionesDataAction.java:63)
at oracle.adf.controller.struts.actions.DataAction.executeImpl(DataAction.java:104)
at oracle.adf.controller.struts.actions.DataAction.execute(DataAction.java:69)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1485)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:509)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:356)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:16)
at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:148)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:20)
at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:148)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:610)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:317)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:784)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:186)
at java.lang.Thread.run(Thread.java:536)
I'm sure I'm doing somthing wrong, but don't know what. Thank you for your help. -
No communication between applet - servlet
hi
my applet and my servlet is not at all communicating in the browser.
any body knows how to solve this problem?
in my applet code:Jus i am pasing as name string to invoke the serlvet via URL
String location = "http://ctp-vi0275:8880/HandlePassword?"+"Name=XXX";
URL testServlet = new URL( location );
URLConnection servletConnection = testServlet.openConnection();
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
servletConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
servletConnection.connect();
i have changed server.xml file to listen the port number 8880.(in tomcat)
in my servlet code:
doGet Method in servlet
String str = req.getParameter("Name");
System.out.println(str);
here i am jus printing the name
but when i run my applet is not at all invoking the serlvet - HandlePassword.I have placed the
servlet in ROOT\web-inf\classes\HandlePassword
in web.xml
<web-app>
<servlet>
<servlet-name>HandlePassword</servlet-name>
<servlet-class>HandlePassword</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HandlePassword</servlet-name>
<url-pattern>/HandlePassword</url-pattern>
</servlet-mapping>
</web-app>
where i am doing wrong here?You do following things and let me know:
1. Does the servlet work when you type "http://ctp-vi0275:8880/HandlePassword?Name=XXX" in your browser?
2. Run applet using appletviewer. Does it work?
3. If it works using appletviewer then enable java console in your browser and see error stacks if any.
4. If there are applet security errors on java console, try creating servlet URL in applet code by calling getDocumentRoot() method and see what happens. -
The server encountered an internal error () that prevented it from fulfilli
Hi.
Could any one tell me where i start looking for the error in this log.
It works fine under sun studio creator, but when i upload the project to the server and call the page i get this error.
I found out that it is something with my servlet wich do some work for getting my image. (see sevlet below)
DetailsTimestamp: 2006-06-09 16:26:39.513
Log Level: SEVERE
Logger: javax.enterprise.system.container.web
Name-Value Pairs: _ThreadID=16;
Record Number: 3644
Message ID: StandardWrapperValve[Faces Servlet]
Complete Message
Servlet.service() for servlet Faces Servlet threw exceptioncom.sun.rave.web.ui.appbase.ApplicationException: javax.servlet.ServletException at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.destroy(ViewHandlerImpl.java:601) at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(ViewHandlerImpl.java:316) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:225) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:194) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAsPrivileged(Subject.java:517) at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282) at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:257) at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:55) at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:161) at java.security.AccessController.doPrivileged(Native Method) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.sun.rave.web.ui.util.UploadFilter.doFilter(UploadFilter.java:194) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:55) at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:161) at java.security.AccessController.doPrivileged(Native Method) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:263) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:225) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:173) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:132) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:933) at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:189) at com.sun.enterprise.web.connector.grizzly.ProcessorTask.doProcess(ProcessorTask.java:604) at com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:475) at com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(ReadTask.java:371) at com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(ReadTask.java:264) at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:281) at com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:83)Caused by: javax.faces.FacesException: javax.servlet.ServletException at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:331) at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:132) at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(ViewHandlerImpl.java:311) ... 41 moreCaused by: javax.servlet.ServletException at org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:827) at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:763) at org.apache.jsp.medarbejdere_jsp._jspService(medarbejdere_jsp.java:111) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:105) at javax.servlet.http.HttpServlet.service(HttpServlet.java:860) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:336) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:297) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:247) at javax.servlet.http.HttpServlet.service(HttpServlet.java:860) at sun.reflect.GeneratedMethodAccessor100.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAsPrivileged(Subject.java:517) at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282) at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:257) at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:55) at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:161) at java.security.AccessController.doPrivileged(Native Method) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:723) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:482) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:417) at org.apache.catalina.core.ApplicationDispatcher.access$000(ApplicationDispatcher.java:80) at org.apache.catalina.core.ApplicationDispatcher$PrivilegedForward.run(ApplicationDispatcher.java:95) at java.security.AccessController.doPrivileged(Native Method) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313) at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:326) ... 43 more
Diagnostic Causes
package servlets;
* Returns the requested JPG from the database; input parameters are:
* @param imageid The id of the image to return
* @param size "full" or "thumbnail", default is "full"
// Import the JNDI classes
import java.io.*;
import javax.naming.*;
// Import the Servlet classes
import javax.servlet.*;
import javax.servlet.http.*;
// Import our database classes
import java.sql.*;
import javax.sql.*;
//import compare.*;
* Cache a reference to the datasource object that we will use later to obtain
* a connection to the database
public class ShowImages extends HttpServlet
public ShowImages() {
public void init() throws ServletException
try
// InitialContext ic = new InitialContext();
// this.datasource = ( DataSource )ic.lookup( "java:/WebPhotoGalleryDS" );
catch( Exception e )
throw new ServletException( e );
public void service( HttpServletRequest req, HttpServletResponse res ) throws ServletException
String ini = req.getParameter("ini");
ResultSet rs = null;
try
boolean aaben = false;
boolean luk = false;
//ResultSet rs = null;
compare.DB data = new compare.DB();
aaben = data.openDBConnection();
rs = data.getResultSet("SELECT Billede FROM Medarbejdere WHERE Ini = '"+ini+"')");
//ResultSet rs= this.getData(model);
BufferedInputStream b = null;
while(rs.next())
b = new BufferedInputStream(rs.getBinaryStream("Billede")) ;
luk = data.closeDBConnection();
res.setContentType( "image/jpg" );
BufferedOutputStream out = new BufferedOutputStream( res.getOutputStream() );
byte by[] = new byte[ 32768 ];
int index = b.read( by, 0, 32768 );
while ( index != -1 )
out.write( by, 0, index );
index = b.read( by, 0, 32768 );
out.flush();
catch( Exception e )
e.printStackTrace();
throw new ServletException( e );
finally
}The origin of the error could be truncated by limitation of a stack trace. In your case:
com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:326)
... 43 more
What you can do is add Java option: "-XX:MaxJavaStackTraceDepth=0" - this will make appserver print all Java stack trace and you will be able to see the origin of your exception.
Maybe you are looking for
-
Unable to run HelloWorld Programm from different jdevloper project.
HI, I have created the HelloWorld programm provided in cdb development kit in another jdevelper project and included all the jar files provided in the cdb development kit lib folder. the program looks like this. package bean; * Copyright (c) 2007, Or
-
IPod Touch 1g not being recognized after installing iTunes.
Win 7 Ultimate itunes 9.0.2 64 bit With iTunes or any Apple software uninstalled the iPod is recognized in device manager under portable devices> Apple iPod. I can browse to it within Win Explorer. All looks normal. Once I install iTunes and I plug i
-
Hi All, Can i get a standard QM reports showing the following data Report 1 - Report showing Vendor,Quanity recied from vendor in a given period,Quantity accepted and defective quantity.This is somewhat similar to MCVI but MCVI does not show accepted
-
How to create ALIAS on Macbook Pro? Samples?
Here are the directions.... The installer creates a sound library folder at "/Library/Application Support/UVISoundBanks/". All sound library must be copied or aliased to this folder so UVI Workstation can access to the contents easily. So, I want to
-
I am using PSE 8 on Mac OS 10.6. When I select Save as a Copy it does not add the word 'copy' to the file name and just overwrites the exisiting file. I ca't see any perferences which could affect this - does anyone have any ideas as to the solution.