Double casting (code example from Struts)

I saw a line when I was looking at a Struts example:
String username = ((LogonForm) form).getUsername();This was the first time I saw double casting.
I couldnt understand what was happening here.
I think the programmer wrote it this way to compact the code,
but if u were to write it in long form, I wasn't sure what it would look like.

izzy75 wrote:
This was the first time I saw double casting.
I couldnt understand what was happening here.It's not "double casting". The programmer is doing only one cast: casting form to a LogonForm, and then using a set of outer parenthesis to then call a LogonForm method. If he just did this:
(LogonForm)form.getUsername()the compiler would think that he was calling a form method. The outer parenthesis tell the compiler that getUsername is in fact a LogonForm method.

Similar Messages

  • Error running code examples from Training Video

    I am currently learning Java and I am using a Java Training series from Sun. There are several code examples that I am having problems running. I am 99.9% sure that my code is correct. That is the code that I have followed along and written.
    Here is an example of code that I am trying to run. ( I am on OS X 10.5 BTW )
    public class Person
         public int ageYears = 32;
         public void calculateAge()
              int ageDays = ageYears * 365;
              long ageSeconds = ageYears * 365 * 24L * 60 *60;
              long ageMinutes = ageSeconds / 60;
              long ageMilliseconds = ageSeconds * 1000;
              System.out.println("You are " + ageDays +  " days old.");
              System.out.println("You are " + ageSeconds + " seconds old.");
              System.out.println("You are " + ageMinutes + " minutes old.");
              System.out.println("You are " + ageMilliseconds + " milliseconds old.");
    }After I create the file (which is named Person.java) I open the terminal and cd to the directory the file is in. In my terminal I first say
    javac Person.java
    I don't get any errors at all. Then I try to run the program like this.
    java Person
    When I try this I get the following error
    Exception in thread "main" java.lang.NoSuchMethodError: main
    I am not sure why I get this error. On the instruction video the instructors code seams to run just fine with out have a main function. The instructor is on Windows and I am not sure if that has anything to do with it or not?
    Any thoughts or suggestions would be really helpful.

    mswallace wrote:
    I am currently learning Java and I am using a Java Training series from Sun. There are several code examples that I am having problems running. I am 99.9% sure that my code is correct. That is the code that I have followed along and written. Trust what the compiler and the JVM say to you.
    I am not sure why I get this error. On the instruction video the instructors code seams to run just fine with out have a main function. The instructor is on Windows and I am not sure if that has anything to do with it or not?
    Any thoughts or suggestions would be really helpful.So, as the error is asking you, where is the main method that every runnable program must have? This has nothing to do with windows and everything to do with all programs needing a main method to run (even applets where the main method is I believe within the Applet class code).

  • What can be done to make these code examples work on web Browsers?

    I have tried numerous versions of ?Hello World? examples over the web to display the text on a web page. All the examples work on my local machine in the application viewer, but they don?t work when from a web browser. I have tried both Firefox and IE.
    Some of them include:
    [http://java.sun.com/docs/books/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java|http://java.sun.com/docs/books/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java]
    Firefox error:
    java.lang.reflect.InvocationTargetException
         at com.sun.deploy.util.DeployAWTUtil.invokeAndWait(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.runOnEDT(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.ClassCastException: start.HelloWorldSwing cannot be cast to java.applet.Applet
         at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Exception: java.lang.reflect.InvocationTargetException [http://en.wikipedia.org/wiki/Swing_%28Java%29|http://en.wikipedia.org/wiki/Swing_%28Java%29]
    Error when viewed on Firefox:
    java.lang.reflect.InvocationTargetException
         at com.sun.deploy.util.DeployAWTUtil.invokeAndWait(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.runOnEDT(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.ClassCastException: start.SwingExample cannot be cast to java.applet.Applet
         at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Exception: java.lang.reflect.InvocationTargetException An Ideal Code if someone could decipher why it fails from a browser is:
    import javax.swing.*;
    public class SwingHelloWorld extends JFrame {
        public SwingHelloWorld(String name) {
          super(name);
          this.setDefaultCloseOperation(EXIT_ON_CLOSE);
          JLabel label = new JLabel(name);
          // label.setPreferredSize(new Dimension(210, 80));
          this.getContentPane().add(label);
          this.pack();
          this.setVisible(true);
      public static void main(String argv[]) {
            SwingHelloWorld swingHelloWorld = new SwingHelloWorld("This would be great if it worked via a browser!");
    } Error from Firefox:
    java.lang.reflect.InvocationTargetException
         at com.sun.deploy.util.DeployAWTUtil.invokeAndWait(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.runOnEDT(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.RuntimeException: java.lang.InstantiationException: start.SwingHelloWorld
         at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.InstantiationException: start.SwingHelloWorld
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         ... 9 more
    Exception: java.lang.reflect.InvocationTargetException The latter code is very short and would serve the intended purpose most ideal. It can accept input and allow me to replace the ?System.out.println? function that works so well to display when working with code in the development environment.
    Thanks in advance for any input on this.
    -- L. James
    L. D. James
    Edited by: apollothethird on Mar 8, 2010 5:05 AM

    paulcw wrote:
    As per your suggestion, I changed the “extend” to Applet and changed it to “JApplet”. Making that change will result in code that won?t even compile.Right. You're going to have to change your program to actually work as an applet.
    Either that or use Java Web Start, which is probably the best option.Thanks. The code I presented was my attempt to find examples that represented the advice I thought I was getting (to use JFrame and JLabels). I?m changing the direction of the examples I?m looking for now.
    >
    The current code as published by sun.com actually compiles and displays in the Netbeans programming environment. It looks great. But I?m kind of stuck with the missing link for making it output to the browser.Different things work in different ways. You wrote a standalone application which compiles and runs. Writing an applet is a different thing, and works in a different way. Read the applet tutorials for more information on applet methods and the applet lifecycle.Thanks. I?m reading. I try to execute some of the examples from my reading, but and stuck. So, I?m asking for some clarifications of some of the components I?m stuck with. Having some of my questions answered would help me to understand better the lots of reading and studying that I?m doing.
    I?m taking in all the advice that is given, and I appreciate it a lot.
    >
    Thanks for the hints. Thanks also in advance if you happen to know how to change the extend to Applet or JApplet instead of “JFrame” and it works.This is made clear in the applet tutorials. It's more than just changing the class to extend. Note that Applet/JApplet extends Panel/JPanel, so that changes the way your program is constructed. Basically, you don't have to create your own frame.Also, I don?t want a frame. I?m trying to find a way to make my question clear. I appreciate the time you?re taking to respond to a new user?s scope.
    >
    But again, web start is probably a better choice if you have a running app.
    You should probably abandon the idea that you just have to nudge a program slightly in a new direction to make a wholly new thing. Programming is all about reducing complex problems to a set of concrete solutions.Absolutely. I have some examples that will actually print a string to a browser. However, those examples will print what?s written in the immediate code, with no apparent method (that I can) make into a variable. The ?Hello World? example that I find that has a main class is the ones that are failing. The ones that don?t have a main class will print.
    I have been trying to find a way to pass a variable to this code that will print over the web:
    import javax.swing.JApplet;
    import javax.swing.SwingUtilities;
    import javax.swing.JLabel;
    public class HelloWorld extends JApplet {
        //Called when this applet is loaded into the browser.
        public void init() {
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        JLabel lbl = new JLabel("Hello World");
                        add(lbl);
            } catch (Exception e) {
                System.err.println("createGUI didn't complete successfully");
    }However when I try to add a functioning main class and change the ?Hello World? to a string variable, it fails. I understand it fails because I?m having a missing link about how to turn the class into something that can take input.
    I know I?ll be ridiculed for the example I?m about to print, but I?m printing it to give an example of having a variable for my output.
    Look at the code that fails (just to get an idea of what I?m trying to explain):
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package test1;
    * @author teama
    import javax.swing.JApplet;
    import javax.swing.SwingUtilities;
    import javax.swing.JLabel;
    public class HelloWorld extends JApplet {
        //Called when this applet is loaded into the browser.
        public void init() {
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run(String myhello) {
                        JLabel lbl = new JLabel(myhello);
                        add(lbl);
            } catch (Exception e) {
                System.err.println("createGUI didn't complete successfully");
            public static void main(String[] args) {
                // This is the output of my calculation
                // HelloWorld.void("Hello World")
                run("My Hello")               
    } -- L. James
    L. D. James

  • Magenta cast when printing from any app in Mountain Lion

    I get a serious magenta cast when printing from any application using my Epson R3000 inkjet. I am aware of the double profile issue. For example in Photoshop I let it do the color management. ML automatically turns off printer color management. My monitor is calibrated with Xrite Color Munki. I did not have this issue before upgrading to ML 8.2. Is there a driver issue?

    In System Preferences->Monitors->color is the correct
    color profile set?
    Do you you have the correct profile for the printer
    selected in Photoshop?
    Also, are you using Proof Setup in Views?
    Need to ask since sometimes a person can stare at
    something too long and think it is correct (done it myself often).
    It may not be a driver but an issue with color profiles.
    It is possible one or more of the color profiles may be corrupted.
    Go to Utilities->ColorSync Utility select and run Profile First Aid.
    See if problems found in profiles.
    Using PS CS6 myself and have not seen any such issues with
    color and 10.8.2.

  • Setting ViewObject Stored Procedure Where Clause Param from Struts Action

    I adapted/used Steve's example to get stored procedure to populate my ViewObject. However, I could not retrieve any rows after passing whereClause value from Struts action. The param in execureQueryForCollection returns null.
    What could be wrong. Thanks.
    Here's my code.
    ViewObjectImpl:
    package org.adb.sls.model;
    import java.math.BigDecimal;
    import java.sql.CallableStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.sql.Types;
    import oracle.jbo.JboException;
    import oracle.jbo.domain.Date;
    import oracle.jbo.domain.Number;
    import oracle.jbo.server.DBTransaction;
    import oracle.jbo.server.ViewObjectImpl;
    import oracle.jbo.server.ViewRowImpl;
    import oracle.jbo.server.ViewRowSetImpl;
    import oracle.jdbc.driver.OracleCallableStatement;
    import oracle.jdbc.driver.OracleTypes;
    // --- File generated by Oracle ADF Business Components Design Time.
    // --- Custom code may be added to this class.
    public class ViewApplicableLoanTypesImpl extends ViewObjectImpl
    * PLSQL block that will execute the REF_CURSOR
    private static final String SQL =
    "begin ? := sls_loan_types_pkg.get_applcbl_staff_lns_fn(?); end;";
    * PLSQL block that will count the REF_CURSOR returned rows
    private static final String COUNTSQL =
    "begin ? := sls_loan_types_pkg.get_count_applcbl_staff_lns_fn(?); end;";
    * This is the default constructor (do not remove)
    public ViewApplicableLoanTypesImpl()
    * Overridden framework method.
    * Wipe out all traces of a built-in query for this VO
    protected void create() {
    getViewDef().setQuery(null);
    getViewDef().setSelectClause(null);
    setQuery(null);
    * Overidden framework method
    protected void executeQueryForCollection(Object qc, Object[] params, int noUserParams)
    // input parameter is employee number
    String employeeNumber = null;
    if (params != null) {
    employeeNumber = (String) params[0];
    } else
    System.out.println("param is null");
    storeNewResultSet(qc,retrieveRefCursor(qc,employeeNumber));
    super.executeQueryForCollection(qc, params, noUserParams);
    protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs)
    * We ignore the JDBC ResultSet passed by the framework (null anyway) and
    * use the resultset that we've stored in the query-collection-private
    * user data storage
    rs = getResultSet(qc);
    * Create a new row to populate
    ViewRowImpl r = createNewRowForCollection(qc);
    try {
    * Populate new row by attribute slot number for current row in Result Set
    populateAttributeForRow(r,0, nullOrNewNumber(rs.getBigDecimal(1)));
    populateAttributeForRow(r,1, nullOrNewNumber(rs.getBigDecimal(2)));
    populateAttributeForRow(r,2, rs.getString(3));
    populateAttributeForRow(r,3, nullOrNewNumber(rs.getBigDecimal(4)));
    populateAttributeForRow(r,4, rs.getString(5));
    catch (SQLException s) {
    throw new JboException(s);
    return r;
    protected boolean hasNextForCollection(Object qc)
    ResultSet rs = getResultSet(qc);
    boolean nextOne = false;
    try {
    nextOne = rs.next();
    * When were at the end of the result set, mark the query collection
    * as "FetchComplete".
    if (!nextOne) {
    setFetchCompleteForCollection(qc, true);
    * Close the result set, we're done with it
    rs.close();
    catch (SQLException s) {
    throw new JboException(s);
    return nextOne;
    protected void releaseUserDataForCollection(Object qc, Object rs)
    * Ignore the ResultSet passed in since we've created our own.
    * Fetch the ResultSet from the User-Data context instead
    ResultSet userDataRS = getResultSet(qc);
    if (userDataRS != null) {
    try {
    userDataRS.close();
    catch (SQLException s) {
    /* Ignore */
    super.releaseUserDataForCollection(qc, rs);
    public long getQueryHitCount(ViewRowSetImpl viewRowSet)
    Object[] params = viewRowSet.getParameters(true);
    String id = (String)params[0];
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement(COUNTSQL,DBTransaction.DEFAULT);
    * Register the first bind parameter as our return value of type CURSOR
    st.registerOutParameter(1,Types.NUMERIC);
    * Set the value of the 2nd bind variable to pass id as argument
    if (id == null) st.setNull(2,Types.VARCHAR);
    else st.setString(2,id);
    st.execute();
    return st.getLong(1);
    catch (SQLException s) {
    throw new JboException(s);
    finally {try {st.close();} catch (SQLException s) {}}
    * Return a JDBC ResultSet representing the REF CURSOR return
    * value from our stored package function.
    private ResultSet retrieveRefCursor(Object qc,String id) {
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement(SQL,DBTransaction.DEFAULT);
    * Register the first bind parameter as our return value of type CURSOR
    st.registerOutParameter(1,OracleTypes.CURSOR);
    * Set the value of the 2nd bind variable to pass id as argument
    if (id == null) st.setNull(2,Types.VARCHAR);
    else st.setString(2,id);
    st.execute();
    ResultSet rs = ((OracleCallableStatement)st).getCursor(1);
    * Make this result set use the fetch size from our View Object settings
    rs.setFetchSize(getFetchSize());
    return rs ;
    catch (SQLException s) {
    s.printStackTrace();
    throw new JboException(s);
    finally {try {st.close();} catch (SQLException s) {}}
    * Store a new result set in the query-collection-private user-data context
    private void storeNewResultSet(Object qc, ResultSet rs) {
    ResultSet existingRs = getResultSet(qc);
    // If this query collection is getting reused, close out any previous rowset
    if (existingRs != null) {
    try {existingRs.close();} catch (SQLException s) {}
    setUserDataForCollection(qc,rs);
    hasNextForCollection(qc); // Prime the pump with the first row.
    * Retrieve the result set wrapper from the query-collection user-data
    private ResultSet getResultSet(Object qc) {
    return (ResultSet)getUserDataForCollection(qc);
    * Return either null or a new oracle.jbo.domain.Date
    private static Date nullOrNewDate(Timestamp t) {
    return t != null ? new Date(t) : null;
    * Return either null or a new oracle.jbo.domain.Number
    private static Number nullOrNewNumber(BigDecimal b) {
    try {
    return b != null ? new Number(b) : null;
    catch (SQLException s) { }
    return null;
    Struts Action
    package org.adb.sls.view;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import oracle.jbo.ApplicationModule;
    import oracle.jbo.ViewObject;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import oracle.adf.model.binding.DCDataControl;
    import oracle.adf.model.bc4j.DCJboDataControl;
    import oracle.jbo.html.BC4JContext;
    public class IndexAction extends DefaultADFAction
    protected ActionForward performActionLogic(ActionMapping mapping,
    ActionForm form, HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
    try {    
    ApplicationModule am = getApplicationModule("SLSApplicableLoanTypesDataControl", request);
    if (am == null)
    System.out.println("am is null");
    ViewObject vo = am.findViewObject("ViewApplicableLoanTypes");
    vo.setWhereClauseParam(0,request.getSession().getAttribute("SSO_EMPLOYEE_NUMBER"));
    vo.executeQuery();
    } catch (Exception e)
    e.printStackTrace();
    return mapping.findForward("success");
    Struts Config
    <form-beans>
    <form-bean name="DataForm" type="oracle.adf.controller.struts.forms.BindingContainerActionForm"/>
    </form-beans>
    <action-mappings>
    <action path="/index" className="oracle.adf.controller.struts.actions.DataActionMapping" type="org.adb.sls.view.IndexAction" name="DataForm" unknown="false">
    <set-property property="modelReference" value="indexUIModel"/>
    <forward name="success" path="/home.do"/>
    </action>
    <action path="/home" className="oracle.adf.controller.struts.actions.DataActionMapping" type="oracle.adf.controller.struts.actions.DataForwardAction" name="DataForm" parameter="/index.uix" unknown="true">
    <set-property property="modelReference" value="indexUIModel"/>
    </action>
    </action-mappings>

    I just found the solution. I've overridden setWhereClause method.
    public void setWhereClauseParams(Object[] values)
    ViewObjectImpl vo = (ViewObjectImpl) super.getViewObject();
    vo.setWhereClauseParam(0,values[0]);
    }

  • A Toplink Java code example in Jdev 10.1.2

    Hello every body
    I have just begun using Toplink 10g in Jdev 10.1.2, and I want examples of Java code to insert, edit and show information from struts application whose model is Toplink.
    Thanks

    If you are using toplink 9045 which ships with Jdev 1012, and just starting out then you might consider using Jdev1013 along with toplink 1013 since there is some measurable difference between the two releases.
    Information about toplink and examples.
    http://www.oracle.com/technology/products/ias/toplink/examples/index.html
    http://www.oracle.com/technology/products/ias/toplink/technical/index.html

  • Java.util.HashMap cannot be cast to org.apache.struts.action.ActionForm

    Hi!
    anybody could help me?
    i am getting java.util.HashMap cannot be cast to org.apache.struts.action.ActionForm error when I run my jsp...
    heres my code :
    CommentAction.java
    package com.provintl.rmis.actions;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.sql.DataSource;
    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 com.provintl.rmis.forms.CommentForm;
    public class CommentAction extends Action {
         Statement stmt = null;
         Connection con = null;
         javax.sql.DataSource dataSource;
         PreparedStatement ps = null;
         ResultSet rs=null;
         byte updFlg = 0;
         Map commentlist = new HashMap();
         /* (non-Javadoc)
         * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
         @Override
         public ActionForward execute(ActionMapping mapping, ActionForm form,
                   HttpServletRequest request, HttpServletResponse response)
         throws Exception {
              CommentForm commentForm = new CommentForm();
              Date date = commentForm.getDaterecord();
              String comment = commentForm.getComment();
              //TODO : temporary 1 == rose
              int userID =1;
              int appID =1;
              String SelectQry = "SELECT "+
                                       "APPLICANT_TBL.CHFNAME, "+
                                       "APPLICANT_TBL.CHLNAME, "+
                                       "APPLICANT_TBL.INTAPPID, "+
                                       "USERHST_TBL.CHCOMMENT, "+
                                       "USERHST_TBL.DTDATECREATED, "+
                                       " USERHST_TBL.INTHSTID "+
                                       "FROM "+
                                       "APPLICANT_TBL "+
                                       "INNER JOIN USERHST_TBL ON (APPLICANT_TBL.INTAPPID = USERHST_TBL.INTAPPID) " +
                                       "WHERE APPLICANT_TBL.CHFNAME ='"+request.getParameter("first")+"' " +
                                                 "AND APPLICANT_TBL.CHLNAME ='"+request.getParameter("last")+"'";
              try {
                   dataSource = (DataSource)getDataSource(request, "RMIS");
                   con = dataSource.getConnection();
                   con.setAutoCommit(false);
                   stmt = con.createStatement();
                   System.out.println("database connected");
                   rs = stmt.executeQuery(SelectQry);
                   System.out.println("database connected");
                   int ctr = 1;
                   while(rs.next()){
                        commentlist.put(ctr,new CommentForm(rs.getString("CHFNAME"),rs.getDate("DTDATECREATED")));
                        ctr++;
                   if(updFlg !=0){
                        String insQry = "INSERT INTO RECRUIT.USERHST_TBL (CHCOMMENT, INTUSERID, INTAPPID)" +
                        "VALUES ('"+comment+"',"+userID+","+appID+")";
                        stmt.executeUpdate(insQry);
                        con.commit();
                        updFlg = 0;
                   HttpSession session = request.getSession();
                   session.setAttribute("commentlist", commentlist);
                   //con.setAutoCommit(true);
              } catch (SQLException se) {
                   System.out.println("We got an exception while preparing a statement:" +
                   "Probably bad SQL.");
                   System.out.println(SelectQry);
                   se.printStackTrace();
                   //System.exit(1);
              finally {
                   try {
                        rs.close();
                        stmt.close();
                        con.close();
                   } catch (SQLException e) {
                        e.printStackTrace();
              return mapping.findForward("comment");
    commentform.jsp
    =============
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-html"     prefix="html"%>
    <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
    <%@ taglib uri="http://java.sun.com/jstl/sql_rt" prefix="sql"%>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <script>
    function putLabel(lbl, formName){
    if (opener && !opener.closed){
    opener.document.addapp.jobposition.value=lbl;
    window.close();
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>List of open positions</title>
    </head>
    <body>
    <h2>Job Positions Available</h2>
    <%
    int ctr = 1; %>
    <logic:iterate id="myString" name="commentlist" scope="session">
    <table width="100%" border="0">
    <%
    String bakcolor;
    if((ctr % 2) == 0){
         bakcolor = "WHITE";
         ctr++;
    else{
         bakcolor = "SILVER";
         ctr++;
    %>
    <tr><td bgcolor="<%= bakcolor %>">
    <bean:write name="myString" property="value" />
    </td></tr>
    ${commentlist}
    </table>
    </logic:iterate>
    </body>
    </html>
    thank you in advance!

    Shilnag wrote:
    Hello guys,
    I am new to java... I am trying to develop a web application using
    1.Struts1.2
    2.tomcat 5.5
    3.eclipse 3.2.2Big mistake. Nobody new to Java should jump straight into webapps, let alone using a framework like Struts. Debatably, even Eclipse should be left alone.
    It's precisely because of this that you're having problems. Presumably you're following a tutorial or something, but - as demonstrated - as soon as it goes wrong, you're stuck. Learn some core Java first, trust me

  • Database Server - SQL Access: Cannot connect from code but from SSMS

    Hi,
    I am using following connection string in my asp.net web.config:
    [Less than symbol] add name="FMMConnectionString" connectionString="Data Source=xxxxxxxxx,1234;Initial Catalog=Test1Db;User Id=Rajeev;Password=xxxxxxxxxxxxx;" providerName="System.Data.SqlClient" [Slash][Greater than symbol]
    The database is on remote database server. The sql user/ developer 'Rajeev' is deliberately given restricted permissions (to protect our schema) using following sql commands:
    GRANT ALTER,EXECUTE, SELECT,INSERT,UPDATE,DELETE ON SCHEMA ::dbo TO Rajeev
    DENY VIEW DEFINITION ON SCHEMA::dbo TO Rajeev;
    GRANT CREATE PROCEDURE TO Rajeev;
    GRANT CREATE FUNCTION TO Rajeev;
    DENY ALTER ON SCHEMA::dbo TO Rajeev; -- To disallow Rajeev to create objects on dbo schema but only create in Rajeev schema while still being able to select, insert, execute on dbo schema. 
    The above connection string works perfectly fine when used from Visual Studio> Server Explorer. I am able to execute following sql queries without issues. Same is true when using SQL Server Management Studio using Rajeev credentials.
    select top 100 * from XYZEmployees
    execute usp_GetMMBSchemeDetails '1' 
    The error I get in web page is following:
    The stored procedure 'usp_GetMMBSchemeDetails' doesn't exist.
    When I ran code using breakpoints to see what is happening, I see that when connection object is being instantiated, the connection state is being closed with following error:
    at System.Data.SqlClient.SqlConnection.GetOpenConnection()
    at System.Data.SqlClient.SqlConnection.get_ServerVersion()
    I turned off my firewall to see if it was blocking but it did not help. I tried using Visual Studio 2012 as well as Visual Studio 2013 but same issue showed up.
    Kindly let me know why I am able to execute sql queries from SSMS and Visual Studio's Server Explorer but not from application code. Is there something that needs to be enabled on remote database server so that the queries can run from code? I like to create
    more users like Rajeev with restricted permissions to develop my application. So kindly provide a solution if you know.
    Thanks,
    Pullet

    Thanks Everyone for your insights :) 
    RSingh, Your approach works when using SSMS, not when called from application code (example: asp.net code-behind page calling a stored proc using connection object).
    My requirement is, I only wanted developer to do front end programming without having the ability to look at backend sql objects definitions. He/she can call the sql objects in the program as needed. 
    I am able to finally solve this requirement by following approach. Hope it helps others. 
    1. Right-click Rajeev user in Database> Security>Users and unselect 'dbowner' from 'General' tab> 'Database Role Membership' section even though Default Schema shows up as Rajeev schema. Now, this user can't do anything on dbo schema of database
    (as well as in any other user's schema in this database).
    2. Ran above commands but excluded following command which was identified as root-cause.
    DENY VIEW DEFINITION ON SCHEMA::dbo TO Rajeev;
    3. Now ran a script that denies 'view definition' of dbo schema's tables. It loops through all tables and denies 'view definition' on each table. Adapted the script of http://blog.extreme-advice.com/2013/01/23/grant-view-defination-permission-to-all-stored-procedures-in-sql-server/.
    Now, the user Rajeev can execute dbo schema objects both from SSMS as well as from application code.
    4. DENY EXECUTE, SELECT ON SCHEMA::INFORMATION_SCHEMA TO Rajeev; -- Restricts Rajeev from executing INFORMATION_SCHEMA objects seen in SSMS.
    However one remaining open item is, I could not hide the system objects (which are part of sys schema) in SSMS. Ideally, I do not want Rajeev to execute the 'system views', 'system stored procedures', etc. When I execute same command (below command), it
    runs without errors but does not apply this restriction.
    DENY EXECUTE, SELECT ON SCHEMA::sys TO Rajeev;
    If you know the reason why it is happening like this, please kindly share.
    Cheers,
    Pullet
    Cheers | Pullet

  • How do i get a Base code (Material) from a description through BOM?

    Hi,
    the right base code(material) for the production order '68647' is 100827 descriotion 'PIPE BASIC' .
    my requirement is i have an production order and relevent plant, how do i get a basecode ?
    from my previous finding i read that All BOMs will have are associated with the description.
    Targeting this description will always return the right base code for the order.
    but i did not get any idea out of it.
    Please tell me how do i get a Base code (Material) from a description through BOM?
    Thanks in advance.
    Edited by: gulab zehra on Sep 22, 2009 9:17 AM

    Hi Keven,
    I had a look at the example "programmaticbuild2.vi" that you can find at this link:
    in this application the error that eventually comes out from the "BuildTargetBuildSpecification.vi" is written in the error_log.txt through a case structure.
    You can change the code inside the Error case if you want to handle the error in a different way. For example you could connect the error wire to a General Error Handler, that displays a message if an error occurs, or you could light up a led that inform you the error has occurred.
    Best regards,
    Serena M.

  • Beginner Question | The use of modulus in this simple code example.

    Hello everyone,
    I am just beginning to learn Java and have started reading "Java Programming for the absolute beginner". It is quite a old book but seems to be doing the trick, mainly.
    There is a code example which I follow mostly but the use of the modulus operator in the switch condition doesn't make sense to me, why is it used? Could someone shed some light on this for me?
    import java.util.Random;
    public class FortuneTeller {
      public static void main(String args[]) {
        Random randini = new Random();
        int fortuneIndex;
        String day;
        String[] fortunes = { "The world is going to end :-(.",
          "You will have a HORRIBLE day!",
          "You will stub your toe.",
          "You will find a shiny new nickel.",
          "You will talk to someone who has bad breath.",
          "You will get a hug from someone you love.",
          "You will remember that day for the rest of your life!",
          "You will get an unexpected phone call.",
          "Nothing significant will happen.",
          "You will bump into someone you haven't seen in a while.",
          "You will be publicly humiliated.",
          "You will find forty dollars.",
          "The stars will appear in the sky.",
          "The proper authorities will discover your secret.",
          "You will be mistaken for a god by a small country.",
          "You will win the lottery!",
          "You will change your name to \"Bob\" and move to Alaska.",
          "You will discover first hand that Bigfoot is real.",
          "You will succeed at everything you do.",
          "You will learn something new.",
          "Your friends will treat you to lunch.",
          "You will meet someone famous.",
          "You will be very bored.",
          "You will hear your new favorite song.",
          "Tomorrow... is too difficult to predict" };
        System.out.println("\nYou have awakened the Great Randini...");
        fortuneIndex = randini.nextInt(fortunes.length);
        switch (randini.nextInt(7) % 7) {   
          case 0:
            day = "Sunday";
            break;
          case 1:
            day = "Monday";
            break;
          case 2:
            day = "Tuesday";
            break;
          case 3:
            day = "Wednesday";
            break;
          case 4:
            day = "Thursday";
            break;
          case 5:
            day = "Friday";
            break;
          case 6:
            day = "Saturday";
            break;
          default:
            day = "Tomorrow";
        System.out.println("I, the Great Randini, know all!");
        System.out.println("I see that on " + day);
        System.out.println("\n" + fortunes[fortuneIndex]);
        System.out.println("\nNow, I must sleep...");
    }

    randini.nextInt(7) % 7randini.nextInt(7) returns a value in the range 0 <= x < 7, right? (Check the API!) And:
    0 % 7 == 0
    1 % 7 == 1
    2 % 7 == 2
    3 % 7 == 3
    4 % 7 == 4
    5 % 7 == 5
    6 % 7 == 6Looks like superfluous code to me. Maybe originally they wrote:
    randini.nextInt() % 7Note this code has problems, because, for example -1 % 7 == -1

  • Code generated from imported web service model does not compile

    I have created a model in Web Dynpro by importing a web service model using a valid WSDL, but the generated code won't compile because of type mismatches.
    The problem is that methods sometimes try to pass plain objects to methods whose parameter is an array of that object, and a List to methods whose parameter is a plain object.
    [Examples from SAP Netweaver tasks below]
    Thanks,
    Alastair
    snip
    The method setSessionData(EntInstType) in the type AssessRequestData is not applicable for the arguments (EntInstType[])     
    ComplexType_AssessRequestData.java
    Type mismatch: cannot convert from EntInstType to EntInstType[]     
    ComplexType_AssessRequestData.java
    The method setResult(List) in the type Response_JrbrsRefGeneric_listGoals is not applicable for the arguments (EntType)
    Request_JrbrsRefGeneric_listGoals.java

    I'm getting the same error.
    Type mismatch: cannot convert from short[][] to short[]
    ComplexType_Carton.java
    and...
    The method setNumeroscarton(short[][]) in the type Carton is
    not applicable for the arguments (short[])
    ComplexType_Carton.java     
    Steps to recreate the problem:
    1. Create and Expose webservice method with a parameter whose type has a short[][] (or bidimensional array of anything) field (property).
    2. Try to import the web service in web dynpro... <b>kaputt</b> it won't compile.
    <b>Seems like a bug to me. Someone please advice.</b>

  • Populating company code data from 02LIS_03_BX ??

    Hi,
    I am trying to load data from 02LIS_03_BX,02LIS_03_BF,02LIS_03_UM thru Custom ODS to Custom Cube
    We did nt enhance any of the extractors.
    02LIS_03_BF,02LIS_03_UM  has company code from the Datasource going to ODS to cube.
    I want to populate the comp code from BX too .
    02LIS_03_BX has BURKS in the extract structure but nt available in the datasource.
    How to populate the Company code from 02LIS_03_BX  ??
    I know that 02LIS_03_BX brings the data from stock tables ( MARC, MARD).
    From one of the SAP Notes, i get the following
    Enhancement possibilities for 2LIS_03_BX:
    Note that the 2LIS_03_BX DataSource cannot be extended in the
    same way as the 2LIS_03_BF DataSource, for example.
    Only SAP can enhance this DataSource (Note 684789).
    Can anybody throw some light on this ?
    I wanted to load Comp code data from BX/UM/UF all three to ODS-->Cube
    Thanks a lot
    BWQ

    Hi BWQ
    I think that you cannot update company code from 2lis_03_BX
    In the update rules put inicial value; and update the information from the other datasources.
    The datasource 2lis_03_BX is only for create  a balance from the inventory.
    Hope its help
    Greetings
    Monica

  • ABAP Code example using "GENERATE DYNPRO"

    I am looking for ABAP code example who use the "Generate dynpro" dynamic generation of dynpro at runtime under SAP 4.6C version.
    Best regards,

    We have some programs that do:
    form %view.
    data: anz type i,
          prog like sy-repid.
      prog = sy-repid.
      perform init_download(rsaqexce).
      case %tab.
      when 'G00'.
        perform generate_view_dynpro(rsaqexce)
                using prog text-grl.
        describe table %g00 lines anz.
        tview100-lines = anz.
        perform init_view(rsaqexce) tables %g00 using tview100.
        call screen 100.
        perform reset_view_dynpro(rsaqexce).
      when others.
        message s860(aq).
      endcase.
    endform.
    I think they were copied from existing SAP programs. In any event, look at the relevant forms in program rsaqexce.
    And as Rich noted, SAP doesn't recommend this.
    Rob

  • Code Example connection to MS Exchange

    Hi
    Has anyone got a link to a code example showing how to log into an account on MS Exchange server
    I am trying to log in and read emails from my student account that is on a ms exchange server but am having little luck.
    Could someone give me a couple of good links where i can get some helpful information.
    Thanks very much

    hi
    i am sitting with the same problem, if you find anything please let me know. thanx

  • Need Code Example

    Can someone please show me a code example of how to use RS_EXTERNAL_SELSCREEN_STATUS function.
    I want to delete "Create delivery in background" pushbutton from report vl10h.

    This is the example given in the FM documentation.
    Example
    Example for calling RS_EXTERNAL_SELSCREEN_STATUS:
    PROGRAM SAPDBxyz DEFINING DATABASE xyz.
    FORM INIT.
    CALL FUNCTION 'RS_EXTERNAL_SELSCREEN_STATUS'
    EXPORTING P_FB = 'TEST_EXTERNAL_STATUS'.
    ENDFORM.
    Example for function module that sets the status:
    FUNCTION TEST_EXTERNAL_STATUS.
    ""Local interface:
    *" IMPORTING
    *" P_SUBMIT_MODE
    *" TABLES
    *" P_EXCLUDE STRUCTURE RSEXFCODE
    *" EXCEPTIONS
    *" NO_ACTION
    IF P_SUBMIT_MODE NE SPACE.
    RAISE NO_ACTION.
    ENDIF.
    SET PF-STATUS 'TEST' EXCLUDING P_EXCLUDE.
    SET TITLEBAR 'TST'.
    ENDFUNCTION.
    INITIALIZATION.
    CUA *
    IMPORT T185V FROM MEMORY
    ID SD_COND_MEM_01. "JAY
    RV13B-KVEWE = 'B'.
    RV13B-KOTABNR = '001'.
    CALL FUNCTION 'RS_SUBMIT_INFO'
    IMPORTING
    P_SUBMIT_INFO = RSSUBINFO.
    IF NOT RSSUBINFO-MODE_NORML IS INITIAL.
    TITEL = T185V-CTITEL.
    CALL FUNCTION 'RV_CONDITION_GET_CUA_REPO'
    EXPORTING
    PFKEY_I = 'BSELE'
    TITLE_I = TITEL
    PAR1_I = T185V-PARA1
    PAR2_I = T185V-PARA2
    PAR3_I = T185V-PARA3
    PAR4_I = T185V-PARA4
    TABLES
    EXCL_I = AUSSCHLUSS.
    CALL FUNCTION 'RS_EXTERNAL_SELSCREEN_STATUS'
    EXPORTING
    P_FB = 'RV_CONDITION_SET_CUA_REPO'.
    ENDIF.

Maybe you are looking for