Wednesday, December 03, 2008

Hans's Top Ten JSP Tips

http://www.oreillynet.com/pub/a/oreilly/java/news/jsptips_1100.html


JavaServer Pages (JSP) is the latest tool for Java-based Web application
development. A JSP page contains regular markup code plus special JSP
elements. When the page is requested, the static markup code and the
dynamic content produced by the JSP elements are combined to form the
complete response to the request.




It's impossible to tell you everything you need to know to use JSP
effectively in a short article like this (that's why I wrote
JavaServer Pages).
Instead, this article focuses on the frequently asked questions that I've
heard from people who have just started to play around with JSP.





  1. Choosing the Right Include Mechanism



    A JSP page can include page fragments from other files to form the complete
    response. You can use this, for instance, to keep header, footer, and
    navigation bar content in separate files and include them in all other
    pages. There are two include mechanisms: the include directive and
    the include action. It's not always obvious which one to use,
    though.


    The include directive, <%@ include file="filename.inc" %>,
    includes the content of the specified file during the translation
    phase--when the page is converted to a servlet. The main page and the
    included file are simply merged. This means that scripting variables
    declared in one file (using scripting elements or an action element like
    <jsp:useBean>) are visible in all files and must have unique
    names. Some containers detect changes in files included with the directive,
    but the specification doesn't require it. Therefore, changes you make to
    the included file in a running system may not be reflected immediately; you
    may have to update the main JSP page, or remove the class file generated
    for the main page in order to see the change.







    The include action,
    <jsp:include page="pagename.jsp" flush="true" />,
    includes the response generated by executing the specified page (a
    JSP page or a servlet) during the request processing phase--when the page
    is requested by a user. As opposed to the include directive, the page name
    can be specified as a so-called request-time attribute value, so
    which page to include can be decided when the main page is requested. Since
    it's the response generated by the page that is included, not the
    content of the page itself, scripting variables declared in one file are
    not available to the other files. To share an object between the pages you
    must instead place it in one of the following JSP scopes: request, session
    or application scope. If you change a page included with the include
    action, the change always takes effect immediately.




    My rule of thumb for when to use the different mechanisms is this:



    • Use the include directive if the file changes rarely. It's the
      fastest mechanism. If your container doesn't automatically detect changes,
      you can force the changes to take effect by deleting the main page class
      file.


    • Use the include action only for content that changes often, and
      if which page to include cannot be decided until the main page is requested.




  2. Dealing with Buffer Flushing Issues



    An HTTP response message contains both headers and a body. The headers tell
    the browser things like what type of data the body contains (HTML text, an
    image), the size of the body, if the body can be cached, and so on. Headers
    are also used to set cookies and to tell the browser to automatically get
    another page (a redirect). All response headers must be sent to the browser
    before the body is sent.


    To allow parts of the body to be produced (from static template text as
    well as content generated dynamically by JSP elements) before headers are
    set, the body is buffered. Instead of sending the response to the browser
    as soon as something is written to the response body, the JSP container
    writes all static markup code and all dynamic content generated by JSP
    elements to the buffer. At some point, such as when the buffer is full or
    the end of the page is reached, the container sends all headers that have
    been set followed by the buffered body content. In servlet speak, this is
    called committing the response. After the response has been
    committed, you can't set headers, such as for cookies or a redirection
    instruction. Another thing you can't do is forward the request to another
    page.


    In most cases, this is not a problem. The default buffer size is 8KB, more
    than enough for a typical page, and you can increase it with the
    buffer attribute of the page directive. But if you use
    the include action in a page, you may be in for a surprise. Due to
    limitations in the way the servlet features used by
    <jsp:include> are specified, the buffer is always flushed
    before the target page is invoked. This means that you can't set headers or
    use <jsp:forward> after a <jsp:include> action.



    An unfortunate side-effect of this automatic flushing is that runtime
    errors triggered by JSP elements after a <jsp:include> action
    may not be reported correctly, since many JSP containers use the forward
    mechanism to display the error page. If you see an error message like
    "response already committed" in a page with <jsp:include>
    elements, I suggest that you use the include directive instead (at least
    until you have isolated the problem).


  3. Passing Data Between Pages Processing the Same Request


    Quite often, more than one JSP page is used to process a single request.
    One example is when you use the include action to include a
    common navigation bar in all pages. Another example is when you use one
    page for request processing (e.g., input validation and database access) and
    then use the forward action, <jsp:forward page="pagename.jsp"
    />
    , to let another page generate the response. There are two ways to
    pass data from one page to another: using request parameters or request

    attributes.


    First of all, the page invoked using a <jsp:include> or
    <jsp:forward> action has access to all HTTP request parameters
    that were sent to the first page. In addition, you can specify new request
    parameters using nested <jsp:param> actions:




    <jsp:forward page="login.jsp">
    <jsp:param name="errMsg"
    value="The name or password is not valid" />
    </jsp:forward>



    The target page has access to the all request parameters the same way, no
    matter if they are original or additional parameters.


    Request parameters can only hold string values. If you need to pass an
    object, say a UserInfoBean with various user information
    properties, you need to pass it as a request attribute instead (or as a
    session or application scope bean, but let's ignore that for now). A
    request attribute is the same thing as a request scope object, so the first
    page can create the object and set all its properties with the

    <jsp:useBean> and <jsp:setProperty> actions:



    <jsp:useBean id="userInfo" scope="request"
    class="com.mycompany.UserInfoBean">
    <jsp:setProperty name="userInfo" property="*" />
    </jsp:useBean>

    ...
    <jsp:forward page="nextpage.jsp" />



    In order to use the bean in a page invoked through <jsp:forward>
    or <jsp:include>, you must use the <jsp:useBean>
    action in the invoked page as well. This is so that the bean created by the
    first page can be located and associated with the specified id. It can then
    be used by scripting code or other actions, such as

    <jsp:getProperty>, in the new page:



    <jsp:useBean id="userInfo" scope="request"
    class="com.mycompany.UserInfoBean" />
    <jsp:getProperty name="userInfo" property="firstName" />



  4. Choosing Between Forward and Redirect


    If you want to pass the control from one page to another, you can either
    forward to the other page, as described above, or redirect to
    the new page (using the sendRedirect() method of the implicit
    response object).



    There's an important difference between a forward and a redirect. When you
    forward, the target page is invoked by the JSP container through an
    internal method call; the new page continues to process the same request
    and the browser is not aware of the fact that more than one page is
    involved. A redirect, on the other hand, means that the first page tells
    the browser to make a new request to the target page. The URL shown in the
    browser therefore changes to the URL of the new page when you redirect, but
    stays unchanged when you use forward. A redirect is slower than a forward
    because the browser has to make a new request. Another difference is that
    request scope objects are no longer available after a redirect because it
    results in a new request. If you need to pass data to the page you redirect
    to, you have to use a query string and pass them as request parameters (or
    save the data as session or application scope objects).


    So how do you decide if you should use forward or redirect? I look at it
    like this: Forwarding is always faster, so that's the first choice. But
    since the URL in the browser refers to the start page even after the
    forward, I ask myself what happens if the user reloads the page (or just
    resizes the window; this often reloads the page automatically). If the
    start page is a page that updates some information, such as adding an item
    to the shopping cart or inserting information in a database, I don't want
    it to be invoked again on a reload. To show the result of the processing,
    I therefore redirect to a page with a confirmation message, instead of
    using forward.


  5. Choosing Between Beans and Custom Actions


    In JSP 1.0, JavaBeans were the only type of components that you could use
    to encapsulate the Java code and invoke using standard JSP action elements,
    such as <jsp:getProperty> and <jsp:setProperty>.
    JSP 1.1 adds custom action elements to the component toolbox. A
    Java class, called a tag handler, implements a custom action's
    behavior. In its most simple form, it's just a JavaBeans class with
    property access methods corresponding to the custom action elements plus
    a few extra methods used by the container to invoke the tag handler (so it
    can do its job). Tag handlers that need to process the element's body or
    create objects assigned to scripting variables requires a bit more effort
    to develop, but it's still not rocket science. It is, however, too much to
    describe in detail here. My book contains two chapters with all the
    details about how to develop custom action tag handlers.



    As is often the case in software development, it's hard to say exactly
    when a bean or a custom action is the preferred component type. My rule of
    thumb is that a bean is a great carrier of information and a custom
    action is great for processing information. Custom actions can use
    beans as input and output. For instance, you can use a bean to capture
    form input, with the <jsp:setProperty> action, and then a
    custom action to save the properties of the bean in a database. The
    reverse is also a good example; get information from a database using a
    custom action that makes it available to the page as a bean.


  6. Using Packages for Bean Classes


    When you develop a bean to be used in a JSP page, I recommend that you
    make it part of a named package. A Java class that does not use a

    package statement ends up in the so-called unnamed package.
    The servlet class generated from the JSP page is, however, typically
    assigned to a named package. If you try to refer to a class in the unnamed
    package from a class in a named package, Java cannot find the class
    unless you use an import statement to import it. In a JSP page that means
    you must use both a page directive to import the class, and the
    <jsp:useBean> action to make it available:



    <%@ page import="UserInfoBean" %>
    <jsp:useBean id="userInfo" class="UserInfoBean" />




    If the bean is part of a named packed, the <jsp:useBean>
    action is all you need:



    <jsp:useBean id="userInfo"
    class="com.mycompany.UserInfoBean" />



  7. Mixing Scripting Variables and Scope Variables



    My general advice is that you avoid embedding Java code in your JSP pages.
    Code in scripting elements can easily lead to hard to find syntax errors
    and too much code in the pages makes the Web application hard to maintain.
    One specific area of confusion when you use both Java code scriptlets and
    JSP action elements is how scripting variables and objects created by an
    action element in a JSP scope interact. Or rather, don't interact.
    Consider this example:



    <jsp:useBean id="userInfo"
    class="com.mycompany.UserInfoBean" >
    <jsp:setProperty name="userInfo" property="firstName" />
    </jsp:useBean>
    <%
    userInfo = new com.mycompany.UserInfoBean();
    %>
    <jsp:getProperty name="userInfo" property="firstName" />




    Here a UserInfoBean instance is created by the
    <jsp:useBean> action in the page scope (default) and its
    firstName property is set to the value passed as a request
    parameter with the same name. The <jsp:useBean> also makes the
    bean available as a scripting variable with the same name as the scope
    variable (userInfo in this example). Next, a scriptlet creates a
    new instance of the UserInfoBean class and assigns it to the

    userInfo scripting variable. Finally, the
    <jsp:getProperty> action retrieves the value of the bean's
    firstName property. But which instance of the UserInfoBean
    does <jsp:getProperty> use? The answer is the instance
    available in the page scope. The <jsp:getProperty> action, or
    any action element for that matter, cannot access scripting variables,
    only objects placed in one of the standard JSP scopes: page, request,
    session and application. If you must use scripting elements to create
    objects that you then want to let actions access, you must also place them
    in the appropriate scope:




    ...
    <%
    userInfo = new com.mycompany.UserInfoBean();
    pageContext.setAttribute("userInfo", userInfo);
    %>
    <jsp:getProperty name="userInfo"
    property="firstName" />



    In this modified example, the setAttribute() method is used to
    replace the page scope object created by <jsp:useBean> with
    the instance created by the scriptlet. Hence, the

    <jsp:getProperty> action finds the new instance.


  8. Setting Properties to Non-String Data Type Values


    Bean properties, as you probably know, are represented by accessor
    methods: a setter method for a writeable property and a getter method for
    a readable property. The data type of the property is the data type of the
    setter method's single argument and the getter methods return type.



    The <jsp:setProperty> action is often used to set a bean's
    property to the values of request parameters. Request parameters are sent
    as strings, so what happens if the bean's properties are of other types
    than String? The JSP container is nice enough to convert
    String values to the most commonly used Java data types, as
    described in the following table:











    Property TypeConversion Method


    boolean or

    BooleanBoolean.valueOf(String)


    byte or ByteByte.valueOf(String)


    char or
    CharacterString.charAt(int)


    double or
    DoubleDouble.valueOf(String)


    int or
    IntegerInteger.valueOf(String)

    float or
    FloatFloat.valueOf(String)


    long or LongLong.valueOf(String)










    If your property is of a type not listed in the table, you need to take
    care of the conversion yourself. The most author-friendly way is to use a
    String property, even for properties that logically should be of a
    different type, such as a date or a RGB color value, and let the bean
    convert it internally. But if you really want to use a data type other
    than String or the ones listed above, the page author can use a
    request-time attribute value that evaluates to the correct data type to
    set the property value:




    <jsp:setProperty name="userInfo" property="empDate"
    value='<%= new
    java.util.Date(request.getParameter("empDate")) %>' />



    Note that this example uses a deprecated Date constructor and is
    very error-prone (it fails if the empDate parameter is missing or
    doesn't hold a valid date string). I use it only to illustrate how you can
    set an attribute of a data type that has no JSP-supported conversion rule,
    such as the Date class used here.



    The rules described here for bean properties set by
    <jsp:setProperty> also applies to custom action attributes.


  9. Accessing a Database


    One of the most frequently asked questions on Sun Microsystem's JSP-INTEREST
    mailing list is how to access a database from a JSP page. I'm sorry, but a
    complete description is out of scope for this article. I can give you some
    guidelines, though.


    JSP is Java, so as in all Java programs, you'd use JDBC to access a database.
    You can read more about the JDBC API here.


    I recommend that you do not put the database access code directly
    in the JSP page. Instead, create a bean or a custom action that does all
    the hard work. My book contains a set of custom actions for database
    access that you can use, and there are many other examples available on
    the Net (see Tip 10 of this article). For a complex application,
    you may actually want to use a servlet for all database access and let it
    forward the request to a JSP page that only deals with rendering the
    result. This model is often referred to as the Model-View-Controller (MVC)
    model, or Model 2 (a term used in a prerelease of the JSP specification).
    I show examples of this alternative in my book as well. You can also
    learn more about the MVC model from the Apache Struts project.



    Database access is typically very expensive in terms of server resources.
    You should use a connection pool (covered in the book and frequently
    discussed on the JSP-INTEREST list) to share database connections
    efficiently between all requests. Another resource saver is to cache the
    results of database queries as much as possible. In many cases, the
    database information rarely changes. For instance, product catalog
    information may change only when products are added or deleted, or when
    the prices change. For this type of information you can get the data once
    and save it as an application scope object that all users can access. In
    the rare event that the information changes, just replace the application
    scope object with a new version. Another caching strategy for data that
    changes infrequently is to cache it as a session scope object. The user
    will then see the data as it looks when the session starts, but changes
    made during the session are not visible. If you use the session cache
    strategy, you must also consider if the amount of memory used for the
    cache (one copy per session) is worth the gain in reduced number of
    database accesses. Typically it is worth it, but make sure your server has
    enough memory to handle the peaks.


    If you decide to use a cache, don't use the JDBC ResultSet object
    itself as the cache object. A ResultSet is tightly linked to a
    specific connection and therefore conflicts with the connection pooling.
    Instead, copy the data from the ResultSet into an application
    specific bean, a Vector of Vector's, or something
    similar.


  10. Finding Out More


    I hope you have found something in this article that helps you develop
    your JSP based application. But there's a lot more you should know to use
    this powerful technology as efficiently as possible. I recommend, of
    course, that you read my book,
    JavaServer Pages
    (O'Reilly).


    There's also plenty of information on the Internet. The best place to
    start Sun's JSP
    page
    . There you find the JSP specification, articles and tutorials written
    by Sun employees, and lots of references to other JSP-related sites and
    products.

What is the difference between request.getParameter() and request.getAttribute() ?

Ok, getParameter() first:

http://www.jguru.com/faq/view.jsp?EID=1307699



Ok so when you click the submit button on this HTML page the form will be posted to testJSP.jsp

Code:

<%
String sValue = request.getParameter("testParam");
%>

<%= sValue %>


request.getParameter("testParam") will get the value from the posted form (named testForm) of the input box named testParam which is "Hello Param". It will then print it out, so you should see "Hello Param" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.

Now for request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.

Code:
// Your servlet code
public class SomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/** Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("http://www.website.com/yourResource"); //You could give a relative URL, I'm just using absolute for a clear example.
Object object = new Object(); // You can use any type of object you like here, Strings, Custom objects, in fact any object.
request.setAttribute("ObjectName", object);
rd.forward(request, response);
}
}

Now when you call rd.forward() the request will be forwarded to the resource specified ie: in this case "http://www.website.com/yourResource"

Now in this case yourResource is a Servlet, here is the code

Code:
public class YourResourceServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/** Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Retrieve the object stored in the request.
Object myDispatchedObject = request.getAttribute("ObjectName");
}
}

Now you have the object that you passed from resource to resource on the server side.

Using JavaBean Classes in JSP

jsp:usebean id="b" class="herong.DemoBean"

jsp:setproperty name="b" property="author" value="Someone"
Line 11: author =
jsp:expression>b.getAuthor()jsp:expression




jsp:setproperty/jsp:usebean>

http://www.herongyang.com/jsp/usebean.html

Monday, December 01, 2008

Parse Int problems with leading 0's

Parse Int problems with leading 0's

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_21701871.html


Trying to convert
string with leading 0 to number and it doesn't work

ie:

var test = '08';
var value = parseInt(test);

I wan't 08 I currently get it to work like this, but there must be a better way.

if (test.charAt(0) == '0') test= test.charAt(1);
value = parseInt(test);

answer=
There is an optional parameter that allows you to specify base ten. If there are leading zeros for some unknown reason to me parseInt will treat the number as an octal number (base 8) just do it like this:

var test = '08';
var value = parseInt(test,10);

...That one pissed me off forever until I found out what was going on.

Glad to help :)

Tuesday, October 14, 2008

combine 3 record into 1 record by stored in different field

combine 3 record into 1 record by stored in different field
original
GameID CODESTATUS COUNT
====== ========== =======
GAMEA A 5
GAMEA T 10
GAMEA R 15

TO

GAMEID A_STATUS T_STATUS R_STATUS
======== ======== ========= ==========
GAMEA 5 10 15

===================================================

select gameid, count(gameid) as count, sum(aCount) as Available,sum(tCount) As Taken,sum(rCount) as Reserved from (
select gameid, codestatus,
case when codestatus='A' then 1 else 0 end as aCount,
case when codestatus='T' then 1 else 0 end as tCount,
case when codestatus='R' then 1 else 0 end as rCount
from tibsadmin.gamename_code
) as a group by (gameid)

Monday, October 06, 2008

WINDOW.OPEN using POST instead of GET

function toPreview(f) {

f.action = "";

f.onsubmit = "return true;";
f.target ="preview";

var theHeight = 550;
var theWidth = 480;
var theTop=(screen.height/2)-(theHeight/2);
var theLeft=(screen.width/2)-(theWidth/2);
var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",scrollbars=yes";
window.open('','preview',features);
}

Tuesday, September 02, 2008

db2pd -

A new DB2 UDB utility for monitoring DB2 instances and databases

ref

How can I make an SQL INSERT faster?

DB2 has added a new keyword to the CREATE and ALTER TABLE SQL statements: APPEND. This new keyword enables a pretty simple concept. If you CREATE or ALTER a TABLE to APPEND YES, DB2 simply sticks the new row at the end of the table*, makes no attempt at searching for available space, and makes no effort to preserve any kind of clustering order. Because you can ALTER this attribute on and off, you can switch it on (YES) for that massive insert batch job you run once a month and always follow with REORG/RUNSTATS anyway, then switch it back off (NO) for your day to day online insert processing. REORG is unaffected by the APPEND option so you can use it in conjunction with a tables clustering options allowing the object to take advantage of a faster insert and still maintaining a clustered sequence by the REORG and LOAD utilities.

The APPEND will work for all tables except those created in LOB, XML, and work files table spaces. BTW, this process is for insert and online LOAD operations. There is also a new column, APPEND, in SYSIBM.SYSTABLES so you can track when this feature has been turned on or off. In addition, you are going to see some index relief for inserts in DB2 9. But I'll save that for another post.



Ref

Revision: Runstats vs Reorg

In case you are new, we run REORG & then RUNSTAT when we do mass inserts/updates/deletes on DB or individual tables,so that the query runs faster . REORG and RUNSTAT are DB command.
RUNSTATS
1) Updates datadictionary stats. When a query is fired it reads the data dictionary table (dictionary managed) and calculates the cost,etc.

2) Gathers summary information about the characteristics of the data in table spaces and indexes. This information is recorded in the DB2 catalog, and is used by DB2 to select access paths to data during the bind process. It is available to the database administrator for evaluating database design, and determining when table spaces or indexes should be reorganized .




REORG
1) Put all the contiginous blocks together,so data reads / inserts will happen faster as it need not scan the pages. (example is defragmentation in windows)

2) Reorganized a table space to improve access performance and reclaim fragmented space. In addition, the utility can reorganize a single partition of either a partitioned index ora partitioned table space. If you specify REORG UNLOAD ONLY or REORG UNLOAD PAUSE, the REORG utility unloads data in a format acceptable to the LOAD utility of the same DB2 table space.
REORGCHK
do a reorgchk on a certain schema, which will runstat all tables in the schema, whereas doing runstats alone,
then you need to do it table by table.


TIPS
1) Run REORG & then RUNSTAT.

2) It is not necessary to run reorg for all tables :use REORGCHK ON TABLE ALL find which tables require reoganization and run REORG & then RUNSTAT for that specified tables.


EXAMPLE
REORG INDEXES ALL FOR TABLE MYSCHEMA.TABLEA ALLOW WRITE ACCESS;
RUNSTATS ON TABLE MYSCHEMA.TABLEA WITH DISTRIBUTION AND DETAILED INDEXES ALL;
RUNSTATS ON TABLE MYSCHEMA.TABLEA ON ALL COLUMNS ALLOW WRITE ACCESS;


ref


Where exactly is a DB2 plan stored?

Catalog contains information about plans in the following tables:
  • SYSIBM.SYSDBRM
  • SYSIBM.SYSPLAN
  • SYSIBM.SYSPLANAUTH
  • SYSIBM.SYSPLANDEP
  • SYSIBM.SYSSTMT

And, the DB2 Catalog contains information about packages in the following tables:

  • SYSIBM.SYSPACKAGE
  • SYSIBM.SYSPACKAUTH
  • SYSIBM.SYSPACKDEP
  • SYSIBM.SYSPACKLIST
  • SYSIBM.SYSPACKSTMT
  • SYSIBM.SYSPKSYSTEM
  • SYSIBM.SYSPLSYSTEM
ref

Step SQL Optimize

db2expln -d tibsdb -f xx/sql -o xx.log

db2expln - SQL Explain Command
http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0005736.htm

The Two Biggest DB2 Performance Things
ref

Check index
====
db2 "describe indexes for table tibsadmin.fundtransferhistory"
db2 "SELECT colnames,tbname FROM SYSIBM.SYSINDEXES where upper(tbname) =upper('fundtransferhistory') ";

db2expln -d tibsdb -f 1.sql -o 1.log


drop index ;
CREATE INDEX {index_name} ON {table} ( {column1} ASC,
{column2} ASC) ;
CREATE INDEX
{index_name} ON {table} ( {column1} ASC) CLUSTER ;
**cluster index is physical index. Only 1 cluster index per table

Setup JMeter for load test
====================
pre requisite-put the db2 drirver.jar to jmeter/lib

1)Test Plan -> Add Thread Group
2)Thread Group->Add->Config Element ->JDBC Connection Configuration
3)Max number of connection = {> Number of thread}
Database url = jdbc:db2://{host}:{port}/{dbname}
Jdbc driver classess = com.ibm.db2.jcc.DB2Driver
username=
password=
**package for "com.ibm.db2.jcc" is ibm jdbc driver type4
**package for "COM.ibm.db2.jdbc" is ibm jdbc driver type2 which use by websphere server
**"DB2Driver" class is normal driver
**"DB2ConnectionPoolDataSource" class is connection pool data source.
****jdbc:db2://10.100.101.30:61099/tibsdb


4)Thread Group->Add->Sampler->JDBC Request
**For insert sql, u can create Non Duplicate ID using this function
CHAR( ${__counter(FALSE,100)} )

example:
INSERT INTO Schema.Mytable VALUES ( CHAR( ${__counter(FALSE,100)} )
, 'AbcValue')

5)ThreadGroup ->Add->Listner
i)Summary report - to view summary statistic
ii)View Results Tree - to check the request and response data
iii) Aggregate Report - Have 90% line











ref 1 : How to easily populate a table with random data

Thursday, August 21, 2008

Rational Software Development Conference 2008

19th August 2008 @ Sheraton Subang Hotel

Presentation Slide to be downloaded
http://www-07.ibm.com/my/events/rsdc2008/download.html

What is Jazz?

Developing software in a team is much like playing an instrument in a band. Both require a balance of collaboration and virtuosity. Jazz defines a vision for the way products can integrate to support this kind of collaborative work, and a technology platform to deliver on this vision.

Jazz is an IBM Rational project to build a scalable, extensible team collaboration platform for integrating work across the phases of the development lifecycle. We believe Jazz will help teams build software more effectively while making the software development activity more productive and enjoyable.

Reference

https://jazz.net/pub/index.jsp Jazz.net
i) Collaborative in Context
- Build better

ii)Right size governance
- workflow for check in source code
- earlier bug detection
-pick right process for you

iii)Day One productivity -easy setup development environment

iv)Open & Extensible architecture
http://www.ibm.com/software/rational/collaborate
the flexibility to assemble your own software delivery platform, relying on your preferred vendors and solutions.

"Suppose we expose data to internet?"
Ans:Internet create challenge, solve it.

Scaling Agile Software Deveploment: Apply Agile in Complex Situations

Agile software development refers to a group of software development methodologies that promotes development iterations, open collaboration, and process adaptability throughout the life-cycle of the project. Surveys Exploring The Current State of Information Technology Practices
http://www.ambysoft.com/surveys/
Leader of tomorrow -Adapt Agile technique Jazz platform
-Team concert
-Rational Requirement Composer
-Rational Quality Manager

RMC 7.5 Agile Core -Iteration Development
-Continuous integration
-Test driven Development Reason

------- Whole team will focus for the next iteration Focus more time in planning, compare with traditional methodology which is get everything requirement in the beginning stage which may have alot unseen thing. Statistic saying there is 45% of features of system never use. http://www.agiledata.org/essays/enterpriseArchitecture.html

Enable Security Testing across the Software Development Life cycle with AppScan
Make securty as QA task

Using Rational Requirment Tools to implement Business Driven Development
IBM Rational Requirements Composer http://www.ibm.com/software/rational/announce/rrc -rich test requirement
-use cases
<->good because from user point of view
-UI sketching and storyboarding
-process sketching
-contain iRise + RavenFlow

Wednesday, August 13, 2008

Check index db2

db2 "describe indexes for table tibsadmin.fundtrasnferhistory"

SELECT colnames,tbname FROM SYSIBM.SYSINDEXES
where tbname ='ECEREMITTANCE';

Thursday, July 24, 2008

Retro

Operates by transforming Java class files compiled by a 1.5 compiler into version 1.4 class files which can then be run on any 1.4 virtual machine.

Tuesday, July 01, 2008

catalog node and catalog db @ db2

CATALOG [ADMIN] TCPIP NODE node-name REMOTE hostname [SERVER service-name]
db2 => catalog tcpip node rhbdemo remote 192.168.1.23 server 50000

db2 => list node directory

CATALOG DATABASE database-name [AS alias] [ON drive | AT NODE node-name]
db2 => catalog database ibsdb as rhbdb at node rhbdemo

Tuesday, June 24, 2008

LAB 1: Install OS Zone & DB2

1.LAB 1: Install OS Zone & DB2

1.1.Prerequisites / Hardware Requirement

  1. Solaris OS needs 4 GB disk space and 400MB RAM

  2. Each additional zone needs 70MB hard disk

  3. Swap space

    1. Normally same as the VM physical RAM

    2. Disk space for tmp folder

    3. Check how many swap space for each application servers and sum up (may check from info center)

      • WAS & WPS 6.0, tmp folder needs minimum 1.5GB

      • DB2 512MB RAM

      • IBM HTTP Server 0.5GB RAM, 1GB disk space

      • LDAP

      • Network Deployment

  4. VM Hard disk space = Solaris OS disk space + Swap space

  5. How many zones required? Depending on the infrastructure designs.

Define Zone

Memory

Hard disk (GB)

Zone 1: DB2

0.5 GB

0.2

Zone 2: Network Deployment

0.5 GB (512MB)

0.3

Zone 3: WAS/WPS Cluster 1


(1.7x2)+(1.5x2) = 6.4

Zone 4: WAS/WPS Cluster 2


(1.7x2)+(1.5x2) = 6.4

Zone 5: Web Server

0.5 GB

1

Zone 6: LDAP


0.2

Zone 7: Solaris 10

0.4 GB

4

Swap Space

Equal to physical memory

1.5

TOTAL:

4 GB

20 GB

1.2.Create Virtual Machine

  1. Name and Location

  1. Guest Operating System – Solaris Operating System (64-Bit)

  1. Memory and Processor - 4GB and 2 processors

  1. Hard Disk – 20GB

  1. Network Adapter – Bridged

Notes:

  • Bridged – network created is visible inside and outside.

  • Host Only – invisible from inside and outside.

  • NAT – invisible inside, but can go out.

  1. CD / DVD Drive – Use an ISO image (sol-10-u4-ga-x86-dvd.iso)

  1. Floppy Drive – Don’t add a floppy drive.

  1. USB Controller – either one will do.

  2. Ready to complete – verify summary and click finish.

1.3.Install Solaris 10

  1. Installation Summary

Network: Yes

DHCP: No

Hostname: [Juice/Kfc/Arsenal]

IP: [192.168.16.1 / 192.168.17.1 / 192.168.18.1]

Subnet mask: 255.255.0.0

Enable IPv6: No

  1. Steps for installing

Check Route Table

$ netstat -rn

Shut down Solaris

$ shutdown –g0 –i5 –y OR $ init 5

Reboot Solaris

$ shutdown –g0 –i6 –y OR init 6 OR reboot

  1. DHCP is dynamically assigned IP. If yes, the server is dependant on DHCP (not HA), means if DHCP server down, this will affect our own server.

  2. To know which network it routes to, netmask (BINARY) AND destination IP.

  3. After installation, at VMWare console, click “Add VMWare Plugin” to install plugin to Guest. Select 800x600 resolution.

1.4.Configure SSH

  1. To allow root login remotely

    1. $ cd /etc/ssh

    2. $ vi sshd_config (server config)

  1. edit PermitRootLogin from no to yes

    1. $ svcadm restart ssh

    2. Verify: ssh from another machine

  1. Generate trust key (Every time root remotely login, no need to key in password)

  1. Navigate to root’s home directory

  2. $ ls –a

  3. $cd .ssh

  4. Check if there is id_rsa.pub inside. If no, generate the public and private key:

    1. $ ssh-keygen –t rsa [-f keyname]

  5. If no directory .ssh, generate using command:

    1. $ ssh localhost date (generate .ssh directory in home directory)

  6. $scp id-rsa.pub_root@coffee:/tmp

  7. in coffee server, mv /tmp/id_rsa.pub /root/.ssh/authorized_keys2

  1. Disable send mail

$ svcadm disable sendmail

1.5.Create Virtual Hard Disk

  1. At the VMWare Host,

    1. $ vmware-vdiskmanager –c –s 4GB 0a lsilogic –t 0 disk1.vmdk

  2. At the VMWare Guest GUI, Add Hardware > Add Hard disk

  1. At the VMWare Guest

    1. $ touch/reconfigure (Issue scan OS hardware)

    2. $ init 6

1.6.Create Storage Pool and Zone

Check available disk

$ format

c1t0d0

c1t1d0 (new virtual disk)

Check file system usage

$ df –h

Create storage pool

- zpool create <pool> <virtual device>

$ zpool create tank c1t1d0

Check storage pool status

$ zpool status

Create new ZFS file system

$ zfs create tank/zones

Set mount point to global zone

$ zfs set mountpoint=/zones tank/zones

List all ZFS

$ zfs list

Create a new zone

- zfs create <zone path/zone name>

$ zfs create tank/zones/db

Create zone conf file to install the zone

$ vi /zones/db/db.cfg

Create

set zonepath=/zones/db

set autoboot=false

add net

set physical=e1000g0

set address=192.168.16.2

end

add fs

set type=lofs

set special=/software

set dir=/sw

end

verify

commit

Configure zone

$ zonecfg –z db –f db.cfg

List zones with status

Status: CONFIGURED, INSTALLED, RUNNING

$ zoneadm –z list –cv (zone now is configured)

$ zonecfg –z db info

Change zone mod

Change the file permission for zone root before install

$ chmod 700 db

Install package to zone

(It takes some time to install)

$ zoneadm –z db install

Boot/Start the zone

(Boot the zone since set the autoboot to false)

$ zoneadm –z boot

Login to zone’s system console

$ zlogin –C db

Choose DECVT100 Terminal

Logout zone

$ exit

Login: ~.

Password: ~.

Check zone status continually

$ while true; do zoneadm list –cv; sleep 3; done

1.7.Add Domain Name

  1. Login to the zone

  2. Edit /etc/hosts

  3. Add one domain name to the server ip address

  4. Test the domain name

$ ping <ip address>

$ ping –s <domain name>

1.8.Install DB2 Server on DB Zone

Copy installation file (SSH & Untar)

$ cat C9658ML.tar | ssh root@192.168.16.1 “(mkdir -p /software/db2; cd /software/db2; gzip -cd; tar -xvf -)”

Install DB2 Server

$ cd /software/db2

$ ./db2_install

Enter: DB2.ESE

Import DB2 License

$ /opt/IBM/db2/v8.1/adm/db2licm -a <license: db2ese.lic >

Create group

$ groupadd –g 100 db2fgrp1

$ groupadd –g 101 db2agrp

$ groupadd –g 102 db2igrp1

Create user

$ useradd –u 100 –g db2fgrp1 –d /export/home/db2fenc1-m db2fenc1

$ useradd –u 101 –g db2agrp –d /export/home/db2adm -m db2adm

$ useradd –u 100 –g db2igrp1 –d /export/home/db2inst1-m db2inst1

Change user password

$ passwd db2fenc1

$ passwd db2adm

$ passwd db2inst1

Add instance service port

$ vi /etc/services

Add: db2c_db2inst1 50000/tcp

Create DB instance (It will generate sqllib directory)

$ cd /opt/IBM/db2/V8.1/instance

$ ./db2icrt –a SERVER –p db2c_db2inst1 –s ese –w 64 –u db2fenc1 db2inst1

(To drop the instance, use db2idrop)

Add project

$ projadd –c “DB2 instance 1” user.db2inst1

Set tuning parameter on resources control

$ su – db2inst1

$ id –p

$ exit

Modify project

Login to the zone again and set these:

$ projmod –s –K “project.max-shm-memory=(priv,4G,deny)” user.db2inst1

$ projmod –s –K “project.max-shm-ids=(priv,4K,deny)” user.db2inst1

$ projmod –s –K “project.max-msg-ids=(priv,4K,deny)” user.db2inst1

$ projmod –s –K “project.max-sem-ids=(priv,4K,deny)” user.db2inst1

Create SAMPLE database

$ cd /opt/IBM/db2/V8.1/bin

$ ./db2sampl

Verify database connection

$ db2 list db directory

$ db2 connect to sample user db2inst1

1.9.Install DB2 Client on Application Zone

Install DB2 Client

$ cd /software/db2

$ ./db2_install

Enter: DB2.ADMCL

Create group

$ groupadd –g 100 db2fgrp1

$ groupadd –g 101 db2agrp

$ groupadd –g 102 db2cgrp1

Create user

$ useradd –u 100 –g db2cgrp1 –d /export/home/db2inst1-m db2inst1

Change user password

$ passwd db2inst1

Add instance port

$ vi /etc/services

Add: db2c_db2inst1 50000/tcp

Create instance

$ cd /opt/IBM/db2/instance

$ ./db2icrt –a SERVER –s client –w 32 –u db2inst1 db2inst1

Login as client user

$ su – db2inst1

Catalog node

$ db2 “catalog tcpip node WPSNODE remote <DB Server IP/Hostname> server db2c_db2inst1

Catalog database

$ db2 “catalog database SAMPLE as SAMPLE at node WPSNODE”

1.10.Create Zone Snapshot

Shutdown all zones

$ zlogin <zone> init 5

Snapshot zone

$ zfs snapshot –r tank/zones@<filename>

Tuesday, May 27, 2008

Code Analysis

1) 1.jpg Right click on selected package or particular .java file ->Analysis-> Analysis / New_configuration(1) Here you can actually define the rules of code analysis. 2) 2.jpg Check the result in VIEW "Analysis Result" 3)
3.jpg Clicked the item of Analysis Result will bring you to the source of the issue. 4)
4.jpg Some issue provide u the quick fixed and solution when u clicked on the small symbol at your left handside.

Friday, May 02, 2008

Log4j PatternLayout

ConversionPattern =[%d{ISO8601}] %-5p : : %C{1}.%M : %m%n

Conversion Character Effect
c Used to output the category of the logging event. The category conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full.

For example, for the category name "a.b.c" the pattern %c{2} will output "b.c".

C Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form.

For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass".

WARNING Generating the caller class information is slow. Thus, it's use should be avoided unless execution speed is not an issue.

d Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed.

The date format specifier admits the same syntax as the time pattern string of the SimpleDateFormat. Although part of the standard JDK, the performance of SimpleDateFormat is quite poor.

For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying AbsoluteTimeDateFormat, DateTimeDateFormat and respectively ISO8601DateFormat. For example, %d{ISO8601} or %d{ABSOLUTE}.

These dedicated date formatters perform significantly better than SimpleDateFormat.

F Used to output the file name where the logging request was issued.

WARNING Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue.

l Used to output location information of the caller which generated the logging event.

The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.

The location information can be very useful. However, it's generation is extremely slow. It's use should be avoided unless execution speed is not an issue.

L Used to output the line number from where the logging request was issued.

WARNING Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue.

m Used to output the application supplied message associated with the logging event.
M Used to output the method name where the logging request was issued.

WARNING Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue.

n Outputs the platform dependent line separator character or characters.

This conversion character offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator.

p Used to output the priority of the logging event.
r Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event.
t Used to output the name of the thread that generated the logging event.
x Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.
X

Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character must be followed by the key for the map placed between braces, as in %X{clientNumber} where clientNumber is the key. The value in the MDC corresponding to the key will be output.

See MDC class for more details.

% The sequence %% outputs a single percent sign.



ref

Is it possible to direct log output to different appenders by level?

Is it possible to direct log output to different appenders by level?

Yes it is. Setting the Threshold option of any appender extending AppenderSkeleton, (most log4j appenders extend AppenderSkeleton) to filter out all log events with lower level than the value of the threshold option.


ref

Rolling File and errors to email

Log messages with Level info to fatal to a file and send messages from error to fatal by email. The file should be rolled every 100 KB.

You need mail.jar and activation.jar libraries from J2EE to send emails. Further properties of the SmtpAppender are described here:

http://logging.apache.org/log4j/docs/api/org/apache/log4j/net/SMTPAppender.html

log4j.properties

### file appender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=100KB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.File=test.log
log4j.appender.file.threshold=info
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

#email appender
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
#defines how othen emails are send
log4j.appender.mail.BufferSize=1
log4j.appender.mail.SMTPHost="smtp.myservername.xx"
log4j.appender.mail.From=fromemail@myservername.xx
log4j.appender.mail.To=toemail@myservername.xx
log4j.appender.mail.Subject=Log ...
log4j.appender.mail.threshold=error
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=warn, file, mail


ref

Reconfigure a running log4j configuration

If you analyse a problem you frequently want to change the log level of a running application server. This chapter explains how you can do this. I used Tomcat as example server but you can use any application server you like.

The XML actually offers a method to watch changes in config files.

http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/DOMConfigurator.html#configureAndWatch(java.lang.String)

The problem is that it seems not to work in some situations. But this is no problem as it is quite easy to develop a short tool by yourself. We have two options. We could change the log level during runtime:

Logger root = Logger.getRootLogger();
root.setLevel(Level.WARN);

or we can reload the configuration:

// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);

The following example will check the configuration file in defined intervals and reconfigure log4j if any changes are found.

We need to create three things:

a) a monitor thread, monitoring the configuration file and reconfiguring log4j if needed

b) a servlet starting and stopping the monitor thread

c) an entry in the web.xml, to initialize the servlet

The following class monitors the logj4 configuration file and checks with the last change date has changed:

package de.laliluna.logexample;

import java.io.File;
import java.net.URL;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

public class MonitorThread implements Runnable {

private static Logger log = Logger.getLogger(MonitorThread.class);

boolean interruped;

private long checkIntervalMillis = 10000;

private URL url;

private File file;

// stores the last modification time of the file
private long lastModified = 0;

public void run() {
System.out.println("Initialize " + url.getPath());
file = new File(url.getPath());
// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);
lastModified = file.lastModified();

monitor();
}

private void monitor() {
log.info("Starting log4j monitor");

while (!interruped) {

// check if File changed
long temp = file.lastModified();
if (lastModified != temp) {
log.info("Initialize log4j configuration " + url.getPath());
// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);

lastModified = temp;

} else
log.debug("Log4j configuration is not modified");
try {
Thread.currentThread().sleep(checkIntervalMillis);
} catch (InterruptedException e) {
interruped = true;
}
}
log.info("Shutting down log4j monitor");

}

public URL getUrl() {
return url;
}

public void setUrl(URL url) {
this.url = url;
}

public long getCheckIntervalMillis() {
return checkIntervalMillis;
}

/**
* Sets the interval for checking the url for changes. Unit is
* milliseconds, 10000 = 10 seconds
*
* @param checkIntervalMillis
*/
public void setCheckIntervalMillis(long checkIntervalMillis) {
this.checkIntervalMillis = checkIntervalMillis;
}

public boolean isInterruped() {
return interruped;
}

public void setInterruped(boolean interruped) {
this.interruped = interruped;
}

}

The servlet starts and stops the monitor thread:

package de.laliluna.logexample;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class Log4jConfigLoader extends HttpServlet {

private Thread thread;

@Override
public void destroy() {
thread.interrupt();
super.destroy();
}

public void init() throws ServletException {
super.init();
MonitorThread monitorThread = new MonitorThread();
monitorThread.setCheckIntervalMillis(10000);
monitorThread.setUrl(Log4jConfigLoader.class.getResource("/log4j.xml"));
thread = new Thread(monitorThread);
thread.start();
}

}

We add the servlet to the web.xml to initialize it.



xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

log4j-init
de.laliluna.logexample.Log4jConfigLoader
10




ref