Saturday, June 23, 2012

Struts2 Architecture+lifecycle

reference:-http://viralpatel.net/blogs/introduction-to-struts-2-framework/


  1. The normal lifecycle of struts begins when the request is sent from client. This results invoke the servlet container which in turn is passed through standard filter chain.
  2. The FilterDispatcher filter is called which consults the ActionMapper to determine whether an Actionshould be invoked.
  3. If ActionMapper finds an Action to be invoked, the FilterDispatcher delegates control to ActionProxy.
  4. ActionProxy reads the configuration file such as struts.xml. ActionProxy creates an instance ofActionInvocation class and delegates the control.
  5. ActionInvocation is responsible for command pattern implementation. It invokes the Interceptors one by one (if required) and then invoke the Action.
  6. Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml.
  7. The Interceptors are executed again in reverse order and the response is returned to the Filter (In most cases to FilterDispatcher). And the result is then sent to the servlet container which in turns send it back to client.
     
    last week i have gone through the struts concepts .thanks to mykong's blog.i am becoming his fan.
    REFERENCE:-http://www.mkyong.com/tutorials/struts-2-tutorials/

Saturday, April 14, 2012

successful in understanding google app engine .finished learning a full project,awesome concepts

the whole project can be downloaded form http://www.mediafire.com/?2cwxmg5i2cnl3f6
Understanding datastore??
references:-https://developers.google.com/appengine/docs/java/gettingstarted/usingdatastore

 DatastoreService datastore =  DatastoreServiceFactory.getDatastoreService();     datastore.put(greeting);

Because querying in the High Replication datastore is only strongly consistent within entity groups, we assign all Greetings to the same entity group by setting the same parent for each Greeting. This means a user will always see a Greeting immediately after it was written. However, the rate at which you can write to the same entity group is limited to 1 write to the entity group per second.
The low-level Java API provides a Query class for constructing queries and a PreparedQuery class for fetching and returning the entities that match the query from the datastore. The code that fetches the data is here:



Query query = new Query("Greeting", guestbookKey).addSort("date",Query.SortDirection.DESCENDING);
   List<Entity> greetings = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));
follow this link:
https://appengine.google.com/->newapps6974(my app name)->datastore indexes
in the datastore indexes you will see the entity name and indexes.refer to the datastore-indexes,xml file now and see the matching.
see the datastore viewer.you will see the mesages in the descending order(datewise)).awesome.

working for the first time with google appengine

today i learnt to run a web project under google app engine from my eclipse ide with the help of google appengine plugins
the encircled area denotes the google plugins.
now to create a new project u click the bluish g icon..and do the needful.
the project is deployed by the deploy app engine project
 after deploying u run it as a run-as web application
my url-http://newapps6974.appspot.com/

references:-http://www.mkyong.com/google-app-engine/google-app-engine-hello-world-example-using-eclipse/

Wednesday, April 11, 2012

The day i started using frameworks

it took some time while getting acquainted with hibernate.but no matter what it was easy learning.
why hibernate?
The developers get rid of writing complex SQLs and no more need of JDBC APIs for resultset handling.
x.cfg.xml file provides  the connection with database.
Y.hbm.xml provides mapping between database column and POJO variable.
A simple web app test to know the basics.

remember to create a database connection on the back end and then select that when you open a new project to execute
the code can be downloaded from 
http://www.mediafire.com/?lw5pvhxpfwx5xr9

hibernate.cfg.xml file


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetutorial</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.pool_size">10</property>
        <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="entities/Subscriber.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Subscriber.hbm.xml


<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


<hibernate-mapping>
    <class name="entities.Subscriber" table="test">
        <id name="uname" type="java.lang.String">
            <column name="username" />
            <generator class="assigned"/>
        </id>
        <property name="pwd" type="java.lang.String">
            <column name="password"/>
        </property>
    </class>
  


</hibernate-mapping>


create a jsp page .pass the login and password say through a form into a servlet.create a getter setter class with the instance variables that are to be used to insert data in a database..these are mapped to column names in the Y.hbm.xml file

the servlet file

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        System.out.println("inside the servlet");
        try {
            SessionFactory sf = new Configuration().configure().buildSessionFactory();
            Session s = sf.openSession();
            Subscriber sub = new Subscriber();
            sub.setUname(uname);
            sub.setPwd(pwd);
            s.beginTransaction();
            s.save(sub);
            s.getTransaction().commit();
            s.close();
            sf.close();
            out.println(
                    "<h3 >[" + uname + "  ] has been registered successfully!</h3 >");
        } catch (Exception ex) {
            out.println(
                    "<h3 >[" + uname + "] could NOT be registered!</h3 >");
            System.out.println(ex.getMessage());
        }
    }

Sunday, February 26, 2012

FileUpload using jersey

today i learnt to implement file uploading using jersey

@Path("fileupload")
public class FileUploadResource {

@POST
@Produces("text/plain")
public String loadFile(@Context HttpServletRequest request) {
String resultStatus="fail";
String fileRepository="d:\\"; //the files u choose to upload will be uploaded to this d. directory
//servlet file upload handles multiple files in a html widget

if (ServletFileUpload.isMultipartContent(request)) {//checks if the servlet request contains multipart data.
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items=null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {

e.printStackTrace();
}
if(items!=null) {
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
    if(!item.isFormField() && item.getSize() > 0) {
    String fileName = processFileName(item.getName());
    try {
item.write(new File(fileRepository+fileName));
//the write methodn writes uploaded file into the disk
} catch (Exception e) {
e.printStackTrace();
}
        resultStatus="ok";
    }
}
}
}
return resultStatus;
}

private String processFileName(String fileNameInput) {
String fileNameOutput=null;
fileNameOutput = fileNameInput.substring(fileNameInput.lastIndexOf("\\")+1,fileNameInput.length());
//extracts the name of the file
return fileNameOutput;
}
ur file will be uploaded to the directory

Saturday, February 25, 2012

JAXB (JAVA ARCHITECTURE FOR XML BINDING)

java objects are created to and from XML.the different annotations will be described in the program below.
1)Book.java(a class with getter setter methods)

XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = {"name", "id"})  //the order of output in XML.
public class Book {

    String name;
    int id;
    // If you like the variable name, e.g. "name", you can easily change this
    // name for your XML-Output:

    @XmlElement(name = "bookName")//will see the change when u see the XML as output
2)BookStore.java(a class with an arraylist and getter setter methods)

//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "jaxb implementation")//when u say namespace that means root element of XML.
public class BookStore {
// XmLElementWrapper generates a wrapper element around XML representation

    @XmlElementWrapper(name = "bookList")
    // XmlElement sets the name of the entities
    @XmlElement(name = "book")
    private ArrayList<Book> bookList;
    private String name;
    private String location;
3)BookMain.java the main class
set the values and include the book class object in the arraylist.also .
class x{
private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";
public static void main(){

// create JAXB context and instantiate marshaller
        JAXBContext context = JAXBContext.newInstance(BookStore.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(bookstore, System.out);

        Writer w = null;
        try {
            w = new FileWriter(BOOKSTORE_XML);
            m.marshal(bookstore, w);
        } finally {
            try {
                w.close();
            } catch (Exception e) {
            }
            // get variables from our xml file, created before
            System.out.println();
            System.out.println("Output from our XML File: ");
            Unmarshaller um = context.createUnmarshaller();
     
          BookStore bookstore2 =  (BookStore) um.unmarshal(new FileReader(
                    BOOKSTORE_XML));

           for (int i = 0; i < bookstore2.getBooksList().toArray().length; i++) {
                System.out.println("Book " + (i + 1) + ": "
                      +"id:"  + bookstore2.getBooksList().get(i).getId()+ " "
                     +"author"+":"+ bookstore2.getBooksList().get(i).getName()+"location"+":"+bookstore2.getLocation());
            }

        }
    }
output:-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:bookStore xmlns:ns2="jaxb implementation">//see the rootelement
    <bookList>
        <book>
            <name>sougata</name>
            <bookName>6974</bookName>//see the name change"bookname"
        </book>
    </bookList>
    <location>Frankfurt Airport</location>
    <name>Fraport Bookstore</name>
</ns2:bookStore>

Output from our XML File:
Book 1: id:6974 author:sougata location:Frankfurt Airport

Java Restful API

Rest is an architecture(not a technology mind it) where everything is a resource.now the resource is accessed via some HTTP methods.
here there is a rest server as well as a rest client.same as old ways.the server provides access to the resources and the client makes access to resource as well as can modify the resources.resources are identified by global ids.rest allows resources have different representations.client can get different outputs.(i.e xml,html,json).methods that are supported are get,post,delete,put.
Java defines standard REST support via JAX-RS (The Java API for RESTful Web Services)

@Path("/test")
public class testjersey {
// This method is called if TEXT_PLAIN is request 
@GET
//the class registers its methods for the get request using @GET annotation.Using the @Produces annotation, it defines that it can deliver several MIME types, text, XML and HTML. 
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersaey";
}

// This method is called if XML is request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersddddey" + "</hello>";
}

// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jeffrsey" + "</title>"
+ "<body><h1>" + "Hello Jerseay" + "</body></h1>" + "</html> ";
}
}
the url to access the webapp is like this( http://localhost:8080/resources/test)
see resources is the servlet mapping in web.xml and test is the name of path(base- uri) in the resource.the browser requests the html representation of your resource.so the output will be: Hello Jerseay 

Wednesday, February 22, 2012

Integrate IBM DB2 with netbeans

I have always loved working with mysql databases.but this time as i was making an attempt for IBM -TGMC ,i had to strictly use IBM tools..so IBM DB2 caused much problems initially.but finally got over it.
below are some snapshots to integrate DB2 with IBM
1.first as the old way go to Drivers->right click-new driver








2)













when u click add browse for the db2jcc.jar and db2jcc4.jar where u have db2 installed.db2/sqllib/java(here u will find those jara).now clicking ok the new ibm2 universal driver gets installed.
now again the old way create a new connection as shown in the snapshot below

Tuesday, February 21, 2012

Mouse Not working??

my USB optical mouse was not working for the past 6 months.i hardly cared.but for the past few days my fingers are feeling the pain of touch pad.so today morning i decided to make my mouse work.made restarts didnt work.

so what i did-
go to control panel->performance and maintenance ->system->hardware->device manager

now find the human interface device.expand and find update the USB human interface driver.
as it got updated the mouse started working flawlessly.:))

Saturday, February 18, 2012

Dealing with the netbeans and eclipse error.

Sometimes we often see errors like deployement error port already in use,while we were doing some useful work.i searched throughout the internet.people said do this,do that.really i tried all but didnt help.and so i had to wait for my luck that when will the error go.sometimes it worked on with a restart sometimes it took days.

the best answer is:download a TCP view software.now look for ports which you saw in the error msg.


run tcp view and close the necessary ports.then run your program again.this will ceratainly do.

Friday, February 17, 2012

Working on security for my final year project.(Testing )

Filters:Little bit on life cycle
The init() method is used to initialize any code that is used by Filter. Also note that, init() method will get an object of FilterConfig which contains different Filter level information as well as init parameters which is passed from Web.xml (Deployment descriptor).

The doFilter() method will do the actual logging of information. You can modify this method and add your code which can modify request/session/response, add any attribute in request etc.
The destroy() method is called by the container when it wants to garbage collect the filter. This is usually done when filter is not used for long time and server wants to allocate memory for other applications.
Tested a very simple web project.
web.xml(only the flter configuration showed)
    <filter>
        <filter-name>LogFilter</filter-name>
        <filter-class>com.in.Filter.LogFilter</filter-class>
        <init-param>
            <param-name>test-param</param-name>
            <param-value>This is for testing</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>LogFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
     </web-app>

the FILTER
public class LogFilter implements Filter {
    private static final boolean debug = true;
    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;
    public LogFilter() {
    }
    private void doBeforeProcessing(ServletRequest request, ServletResponse response)//abstract methods
            throws IOException, ServletException {
    }

    private void doAfterProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        RequestDispatcher rd = null;
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        rd = getFilterConfig().getServletContext().getRequestDispatcher("/LoginServlet");
        if (rd != null) {
            rd.include(req, res);
        }
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        Throwable problem = null;
        try {
            chain.doFilter(request, response);
        } catch (Throwable t) {
            // If an exception is thrown somewhere down the filter chain,
            // we still want to execute our after processing, and then
            // rethrow the problem after that.
            problem = t;
            t.printStackTrace();
        }
        // If there was a problem, we want to rethrow it if it is
        // a known type, otherwise log it.
        if (problem != null) {
            if (problem instanceof ServletException) {
                throw (ServletException) problem;
            }
            if (problem instanceof IOException) {
                throw (IOException) problem;
            }
            sendProcessingError(problem, response);
        }
        //Get the IP address of client machine.
        String ipAddress = request.getRemoteAddr();

        //Log the IP address and current timestamp.
        System.out.println("IP " + ipAddress + ", Time "
                + new Date().toString());
   HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String name=req.getParameter("user");
        System.out.println(""+name);//as it is a filter and in xml see the mapping.the url pattern is /*.so after     //getting the servlet i again shows the value in the filter.from this we can know abut any unauthorized //access.

        doAfterProcessing(request, response);
        chain.doFilter(request, response);
    }

    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter 
     */
    public void destroy() {
    }

    /**
     * Init method for this filter 
     */
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        
        //Get init parameter
        String testParam = filterConfig.getInitParameter("test-param");

        //Print the init parameter
        System.out.println("Test Param: " + testParam);
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        if (filterConfig == null) {
            return ("LogFilter()");
        }
        StringBuffer sb = new StringBuffer("LogFilter(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }

    private void sendProcessingError(Throwable t, ServletResponse response) {
    }

    public static String getStackTrace(Throwable t) {
        String stackTrace = null;
        try {
        } catch (Exception ex) {
        }
        return stackTrace;
    }

    public void log(String msg) {
        filterConfig.getServletContext().log(msg);
    }
}