GetServletContext().getInitParameter("param_name")

Hi,
I am trying to get a parameter from the web.xml file.
In the Web.xml file I enter the following:
<context-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
in my servlet I write
getServletContext().getInitParameter("driver")
While compiling the program I get the following error message:
Error: E:\VisualCafe\Projects\luxwood\ClientsServlet.java(69): Method getInitParameter(java.lang.String) not found in javax.servlet.ServletContext
What should I do
Tnx Eli

Sorry, my mistake. The syntax you stated was correct.
It seems there may be a problem with your servlet.jar. Get the latest copy of Tomcat 3.2/3 and try again.
Anthony

Similar Messages

  • WL6.1sp3 problem with getServletContext?

              I have just installed WL6.1sp3 and tried to move a web application from Tomcat
              4.02 to WebLogic. When I access a jsp, I get the following compile error indicating
              that it does not recognize the getServletContext method.
              Can anyone tell me why this is happening and how I can fix this?
              E:\WRS\WEB-INF\_tmp_war_WRS\jsp_servlet\__wrslogin.java:101: cannot resolve symbol
              symbol : method getServletContext ()
              location: class jsp_servlet.__wrslogin
              String wrsDBLogin = getServletContext().getInitParameter("wrsDBLogin");
              //[ /WRSLogin.jsp; Line: 12]
              Thanks,
              Chris
              

    AFAIK there is no getServletContext() method in javax.servlet.Servlet.
              change your JSP to
              String wrsDBLogin =
              getServletConfig().getServletContext().getInitParameter("wrsDBLogin");
              or
              String wrsDBLogin = application.getInitParameter("wrsDBLogin");
              "Chris L" <[email protected]> wrote in message
              news:[email protected]..
              >
              > I have just installed WL6.1sp3 and tried to move a web application from
              Tomcat
              > 4.02 to WebLogic. When I access a jsp, I get the following compile error
              indicating
              > that it does not recognize the getServletContext method.
              >
              > Can anyone tell me why this is happening and how I can fix this?
              >
              > E:\WRS\WEB-INF\_tmp_war_WRS\jsp_servlet\__wrslogin.java:101: cannot
              resolve symbol
              > symbol : method getServletContext ()
              > location: class jsp_servlet.__wrslogin
              > String wrsDBLogin =
              getServletContext().getInitParameter("wrsDBLogin");
              > //[ /WRSLogin.jsp; Line: 12]
              >
              >
              >
              > Thanks,
              >
              > Chris
              Dimitri
              

  • SSO login for custom BO SDK Application

    Hi,
    I am trying to build custom application using BO SDK. Requirement is application should be SSO configured.
    Below is my sample code of JSP
    <%@ page import = "com.crystaldecisions.sdk.framework.ISessionMgr"%>
    <%@ page import = "com.crystaldecisions.sdk.framework.IEnterpriseSession"%>
    <%@ page import = "com.crystaldecisions.sdk.exception.SDKException"%>
    <%@ page import = "com.crystaldecisions.sdk.occa.infostore.IInfoStore"%>
    <%@ page import="com.crystaldecisions.sdk.framework.CrystalEnterprise" %>
    <%@ page import="org.ietf.jgss.GSSCredential"%>
    <%@ page import="org.ietf.jgss.GSSManager"%>
    <%@ page import="com.businessobjects.sdk.credential.CredExtractor"%>
    <%
                   GSSCredential creds = null;
                   GSSManager manager = null;
                   CredExtractor credExtractor = new CredExtractor(request);
                     creds = credExtractor.GetCredential();
                     manager = credExtractor.GetManager();     
                   ISessionMgr sm = CrystalEnterprise.getSessionMgr();
                   IEnterpriseSession enterpriseSession = sm.logon(creds, manager, cms, authentication);
                   IInfoStore infoStore = (IInfoStore)enterpriseSession.getService("", "InfoStore");
                   String token=enterpriseSession.getLogonTokenMgr().getDefaultToken();
                   String myUserID=enterpriseSession.getUserInfo().getUserName().toString();
                   session.setAttribute("myUserID",myUserID);
                   session.setAttribute("token", token);
                   session.setAttribute("InfoStore", infoStore);
                   session.setAttribute("enterpriseSession",enterpriseSession);
                response.sendRedirect("home.jsp");
    %>
    i am redirecting to home.jsp and on home.jsp page i am just displaying userID whish is set in above code
    I am deploying my application on server which is SSO enable (Vintela)i have made the necessary changes in web.xml file also
    below is my web.xml file
    <filter>
              <filter-name>authFilter</filter-name>
              <filter-class>com.businessobjects.sdk.credential.WrappedResponseAuthFilter</filter-class>
              <init-param>
                   <param-name>idm.realm</param-name>
                   <param-value>abcd.AD.some.COM</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.princ</param-name>
                   <param-value>abso/SYSBODEV.abcd.ad.some.com</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.keytab</param-name>
                   <param-value>C:\winnt\sysbodev.keytab</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.allowUnsecured</param-name>
                   <param-value>true</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.allowNTLM</param-name>
                   <param-value>false</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.logger.name</param-name>
                   <param-value>simple</param-value>
                   <description>The unique name for this logger.</description>
              </init-param>
              <init-param>
                   <param-name>idm.logger.props</param-name>
                   <param-value>error-log.properties</param-value>
              <description>                Configures logging from the specified file.            </description>       
              </init-param>
              <init-param>
                   <param-name>error.page</param-name>
                   <param-value>/frame/errorSSO.jsp</param-value>
                   <description>The URL of the page to show if an error occurs during authentication.</description>
              </init-param>
         </filter>
    <filter-mapping>
            <filter-name>authFilter</filter-name>
            <url-pattern>/frame/frameset.jsp</url-pattern>
        </filter-mapping>
    but i am getting error saying VSJ authentication was not performed for this request.
    can any one help me ouot where i am going wrong
    Edited by: Asraf_Shaikh on Aug 25, 2011 6:39 PM

    Hi ivan,
    since i was busy with something else, so i could not logging to the forum and reply on time, anyways if your problem is still not solved.
    then follow the approach ( this is for java only)
    1. see if you can access infoview application , if yes then check web.xml file and try to uncomment the comment elements in web.xml file.
    2. check the jar file needed for sso , like credential.jar. you can take all the jar file from infoview application
    below is my code for sso login( only the important things i am putting rest you can manage)
    imports
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.log4j.Logger;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.ietf.jgss.GSSCredential;
    import org.ietf.jgss.GSSManager;
    import com.businessobjects.sdk.credential.CredExtractor;
    import com.crystaldecisions.sdk.framework.CrystalEnterprise;
    import com.crystaldecisions.sdk.framework.IEnterpriseSession;
    import com.crystaldecisions.sdk.occa.infostore.IInfoStore;
    code
    GSSCredential myCredential = null;
    GSSManager myManager = null;
    CredExtractor myCredExtractor = new CredExtractor(request);               
    myCredential = myCredExtractor.GetCredential();
    myManager = myCredExtractor.GetManager();
    String myCmsName = getServlet().getServletContext().getInitParameter("cms.default");
    IEnterpriseSession myIEnterpriseSession = CrystalEnterprise.getSessionMgr().logon(myCredential,myManager, myCmsName, SEC_WINAD);
    IInfoStore myIInfoStore = (IInfoStore) myIEnterpriseSession.getService(PortalConstants.EMPTYSTRING, PortalConstants.INFOSTORE);
    you can put try catch block -
    web.xml file
         <filter>
              <filter-name>authFilter</filter-name>
              <filter-class>com.businessobjects.sdk.credential.WrappedResponseAuthFilter</filter-class>
              <init-param>
                   <param-name>idm.realm</param-name>
                   <param-value>HODC.AD.abc.COM</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.princ</param-name>
                   <param-value>BOSSO/SYSBODEV.hodc.ad.abc.com</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.keytab</param-name>
                   <param-value>C:\winnt\sysbodev.keytab</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.allowUnsecured</param-name>
                   <param-value>true</param-value>
              </init-param>
              <init-param>
                   <param-name>idm.allowNTLM</param-name>
                   <param-value>false</param-value>
              </init-param>
              <init-param>
                   <description>The unique name for this logger.</description>
                   <param-name>idm.logger.name</param-name>
                   <param-value>simple</param-value>
              </init-param>
              <init-param>
                    <description>Configures logging from the specified file.</description> 
                   <param-name>idm.logger.props</param-name>
                   <param-value>error-log.properties</param-value>
              </init-param>
              <init-param>
                   <description>The URL of the page to show if an error occurs during authentication.</description>
                   <param-name>error.page</param-name>
                   <param-value>/JSP/failure.jsp</param-value>
              </init-param>
         </filter>
              <filter-mapping>
              <filter-name>authFilter</filter-name>
              <url-pattern>/logon.do</url-pattern>
         </filter-mapping>
    above code is working , so if you can follow the same,it should work for you also.and it for secWinad and sso is vintela
    let me know the status

  • Get init parameter from JSP

    Hello folks
    First of all, I want to say sorry for my English.
    Well, I have one jsp file and I want to pass one value from web.xml file to it but I don't know how
    I also did the same thing with servlet and it's OK, I used function getInitParameter in ServletConfig and modified file web.xml in Tomcat 3.2.
    Please help me
    Thanks in advance.

    Hi,
    For example, if your web.xml has something like:
    <context-param>
    <param-name>testParam</param-name>
    <param-value>[email protected]</param-value>
    </context-param>
    You can access the "testParam" init param from within your JSP scriptlet as:
    String value = getServletContext().getInitParameter("testParam");
    where "testParam" matches the <param-name> element of one of these initialization parameters.
    Hope that helps.
    Regards,
    Senthil Babu
    Developer Technical Support
    SUN Microsystems
    http://www.sun.com/developers/support/

  • Open a Local file from JSP

    Hi All,
    I want to access a local file from a JSP. On click of the link the local file should open. The location of the local file is
    O:/VWS00000000000000000001/REPORT_FRAGMENTS/Title1.doc
    and the hyper link on the JSP shows
    file:///O:/VWS00000000000000000001/REPORT_FRAGMENTS/Title1.doc
    somehow the file does not open from the JSP page but it opens from the browser if I type
    'file:///O:/VWS00000000000000000001/REPORT_FRAGMENTS/Title1.doc' in the address bar.
    Can anybody please help.
    regards,
    Shardul.

    if you'd like to show the real path to the user, use simply an ftp server !
    however, if you prefer a secure solution, so use a servlet:
    example:
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class SendWord extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        //get the 'file' parameter
        String fileName = (String) request.getParameter("file");
        if (fileName == null || fileName.equals(""))
          throw new ServletException(
              "Invalid or non-existent file parameter in SendWord servlet.");
        // add the .doc suffix if it doesn't already exist
        if (fileName.indexOf(".doc") == -1)
          fileName = fileName + ".doc";
        String wordDir = getServletContext().getInitParameter("word-dir");
        if (wordDir == null || wordDir.equals(""))
          throw new ServletException(
              "Invalid or non-existent wordDir context-param.");
        ServletOutputStream stream = null;
        BufferedInputStream buf = null;
        try {
          stream = response.getOutputStream();
          File doc = new File(wordDir + "/" + fileName);
          response.setContentType("application/msword");
          response.addHeader("Content-Disposition", "attachment; filename="
              + fileName);
          response.setContentLength((int) doc.length());
          FileInputStream input = new FileInputStream(doc);
          buf = new BufferedInputStream(input);
          int readBytes = 0;
          while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
        } catch (IOException ioe) {
          throw new ServletException(ioe.getMessage());
        } finally {
          if (stream != null)
            stream.close();
          if (buf != null)
            buf.close();
      public void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        doGet(request, response);
    }hope that helps

  • How can I forward to an external URL from within a DataAction?

    This is a very simple question I'd guess -- but what I thought was the obvious answer turned out not to be. Keep in mind I am using struts, and the URL is constructed dynamically, so I cannot place a struts forward action in the struts-config.xml file. Here is what I tried from within my DataAction's prepareModel() method:
    actionContext.setActionForward(newURL);
    actionContext.setRedirect(true);
    This didn't work -- nothing happened. Anyone have any ideas?
    Brad

    In our application, we had a forward named Cancel, but for it to work properly we wanted a Redirect to occur to another page. The redirect was not working until we created a new actionforward and set th action forward to it as seen below. You can't programmatically change the forwards at runtime without error, from what I remember.
    DataActionMapping mapping = ctx.getActionMapping();
    ActionForward af = mapping.findForward("Cancel");
    ActionForward afNew = new ActionForward();
    afNew.setPath(ctx.getHttpServletRequest().getSession().getServletContext().getInitParameter("rootURL") + af.getPath());
    afNew.setRedirect(true);
    ctx.setActionForward(afNew);

  • ORA-00911 Error code in JDBC where no special character is used - Oracle 10

    Hi,
    I am using Oracle 10G and Tomcat 5.5. I am trying to update a the CONFIRMED column of a table called LISTSERV_WAITING_LIST_TABLE. Please see my code below.
    public void doPost(HttpServletRequest request, HttpServletResponse response){
         String resRef = getServletContext().getInitParameter("java.comp.env");
         String jdbcDbRef = getServletContext().getInitParameter("jdbc.database");
         Context dbInitContext = null;
         Context dbEnvContext = null;
         DataSource dbSource = null;
         Connection conn = null;
    PreparedStatement prepStatement = null;
    String uemail = request.getParameter("email").toUpperCase();
         String userId = request.getParameter("userId");
         String waitingListTable = getServletContext().getInitParameter("db.waiting.list.table.name");
         try{ 
              dbInitContext = new InitialContext();
              dbEnvContext = (Context)dbInitContext.lookup(resRef);
              dbSource = (DataSource)dbEnvContext.lookup(jdbcDbRef);
              conn = dbSource.getConnection();
    String sqlcmd = "update " + waitingListTable + " SET CONFIRMED = 'YES' WHERE UEMAIL = '" + uemail + "' and USERID = '" + userId + "';";
    prepStatement = conn.prepareStatement(sqlcmd);
    prepStatement.executeUpdate();
         }catch(NamingException e){
              log("Area 4A: NamingException occured");
         }catch( SQLException e){
         log("Area 4B: Exception occured", e);
    When I run the code, I receive the following error message:
    SEVERE: FinalSubscriber: Area 4B: Exception occured
    java.sql.SQLException: ORA-00911: invalid character
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
         at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
         at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:213)
         at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:952)
         at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1160)
         at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3285)
         at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3368)
         at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:101)
         at com.sainc.nsb.FinalSubscriber.doPost(FinalSubscriber.java:40)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         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.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.Http11AprProcessor.process(Http11AprProcessor.java:831)
         at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:639)
         at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1203)
         at java.lang.Thread.run(Unknown Source)
    However, when I type the value of the string sqlcmd (used in the PreparedStatement) directly into Oracle, the update works. An example of that string is:
    update listserv_waiting_list SET CONFIRMED = 'YES' WHERE UEMAIL = '[email protected]' and USERID = '1142369642862';
    It contains no stange character and rows are inserted successfully in another class of the program that uses the same mechanism. The problem comes when I update the table.
    Any idea as to what is wrong? Your help will be appreciated.
    Thanks,
    Nguessan

    buddy, why don't you use a stored procedure and make your update, i hate that upkeeping.
    callablestatement and the power of Plsql are ur saviours.
    regards, djoudi.

  • File download with JSP

    I have found some code within this forum that I have been attempting to use to allow customers to download text files to their PC's. The code below is what I have come up with from my understandings on exactly how it should work, but it just will not work ...
    Am I correct in assuming that the file that I want to make available for download is specified within the File f = new File(path+filename); section???
    I have made the path variable refer directly to the file system (/disk2/invoice/) as well as via http (http://domain.com/invoice/) but it will not work !!!
    It returns the save/open dialog but as soon as I select an option it returns a windows error prompt as follows:
    Internet Explorer cannot download ...p?filename=123414_76453_437 from www.domain.com.
    Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later.
    Can someone please tell me, where am I supposed to reference the file to be downloaded and how am I to reference it ???
    <%
    // get the file name from the calling page
    String filename = request.getParameter("filename");
    //get the file path to the file I want to make available via download
    String path = getServletContext().getInitParameter("invoicePath");
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\";");
    int iRead;
    FileInputStream stream = null;
    try {
         File f = new File(path+filename);
         stream = new FileInputStream(f);
         while ((iRead = stream.read()) != -1) {
              out.write(iRead);
         out.flush();
    finally {
         if (stream != null) {
              stream.close();
    %>
    <%@ page import="java.io.*,javax.servlet.*,java.util.* " contentType="text/html" %>
    <html>
    finally we have success ...     
    </html>

    For those of you who are still having issues that have been unresolved trying to download a file from a webserver to a client, I have finally figured out how to do so ...
    The following code now works for me on Solaris running Tomcat 3.1 and on W2K running JRun 3.2 ...
    Issue 1: I specified a contentType=text/html in the page specification ... This must be removed ...
    <%@ page ... contentType=text/html%>
    Issue 2: The new File() reference must be a direct path to the file on the operating system. This does not work if it is referenced with a http path.
    Other than that, I have included the code that I use to make files available for download on our webserver.
    <%@ page import="java.io.*,javax.servlet.*,java.util.* "%>
    <%
    // get the file name
    String filename = request.getParameter("filename");
    //get the file path
    String path = getServletContext().getInitParameter("invoicePath");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\";");
    int iRead;
    FileInputStream stream = null;
    try {
         File f = new File("/disk2/wwwhome/psmerged/invoice/" + filename);
         stream = new FileInputStream(f);
         while ((iRead = stream.read()) != -1) {
              out.write(iRead);
         out.flush();
    finally {
         if (stream != null) {
              stream.close();
    %>

  • Significance of context param in web.xml to initialize any variable?servlet

    I am writing a standalone web appplication for rss (xml) creation where i am having jsp servlets class etc.
    Now to write rss.xml and read it back in application i have temporarily used c:\\rss.xml but to make it capable working in web application which can be uploaded in website i need to make it configurable i need to kep it in context param of web.xml and in init() method of servlet of my application what exactly i should do there.what i have tried is this :
    public class Startup extends HttpServlet {
    private static String rssFeed;
    private ServletContext ctx;
    Logger log = Logger.getLogger(Startup.class);
    public void init(){
    log.debug("Initializing APPLICATION CONTEXT Variables");
    ctx = getServletContext();
    rssFeed = (String)ctx.getInitParameter("RssFeed");
    log.debug("Rss : " + rssFeed);
    String rssFile = this.getServletContext().getRealPath("") + File.separator + "WEB-INF" + File.separator + "rss.properties";
    Properties property = new Properties();
    try{
    InputStream propertiesFile = new FileInputStream(rssFile);
    property.load(propertiesFile);
    catch (IOException e) {
    log.error("IOException during domainValuesList file Reading");
    e.printStackTrace();
    log.error("Exception while loading AllowedDomainValues file");
    log.debug("Domain Values Lists Updated");
    /** Get Host Name (Server Name) where application is hosted on
    public static String getRssFeed(){
    return rssFeed;
    after that i called this startup servlet class in other servlet taken this getRssFeed()
    stored it as string passed as parametr to other class where i need to call it but there i am getting null pointer exception which says not initialized.
    even what i have written in web.xml is here:
    <context-param>
    <param-name>RssFeed</param-name>
    <param-value>c:\\rsshandler.xml</param-value>
    </context-param>
    <servlet>
    <servlet-name>Startup</servlet-name>
    <servlet-class>src.Startup</servlet-class>
    <init-param>
    <param-name>RssFeedConfig</param-name>
    <param-value>/WEB-INF/rss-config.xml</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>Startup</servlet-name>
    <url-pattern>/Startup</url-pattern>
    <load-on-startup>1</load-on-startup>
    </servlet-mapping>
    i tried what i know or understood but its not working.
    one more thing i have doneis:created rss.properties files in web-inf
    lines added are
    rssfeed=c:\\rsshandler.xml
    but even i am not getting this why
    or what sholud i do here.
    this thing needs to be configurablewhich we can change later easily.
    any suggestions.
    thanks
    vijendra

    Ben -
    There can be init params for the servlet or for the servlet context. For the servlet, this looks like:
    <servlet>
    <servlet-name>InitServlet</servlet-name>
    <servlet-class>package1.InitServlet</servlet-class>
    <init-param>
    <param-name>message</param-name>
    <param-value>Hello From Initialization Parameter</param-value>
    </init-param>
    </servlet>
    in the web.xml file, and is accessed using:
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    message = config.getInitParameter("message");
    For a servlet context init param, you define it as you did using the web.xml settings editor:
    <context-param>
    <param-name>hello</param-name>
    <param-value>hi</param-value>
    </context-param>
    This is accessed using:
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    message1 = config.getServletContext().getInitParameter("hello");
    Hope this helps,
    Lynn
    Java Tools Team

  • Exception while excel processing after upload using commons file upload

    Hi all,
    I am experiencing problem while creating a workbook after getting the input stream from the uploaded file. its not going catch block instead it is going to finally and giving null pointer exeption in finally as one variable in finally is not defined. the variable is defined in try as well as catch but during run time the variable is not getting assigned any value also. I'll put the code over here. please help me with a solution
    import org.w3c.dom.* ;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import jxl.*;
    import org.apache.commons.fileupload.*;
    import org.apache.commons.fileupload.disk.*;
    import org.apache.commons.fileupload.servlet.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    public class CescoreUploadServlet extends baseHttpServlet
         private DataSource cesDS = null;
         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
              doPost(req, res);
         public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
              String targetPage = null;
              File f = null;
              System.out.println("Upload Controller");
              HttpSession session = req.getSession(true);
              try
                   if(cesDS == null){
                        cesDS = new JNDIDataSource(getServletContext().getInitParameter(Constants.DATA_SOURCE_NAME));
                   CesRepository cRep = new CesRepository(cesDS);
                   if (session.getAttribute("DataContainerInfo") == null) {
                        System.out.println("Initializing DataContainerInfo");
                        DataContainer DataContainer = new DataContainer();
                        cRep.setInitialParameters(DataContainer);
                        session.setAttribute("DataContainerInfo",DataContainer);
                   else System.out.println("DataContainerInfo is available");
                   UserInfo userInfo = null;               
                   String login_id = req.getRemoteUser();
                   if(session.getAttribute("UserID") != null) login_id = (String)session.getAttribute("UserID");
                   if(session.getAttribute("userProfile") == null ) session.setAttribute("userProfile", cRep.getUserInfo(login_id));
                   userInfo = (UserInfo)session.getAttribute("userProfile");
                   System.out.println("<<<<<< userInfo contains : "+userInfo.getHrID()+" >>>>>>");
                   String projIdValue = null;
                   String msg = null;
                   boolean isMultipart = FileUpload.isMultipartContent(req);
                   if(isMultipart){
                        System.out.println("is MultiPart");
                        DiskFileUpload upload = new DiskFileUpload();
                        List fileList = upload.parseRequest(req);
                        InputStream uploadedFileStream = null;
                        String uploadedFileName = null;
                        ArrayList impArray = new ArrayList();
                        Iterator iter = fileList.iterator();
                        while (iter.hasNext()) {
                             System.out.println("inside while");
                             FileItem item = (FileItem) iter.next();
                             if (!item.isFormField()) {
                                  System.out.println("item is not form field");
                                  if (item.getSize() < 1)
                                       throw new Exception("No file was uploaded");
                                  else
                                       uploadedFileName = item.getName();
                                       System.out.println("uploaded file name "+uploadedFileName);
                                       System.out.println("uploaded file size is "+item.getSize());
                                       uploadedFileStream = item.getInputStream();
                                       System.out.println("uploaded input stream available size is "+uploadedFileStream.available());
                             else
                                  System.out.println("item is form field");
                                  String key     = item.getFieldName();
                                  String value = item.getString();
                                  System.out.println("key is"+key);
                                  System.out.println("value is"+value);
                                  if(key.equals("projectId2")){
                                       projIdValue = value;
                        System.out.println("outside while");
                        POIFSFileSystem fs = new POIFSFileSystem(uploadedFileStream);
                        System.out.println("got POIFSFileSystem");//this is been printed in logs
                        HSSFWorkbook wb = new HSSFWorkbook(fs);//it is breaking over here
                        System.out.println("got HSSFWorkbook");//this is not been printed in logs
                        HSSFSheet sheet = wb.getSheetAt(0);
                        System.out.println("got HSSFSheet");
                        Iterator rows = sheet.rowIterator();
                        if(rows.hasNext()){
                        while( rows.hasNext() ) {
                             System.out.println("rows iteration");
                             HSSFRow row = (HSSFRow) rows.next();
                             Iterator cells = row.cellIterator();
                             while( cells.hasNext() ) {
                                  System.out.println("cell iteration");
                                  HSSFCell cell = (HSSFCell) cells.next();
                                  HashMap hm = new HashMap();//if everything is fine i'll use this hashmap to store values
                             System.out.println("CES UPLOAD.SERVLET. After adding");
                             msg = "Attendees have been added successfully";
                             req.setAttribute("msgText", msg);
                             targetPage = "/ces_disp.jsp";
                        else
                             throw new Exception("The Excel Sheet Uploaded has no entries. Please check and try again");
                   else{
                        throw new Exception("The Form is not Multipart");
              catch (Exception e)
                   System.out.println("CES UPLOAD.SERVLET.EXCEPTION ::: Exception");
                   targetPage = "/ces_disp.jsp";
                   if(e != null) req.setAttribute("msgText", e.getMessage());
                   else req.setAttribute(Constants.EXCEPTION_ATTR_NAME, new Exception("Unknown Exception"));
                   e.printStackTrace();
              finally{
                   System.out.println("CES UPLOAD.SERVLET. ::: Finally");
                   ServletContext stx = getServletConfig().getServletContext();
                   RequestDispatcher dispatcher = sCx.getRequestDispatcher(targetPage);
                   dispatcher.forward(req, res);
    Message was edited by: Noufal
    Noufal_k
    Message was edited by:
    Noufal_k

    import org.w3c.dom.* ;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import jxl.*;
    import org.apache.commons.fileupload.*;
    import org.apache.commons.fileupload.disk.*;
    import org.apache.commons.fileupload.servlet.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    public class CescoreUploadServlet extends baseHttpServlet
    private DataSource cesDS = null;
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    doPost(req, res);
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    //including only relevant code
    String targetPage = null;
    System.out.println("Upload Controller");
    HttpSession session = req.getSession(true);
    try
    String projIdValue = null;
    String msg = null;
    boolean isMultipart = FileUpload.isMultipartContent(req);
    if(isMultipart){
    System.out.println("is MultiPart");
    DiskFileUpload upload = new DiskFileUpload();
    List fileList = upload.parseRequest(req);
    InputStream uploadedFileStream = null;
    String uploadedFileName = null;
    Iterator iter = fileList.iterator();
    while (iter.hasNext()) {
    System.out.println("inside while");
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField()) {
    System.out.println("item is not form field");
    if (item.getSize() < 1)
    throw new Exception("No file was uploaded");
    else
    uploadedFileName = item.getName();
    System.out.println("uploaded file name "+uploadedFileName);//printing  c:/excelsheets/fileToUpload.xls
    System.out.println("uploaded file size is "+item.getSize());//printing size is 15872
    uploadedFileStream = item.getInputStream();
    System.out.println("uploaded input stream available size is "+uploadedFileStream.available());//printing available input stream size is 15872
    else
    System.out.println("item is form field");
    String key = item.getFieldName();
    String value = item.getString();
    System.out.println("key is"+key);
    System.out.println("value is"+value);
    if(key.equals("projectId2")){
    projIdValue = value;
    System.out.println("outside while");
    POIFSFileSystem fs = new POIFSFileSystem(uploadedFileStream);
    System.out.println("got POIFSFileSystem");//this is been printed in logs
    HSSFWorkbook wb = new HSSFWorkbook(fs);//it is breaking over here
    System.out.println("got HSSFWorkbook");//this is not been printed in logs
    HSSFSheet sheet = wb.getSheetAt(0);
    System.out.println("got HSSFSheet");
    Iterator rows = sheet.rowIterator();
    if(rows.hasNext()){
    while( rows.hasNext() ) {
    System.out.println("rows iteration");
    HSSFRow row = (HSSFRow) rows.next();
    Iterator cells = row.cellIterator();
    while( cells.hasNext() ) {
    System.out.println("cell iteration");
    HSSFCell cell = (HSSFCell) cells.next();
    HashMap hm = new HashMap();//if everything is fine i'll use this hashmap to store values
    System.out.println("CES UPLOAD.SERVLET. After adding");
    msg = "Attendees have been added successfully";
    req.setAttribute("msgText", msg);
    targetPage = "/ces_disp.jsp";
    else
    throw new Exception("The Excel Sheet Uploaded has no entries. Please check and try again");
    else{
    throw new Exception("The Form is not Multipart");
    catch (Exception e)
    System.out.println("CES UPLOAD.SERVLET.EXCEPTION ::: Exception");
    targetPage = "/ces_disp.jsp";
    if(e != null) req.setAttribute("msgText", e.getMessage());
    else req.setAttribute(Constants.EXCEPTION_ATTR_NAME, new Exception("Unknown Exception"));
    e.printStackTrace();
    finally{
    System.out.println("CES UPLOAD.SERVLET. ::: Finally");
    ServletContext stx = getServletConfig().getServletContext();
    RequestDispatcher dispatcher = stx.getRequestDispatcher(targetPage);//throwing null pointer exception for this line
    dispatcher.forward(req, res);
    }

  • Support Dynamic JDBC Credentials

    Can I use something similar in JDeveloper 11g like in this example http://www.oracle.com/technology/products/jdev/howtos/10g/dynamicjdbchowto.html

    Here is the class
    package userinterface;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.Iterator;
    import java.util.Map;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.servlet.jsp.JspTagException;
    import oracle.adf.model.servlet.ADFBindingFilter;
    import oracle.adf.share.ADFContext;
    import oracle.jbo.client.Configuration;
    import oracle.jbo.common.JBOClass;
    import oracle.jbo.common.ampool.ApplicationPoolException;
    public class DynamicJDBCBindingFilter extends ADFBindingFilter {
    public DynamicJDBCBindingFilter() {
    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException,
    ServletException {
    HttpServletRequest svrRequest = (HttpServletRequest)request;
    HttpSession session = svrRequest.getSession(true);
    if (!isLoggedIn(session)) {
    if (!isLoginRequest(svrRequest)) {
    String method = svrRequest.getMethod();
    String requestUri = svrRequest.getRequestURI();
    if (method.equalsIgnoreCase("GET") &&
    requestUri.endsWith(loginPageRedirectName())) {
    super.doFilter(request, response, chain);
    } else {
    forwardToLoginPage(request, response);
    } else {
    try {
    String usrName = request.getParameter(USERNAME_PARAM);
    String pswd = request.getParameter(PASSWORD_PARAM);
    * If you need to support dynamically changing the JDBC URL
    * (for example to support changing which database instance
    * you are pointing at on the fly, then you need to change
    * the line of code below to assign a non-null value to the
    * jdbcURL variable. You would need to take the user-supplied
    * information and formulate a valid JDBC connection URL connection
    * string (without username and password) that looks like this:
    * jdbc:oracle:thin:@localhost:1521:ORCL
    * machine port SID
    * and then set this the jdbcURL variable to this value.
    String jdbcURL = "jdbc:oracle:thin:@10.3.3.68:1521:des10g";
    if (usrName == null || usrName.length() == 0 ||
    pswd == null || pswd.length() == 0) {
    throw new BlankUserNameOrPassword();
    session.setAttribute(Configuration.DB_USERNAME_PROPERTY,
    usrName);
    session.setAttribute(Configuration.DB_PASSWORD_PROPERTY,
    pswd);
    if (jdbcURL != null) {
    session.setAttribute(Configuration.DB_CONNECT_STRING_PROPERTY,
    jdbcURL);
    super.doFilter(request, response, chain);
    if (request.getAttribute(FAILED_ATTR) == null) {
    session.setAttribute(LOGGEDIN_ATTR, NON_NULL_VALUE);
    } catch (Exception e) {
    if (isFailedLoginException(e)) {
    signalFailedLoginAttempt(svrRequest);
    redirectToLoginPageOnLogonError(request, response);
    } else if (e instanceof ServletException) {
    throw (ServletException)e;
    } else {
    e.printStackTrace();
    throw new ServletException(e);
    } else {
    super.doFilter(request, response, chain);
    * Encapsulate detecting if the exception thrown
    * represents a failed login attempt.
    private boolean isFailedLoginException(Exception e) {
    * In 9.0.5.2, our eager AM acquisition will
    * cause the application pool exception to appear
    * without being wrapped.
    if (e instanceof ApplicationPoolException ||
    e instanceof BlankUserNameOrPassword) {
    return true;
    } else if (e instanceof ServletException) {
    Throwable rootCause = ((ServletException)e).getRootCause();
    * In 10.1.2 Struts, our lazy AM acquisition causes
    * the failed database login to be wrapped in a
    * ServletException that contains the ApplicationPoolException
    if (rootCause instanceof ApplicationPoolException) {
    return true;
    * In 10.1.2 JSP Model 1, our lazy AM acquisition causes
    * the failed database login to be wrapped in a
    * ServletException that contains a JspTagException.
    * The JspTagException does not wrap the original error,
    * but only encapsulate the original errors getMessage() value.
    if (rootCause instanceof JspTagException) {
    String errMsg = ((JspTagException)rootCause).getMessage();
    if (errMsg != null && errMsg.startsWith(APP_POOL_ERR_MSG)) {
    return true;
    return false;
    * Forwards control to the login page.
    private void forwardToLoginPage(ServletRequest request,
    ServletResponse response) throws ServletException,
    IOException {
    HttpServletResponse responseHttp = (HttpServletResponse)response;
    responseHttp.sendRedirect(loginPageRedirectName());
    markResponseCompleteIfUsingJSF();
    private void redirectToLoginPage(ServletRequest request,
    ServletResponse response) throws ServletException,
    IOException {
    HttpServletResponse responseHttp = (HttpServletResponse)response;
    responseHttp.sendRedirect(loginPageRedirectName());
    markResponseCompleteIfUsingJSF();
    private void redirectToLoginPageOnLogonError(ServletRequest request,
    ServletResponse response) throws ServletException,
    IOException {
    HttpServletResponse responseHttp = (HttpServletResponse)response;
    responseHttp.sendRedirect(loginPageRedirectName((HttpServletRequest)request) + "?failed=true");
    markResponseCompleteIfUsingJSF();
    * Signal a failed login attempt
    private void signalFailedLoginAttempt(HttpServletRequest request) {
    HttpSession session = request.getSession(true);
    session.setAttribute(LOGGEDIN_ATTR, null);
    request.setAttribute(FAILED_ATTR, NON_NULL_VALUE);
    session.invalidate();
    * If we are running in a Faces environment, invoke
    * the FacesContext.responseComplete() method after
    * the session invalidate. We use Java reflection
    * so that our code can still work in a Non-Faces
    * environment, too.
    private void markResponseCompleteIfUsingJSF() {
    try {
    Class c = JBOClass.forName("javax.faces.context.FacesContext");
    Method m = c.getMethod("getCurrentInstance", null);
    Object obj = m.invoke(null, null);
    m = c.getMethod("responseComplete",null);
    m.invoke(obj,null);
    } catch (InvocationTargetException ex) {
    throw new RuntimeException(ex);
    } catch (IllegalAccessException ex) {
    throw new RuntimeException(ex);
    } catch (NoSuchMethodException ex) {
    throw new RuntimeException(ex);
    } catch (ClassNotFoundException ex) {
    // Ignore, we're not running in a faces context.
    * Returns true if user is currently logged in
    private boolean isLoggedIn(HttpSession session) {
    return session.getAttribute(LOGGEDIN_ATTR) != null;
    * Returns true if the current request is a login request.
    private boolean isLoginRequest(HttpServletRequest request) {
    return request.getParameter(IS_LOGIN_PAGE_PARAM) != null &&
    request.getMethod().equalsIgnoreCase("POST");
    private static final String LOGIN_PAGE_REDIRECT_PARAM = "RedirectToLogin";
    private static final String FACES_URL_PATTERN_PARAM = "FacesURLPattern";
    private static final String LOGGEDIN_ATTR = "loggedin";
    private static final String FAILED_ATTR = "failed";
    private static final String USERNAME_PARAM = "form:username";
    private static final String PASSWORD_PARAM = "form:password";
    private static final String IS_LOGIN_PAGE_PARAM = "form:_loginpage";
    private static final String NON_NULL_VALUE = "x";
    private static final String APP_POOL_ERR_MSG = "JBO-30003";
    private static String loginPageRedirectName = null;
    private String facesURLPattern = null;
    private String loginPageRedirectName() {
    return loginPageRedirectName;
    private String loginPageRedirectName(HttpServletRequest request) {
    if (facesURLPattern != null) {
    if (request.getRequestURI().indexOf(facesURLPattern) == -1) {
    return facesURLPattern+loginPageRedirectName;
    return loginPageRedirectName;
    public void init(FilterConfig filterConfig) throws ServletException {
    super.init(filterConfig);
    loginPageRedirectName =
    filterConfig.getServletContext().getInitParameter(LOGIN_PAGE_REDIRECT_PARAM);
    facesURLPattern =
    filterConfig.getServletContext().getInitParameter(FACES_URL_PATTERN_PARAM);
    }

  • Displaying xml content in the browser

    Hi,
    In my application i am generating an XML content which i was storing into a file. Now as per the new requirement, this xml content needs to be displayed in the browser. (The way it gets displayed when we double click on an xml file).
    Can some one plz tel me how to do this? I am using the jsp/servlet architechture..? plz help
    Thanx

    Program 1
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class SendXml extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        //get the 'file' parameter
        String fileName = (String) request.getParameter("file");
        if (fileName == null || fileName.equals(""))
          throw new ServletException(
              "Invalid or non-existent file parameter in SendXml servlet.");
        // add the .doc suffix if it doesn't already exist
        if (fileName.indexOf(".xml") == -1)
          fileName = fileName + ".xml";
        String xmlDir = getServletContext().getInitParameter("xml-dir");
        if (xmlDir == null || xmlDir.equals(""))
          throw new ServletException(
              "Invalid or non-existent xmlDir context-param.");
        ServletOutputStream stream = null;
        BufferedInputStream buf = null;
        try {
          stream = response.getOutputStream();
          File xml = new File(xmlDir + "/" + fileName);
          response.setContentType("text/xml");
          response.addHeader("Content-Disposition", "attachment; filename="
              + fileName);
          response.setContentLength((int) xml.length());
          FileInputStream input = new FileInputStream(xml);
          buf = new BufferedInputStream(input);
          int readBytes = 0;
          while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
        } catch (IOException ioe) {
          throw new ServletException(ioe.getMessage());
        } finally {
          if (stream != null)
            stream.close();
          if (buf != null)
            buf.close();
      public void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        doGet(request, response);
    Program 2
    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class ResourceServlet extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        //get web.xml for display by a servlet
        String file = "/WEB-INF/web.xml";
        URL url = null;
        URLConnection urlConn = null;
        PrintWriter out = null;
        BufferedInputStream buf = null;
        try {
          out = response.getWriter();
          url = getServletContext().getResource(file);
          //set response header
          response.setContentType("text/xml");
          urlConn = url.openConnection();
          //establish connection with URL presenting web.xml
          urlConn.connect();
          buf = new BufferedInputStream(urlConn.getInputStream());
          int readBytes = 0;
          while ((readBytes = buf.read()) != -1)
            out.write(readBytes);
        } catch (MalformedURLException mue) {
          throw new ServletException(mue.getMessage());
        } catch (IOException ioe) {
          throw new ServletException(ioe.getMessage());
        } finally {
          if (out != null)
            out.close();
          if (buf != null)
            buf.close();
      public void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        doGet(request, response);
    }Have fun

  • Sending an e-mail using java

    Hi,
    I am sending an e-mail using java. It works fine, but I wanted to know if there is any possibility to attach a document, without using a File object. Because I have to write the File object and then delete it at the end. I would like to know if I can use for example a byte [], or something else.
    Thank you very much.
    This is my code, if that helps.
    public static void sendWithAttach(String p_sender, String p_receiver, String p_subject,
    String p_comment, int p_nombrePiecesJoints, HashMap<String, byte[]> p_files) {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", Solapcore.getCurrent().getServletConfig().getServletContext().getInitParameter("SMTP"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage sender = new MimeMessage(session);
    MimeBodyPart mbp1 = new MimeBodyPart();
    Multipart mp = new MimeMultipart();
    List<File> listeFiles = new ArrayList<File>();
    try {
    //On assigne to, from, subject, body, priority
    sender.setRecipients(javax.mail.Message.RecipientType.TO,
    InternetAddress.parse(p_receiver, false));
    sender.setFrom(new InternetAddress(p_sender));
    sender.setSubject(p_subject);
    mbp1.setText(p_comment);
    //sender.setPriority(0);
    mp.addBodyPart(mbp1);
    //On attache les documents
    for(Map.Entry<String, byte[]> entry : p_files.entrySet()) {
    MimeBodyPart mbp2 = new MimeBodyPart();
    String fileName = entry.getKey();
    byte [] dataFile = entry.getValue();
    File file = new File(fileName);
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(dataFile);
    mbp2.attachFile(file);
    mbp2.setFileName(fileName);
    mp.addBodyPart(mbp2);
    listeFiles.add(file);
    sender.setContent(mp);
    Transport.send(sender);
    }catch(MessagingException mex) {
    mex.printStackTrace();
    }catch(FileNotFoundException fnf) {
    fnf.printStackTrace();
    }catch(IOException ioe) {
    ioe.printStackTrace();
    }finally {
    Iterator<File> itListeFiles = listeFiles.iterator();
    while(itListeFiles.hasNext()) {
    File tempFile = (File)itListeFiles.next();
    tempFile.delete();
    }

    Thank you very much.
       public static void sendWithAttach(String p_sender, String p_receiver, String p_subject,
          String p_comment, int p_nombrePiecesJoints, HashMap<String, byte[]> p_files) {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", Solapcore.getCurrent().getServletConfig().getServletContext().getInitParameter("SMTP"));
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage sender = new MimeMessage(session);
        MimeBodyPart mbp1 = new MimeBodyPart();
        Multipart mp = new MimeMultipart();
        List<File> listeFiles = new ArrayList<File>();
        try {
          //On assigne to, from, subject, body, priority
          sender.setRecipients(javax.mail.Message.RecipientType.TO,
              InternetAddress.parse(p_receiver, false));
          sender.setFrom(new InternetAddress(p_sender));
          sender.setSubject(p_subject);
          mbp1.setText(p_comment);
          //sender.setPriority(0);
          mp.addBodyPart(mbp1);
          //On attache les documents
          for(Map.Entry<String, byte[]> entry : p_files.entrySet()) {
            MimeBodyPart mbp2 = new MimeBodyPart();
            String fileName = entry.getKey();
            byte [] dataFile = entry.getValue();
            File file = new File(fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(dataFile);
            mbp2.attachFile(file);
            mbp2.setFileName(fileName);
            mp.addBodyPart(mbp2);
            listeFiles.add(file);
          sender.setContent(mp);
          Transport.send(sender);
        }catch(MessagingException mex) {
          mex.printStackTrace();
        }catch(FileNotFoundException fnf) {
          fnf.printStackTrace();
        }catch(IOException ioe) {
          ioe.printStackTrace();
        }finally {
          Iterator<File> itListeFiles = listeFiles.iterator();
          while(itListeFiles.hasNext()) {
            File tempFile = (File)itListeFiles.next();
            tempFile.delete();
        }

  • Add file config for hole application?

    Hi everyone,
    Is there any one worked with build file config for hole fusion adf application? It is similar with web.config in .NET ASP web site. I think in jdeveloper, we can use web.xml for add some parameter but don't know how to read this parameter?
    Any help is appreciate!
    Thank.

    User, please tell us your jdeveloper version!
    In general you can read context or innit parameters from web.xml.
    You get to them via the servlet context
    String databaseHost =getServletContext().getInitParameter("database.host");
    And to get to the servlet context use
    FacesContext ctx = FacesContext.getCurrentInstance(); ServletContext servletContext = (ServletContext) ctx.getExternalContext().getContext();
    Timo

  • JSP - Bean - Scope Issue with ResultSet

    Hi there,
    I have a JSP page that uses a Bean to get ResultSets from a db. My methods return ResultSets, but they seem to get out of scope on the JSP page when I try to use them. I'm not sure why. I have included 2 snippets below one that works and one that doesn't. I get a java.lang.null exception when the page is run. Not sure how or why the variable seems to go out of scope? I can work around it, but I would rather find out why this is happening.
    This one fails:
    <%@ page errorPage="error.jsp" %>
    <%@ page import="utils.LookupBean" %>
    <%@ page import="java.sql.ResultSet" %>
    <%
    try{
    %>
    <html>
    <head>
    <title>lookup</title>
    </head>
    <body>
    <jsp:useBean id="lookup" class="utils.LookupBean">
    <%
    ResultSet roem = lookup.getOEMDropdown();
    //open db conn
    lookup.openIlprod();
    if(roem!=null){
    %>
    OEM:  
    <select name="OEM">
    <%
    while(roem.next()){
    %>
    <option value="<%=roem.getString("id")%>"><%=roem.getString("name")%></option>
    <%
    %>
    </select><br><br>
    <%
    else{
    out.println("OEM:  no records<br><br>");
    %>
    </jsp:useBean>
    </body>
    </html>
    <%
    catch(Exception e){     
         //log to Tomcat
    %>
    This one works....why??
    <%@ page errorPage="error.jsp" %>
    <%@ page import="utils.LookupBean" %>
    <%@ page import="java.sql.ResultSet" %>
    <%
    try{
    %>
    <html>
    <head>
    <title>lookup</title>
    </head>
    <body>
    <jsp:useBean id="lookup" class="utils.LookupBean">
    <%
    //open db conn
    lookup.openIlprod();
    ResultSet roem = lookup.getOEMDropdown();
    if(roem!=null){
    %>
    OEM:  
    <select name="OEM">
    <%
    while(roem.next()){
    %>
    <option value="<%=roem.getString("id")%>"><%=roem.getString("name")%></option>
    <%
    %>
    </select><br><br>
    <%
    else{
    out.println("OEM:  no records<br><br>");
    %>
    </jsp:useBean>
    </body>
    </html>
    <%
    catch(Exception e){     
         //log to Tomcat
    %>

    <%@ page errorPage="error.jsp" %>
    <%@ page import="utils.LookupBean" %>
    <%@ page import="java.sql.ResultSet" %>
    <%
    String ilprod_db_user;
    String ilprod_db_pass;
    String tedsi_prod_owner;
    String nsp_portal_owner;
    String iladmin_owner;
    String ilprod_db_host;
    String ilprod_db_port;
    String ilprod_db_service;
    try{
         //get the ilprod_db_user from the deployment descriptor
         ilprod_db_user = (String)getServletContext().getInitParameter("ilprod_db_user");
         //ensure a value is present
         if(ilprod_db_user==null||ilprod_db_user.equals("")){
         throw new ServletException("Error retrieving ilprod_db_user from deployment descriptor. - ilprod_db_user is null or an empty string");
         //get the ilprod_db_pass from the deployment descriptor
         ilprod_db_pass = (String)getServletContext().getInitParameter("ilprod_db_pass");
         //ensure a value is present
         if(ilprod_db_pass==null||ilprod_db_pass.equals("")){
         throw new ServletException("Error retrieving ilprod_db_pass from deployment descriptor. - ilprod_db_pass is null or an empty string");
         //get the tedsi_prod_owner from the deployment descriptor
         tedsi_prod_owner = (String)getServletContext().getInitParameter("tedsi_prod_owner");
         //ensure a value is present
         if(tedsi_prod_owner==null||tedsi_prod_owner.equals("")){
         throw new ServletException("Error retrieving tedsi_prod_owner from deployment descriptor. - tedsi_prod_owner is null or an empty string");
         //get the nsp_portal_owner from the deployment descriptor
         nsp_portal_owner = (String)getServletContext().getInitParameter("nsp_portal_owner");
         //ensure a value is present
         if(nsp_portal_owner==null||nsp_portal_owner.equals("")){
         throw new ServletException("Error retrieving nsp_portal_owner from deployment descriptor. - nsp_portal_owner is null or an empty string");
         //get the iladmin_owner from the deployment descriptor
         iladmin_owner = (String)getServletContext().getInitParameter("iladmin_owner");
         //ensure a value is present
         if(iladmin_owner==null||iladmin_owner.equals("")){
         throw new ServletException("Error retrieving iladmin_owner from deployment descriptor. - iladmin_owner is null or an empty string");
         //get the ilprod_db_host from the deployment descriptor
         ilprod_db_host = (String)getServletContext().getInitParameter("ilprod_db_host");
         //ensure a value is present
         if(ilprod_db_host==null||ilprod_db_host.equals("")){
         throw new ServletException("Error retrieving ilprod_db_host from deployment descriptor. - ilprod_db_host is null or an empty string");
         //get the ilprod_db_port from the deployment descriptor
         ilprod_db_port = (String)getServletContext().getInitParameter("ilprod_db_port");
         //ensure a value is present
         if(ilprod_db_port==null||ilprod_db_port.equals("")){
         throw new ServletException("Error retrieving ilprod_db_port from deployment descriptor. - ilprod_db_port is null or an empty string");
         //get the ilprod_db_service from the deployment descriptor
         ilprod_db_service = (String)getServletContext().getInitParameter("ilprod_db_service");
         //ensure a value is present
         if(ilprod_db_service==null||ilprod_db_service.equals("")){
         throw new ServletException("Error retrieving ilprod_db_service from deployment descriptor. - ilprod_db_service is null or an empty string");
    %>
    <html>
    <head>
    <title>lookup</title>
    </head>
    <body>
    <jsp:useBean id="lookup" class="utils.LookupBean">
    <jsp:setProperty name="lookup" property="ilprod_db_user" value="<%=ilprod_db_user%>"/>
    <jsp:setProperty name="lookup" property="ilprod_db_pass" value="<%=ilprod_db_pass%>"/>
    <jsp:setProperty name="lookup" property="tedsi_prod_owner" value="<%=tedsi_prod_owner%>"/>
    <jsp:setProperty name="lookup" property="nsp_portal_owner" value="<%=nsp_portal_owner%>"/>
    <jsp:setProperty name="lookup" property="iladmin_owner" value="<%=iladmin_owner%>"/>
    <jsp:setProperty name="lookup" property="ilprod_db_host" value="<%=ilprod_db_host%>"/>
    <jsp:setProperty name="lookup" property="ilprod_db_port" value="<%=ilprod_db_port%>"/>
    <jsp:setProperty name="lookup" property="ilprod_db_service" value="<%=ilprod_db_service%>"/>
    <%
    //open db conn
    lookup.openIlprod();
    ResultSet roem = lookup.getOEMDropdown();
    ResultSet rstat = lookup.getStatusDropdown();
    if(roem!=null){
    %>
    OEM:��
    <select name="OEM">
    <%
    while(roem.next()){
    %>
    <option value="<%=roem.getString("id")%>"><%=roem.getString("name")%></option>
    <%
    %>
    </select><br><br>
    <%
    else{
    out.println("OEM:  no records<br><br>");
    //******* IF I PUT ResultSet IN FRONT OF rstat HERE IT WORKS FINE?
    rstat = lookup.getStatusDropdown();
    if(rstat!=null){
    %>
    Status:��
    <select name="status">
    <%
    while(rstat.next()){
    %>
    <option value="<%=rstat.getString("id")%>"><%=rstat.getString("description")%></option>
    <%
    %>
    </select><br><br>
    <%
    else{
    out.println("Status:  no records<br><br>");
    //close db conn
    lookup.closeIlprod();
    %>
    </jsp:useBean>
    </body>
    </html>
    <%
    catch(Exception e){
         //set request attributes to pass to error page
         request.setAttribute("javax.servlet.error.exception",e);
         request.setAttribute("javax.servlet.error.message",e.getMessage());
         request.setAttribute("javax.servlet.error.request_uri",     request.getRequestURI());
         request.setAttribute("javax.servlet.error.servlet_name", request.getServletPath());
         //log to Tomcat
         application.log(" Message: "+e.getMessage()+'\r'+'\n'+"RequestURI: "+request.getRequestURI()+'\r'+'\n'+"Servlet Path: "+request.getServletPath(),e);
         //forward to the error page
         RequestDispatcher rd =     request.getRequestDispatcher("error.jsp");
         rd.forward(request,response);
         //out.println(e.getMessage());
    %>

Maybe you are looking for

  • Float not being cleared-- why not?

    On the webpage http://amethystartworks.com/ I am trying to get the container div <div id="header_again"> to expand to the height of the div inside it: <div id="left"> . I have inserted a spacer div <div class="spacer"> </div> immediately after <div i

  • Help with a vertical scroll bar issue with a List component

    hi. i have a basic <s:list> that uses an XMLListCollection as it's data provider and a very basic itemrenderer. when a row in the list is clicked a function gets the list.selectedIndex then populates some text fields with more xml data. that all work

  • How to install external Hard Disk Drive

    I don't know if it is a good idea or even if there are other options, but I need to know how to install a GreenDrive ex. hard disk with out screwing everythinp up. Please help

  • Usage of htmlb controls  in javascript

    hi, Could anybody give links regarding the usage of htmlb controls in javascript?

  • Camera specific details

    Yes this will seem a very thick question .... I've downloaded and installed Camera Profiles Beta 2 .... In the drop down list for LR and ACR should there be specific mention of 5DII ? or is Camera Faithful etc as good as it gets.... I just want to kn