Welcome to my blog, hope you enjoy reading
RSS

Thursday 25 April 2013

How to get context-param from web.xml in struts app


How to get context-param from web.xml in struts app

The visibility of Context-param from web.xml is in servlet.In Struts the servlet is the ActionServlet. so in ActionServlet  class to get the context param values

example:

ServletContext cg=getServlet().getServletContext();

String driver = cg.getInitParameter("driver");

program:

package com.java.struts.Login;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;

public class UserLoginAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response)throws java.lang.Exception
{
String driver,url,user,pwd1;
DynaValidatorForm dform=(DynaValidatorForm) form;
HttpSession session=request.getSession(true);
String result="failed";
try
{
if(session!=null)
{
ServletContext cg=getServlet().getServletContext();
driver = cg.getInitParameter("driver");
url = cg.getInitParameter("url");
user = cg.getInitParameter("user");
pwd1 = cg.getInitParameter("password");
System.out.println(driver+" "+url+" "+user+" "+pwd1);
String username=dform.get("username").toString();
String pwd=dform.get("password").toString();
if(username!=null&&pwd!=null)
{
System.out.println(username+" "+pwd);
System.out.println("success");
}
}
}catch(Exception e)
{
System.out.println(e.toString());
}
return mapping.findForward(result);
}
}

Share

Wednesday 24 April 2013

Can we override static method in Java - Method Hiding

Can we override static method in Java - Method Hiding
No, you cannot override static method in Java because method overriding is based upon dynamic binding at runtime and static methods are bonded using static binding at compile time. Though you can declare a method with same name and method signature in sub class which does look like you can override static method in Java but in reality that is method hiding. Java won't resolve method call at runtime and depending upon type of Object which is used to call static method, corresponding method will be called. It means if you use Parent class's type to call static method, original static will be called from patent class, on ther other hand if you use Child class's type to call static method, method from child class will be called. In short you can not override static method in Java. If you use Java IDE like Eclipse or Netbeans, they will show warning that static method should be called using classname and not by using object becaues static method can not be overridden in Java.

package com.javanotes2all.java.inheritence;

public class CanWeOverrideStaticMethod
{
public static void main(String args[])
{
Screen scrn = new ColorScreen();
//if we can override static ,
//this should call method from Child class
//IDE will show warning, static method should be called from classname
scrn.staticMethod();
scrn.nonStaticMethod();
}
}

class Screen
{
/*
* public static method which can not be overridden in Java
*/
public static void staticMethod()
{
System.out.println("Static method from parent class");
}
/**
* non static method
*/
public void nonStaticMethod()
{
System.out.println("non-Static method from parent class");
}
}

class ColorScreen extends Screen{
/*
* static method of same name and method signature as existed in super
* class, this is not method overriding instead this is called
* method hiding in Java
*/
public static void staticMethod()
{
System.err.println("Overridden static method in Child Class in Java");
}
/**
* non static method
*/
public void nonStaticMethod()
{
System.out.println("non-Static method from Child class");
}
}

output:
Static method from parent class
non-Static method from Child class

we can not override static method, we can only hide static method in Java. Creating static method with same name and mehtod signature is called Method hiding in Java.


Share

Monday 15 April 2013

How many ways to create object in java?


How many ways to create object in java?


There are different ways to create object in java as follows:--

1. Using new keyword
we can create the instance normally using new operator which is called as static instance creation.
Hello hello =  new Hello();

2.using Class.forName()
we can create the instance dynamically without using new operator as follow
Hello hello=(Hello)Class.forName("com.bikash.Hello").newInstance();
or
Class cls = Class.forName("com.bikash.Hello");
Hello hello = (Hello)cls.newInstance();

3.using clone().
clone() method can be used to copy of the existing object.
Hello hello=new Hello();
Hello hello1=(Hello)hello.clone();

4.using object deserialization.
deserializion is the process of creating the new object on the remote mechine from its serialize form.
ObjectInputStream ois =new ObjectInputStream();
Hello hello = (Hello)ois.readObject();
Share

Autoboxing and Unboxing


Autoboxing and Unboxing


The Autoboxing and Unboxing  was released with the Java 5.

Autoboxing

During assignment, the automatic transformation of primitive  type(int, float, double etc.) into their object equivalents or wrapper type(Integer, Float, Double,etc) is known as Autoboxing.

Ex:

Integer intObject = 5; // autoboxing
auto-unboxing

During assignment or calling of constructor, the automatic transformation of wrapper types into their primitive equivalent  is known as Unboxing.
Ex:
int inative = 0;
inative = new Integer(5); // auto-unboxing

Autoboxing also works with comparison
int a = 10;
Integer b = 10;
System.out.println(a==b); // true
Share

GWT event listeners


GWT event listeners

GWT defines event listeners that you can attach to your widgets to monitor browser events. Event Listeners are just interfaces that you can implement in your widget. If you want to trap mouse click events, then your widget should implement the ClickListener interface and define theonClick(Widget sender) method. The code inside this method will be fired every time the user clicks on your widget.

You can create a new anonymous ClickListener every time you want to assign it to a widget as given in the Hello gwt example.
button.addClickListener(new ClickListener() {
 public void onClick(Widget sender) {
  processData(sender.getText());
  reportData(sender.getText());
  logResults();
 }
});
But this results in localized code and lesser code reusability. Let us say we want to add another widget (a HTML link), which has to run the same code as in the onClick() method. We would be using the addClickListenermethod for this link and would be rewriting the same code again separately. And if we need to add another method in the onClick() method code between processData() and reportData() we will have to change each instance of onClick().

Alternatively, we can implement the listeners in the container widget to handle the events of contained widgets as shown below, making the code more reusable.
public class MainPanel extends Composite 
 implements ClickListener{

 private Button button=new Button("Button");
 public MainPanel(){
 
  //...
  button.addClickListener(this);
 }

 public void onClick(Widget sender){
  if(sender==button){
   processData(sender.getText());
   reportData(sender.getText());
   logResults();
  }
 }
}
With this approach, if we want to add a HTML widget link that implements the same function, we would just have to add the line
link.addClickListener(this);
in MainPanel() and modify one line in the onClick(Widget sender)method
if(sender==button||sender==link)
Given Below is a listing of GWT Event listeners for handling various events:

ListenerEvent notificationsMethods Defined
HistoryListenerChanges to Browser HistoryonHistoryChanged(String historyToken)
WindowCloseListenerWindow Closure EventsonWindowClosed()
onWindowClosing()
WindowResizeListenerWindow Resizing EventsonWindowResized(int width, int height)
ChangeListenerfires when a widget changesonChange(Widget sender)
ClickListenerfires when a widget receives a 'click'onClick(Widget sender)
FormHandlerfires on receiving Form events from the FormPanel to which it is attachedonSubmit(FormSubmitEvent event)
onSubmitComplete( FormSubmitCompleteEvent event)
FocusListenerFocus EventsonFocus(Widget sender)
onLostFocus(Widget sender)
KeyBoardListenerKeyboard EventsonKeyDown(Widget sender, char keycode, int modifiers)
onKeyPress(Widget sender, char keycode, int modifiers)
onKeyUp(Widget sender, char keycode, int modifiers)
LoadListenerlistens to 'load' event of a widgetonLoad(Widget Sender)
onError(Widget Sender)
MouseListenerlistens to mouse events of a widgetonMouseEnter(Widget sender)
onMouseLeave(Widget sender)
onMouseDown(Widget sender, int x, int y)
onMouseUp(Widget sender, int x, int y)
onMouseMove(Widget sender, int x, int y)
PopupListenerlistens to the events of a PopupPanel widgetonPopupClosed(PopupPanel sender, boolean autoClose)
ScrollListenerlistens to Scroll eventsonScroll(Widget widget, int scrollLeft, int scrollTop)
TableListenerlistens to events pertaining to a Table widgetonCellClicked( SourcesTableEvents sources, int row, int cell)
TabListenerlistens to the events of a Tab WidgetonBeforeTabSelected( SourcesTabEvents sender, int tabIndex)
onTabSelected( SourcesTabEvents sender, int tabIndex)
TreeListenerlistens to the events of a Tree WidgetonTreeItemSelected( TreeItem item)
onTreeItemChanged( TreeItem item)

The Button widget defines the addClickListener method which attaches a ClickListener object to it. Similarly, the Tree widget defines theaddTreeListener method. Not all event listeners are available for all widgets - for example, the addMouseListener method is not defined for aDockPanel Widget. One way to add the MouseListener functionality to thisDockPanel is to create a composite that includes a FocusPanel widget (which supports addMouseListener) and wrap the DockPanel widget within it.
Share

Wednesday 10 April 2013

How do I use DatabaseMetaData to get table column details


How do I use DatabaseMetaData to get table column details

In DatabaseMetaData class we have a method getColumns

getColumns

ResultSet getColumns(String catalog,
                     String schemaPattern,
                     String tableNamePattern,
                     String columnNamePattern)
                     throws SQLException
Retrieves a description of table columns available in the specified catalog.Only column descriptions matching the catalog, schema, table and column name criteria are returned. They are ordered by TABLE_CAT,TABLE_SCHEMTABLE_NAME, and ORDINAL_POSITION.
Each column description has the following columns:
  1. TABLE_CAT String => table catalog (may be null)
  2. TABLE_SCHEM String => table schema (may be null)
  3. TABLE_NAME String => table name
  4. COLUMN_NAME String => column name
  5. DATA_TYPE int => SQL type from java.sql.Types
  6. TYPE_NAME String => Data source dependent type name, for a UDT the type name is fully qualified
  7. COLUMN_SIZE int => column size.
  8. BUFFER_LENGTH is not used.
  9. DECIMAL_DIGITS int => the number of fractional digits. Null is returned for data types where DECIMAL_DIGITS is not applicable.
  10. NUM_PREC_RADIX int => Radix (typically either 10 or 2)
  11. NULLABLE int => is NULL allowed.
    • columnNoNulls - might not allow NULL values
    • columnNullable - definitely allows NULL values
    • columnNullableUnknown - nullability unknown
  12. REMARKS String => comment describing column (may be null)
  13. COLUMN_DEF String => default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be null)
  14. SQL_DATA_TYPE int => unused
  15. SQL_DATETIME_SUB int => unused
  16. CHAR_OCTET_LENGTH int => for char types the maximum number of bytes in the column
  17. ORDINAL_POSITION int => index of column in table (starting at 1)
  18. IS_NULLABLE String => ISO rules are used to determine the nullability for a column.
    • YES --- if the parameter can include NULLs
    • NO --- if the parameter cannot include NULLs
    • empty string --- if the nullability for the parameter is unknown
  19. SCOPE_CATLOG String => catalog of table that is the scope of a reference attribute (null if DATA_TYPE isn't REF)
  20. SCOPE_SCHEMA String => schema of table that is the scope of a reference attribute (null if the DATA_TYPE isn't REF)
  21. SCOPE_TABLE String => table name that this the scope of a reference attribure (null if the DATA_TYPE isn't REF)
  22. SOURCE_DATA_TYPE short => source type of a distinct type or user-generated Ref type, SQL type from java.sql.Types (null if DATA_TYPE isn't DISTINCT or user-generated REF)
  23. IS_AUTOINCREMENT String => Indicates whether this column is auto incremented
    • YES --- if the column is auto incremented
    • NO --- if the column is not auto incremented
    • empty string --- if it cannot be determined whether the column is auto incremented parameter is unknown
The COLUMN_SIZE column the specified column size for the given column. For numeric data, this is the maximum precision. For character data, this is the length in characters. For datetime datatypes, this is the length in characters of the String representation (assuming the maximum allowed precision of the fractional seconds component). For binary data, this is the length in bytes. For the ROWID datatype, this is the length in bytes. Null is returned for data types where the column size is not applicable.
Parameters:
catalog - a catalog name; must match the catalog name as it is stored in the database; "" retrieves those without a catalog; null means that the catalog name should not be used to narrow the search
schemaPattern - a schema name pattern; must match the schema name as it is stored in the database; "" retrieves those without a schema; null means that the schema name should not be used to narrow the search
tableNamePattern - a table name pattern; must match the table name as it is stored in the database
columnNamePattern - a column name pattern; must match the column name as it is stored in the database
Returns:
ResultSet - each row is a column description
Throws:
SQLException - if a database access error occurs
See Also:
getSearchStringEscape()

Example program:



package com.javanotes2all.java.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DatabaseMetadataExample {

 private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost/test";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";
    
    public static void main(String[] args) throws Exception {
        Connection connection = null;
 try {
     Class.forName(DRIVER);
     connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
     
     DatabaseMetaData metadata = connection.getMetaData();
     // data is database table
     ResultSet resultSet = metadata.getColumns(null, null, "data", null);
     while (resultSet.next()) {
  String name = resultSet.getString("COLUMN_NAME");
  String type = resultSet.getString("TYPE_NAME");
  int size = resultSet.getInt("COLUMN_SIZE");
  String dvalue=resultSet.getString("COLUMN_DEF");
  
  System.out.println("Column name: [" + name + "]; type: [" + type 
      + "]; size: [" + size + "]"+"; defaultvalue:["+dvalue+"];");
     }
 } catch (SQLException e) {
     e.printStackTrace();
 } finally {
     connection.close();
 }
    }

}


OUTPUT:
Column name: [dataid]; type: [INT]; size: [10]; defaultvalue:[null];
Column name: [dataname2]; type: [VARCHAR]; size: [50]; defaultvalue:[aaaa];
Column name: [dataname1]; type: [VARCHAR]; size: [50]; defaultvalue:[aaa]; Share

Tuesday 9 April 2013

How to read the text from Pdf using java

How to read the text from Pdf using java 

how to create pdf and write data see in following link
http://javanotes2all.blogspot.in/2013/01/how-to-create-pdf-file-using-itext-in.html


package com.javanotes2all.java.pdf;

import java.io.IOException;

import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.parser.PdfTextExtractor;

public class ReadDataFromPdf {

//import itext.jar
public static void main(String[] args) throws IOException
{
PdfReader reader = new PdfReader(filename);
int noPages = reader.getNumberOfPages();
PdfTextExtractor extractor = new PdfTextExtractor(reader);

String content="";
for(int page=1;page<=noPages;page++){
int index = 1;
System.out.println(page);
content = extractor.getTextFromPage(page);
System.out.println(content);
    }

}

}
Share

Friday 5 April 2013

Difference between path and classpath in Java environment


Difference between path and classpath in Java environment

Both are the Environment variables, which is mainly used to set with some values which is in some location and used in some other locations.
PATH: is a system variable used to tel to OS all locations of exec files.
example:- Like your java, javac, jar etc are located in C:\java\bin (if java installed in C:\java location). Here these commands can be used by only that location, in case if you the program in different location, then this location does not know where these commands there, CMD promt simply says Command not recognized.
This we set three ways - Command based ( this will available only for tht command)
- Window based ( this will available only for tht window)
- Through Environment variable ( this will available only for all widows)
CLASSPATH : Is Pure java variable, which is used to tel locations of all jar/zip(classes) files to Compiler.
example:- If we are using JDBC Driver then we need to keep classes12.jar in classpath
:- If we are using sevlets future then we need to keep servlet-api.jar in classpath .. like these so many places we use this.
This we set three ways - Command based ( this will available only for tht command)
- Window based ( this will available only for tht window)
- Through Environment variable ( this will available only for all widows)
Share

How to set path and classpath for java in windows

How to set path and classpath for java in windows

Update the PATH Environment Variable (Microsoft Windows)

You can run Java applications just fine without setting the PATH environment variable. Or, you can optionally set it as a convenience.

Set the PATH environment variable if you want to be able to conveniently run the executables (javac.exejava.exejavadoc.exe, and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:
C:\Java\jdk1.7.0\bin\javac MyClass.java
Share

Why is Java not a pure OOP Language?


Why is Java not a pure OOP Language?


Java is a OOP language and it is not a pure Object Based Programming Language.
Many languages are Object Oriented. There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:
  1. Encapsulation/Data Hiding
  2. Inheritance
  3. Polymorphism
  4. Abstraction
  5. All predefined types are objects
  6. All operations are performed by sending messages to objects
  7. All user defined types are objects.
Java is not because it supports Primitive datatype such as int, byte, long… etc, to be used, which are not objects.
Contrast with a pure OOP language like Smalltalk, where there are no primitive types, and boolean, int and methods are all objects.


Share