Initialization on demand holder idiom

From Wikipedia I learnt that this code is thread safe:
public class Something {
     private Something() {
     private static class LazyHolder {
          private static final Something INSTANCE = new Something();
     public static Something getInstance() {
          return LazyHolder.INSTANCE;
}But can the same trick be used with a non-static method?
public class Something {
    private static class LazyHolder {
        private static final Something INSTANCE = new Something();
    public Something getInstance() {
        return LazyHolder.INSTANCE;
}How about using static blocks?
public class Something {
    private static class LazyHolder {
        private static final Something INSTANCE;
        static {
            INSTANCE = new Something();
    public Something getInstance() {
        return LazyHolder.INSTANCE;
}I'm asking this because I really want to initialize a time consuming object only once, but I can't expose static methods.
Another thing, how about a thread safe lazy accessor (at instance level)? Can it be done without applying "synchronized" to the whole method?
    public synchronized Something getInstance() {
        if (something != null) {
            something = new Something();
        return something;
    }

Peter,
Thank you.
Life cycle goes like this:
->Client receives a FacadeService (via a remote invocation, so I really don't have much control on how many instances are available, but I know there can be more than one FacadeService instance in memory).
-> Client calls a method in his Facade Service instance
-> The method perform heavy calculations, network access and database operations. When it is done, the result object gets cached locally and then returned to the client
-> Client calls other method
-> The same thing happen and other objects are cached locally.
-> Client calls one of the above Methods
-> method quickly return the cached result
Client will use the Facade in a Concurrent environment, and it is our responsibility to make it all thread safe.
So, what I want to do is mimic the behavior of Something like this:
public class ServiceFacadeImpl {
    // Results are Immutable objects
    private Result1 result1;
    private Result2 result2;
    public Result1 getResult1() {
        if (result1 == null) {
            // heavy operation to create result1
        return result1;
    public Result2 getResult2() {
        if (result2 == null) {
            // heavy operation to create result2
        return result2;
}In a thread safe fashion.
Using "synchronized" methods would be a way... But I'm sure it can be done in a less restrictive way (having every method, even the ones that would simple return a cache result, waiting for other method to finish it's long operations in order to get the object lock just don't do it).
public synchronized Result1 getResult1() {
        if (result1 == null) {
            // heavy operation to create result1
        return result1;
    }Double-checked locking isn't thread safe
Demand holder idiom is.
So, back to question 1, is this thread safe?
public class ServiceFacadeImpl {
    private Result1 result1;
    private Result2 result2;
    private static class LazyHolder1 {
        private static final Result1 INSTANCE = new Result1();
    private static class LazyHolder2 {
        private static final Result2 INSTANCE = new Result2();
    public Result1 getResult1() {
        return LazyHolder1.INSTANCE;
    public Result2 getResult2() {
        return LazyHolder2.INSTANCE;
    public static void main(String[] args) {
        ServiceFacadeImpl sfi = new ServiceFacadeImpl();
        sfi.getResult1();
        sfi.getResult2();
}And question 2: Is there a way to implement a less restrictive lazy load approach without appealing to static inner classes? I would love to cache Result1 and Result2 as ServiceFacadeImpl instance variables instead of static inner class - static variables lol).
Inner Enums are cool, but as you told me, they are implicit static, plus the
public enum SomethingFactory {
  INSTANCE;
  public Something createInstance() {
      return new SomethingElse();
} approach don't work since newSomethingElse() (that represents heavy computation) will be called every time.
I could use a enum Constructor Approach like this:
    public enum Factory1 {
        INSTANCE;
        Result1 result = new Result1();
   public enum Factory2 {
        INSTANCE;
        Result2 result = new Result2();
   public Result1 getResult1() {
        return Factory1.INSTANCE.result;
    public Result2 getResult2() {
        return Factory2.INSTANCE.result;
    }I can't have a enum Factory holding all results because the constructors for all of its values are called at once... So I would have to mantain a lot of enums like enum Factory1, enum Factory2, etc, just like the static inner classes case. Lazy Loading a instance variable in a non restrictive / thread safe way in java is proving to be quite challenging.

Similar Messages

  • Singletons and multithreading question

    Hi, I had a class created as a singleton as it was only used in one place. However since Ive now multithreaded the part of the program that calls the singleton code so it could be called twice at the same time.
    If the method being called initializes all its variables within the method, is that method safe to be called in a mutli-threaded env or not ?
    If it in my situation all variables are declared within the method except a precompiled javax.xml.XPathExpression class, the same one is used to parse an Input Source, the input source itself is created within the method. I
    think I am having concurrency problems , (SAXParser Exceptions) and I think it is because of this XPathExpression class but cannot clearly understand why.
    What is the correct solution, I dont want to initilize the XPathExpression within the method because the method is called many times always for the same expression, dropping the singleton and creating new instances of the class on every call would be even worse. I require multithreading to improve concurrency is there a safe Multi Singleton pattern that i should be using ?

    There are two issues:
    a) is the singleton object safe for multithreaded use
    b) how do I safely create a singleton in a multi-threaded application
    The answer to (a) depends on the class. It sounds from your description that you are using an object (the XPathExpression) that might not be thread-safe. I can't tell you if it is or not. Assuming it is not you either need to synchronize this method so that all threads will go through it (and use the expression) one at a time - which may defeat the purpose of multi-threading - or else you need a way to use multiple instances of these expressions in different threads. As I'm not familiar with these classes I can't tell you what you can and can't do concurrently.
    There are a number of answers to (b). Construction via static initialization is the simplest and safest. If you want lazy initialization and the class that holds the reference to the singleton must be loaded even if the singleton isn't needed, then lookup the initialize-on-demand-holder-class idiom (see Josh Bloch's "Effective Java" item 48)

  • Static field initialization

    Ok, I know this was a good practices issue in C++, where order of initializing static fields from different source files was unknown, but I'm not sure if Java is smart enough to figure it out.
    So, say you have in one file
    public class A{
       public static B b = new B();
    }And in the other:
    public class C{
       private static D  d = A.b.getD();
    }Will this always work? Or does it depend on the order in wich classes A and C are loaded.

    jschell wrote:
    In multiple threads on some systems (potentially) the construction of B() is not guaranted before access to 'b' is allowed.Class initialization is synchronized, so the construction of B() should be fully visible to other threads without explicit synchronization or making the field final.
    From JLS 12.4.3:
    Code generators need to preserve the points of possible initialization of a class or interface, inserting an invocation of the initialization procedure just described. If this initialization procedure completes normally and the Class object is fully initialized and ready for use, then the invocation of the initialization procedure is no longer necessary and it may be eliminated from the code-for example, by patching it out or otherwise regenerating the code.So class initialization is attempted whenever the code generator feels it might be the first use of a class.
    And from 12.4.2:
    The procedure for initializing a class or interface is then as follows:
    1. Synchronize (§14.19) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.1).
    2. If initialization is in progress for the class or interface by some other thread, then wait on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.So the class is synchronized on until initialization (which includes all static initializers) finishes. This makes possible the class holder idiom for singletons.

  • Regarding Logical level key and row wise initialization

    Hi Gurus,
    What is the purpose of row wise initialization in external table authentication and when we have to go for row wise initialization.
    Why we have to enable logical level key in hierarchy is this only for getting drill down to the next level if we make two columns as logical level key what will happens. If we want to enable a column as a logical level key what are the character sticks that column should satisfy.
    Thanks,

    1) Row Wise Initialization used to hold multiple values in a variable. Let says SQL gives 4 rows (A,B,C,D) as output. Now I want to hold 4 value in a variable to get this happen we need to go for RowwiseIniziation. If you do not do this at any point in time Variable holds only value A not others. Simply it works as Array.
    2) Level keys define the unique elements in each level and provide the context for drill down. You can make two logical columns as logical key but you need to make sure what to be displayed in your hierarchy by selecting DISPLAY. If you make to as separate logical keys and set Display for both you get two columns in the hierarchy
    http://gerardnico.com/wiki/dat/obiee/hierarchy_level_based

  • Data Handler source code need modification

    I found this in the forum and try to implement it in my page. The code is running okay but just that when I first load the page into the browser, It shows ALL the records in the database beneath the searchbox.
    All I want is first time user come to the page, it only show the search box but no result. And after user enter the data, it then performs the search and show the result beneath.
    <%@ page language="java" errorPage="errorpage.jsp" contentType="text/html;charset=ISO-8859-1" %>
    <%@ taglib uri="/webapp/DataTags.tld" prefix="jbo" %>
    <html>
    <head>
    <META NAME="GENERATOR" CONTENT="Oracle JDeveloper">
    <LINK REL=STYLESHEET TYPE="text/css" HREF="/webapp/css/bc4j.css">
    <TITLE>Browse Form</TITLE>
    </head>
    <body>
    <jbo:ApplicationModule id="am" configname="oetest.OeAppModule.OeAppModuleLocal" releasemode="Stateful" />
    <jbo:DataSource id="ds" rangesize="3" appid="am" viewobject="ProductInformationView" />
    <jbo:DataHandler appid="am" />
    <%
    /* This scriplet processes http parameters used to extract the search
    and column strings to build the criteria value string */
    /* Initialize variables to hold string if search string and column doesn't
    change between requests.*/
    String column_name=(String)session.getValue("sessionColumnName");
    String search_value=(String)session.getValue("sessionSearchValue");
    // Set search_value to empty string for first time rendering
    if (search_value == null) search_value="";
    String criteria_value;
    //get search parameter and set in session for persistence
    if (request.getParameter("search")!=null) {
    search_value=request.getParameter("search").trim();
    session.putValue("sessionSearchValue", search_value);
    //get column parameter and set in session for persistence
    if (request.getParameter("column")!=null) {
    column_name=request.getParameter("column").trim();
    session.putValue("sessionColumnName", column_name);
    //Construct the criteria value string.
    criteria_value="like '%" + search_value + "%'";
    %>
    <jbo:OnEvent name="Find" >
    <!-- Create a new ViewCiteria to filter data source. ViewCriteria is a
    container for CriteriaRow and Criteria, which filter the rowset returned
    by the the datasource (view object) -->
    <jbo:ViewCriteria id="vc" datasource="ds" action="new">
    <!-- Create CriteriaRow to restrict the query for every attribute
    Essentially, each CriteriaRow works analogous yp an 'AND' in the where
    Clause of the view object. Here we only want to restrict the
    query based on the chosen column. Using 'uppercolumns' makes the
    restricts case insensitive -->
    <jbo:CriteriaRow id="row" > <!-- uppercolumns="true" -->
    <!-- This ensures that column_name has a non empty value. -->
    <% if (column_name==null || column_name.equals("")) { %>
    <jbo:AttributeIterate id="defvc" datasource="ds" queriableonly="true" >
    <% column_name=defvc.getName(); %>
    </jbo:AttributeIterate>
    <% } // end if %>
    <!-- Create Criteria as part of a CriteriaRow to include one or more
    attributes. Essentially, each CriteriaRow works analogous to
    an 'OR' for each attribute in the where Clause of the
    view object. Specify the column_name and criteria_value in the
    dataitem and value attributes, respectively. -->
    <jbo:Criteria dataitem="<%= column_name %>" value="<%= criteria_value %>" />
    <!-- Close CriteriaRow, ViewCriteria tags, respectively -->
    </jbo:CriteriaRow>
    </jbo:ViewCriteria>
    </jbo:OnEvent>
    <h3>ProductInformationView Browse Form</h3>
    <!-- Add a form for the search input -->
    <form name="exsearch" action="ProductInformationView_Browse.jsp" method="post">
    <table>
    <tr>
    <td align="left" nowrap>
    <img border="0" src="go.gif" align="top" width="22" height="25">
    <b><font face="Arial" size="4" color="#336699"> Search </font></b>
    <!-- use a drop list of column names to select. Iterate through Attribute names -->
    <select name="column">
    <jbo:AttributeIterate id="defvc2" datasource="ds" queriableonly="true" >
    <option value="<%= defvc2.getName() %>" <%= defvc2.getName().equals(column_name)?"selected":"" %> ><%= defvc2.getName() %></option>
    </jbo:AttributeIterate>
    </select>
    <!-- Input field for search string -->
    <input name="search" value="<%= search_value %>">
    <input type="submit" name="jboEvent" value="Find">
    </td>
    </tr>
    </table>
    </form>
    <!-- The rest was generate using the BC4J JSP Wizard to build a Browse form. -->
    <table border="0">
    <tr>
    <td ALIGN="right"><jbo:DataScroller datasource="ds"/></td>
    </tr>
    <tr>
    <td><jbo:DataTable datasource="ds" /></td>
    </tr>
    </table>
    <jbo:ReleasePageResources />
    </body>
    </html>

    JosAH wrote:
    A couple of years ago Sun supplied their javax.comm package (mysteriously versioned as version 2)
    but they stopped it for the PC Windows.
    There's an alternative: rxtx which offers an identical API as Sun did and their own native implementation for serial and parallel port handling; I have used both and the rxtx version is clearly superior to Sun's old version: http://www.rxtx.org
    This question popped up recently.
    tschodt wrote in [http://forums.sun.com/thread.jspa?messageID=10863769#10863769:}
    [Java Communications API|http://java.sun.com/products/javacomm/]
    Implementations of the API are currently available for Solaris SPARC, Solaris x86, and Linux x86.follow the Download link to find
    Sun no longer offer's the Windows platform binaries of javax.comm, however javax.comm 2.0.3 can be used for the Windows platform, by using it in conjunction with the Win32 implementation layer provided by the RxTx project. To use that, download javax.comm for the 'generic' platform (which provides the front-end javax.comm API only, without platform specific back-end implementations bundled). Then acquire the Windows binary implementation rxtx-2.0.7pre1 from http://www.rxtx.org.

  • Urgent help with quick translation questions

    Hello,
    I am somewhat new to Java. I have a translation to hand in in a few hours (French to English). Argh! I have questions on how I worded some parts of the translation (and also if I understood it right). Could you, great developers, please take a look and see if what I wrote makes sense? I've put *** around the words I wasn't sure about. If it sounds strange or is just plain wrong, please let know. I also separated two terms with a slash, when I was in doubt of which one was the best.
    Many thanks in advance.
    1) Tips- Always ***derive*** the exceptions java.lang.Exception and java.lang.RuntimeException.
    Since these exceptions have an excessively broad meaning, ***the calling layers will not know how to
    distinguish the message sent from the other exceptions that may also be passed to them.***
    2) The use of the finally block does not require a catch block. Therefore, exceptions may be passed back to the
    calling layers, while effectively freeing resources ***attributed*** locally
    3) TIPS- Declare the order for SQL ***statements/elements*** in the constant declaration section (private static final).
    Although this recommendation slightly hinders reading, it can have a significant impact on performance. In fact, since
    the layers of access to data are ***low level access***, their optimization may be readily felt from the user’s
    perspective.
    4) Use “inlining.”
    Inlining is a technique used by the Java compiler. Whenever possible, during compilation, the compiler
    copies the body of a method in place of its call, rather than executing a ***memory jump to the method***.
    In the example below, the "inline" code will run twice as fast as the ***method call***
    5)tips - ***Reset the references to large objects such as arrays to null.***
    Null in Java represents a reference which has not been ***set/established.*** After using a variable with a
    large size, it must be ***reassigned a null value.*** This allows the garbage collector to quickly ***recycle the
    memory allocated*** for the variable
    6) TIPS Limit the indexed access to arrays.
    Access to an array element is costly in terms of performance because it is necessary to invoke a verification
    that ***the index was not exceeded.***
    7) tips- Avoid the use of the “Double-Checked Locking” mechanism.
    This code does not always work in a multi-threaded environment. The run-time behavior ***even depends on
    compilers.*** Thus, use the following ***singleton implementation:***
    8) Presumably, this implementation is less efficient than the previous one, since it seems to perform ***a prior
    initialization (as opposed to an initialization on demand)***. In fact, at runtime, the initialization block of a
    (static) class is called when the keyword MonSingleton appears, whether there is a call to getInstance() or
    not. However, since ***this is a singleton***, any occurrence of the keyword will be immediately followed by a
    call to getInstance(). ***Prior or on demand initializations*** are therefore equivalent.
    If, however, a more complex initialization must take place during the actual call to getInstance, ***a standard
    synchronization mechanism may be implemented, subsequently:***
    9) Use the min and max values defined in the java.lang package classes that encapsulate the
    primitive numeric types.
    To compare an attribute or variable of primitive type integer or real (byte, short, int, long, float or double) to
    ***an extreme value of this type***, use the predefined constants and not the values themselves.
    Vera

    1) Tips- Always ***derive*** the exceptions java.lang.Exception and java.lang.RuntimeException.***inherit from***
    ***the calling layers will not know how to
    distinguish the message sent from the other exceptions that may also be passed to them.***That's OK.
    while effectively freeing resources ***attributed*** locally***allocated*** locally.
    3) TIPS- Declare the order for SQL ***statements/elements*** in the constant declaration section (private static final).***statements***, but go back to the author. There is no such thing as a 'constant declaration section' in Java.
    Although this recommendation slightly hinders reading, it can have a significant impact on performance. In fact, since
    the layers of access to data are ***low level access***, their optimization may be readily felt from the user’s
    perspective.Again refer to the author. This isn't true. It will make hardly any difference to the performance. It is more important from a style perspective.
    4) Use “inlining.”
    Inlining is a technique used by the Java compiler. Whenever possible, during compilation, the compiler
    copies the body of a method in place of its call, rather than executing a ***memory jump to the method***.
    In the example below, the "inline" code will run twice as fast as the ***method call***Refer to the author. This entire paragraph is completely untrue. There is no such thing as 'inlining' in Java, or rather there is no way to obey the instruction given to 'use it'. The compiler will or won't inline of its own accord, nothing you can do about it.
    5)tips - ***Reset the references to large objects such as arrays to null.***Correct, but refer to the author. This is generally considered bad practice, not good.
    Null in Java represents a reference which has not been ***set/established.******Initialized***
    After using a variable with a
    large size, it must be ***reassigned a null value.*** This allows the garbage collector to quickly ***recycle the
    memory allocated*** for the variableAgain refer author. Correct scoping of variables is a much better solution than this.
    ***the index was not exceeded.******the index was not out of range***
    The run-time behavior ***even depends on compilers.***Probably a correct translation but the statement is incorrect. Refer to the author. It does not depend on the compiler. It depends on the version of the JVM specification that is being adhered to by the implementation.
    Thus, use the following ***singleton implementation:***Correct.
    it seems to perform ***a prior initialization (as opposed to an initialization on demand)***.I would change 'prior' to 'automatic pre-'.
    ***this is a singleton***That's OK.
    ***Prior or on demand initializations***Change 'prior' to 'automatic'.
    ***a standard
    synchronization mechanism may be implemented, subsequently:***I think this is nonsense. I would need to see the entire paragraph.
    ***an extreme value of this type******this type's minimum or maximum values***
    I would say your author is more in need of a technical reviewer than a translator at this stage. There are far too serious technical errors in this short sample for comfort. The text isn't publishable as is.

  • How to set  dynamic parameter in bean

    I want to set a change able paramerter in my bean what can I do?
    like
    db.setCatalog(" HkData "); hard code, work fine.
    but if
    public String getOurDatabase(){
    return ourDatabase;}
    public void setOurDatabase ( String ourDatabase ) {
    this.ourDatabase =ourDatabase; }
    what is the correct syntax in
    db.setCatalog(" ? ");

    Hi follow is my bean, I need code in ???? place
    Thank you
    package num;
    import java.util.*;
    import java.sql.*;
    public class NameBean1 implements java.io.Serializable {
      /* Member Variables */
      private String fieldNumber;
      private String name;
      private String hiTiter;
      private String subType;
      private String string;
      private String ourDatabase;
      /* ArrayLists to hold recordsets */
      private List fieldNumberList, nameList, hiTiterList, subTypeList;
      /* Helper Variables */
      private int currentRow;
      private int rowCount;
      private boolean anyRecords = false;
      private Connection db = null;
      private ResultSet rs=null;
      /* Constructor */
      public NameBean1() {
         again(); 
      /* Get Database Connection */
      private void dbConnect() {
        if (db == null) {
          try {
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            db = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;selectMethod=cursor","test","1234");
           what is code in here????????
          catch (Exception e) {
            System.out.println("Error Connecting to catalog DB: " + e.toString());
      /* Accessor Methods */
      public String getfieldNumber() {
        return fieldNumber;
    /* one way to set data will get from database */
      public void setFieldNumber(String fieldNumber) {
         this.fieldNumber =fieldNumber;
      public String getName() {
        return name;
      public void setName(String _name) {
        name = _name;
      public String getHiTiter() {
        return hiTiter;
      public void setHiTiter(String _hiTiter) {
        hiTiter = _hiTiter;
       public String getSubType() {
        return subType;
      public void setSubType(String _subType) {
        subType = _subType;
    public  String getString(){
        return string;
    public void setString( String string ) {
       this.string =string;    }
    public void setOurDatabase(String ourDatabase){
            ourDatabase=ourDatabase;
    public String getOurDatabase() {
        return ourDatabase;
      /* Read-only attribute */
      public int getCurrentRow() {
        return currentRow;
      public int getRowCount() {
        return rowCount;
      /* Populate Record List */
      public boolean Mysearch() {
        /* If fieldNumberList is empty, then execute the query  */
        if (fieldNumberList.isEmpty()) {
          try {
                       Statement s = db.createStatement();
                        String Sql=" select ourDatabase.dbo.ViruName00.FieldNumber, Name, HiTiter, SubType, Storage";
                             Sql+=" from ourDatabse.dbo.ViruName00,ourDatabse.dbo.Storage00";
                             Sql+=" where ourDatabse.dbo.ViruName00.NewNum=ourDatabse.dbo.Storage00.NewNum and Name like'%"+string+"%'";
                             Sql+=" Union";
                             Sql+=" ourDatabse.dbo.select ViruName01.FieldNumber,Name, HiTiter,SubType, Storage";
                             Sql+=" from ourDatabse.dbo.ViruName01, ourDatabse.dbo.Storage01";
                             Sql+=" where ourDatabse.dbo.ViruName01.NewNum = ourDatabse.dbo.Storage01.NewNum and Name like'%"+string+"%'";
                             Sql+=" Union";
                             Sql+=" select ourDatabse.dbo.ViruName02.FieldNumber,Name, HiTiter, SubType,Storage";
                             Sql+=" from ourDatabse.dbo.ViruName02, ourDatabse.dbo.Storage02";
                             Sql+=" where ourDatabse.dbo.ViruName02.NewNum=ourDatabse.dbo.ourDatabse.dbo.Storage02.NewNum and Name like'%"+string+"%'";
                             Sql+=" Union";
                             Sql+=" select ViruName03.FieldNumber,Name, HiTiter, SubType, Storage";
                             Sql+=" fromourDatabse.dbo. ViruName03, ourDatabse.dbo.Storage03";
                             Sql+=" where ourDatabse.dbo.ViruName03.NewNum=ourDatabse.dbo.Storage03.NewNum and Name like'%"+string+"%'";
                rs = s.executeQuery (Sql);
            fieldNumberList.clear();
            nameList.clear();
            hiTiterList.clear();
            subTypeList.clear();
            rowCount = 0;
            while (rs.next()) {
               fieldNumberList.add(rs.getString("FieldNumber"));
               nameList.add(rs.getString("Name"));
               hiTiterList.add(rs.getString("HiTiter"));   
               subTypeList.add(rs.getString("SubType"));
               rowCount++;
              anyRecords = true;
            }//end while
          }//end try
          catch (Exception e) {
            System.out.println("Error populating productBean: " + e.toString());
        }//end if   
         return anyRecords; }//end function
    public boolean getAnyRecords() {
        return anyRecords;  }
      /* Reset current row */
      public void setStartRow(int start) {
        if (start < rowCount) {
          currentRow = start;
      /* Move to next row */
      public int nextRow() {
        if (currentRow == rowCount) {
          currentRow = 0; // Reset for next page request
          return 0; // return 0 to indicate end of recordset
        /* Populate bean properties with current row */
        setFieldNumber((String)fieldNumberList.get(currentRow));
        setName((String)nameList.get(currentRow));
        setHiTiter((String)hiTiterList.get(currentRow));
        setSubType((String)subTypeList.get(currentRow));   
        currentRow++;
        /* return currentRow*/
        return currentRow;
    public void again(){
        /* Initialize bean properties */
        setFieldNumber("");
        setName("");
        setHiTiter("");
        setSubType("");
        /* Initialize arrayLists to hold recordsets */
        fieldNumberList = new ArrayList();
        nameList = new ArrayList();
        hiTiterList = new ArrayList();
        subTypeList = new ArrayList();
         fieldNumberList.clear();
            nameList.clear();
            hiTiterList.clear();
            subTypeList.clear();
        /* Initialize helper variables */
        currentRow = 0;
        rowCount = 0;
        anyRecords= false;
        /* Get database connection */
        dbConnect();
      rs=null;
    }

  • BW ABAP best practice

    Hello,
    I have always coded my logic in update rules/start routines.  However, is there a better practice?  Should my comparison values come from a table?
    For example -
    In an update rule I could have:
      IF ( ( COMM_STRUCTURE-comp_code = '0010' AND
             COMM_STRUCTURE-/bic/zcopastd EQ c_zcopastd and
             COMM_STRUCTURE-/bic/zcopaicc EQ c_zcopaicc and
             COMM_STRUCTURE-vtype NE '020' )
          OR COMM_STRUCTURE-/bic/zcopaqtyb = 0 ).
    In a start routine I could have:
    DELETE DATA_PACKAGE WHERE SALESORG = '0005'.
    Should those values of 0005, 0010, 020 be in a table somewhere that gets referenced, or is this just how we handle coding in BW?  I am not an abap'r so just looking for best practice and reasoning.
    Thanks,
    Nick

    Hi Nick,
    Hardcoding should be avoided in any kind of coding in any language. If you hardcode any value and after some period the value changes then you have to change all occurence of the value otherwise it may result in inconsistency. Secondly if will be a time consuming process.
    To avoid hardcoding you can use following ways:
    1. Use Variable declaration and initialization which will hold your value. (This is also kind of hardcoding).
    2. Else you can declare that value to be constant with value. (if it is pretty constant over period of time).
    3. The best way is to refer the value from the table:
    3.1 You can very well refer standard value from system    table.
    3.2 Or Else if you have those values with you and you can not refer through system table then you can create those variable as an entry into TVARV table. TVARV table can be refered in the update rules as well as in start routine to read the value. Infact we can change the value in TVARV so that the value become dynamic and can be consistently accessed through the system.
    first two solutions are also hardcoding but are more accepted. But the third one is the standard way to refer the value in the routine or code.

  • ADF Faces : session timeout best practice

    hi
    I made these small modifications to the web.xml file in the SRDemoSample application:
    (a) I changed the login-config from this ...
      <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
          <form-login-page>infrastructure/SRLogin.jspx</form-login-page>
          <form-error-page>infrastructure/SRLogin.jspx</form-error-page>
        </form-login-config>
      </login-config>... to this
      <login-config>
        <auth-method>BASIC</auth-method>
      </login-config>(b) I changed the session-timeout to 1 minute.
      <session-config>
        <session-timeout>1</session-timeout>
      </session-config>Please consider this scenario:
    (1) Run the UserInterface project of the SRDemoSample application in JDeveloper.
    (2) Authenticate using "sking" and password "welcome".
    (3) Click on the "My Service Requests" tab.
    (4) Click on a "Request Id" like "111". You should see a detail page titled "Service Request Information for SR # 111" that shows detail data on the service request.
    (5) Wait for at least one minute for the session to timeout.
    (6) Click on the "My Service Requests" tab again. I see the same detail page as in (4), now titled "Service Request Information for SR #" and not showing any detail data.
    question
    What is the best practice to detect such session timeouts and handle them in a user friendly way in an ADF Faces application?
    thanks
    Jan Vervecken

    Hi,
    no. Here's the content copied from a word doc:
    A frequent question on the JDeveloper OTN forum, and also one that has been asked by customers directly, is how to detect and graceful handle user session expiry due to user inactivity.
    The problem of user inactivity is that there is no way in JavaEE for the server to call the client when the session has expired. Though you could use JavaScript on the client display to count
    down the session timeout, eventually showing an alert or redirecting the browser, this goes with a lot of overhead. The main concern raised against unhandled session invalidation due to user
    inactivity is that the next user request leads to unpredictable results and errors messages. Because all information stored in the user session get lost upon session expiry, you can't recover the
    session and need to start over again. The solution to this problem is a servlet filter that works on top of the Faces servlet. The web.xml file would have the servlet configured as follows
    1.     <filter>
    2.         <filter-name>ApplicationSessionExpiryFilter</filter-name>
    3.         <filter-class>
    4.             adf.sample.ApplicationSessionExpiryFilter
    5.         </filter-class>
    6.         <init-param>
    7.             <param-name>SessionTimeoutRedirect</param-name>
    8.             <param-value>SessionHasExpired.jspx</param-value>
    9.         </init-param>
    10.     </filter>
    This configures the "ApplicationSessionExpiryFilter" servlet with an initialization parameter for the administrator to configure the page that the filter redirects the request to. In this
    example, the page is a simple JSP page that only prints a message so the user knows what has happened. Further in the web.xml file, the filter is assigned to the JavaServer Faces
    servlet as follows
    1.     <filter-mapping>
    2.             <filter-name>ApplicationSessionExpiryFilter</filter-name>
    3.             <servlet-name>Faces Servlet</servlet-name>
    4.         </filter-mapping>
    The Servlet filter code compares the session Id of the request with the current session Id. This nicely handles the issue of the JavaEE container implicitly creating a new user session for the incoming request.
    The only special case to be handled is where the incoming request doesn't have an associated session ID. This is the case for the initial application request.
    1.     package adf.sample;
    2.     
    3.     import java.io.IOException;
    4.     
    5.     import javax.servlet.Filter;
    6.     import javax.servlet.FilterChain;
    7.     import javax.servlet.FilterConfig;
    8.     import javax.servlet.ServletException;
    9.     import javax.servlet.ServletRequest;
    10.     import javax.servlet.ServletResponse;
    11.     import javax.servlet.http.HttpServletRequest;
    12.     import javax.servlet.http.HttpServletResponse;
    13.     
    14.     
    15.     public class ApplicationSessionExpiryFilter implements Filter {
    16.         private FilterConfig _filterConfig = null;
    17.        
    18.         public void init(FilterConfig filterConfig) throws ServletException {
    19.             _filterConfig = filterConfig;
    20.         }
    21.     
    22.         public void destroy() {
    23.             _filterConfig = null;
    24.         }
    25.     
    26.         public void doFilter(ServletRequest request, ServletResponse response,
    27.                              FilterChain chain) throws IOException, ServletException {
    28.     
    29.     
    30.             String requestedSession =   ((HttpServletRequest)request).getRequestedSessionId();
    31.             String currentWebSession =  ((HttpServletRequest)request).getSession().getId();
    32.            
    33.             boolean sessionOk = currentWebSession.equalsIgnoreCase(requestedSession);
    34.           
    35.             // if the requested session is null then this is the first application
    36.             // request and "false" is acceptable
    37.            
    38.             if (!sessionOk && requestedSession != null){
    39.                 // the session has expired or renewed. Redirect request
    40.                 ((HttpServletResponse) response).sendRedirect(_filterConfig.getInitParameter("SessionTimeoutRedirect"));
    41.             }
    42.             else{
    43.                 chain.doFilter(request, response);
    44.             }
    45.         }
    46.        
    47.     }
    This servlet filter works pretty well, except for sessions that are expired because of active session invalidation e.g. when nuking the session to log out of container managed authentication. In this case my
    recommendation is to extend line 39 to also include a check if security is required. This can be through another initialization parameter that holds the name of a page that the request is redirected to upon logout.
    In this case you don't redirect the request to the error page but continue with a newly created session.
    Ps.: For testing and development, set the following parameter in web.xml to 1 so you don't have to wait 35 minutes
    1.     <session-config>
    2.         <session-timeout>1</session-timeout>
    3.     </session-config> Frank
    Edited by: Frank Nimphius on Jun 9, 2011 8:19 AM

  • 88.9%

    Ok usually I wouldn't mind losing a few points or so on an assignment but when I am a little more than 1% away from an A I am obligated to ask for help. So far I have completed 3/4 of my assignment but need to create one(1) last class to fully finish: the problem is stated below-
    Problem: Write a test driver class that creates an array of type Animal. Instantiate Hippo, Lion, and Tiger objects in the array. Use a for loop(in the driver class) to cycle through the animals and their various behaviors.
    I WOULD APPRECIATE ANY HELP!
    THANK YOU
    The code I have so far is below
    public abstract class Animal
         protected String name;
         protected int age;
         public Animal(String n, int a)
              name = n;
              age = a;
         }//Animal method
         public String getName(){return name;}
         public int getAge() {return age;}
         public void makeNoise()
              System.out.println("Generic animal noise");
         }//method makeNoise
         public abstract void eat();
         public abstract void sleep(int minutes);
         public void roam()
              System.out.println("Generic Animal roam");
         }//roam method
    }//Animal classHippo Class
    public class Hippo extends Animal
         private int bodyMass;
         public Hippo(String n, int a, int bm)
              super (n,a);
              bodyMass=bm;
         }//Hippo method
         public void eat()
              System.out.println(name + " is eating.");
         }//eat method
         public void sleep(int m)
              System.out.println(name + " is sleeping for "+m+" minutes.");
         }//sleep method
    }//Hippo extends Animal classHippo Test Driver
    public class HippoTest
         public static void main(String[] args)
              Hippo hippo=new Hippo("Big Boy", 4, 1250);
              hippo.eat();
              hippo.roam();
              hippo.makeNoise();
              hippo.sleep(22);
         }//main method
    }//HippoTest classFeline Abstract Class extends Animal
    public abstract class Feline extends Animal
         public Feline (String n, int a)
              super (n,a);
         }//feline class
         public void roam()
              System.out.println(name + " is roaming through the grass.");
         }//roam method
    }//Feline classLion Class
    public class Lion extends Feline
         public Lion(String n, int a)
              super(n,a);
         }//Lion method
         public void eat()
              System.out.println(name + " is eating fish.");
         }//eat method
         public void sleep(int m)
              System.out.println(name + " is taking a nap for " + m +  " minutes.");
         }//sleep method
    }//Lion extends Feline classLion Test Driver
    public class LionTest
         public static void main(String[] args)
         Lion lion=new Lion("Mufasa", 19);
         lion.eat();
         lion.roam();
         lion.makeNoise();
         lion.sleep(60);
         }//main method
    }//LionTest classTiger Class
    public class Tiger extends Feline
         public Tiger(String n, int a)
              super(n,a);
         }//Tiger method
         public void eat()
              System.out.println(name + " is eating English homework.");
         public void sleep(int m)
              System.out.println(name + " is sleeping for " + m + " minutes.");
    }//Tiger extends Feline classTiger Test Driver
    public class TigerTest
         public static void main(String[] args)
         Tiger tiger=new Tiger("Tigger", 12);
         tiger.eat();
         tiger.sleep(300);
         tiger.roam();
         }//main method
    }//TigerTest class

    denxnis wrote:
    Write a test driver class that creates an array of type Animal. Instantiate Hippo, Lion, and Tiger objects in the array. Use a for loop(in the driver class) to cycle through the animals and their various behaviors.According to your problem, you need a "test driver class" which contains an array of type Animal. The problem is simple enough to do. You have some test driver classes already, and they do not seem to use an array.
    According to the description of the problem, you need something that would do the following:
    - Declare an array of animals, initialize it to hold three Animal objects
    - Instantiate the Hippo, Lion, and Tiger classes and store them in the array
    - Use a for (or for-each) loop to call the various methods of each animal
    denxnis wrote:
    Can someone create a test Driver --- We are not here to do your homework/assignments for you, but if there is something that you do not understand, we can help with that (if you give enough information).

  • Scrolling Resultset example?

    this is a posting from another thread that I was looking for clarification on. I understand what's being said but I don't quite understand how to reference the resultSet from this explanation:
    USE a Scrollable ResultSet object and put it in the session. Keep a variable that identifies where in the resultset ur pointer is at any point of time.
    Scrollable ResultSets are a feature only available with JDBC 2.0 onwards... so make sure u have THAT first.
    Create a Statement like this...
    Statement st =
    con.createStatement(ResultSet.SCROLLABLE);
    Then run the query n store it in the resultset
    ResultSet rs = st.executeQuery(sql);
    Then move ur pointer to any record u want with methods present in the ResultSet interface:
    relative(int rows) that takes you 'rows' rows ahead.
    absolute(int row) that takes your pointer to the 'row'th ROW.
    Make sure u use 'refreshRow()' so u have the latest content at any point of time. This refreshes the contents in that row. there is also something called refresh() BUT THAT would minimise performace.
    Store this resultset object in the session and call it in each page u want starting with the record number u want to. !!
    Hope this helps... aXe!
    My question is, does someone have a simple example page that does what is described above? Also, to get the number of pages that will be involved, would you first "SELECT * FROM table" and count the rows, divide by the number of rows to display per page, and then create a URL for each number to jump to the next grouping of rows doing something like this?:
    (suppose you want 10 rows per page)
    2
    4
    the code would simple do:
    <% String page = request.getParameter("page");
    rs.absolute(page);
    while (rs.next()){ %>
    <% ...print out row contents here... %>
    <%}%>
    Does this sound correct...where does the "refreshRow()" need to go to clear the row? Also, would you need to use LIMIT (to 10 rows)in the SELECT statement?
    Any help in understanding this is greatly appreciated!
    Chuk.

    well, with some tweaking I had figured it out but ran into another problem:
    I need to know in advance how many pages will be required to display the entire ResultsSet to print 1,2,3,4, etc as hyperlinks and link them to the jsp to scroll back and forth. So I tried to do the following
    (suppose the ResultSet hold 12 records total which I would get like this):
    //get total number of rows, this is a very round about way but I'm new to this
    int totalRows = 0;
    rs.last();
    totalRows = rs.getRow();
    rs.first();
    rs.previous();
    //set the number of rows to display per page
    int pageRows = 10;
    //initialize variable to hold the number of pages needed
    int pages = 0;
    //So then I would calculate the number of pages:
    pages = totalRows/pageRows;
    //then print the page numbers
    for (int i = 0; i <= pages){
    out.println("<a href sample.jsp?page="+i+"> "+i);
    This would work great if only the integer was always rounded up. In this example, I want 10 rows per page displayed and there are 12 total. In this calculation I would want the variable "pages" to equal 2 b/c you would have one page of 10 rows and then the second page of 2 rows. The type integer is always rounded down it seems so I end of with a value of "1" in the integer "pages"
    There must be a better way to do this...anyone have any ideas or have you done this before?
    thanks in advance,
    Chuck

  • Parameter passing into servlet

    Hi,
    I am trying to get the html page to pass some parameters into a servlet. Everytime I try running it, I get "Page could not be found error"
    I use the following path:
    Http://localhost:8080/example/servlets
    I could run the HelloWorld example with no problems.
    I'm trying to run the LoanAmorization.html
    which calls LoanCalculator servlet.
    I just modified the examples that came with jsdk2.1 to get the servlets working.
    HTML code:
    <HTML>
    <HEAD>
    <TITLE>Loan Calculator</TITLE>
    </HEAD>
    <BODY>
    <CENTER>
    <H1>Please enter the following information:</H1>
    <HR>
    <FORM ACTION="http://10.1.11.84:8080/examples/servlet/LoanCalculator" METHOD="GET">
    <TABLE CELLSPACING="2" cellpadding="2" border="0">
    <TR>
    <TD ALIGN="right">Principal: $</TD>
    <TD ALIGN="left"><INPUT TYPE="text" NAME="principal" SIZE="10"></INPUT></TD>
    </TR>
    <TR>
    <TD ALIGN="right">Interest (0.nn): </TD>
    <TD ALIGN="left"><INPUT TYPE="text" NAME="interest" SIZE="10"></INPUT></TD>
    </TR>
    <TR>
    <TD ALIGN="right">Monthly Payment: $</TD>
    <TD ALIGN="left"><INPUT TYPE="text" NAME="payment" SIZE="10"></INPUT></TD>
    </TR>
    <TR>
    <TD COLSPAN="2" ALIGN="center"><INPUT TYPE="submit" NAME="cmdSubmit"
    VALUE="Calculate!"></td>
    </TR>
    </TABLE>
    </FORM>
    </CENTER>
    </BODY>
    </HTML>
    Servlet Code:
    //Import Servlet Libraries
    import javax.servlet.*;
    import javax.servlet.http.*;
    //Import Java Libraries
    import java.io.*;
    //Import html and loan helper classes
    import com.wrox.util.*;
    public class LoanCalculator extends HttpServlet
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    // retrieve parameter values as strings
    String principalAsString = req.getParameter("principal");
    String interestAsString = req.getParameter("interest");
    String paymentAsString = req.getParameter("payment");
    // initialize variables to hold floating point values
    float principal, interest, payment;
    // initialize a variable to hold the loan repayment period
    int months;
    try
    // use the LoanTools class to obtain floating point values
    // stringToFloat throws a NumberFormatException, so we'll have to catch it
    principal = LoanTools.stringToFloat(principalAsString);
    interest = LoanTools.stringToFloat(interestAsString);
    payment = LoanTools.stringToFloat(paymentAsString);
    // use the LoanTools class to calculate the loan period
    // the method throws an IllegalArgumentException, so we'll have to catch it
    months = LoanTools.calculateLoanPeriod(principal, interest, payment);
    // If a NumberFormatException was thrown, we want to
    // replace the error message with something more friendly
    catch (NumberFormatException e)
    handleError(new NumberFormatException("Check that the values entered are numeric"), res);
    return;
    // If any other kind of exception was thrown, we catch it here
    catch (Exception e)
    handleError(e, res);
    return;
    // If no exceptions were thrown, the code continues here
    // so we can send an acknowledgment to the browser
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    HTML h = new HTML("Loan Calculator: Results");
    h.add(HTML.HEADING, "Loan Calculator Results", false);
    h.add(HTML.LINE, "", false);
    h.add(HTML.NORMAL, "Principal Amount: $", false);
    h.add(HTML.NORMAL, Float.toString(principal), true);
    h.add(HTML.NORMAL, "Interest: ", false);
    h.add(HTML.NORMAL, Float.toString(interest), true);
    h.add(HTML.NORMAL, "Payment: $", false);
    h.add(HTML.NORMAL, Float.toString(payment), true);
    h.add(HTML.NORMAL, "Months Until Payoff: ", false);
    h.add(HTML.NORMAL, Integer.toString(months), true);
    out.println(h.getPage());
    out.close();
    // This version of handleError() sends an HTTP Error code to inform
    // the client and server of the error
    private void handleError(Exception e, HttpServletResponse res)
    throws IOException
    res.sendError(400, e.getMessage());
    I really appreciate your help.
    thanks,
    Will

    Hi!
    You have to insert an entry for every Servlet you use in the
    web.xml file of your Servlet-Engine (e.g. tomcat):
    <servlet>
    <servlet-name>
    LoanCalculator
    </servlet-name>
    <servlet-class>
    pkg.LoanCalculator
    </servlet-class>
    <load-on-startup>
    1
         </load-on-startup>
    </servlet>
    Regards,
    Geri

  • Communication avec oscillo TEK TDS2000

    Bonjour,
    Je dialogue via l'USB avec un oscilloscope TDS2012B (utilisation des
    VIs VISA standard). Je souhaite avoir la possibilité de récupérer un
    fichier BMP ou JPEG envoyé par l'oscillo.
    Je fais un test simple avec un format BMP et je récupère bien
    l'entête (14 octets en format chaîne de caractère) mais pas toujours le fichier complet (il est de 77878 octets et je demande 80 000 octets). Pour le JPEG, je ne
    récupère rien.
    Existe-t-il des VIs dédiés pour la récuperation de fichiers sur port série et/ou USB ? Je vous joins mon Vi actuel.
    Par ailleurs, j'utilise aussi un GBFTek AFG avec le driver téléchargé sur le site NI (Tektronix AFG 300 series.lvlib) mais, à priori, un VI pose problème "Default Instrument Setup" appelé par "Initialize" qui demande une commande 'Header Off' non reconnue par ce type de GBF. A voir pour les spécialistes... Je ne suis pas sûr que ce soit l'endroit pour ce type de remarque, mais je ne sais pas à qui m'adresser.
    Merci de vos réponses,
    Cordialement,
    FcRd
    FcRd
    Pièces jointes :
    ImportBMP.vi ‏39 KB

    Merci Rodéric mais pas la peine d'en faire un plat.
    Je suis très mauvais en langue anglaise, et à chaque fois que je m'essaie à les contacter par mèl, je tombe sur de l'anglais!
    C'était juste pour avertir du Pb.
    Par contre j'ai réussi à lire du .BMP de l'oscillo, non sans mal, mais comment lire un .jpeg sur une liaison série ou USB ?
    Je sais mettre l'oscillo en mode export Jpeg et j'ai essayé le même principe mais rien.
    Cordialement,
    FcRd
    PS: je joint mon VI qui lit le .BMP
    FcRd
    Pièces jointes :
    ImportBMP.vi ‏40 KB

  • Can't create javabean

    error occurred when accessing the test.jsp which uses the testBean. The error is:
    Error 500
    Internal Servlet Error:
    javax.servlet.ServletException: Cannot create bean of class eform.testBean
    Root cause:
    java.lang.ClassNotFoundException: class eform.testBean : java.lang.NullPointerException
    The jsp code and javabean are shown as belows:
    <html>
    <head>
    <meta http-equiv="Content-Language" content="en-us">
    <meta http-equiv="Content-Type" content="text/html; charset=big5">
    <title>testing</title>
    </head>
    <%@ page import="eform.testBean" %>
    <body>
    <jsp:useBean id="simpleBean" scope="session" class="eform.testBean"/>
    .........</html>
    package eform;
    import java.util.*;
    import java.sql.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class testBean extends HttpServlet implements java.io.Serializable {
         //Member variables
         private String applyDate, appName;
         private String status;
         //private int appId;
         //arraylists to hold recordsets
         private List applyDateList, appNameList, statusList, appIdList;
         //helper variables
         private int currentRow;
         private int rowCount;
         private Connection db = null;
         //constructor
         public testBean() {
        //initialize properties
        //setAppId("");
        setApplyDate("");
        setAppName("");
        setStatus("");
        //initialize arraylist to hold recordsets
        applyDateList = new ArrayList();
        appNameList = new ArrayList();
        statusList = new ArrayList();
        //appIdList = new ArrayList();
        //initialize helper variables
        currentRow = 0;
        rowCount = 0;
        //get database connection
        dbConnect();
           private boolean dbConnect() {
            // Setup file path property for AppConstants class.
            System.setProperty("prop.file.dir",
                getServletContext().getRealPath("") + "\\WEB-INF\\");
            try {
                db = DBConnection.getConnection();
                return true;
            catch (ClassNotFoundException e) {
                System.out.println("The database driver cannot not be found!\n" + e);
                System.out.println(e.toString());
                return false;
            catch (SQLException e) {
                System.out.println("A problem when accessing database.!\n" + e);
                System.out.println(e.toString());
                return false;
           /*accessor methods*/
         //application id
         /*public void setAppId (String _appId) {
             appId = Integer.parseInt(_appId);
         public int getAppId() {
             return appId;
         //Apply Date
         public void setApplyDate(String _applyDate) {
              applyDate = _applyDate;
         public String getApplyDate() {
             return applyDate;
        //Application title for displaying
        public void setAppName(String _appName) {
             appName = _appName;
         public String getAppName() {
             return appName;
        //status of application
        public void setStatus(String _status) {
             status = _status;
         public String getStatus() {
             return status;
           //read-only attribute
           public int getCurrentRow() {
                return currentRow;
         public boolean populate(HttpServletRequest request) {
              String sql ="";
              //get the parameters  first
              //this.populateParams(request);
              if(applyDateList.isEmpty()) {
                   try {
                        //execute query
                        Statement s = db.createStatement();
                        ResultSet rs = s.executeQuery(sql);
                        sql = "select * from POR_LEAVE where EMCODE = 20";
                        sql+= " order by APPID desc";
                        applyDateList.clear();
                        appNameList.clear();
                        statusList.clear();
                        //appIdList.clear();
                        rowCount = 0;
                             while (rs.next()) {
                                  applyDateList.add(rs.getDate("APPLYDATE"));
                                  appNameList.add("Leave Application");
                                  statusList.add(rs.getString("status"));
                                  //appIdList.add(new Integer (rs.getInt("APPID")));
                                  rowCount++;
                        catch (Exception e) {
                             System.out.println("Error populating UserAppStatusBean: " + e.toString());
                             return false;
                   //return the status of operation
                   return true;
           //reset current row
           public void setStartRow(int _start) {
                if (_start < rowCount) {
                     currentRow = _start;
           //move to next row
           public int nextRow() {
                if (currentRow == rowCount) {
                     currentRow = 0;
                     return 0;
                //populate bean properties with current row
                setApplyDate((String)applyDateList.get(currentRow));
                setAppName((String)appNameList.get(currentRow));
                setStatus((String)statusList.get(currentRow));
                //setAppId((String)appIdList.get(currentRow));
                currentRow++;
                //return currentRow
                return currentRow;
    }

    Why does your bean extend HttpServlet? Why are you trying to instantiate an object of type Servlet?
    There is a null pointer exception occuring when creating your class
    My guess would be the DB connect method the call to getServletContext().
    Because you are instantiating this class directly, it doesn't have a servlet context - thats provided by the container.
    If you are going to make this a servlet let the container create it when you call the servlet.
    If you are going to make this a java bean, then don't extend HttpServlet.
    To track the error correctly, put a try/catch block like this in your constructor, and then check the log files for any error messages.
    ie
    public testBean() {
    try{
    catch(Throwable t){
    t.printStackTrace();
    throw new Exception("Exception while constructing testBean " + t, t);

  • Can I change scope in my jsp file ??

    Hi all,
    I have html form, jsp for display, bean for Logic and I want the project result is doing sarch in html file,
    bean handle the search in database, and display in jsp, since the database is big, the result is lot, so I want my search result be display 10 recode per page there for I had to use session in my display jsp file.but that bother my new search, if I don't reopen my browns I can't do the new search, like first I search chicken it has over 400 recods, then I jump back to my html file and want to search by duck , I still got the result chicken, if I change my scope to request then is easy to start a new search but can't do to next.
    any ideal??

    Hi,
    The problem still at handle continue search and a new search. i add a again method in my jsp file and can handle new search and old session for few search then get error
    IndexOutOfBoundsException: Index: 60, Size: 4
    <html>
    <head>
         <title>select List</title>
    </head>
    <body>
    <basefont face="Arial">
    <%@ page import = "num.NameBean" %>
    <jsp:useBean id="ViruName" scope="session" class="num.NameBean"/>
    <jsp:setProperty name="ViruName" property="*"/>
    </jsp: useBean>
      <%
       if (ViruName.getString()==null){%>
        <center>
         Sorry, you nedd to enter something for search!
      <br>
    <font size=-1>(Please hit the browser 'back' button to continue)</font><br>
    </center>
    <%}else{%>
    <table align="center" width="600"border="1">
         <tr>
              <td width="20%"><b>FieldNumber</b></td>
              <td width><b>Name</b></td>
              <td width="30%"><b>HiTiter</b></td>
              <td width="30%"><b>SubType</b></td>
         </tr>
    <%
         int rowCount = 0;
         int startRow = 0;
         if (ViruName.Mysearch()) {
              String start = (String) request.getParameter("start");
              if (start != null) {
                   startRow = new Integer(start).intValue();
                   ViruName.setStartRow(startRow);
              while (rowCount < 10 && ViruName.nextRow() > 0) {
                   rowCount++;
    %>
         <tr>
                   <td width="10%"><jsp:getProperty name="ViruName" property="fieldNumber"/></td>
                    <td width="30%"><jsp:getProperty name="ViruName" property="name"/></td>
              <td width="30%"><jsp:getProperty name="ViruName" property="hiTiter"/></td>
              <td width="30%"><jsp:getProperty name="ViruName" property="subType"/></td>
         </tr>
    <%
              }//end while
         }//end if
    %>
    </table>
         <!-- Display the back and next links -->
                   <a href="?start=<%= ViruName.getCurrentRow() %>">Next</a>
                            <% ViruName.again();%>
                     <a href ="test.html">new search</a>
    <%
    %>
    </body>
    </html>
    package num;
    import java.util.*;
    import java.sql.*;
    public class NameBean implements java.io.Serializable {
      /* Member Variables */
      private String fieldNumber;
      private String name;
      private String hiTiter;
      private String subType;
      private String string;
      private String text=null;
      /* ArrayLists to hold recordsets */
      private List fieldNumberList, nameList, hiTiterList, subTypeList;
      /* Helper Variables */
      private int currentRow;
      private int rowCount;
      private Connection db = null;
      /* Constructor */
      public NameBean() {
        /* Initialize bean properties */
        setFieldNumber("");
        setName("");
        setHiTiter("");
        setSubType("");
        /* Initialize arrayLists to hold recordsets */
        fieldNumberList = new ArrayList();
        nameList = new ArrayList();
        hiTiterList = new ArrayList();
        subTypeList = new ArrayList();
        /* Initialize helper variables */
        currentRow = 0;
        rowCount = 0;
        /* Get database connection */
        dbConnect();
      /* Get Database Connection */
      private void dbConnect() {
        if (db == null) {
          try {
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            db = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;selectMethod=cursor","test","1234");
            db.setCatalog("HKData");          
          catch (Exception e) {
            System.out.println("Error Connecting to catalog DB: " + e.toString());
      /* Accessor Methods */
      public String getfieldNumber() {
        return fieldNumber;
    /* one way to set data will get from database */
      public void setFieldNumber(String fieldNumber) {
         this.fieldNumber =fieldNumber;
      public String getName() {
        return name;
      public void setName(String _name) {
        name = _name;
      public String getHiTiter() {
        return hiTiter;
      public void setHiTiter(String _hiTiter) {
        hiTiter = _hiTiter;
       public String getSubType() {
        return subType;
      public void setSubType(String _subType) {
        subType = _subType;
    public  String getString(){
        return string;
    public void setString( String string ) {  
       this.string =string;    }
      /* Read-only attribute */
      public int getCurrentRow() {
        return currentRow;
      /* Populate Record List */
      public boolean Mysearch() {
        /* If prodIDList is empty, then execute the query to populate it */
        if (fieldNumberList.isEmpty()) {
          try {
                       Statement s = db.createStatement();
                      String Sql="select ViruName00.FieldNumber, Name, HiTiter, SubType, Storage";
                             Sql+=" from ViruName00, Storage00";
                             Sql+=" where ViruName00.NewNum=Storage00.NewNum and Name like'"+string+"%'";
                            Sql+=" Union";
                             Sql+=" select ViruName01.FieldNumber,Name, HiTiter,SubType, Storage";
                            Sql+=" from ViruName01, Storage01";
                             Sql+=" where ViruName01.NewNum=Storage01.NewNum and Name like'"+string+"%'";
                            Sql+=" Union";
                             Sql+=" select ViruName02.FieldNumber,Name, HiTiter, SubType,Storage";
                             Sql+=" from ViruName02, Storage02";
                             Sql+=" where ViruName02.NewNum=Storage02.NewNum and Name like'"+string+"%'";
                             Sql+=" Union";
                             Sql+=" select ViruName03.FieldNumber,Name, HiTiter, SubType, Storage";
                             Sql+=" from ViruName03, Storage03";
                             Sql+=" where ViruName03.NewNum=Storage03.NewNum and Name like' "+string+"%'";
               ResultSet rs = s.executeQuery (Sql);
            fieldNumberList.clear();
            nameList.clear();
            hiTiterList.clear();
            subTypeList.clear();
            rowCount = 0;
            while (rs.next()) {
              fieldNumberList.add(rs.getString("FieldNumber"));
              nameList.add(rs.getString("Name"));
              hiTiterList.add(rs.getString("HiTiter"));   
              subTypeList.add(rs.getString("SubType"));
              rowCount++;
          catch (Exception e) {
            System.out.println("Error populating productBean: " + e.toString());
            return false;
        /* Return status of operation (assume success if it made it this far) */
        return true;
      /* Reset current row */
      public void setStartRow(int start) {
        if (start < rowCount) {
          currentRow = start;
      /* Move to next row */
      public int nextRow() {
        if (currentRow == rowCount) {
          currentRow = 0; // Reset for next page request
          return 0; // return 0 to indicate end of recordset
        /* Populate bean properties with current row */
        setFieldNumber((String)fieldNumberList.get(currentRow));
        setName((String)nameList.get(currentRow));
        setHiTiter((String)hiTiterList.get(currentRow));
        setSubType((String)subTypeList.get(currentRow));   
        currentRow++;
        /* return currentRow*/
        return currentRow;
    public void again(){
        fieldNumberList.clear();
            nameList.clear();
            hiTiterList.clear();
            subTypeList.clear();
    }

Maybe you are looking for

  • How do I know if my external hard drive is working?

    Hi I was running time machine on a seagate 2TB external Hard Drive with a partition for the hard drive for 1TB and another partition for Music files. One day when I was backing up an error message said something along the lines of "Your time machine

  • Cost price Problem for repair FG.

    hi, Business scierio- Mat "A' Done GR aginst Production order, Now the Same FG undergone the repair, we use to do Creating New FG Mat "B" and making old FG (mat "A") as a component of Mat "B" . Note- for every FG we having the BOM (universal). Now th

  • Cd printing under Linux (Pixma MG5350)

    Hi all, I've bought a Canon Pixma MG5350 just a few weeks ago. It works great but this week I've tried to print with the CD-tray. I have made a nice label using Glabels, and set the printing configuration as followed: Paper tray: CD tray Paper size:

  • Could not get to Spotlight screen

    I could not get to Spotlight screen on my iPhone 6 plus, by either swiping right or pressing the home button.  I can swipe right or left from the other home screens, but not from the first home screen as directed in the iPhone 6 User's Guide.  I reso

  • Importing scrollbar actions

    My problem is I'm trying to play a function contained in an as. file. It's not the main function in the class file. When I downloaded the sample, the as. file was in the same file as the fla, and the only actionscript in the fla file was sb.init(txt_