Using Collections to sorting the specified list into ascending order, according to the natural ordering of its elements

package collection.demos;



import java.util.ArrayList;

import java.util.Collections;



public class SortingListDemo {

    public static void main(String[] args) {

        ArrayList<String> names=new ArrayList<String>();

        names.add("Joy");

        names.add("Bynod");

        names.add("Jaxon");

        names.add("Traimer");

        System.out.println("Before Sorting : "+names);

        Collections.sort(names);

        System.out.println("After Sorting : "+names);

    }

}

/*

OUTPUT

Before Sorting : [Joy, Bynod, Jaxon, Traimer]

After Sorting : [Bynod, Jaxon, Joy, Traimer]

 */

PriorityQueue

Queue is a collection of items in which only the earliest added item may be accessed. Basic operations are add (to the tail) or enqueue and delete (from the head) or dequeue. Delete returns the item removed. Also known as "first-in, first-out" or FIFO.
DeQueue is a queue to be any data structure that can have items inserted and removed from either end.

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator  provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects
The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.

A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically. The details of the growth policy are not specified.
This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

Following program is an example of priority queue

package collection.demos;



import java.util.PriorityQueue;



public class PriorityQueueDemo {



    public static void main(String[] args) {

        PriorityQueue<String> jobs = new PriorityQueue<String>();

        jobs.add("job-3");

        jobs.add("job-4");

        jobs.add("job-1");

        jobs.add("job-2");

        jobs.add("job-4");

        System.out.println("Queue : "+jobs);

        System.out.println("Element at head "+jobs.element());

        System.out.println("Removed element "+jobs.poll());

        System.out.println("Queue : "+jobs);

        jobs.add("job-1");

        System.out.println("Queue : "+jobs);

       

    }

}

TreeSetDemo

It is concrete classes that extends AbstractSet<E> and implements NavigableSet<E>, Cloneable and Serializable interfaces. All elements added to treeset are ordered automatically using their natural ordering, or by a Comparator typically provided at sorted set creation time whether you follow order or not. It does not allows to added duplicate element to set.

The set's iterator will traverse the set in ascending element order. Several additional operations are provided to take advantage of the ordering. 

package collection.demos;
import java.util.TreeSet;
public class TreeSetDemo {
    public static void main(String[] args) {
        TreeSet<String> names=new TreeSet<String>();
        names.add("abc");
        names.add("rit");
        names.add("rit");
        names.add("rit");
        names.add("swek");
        names.add("trog");
        names.add("npr");
        names.add("nvn");
        for (String name : names) {
            System.out.println(name);
        }
    }
}


OUTPUT
abc
npr
nvn
rit
swek
trog



 In the output of program, we get all elements in accending order and rit is displayed only once, So only one instance of rit is added to TreeSet

Logging

It is a process to tracking the different states of system while it is running. We record all the messages according to our observations in executions. It is a way to debugging your application in real time and provides required information to resolve problems. Because, you can set your logging statement at any executable place in you coding, so you can use this feature to test, debug, and profiling.

The entire messages generated by logging are recorded at specified destination of logger and can be retrieved later. Mostly, all messages are redirected to standard output of system and you can view all logging information as you application starts to executes.

Log4j is mostly used Logging tool in java that allows you to log at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost. Logging behavior can be controlled by editing a configuration file, without touching the application binary.

One of the distinctive features of log4j is the notion of inheritance in loggers. Using a logger hierarchy it is possible to control which log statements are output at arbitrarily fine granularity but also great ease. This helps to reduce the volume of logged output and the cost of logging.

Here is an example of Log4j

import org.apache.log4j.*;
public class Log4JDemo1{
    public static void main(String ar[]){
  
        BasicConfigurator.configure();
        Logger  logger1 = Logger.getLogger("logger1");
        logger1.setLevel(Level.INFO);
        Logger logger2 = Logger.getLogger("logger1.logger2");
        logger1.warn("Missing user name");
        logger1.debug("getting user name from database");
        logger2.info("User name found in database");
        logger2.debug("validating user");

    }
}

Struts 2 Tags

Struts 2 Tags

<%@taglib prefix="s" uri="/struts-tags"%>

<h3></h3>

<h3> Conditionals </h3>

<s:if test='name=="abc"'>

you are <s:property value="name"/>

</s:if>

<s:else>

you are not abc

</s:else>





<h3>collections and Iteration(ArrayList) </h3>

<ul>

    <s:iterator value="books" var="book">

    <li><s:property value="book"/></li>

    </s:iterator>

</ul>



<h3>collections and Iteration (Map)</h3>

<ul>

    <s:iterator value="emails">

    <li><s:property value="key"/> : <s:property value="value"/></li>

    </s:iterator>

</ul>



<ul>

    <s:iterator value="emails" var="item">

    <li><s:property value="#item.key"/> : <s:property value="#item.value"/></li>

    </s:iterator>

</ul>



<h3>tracking iteration status </h3>

<ul>

    <s:iterator value="books" var="book" status="stat">

    

    <li>

        

        <s:property value="#stat.index"/>:

        <s:property value="#stat.count"/>:

        <s:property value="#stat.even"/>:

        <s:property value="#stat.odd"/>:

        <s:property value="#stat.first"/>:

        <s:property value="#stat.last"/>:

        <s:property value="#stat.modulus(2)"/>:

        <s:property value="#stat.modulus(4)"/>:

        <s:property value="#stat.count%4"/>:

        <s:property value="book"/>

    </li>

    </s:iterator>

</ul>





<h3> s:generator : it is used to create a list in value stack</h3>

<s:generator val="'1,2,3,4,5'" separator=",">

    <ul>

        <s:iterator>

        <li><s:property/></li>

        </s:iterator>

    </ul>

</s:generator>



<h3> here we can create a variavle that poits the list generated by generator</h3>

<s:generator val="'1,2,3,4,5'" separator="," var="mylist"/>

<h3> now we can use it anywhere</h3>

<ul>

    <s:iterator value="mylist">

    <li><s:property/></li>

    </s:iterator>

</ul>

<h3> After full iteration we can not use mylist itarator again

we need to generate new list</h3>



<h3> Using convertor in generator.

get a object from action class that implements IteratorGenerator.Converter </h3>

<s:generator val="'1,2,3,4,5,6,7,8,9,0'" separator="," var="mylist" converter="digitConverter"/>

<ul>

    <s:iterator value="mylist">

    <li><s:property/></li>

    </s:iterator>

</ul>



<h3>s:append </h3>

<s:append var="appended">

    <s:param value="{1,2,3,4}"/>

    <s:param value="{'a','b','c','d'}"/>

</s:append>



<s:iterator value="appended">

    <s:property/> 

</s:iterator>



<h3>s:merge</h3>



<s:merge var="merged">

    <s:param value="{1,2,3,4}"/>

    <s:param value="{'a','b','c','d'}"/>

</s:merge>



<s:iterator value="merged">

    <s:property/> 

</s:iterator>



<h3>s:subset - use to get iterate on portion of items from collection</h3>

<!--data from books property of action -->

<s:subset source='books' start="2" count="2">

    <s:iterator>

        <s:property/> 

    </s:iterator>

</s:subset>

<%--<s:debug/>--%>





Output

Conditionals

you are not abc

collections and Iteration(ArrayList)

  • Java
  • J2EE
  • JSP
  • Servlet
  • C
  • C++

collections and Iteration (Map)

  • abc : abc@gmail.com
  • xyz : xyz@yahoo.com
  • bbc : bbc@gjh.com
  • abc : abc@gmail.com
  • xyz : xyz@yahoo.com
  • bbc : bbc@gjh.com

tracking iteration status

  • 0: 1: false: true: true: false: 1: 1: 1: Java
  • 1: 2: true: false: false: false: 0: 2: 2: J2EE
  • 2: 3: false: true: false: false: 1: 3: 3: JSP
  • 3: 4: true: false: false: false: 0: 0: 0: Servlet
  • 4: 5: false: true: false: false: 1: 1: 1: C
  • 5: 6: true: false: false: true: 0: 2: 2: C++

s:generator : it is used to create a list in value stack

  • 1
  • 2
  • 3
  • 4
  • 5

here we can create a variavle that poits the list generated by generator

now we can use it anywhere

  • 1
  • 2
  • 3
  • 4
  • 5

After full iteration we can not use mylist itarator again we need to generate new list

Using convertor in generator. get a object from action class that implements IteratorGenerator.Converter

  • one
  • two
  • three
  • four
  • five
  • six
  • seven
  • eight
  • nine
  • zero

s:append

1  2  3  4  a  b  c  d 

s:merge

1  a  2  b  3  c  4  d 

s:subset - use to get iterate on portion of items from collection

JSP  Servlet

Using form tags in Struts 2

Struts 2 provides various tags that simplifies our development.  Here is an example to create the form using struts2 form tags. These tags are processed by struts frame work and values are mapped to coreponding domaon object automatically. The name attribute of tag is used to map the value to data holder variable at server side. 


Here, each name has been prefixed with "user" that specifies the object in action implementation. For example, The value of textfield having name "user.name" will mapped to the variable of object being referenced by user variable of action class.


<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
</head>
<body>
    <s:form action="send" method="post">
        <s:textfield name="user.name" label="Full Name" title="Use text only"/>
        <s:textfield name="user.email" label="Email Id" title="Use valid emailid only"/>
        <s:textfield name="user.phone" label="Mobile Number"/>
        <s:password name="user.password" label="Password"/>
        <s:textarea name="user.address" cols="25" rows="4" label="Address"/>
        <s:checkboxlist key="Books" list="{'Java','J2EE','Servlet','JSP','Struts2'}"/>    
        <s:checkbox key="Qulification" value="y" label="Are you MCA ?" fieldValue="MCA" />
        <s:radio key="Gender" list="{'Male','Female'}"/>
        <s:select key="Job Location" list="{'Delhi','Noida','Gurgao','Channai','Kolkata','Pune'}"/>
        <s:submit/>
    </s:form>
    <s:debug/>
</body>
</html>

struts.xml has folowing contents
 Here, action name is "send" and form is submitted to this action.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUB
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">
        <action name="send" class="TestAction">
            <result name="success">result1.jsp</result>
        </action>
    </package>
</struts>


As we submit this form, action object is get invoked and here is following implemetnation of action class.

public class TestAction{
    private pack.User user;
    public pack.User getUser(){
        return user;
    }
    public void setUser(pack.User user){
        this.user=user;
    }
    public String execute(){
        System.out.println(user);
        return "success";
    }
}

The data of form field is mapped to user object automatically.


package pack;
public class User{
    private String name;
    private String email;
    private int phone;
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }
    public String getEmail(){
        return email;
    }
    public void setEmail(String email)
        this.email=email;
    }
    public int getPhone(){
        return phone;
    }
    public void setPhone(int phone){
        this.phone=phone;
    }
    public String toString(){
        return "User [name="+name+", email="+email+",phone="+phone+"]";
    }
}

List dirvers and connection-urls for connecting java program to databases

DB2
Driver : "com.ibm.db2.jcc.DB2Driver"
URL: "jdbc:db2://localhost:5021/database","user","password"


Apache Derby
driver: "org.apache.derby.jdbc.EmbeddedDriver"
URL: "jdbc:derby://localhost/databasename","user","password"
FrontBase
Driver : "jdbc.frontbase.FBDriver"
URL : "jdbc:frontbase:/DerbyDB/AssetDB","user","password"
OpenBase
Driver : "com.openbase.jdbc.ObDriver"
URL : "jdbc:openbase://localhost/databasename","user","password"
MySQL
Driver : "com.mysql.jdbc.Driver"
URL: "jdbc:mysql://localhost:3306/databasename","user","password"
H2Database
Driver : "org.h2.Driver"
URL: "jdbc:h2:tcp://localhost//data/databasename","user","password"
More info. 
PostgreSQL
Driver : "org.postgresql.Driver"
URL: "jdbc:postgresql://localhost/databasename","user","password"
More info. 
Cache
Driver : "com.intersys.jdbc.CacheDriver"
URL: "jdbc:Cache://localhost/databasename","user","password"
More info. 


Cubrid
Driver : cubrid.jdbc.driver.CUBRIDDriver"
URL: jdbc:CUBRID:127.0.0.1:30000:demodb:dba::","user","password"
More info. 
Oracle 10g
Driver : "oracle.jdbc.OracleDriver"
URL: "jdbc:oracle:thin:@localhost:1521:databasename","user","password"
More info 
Sybase
Driver : "com.sybase.jdbc4.jdbc.SybDriver"
URL: "jdbc:sybase:Tds:localhost:5000/databasename","user","password"
More info  
SQLite
Driver : "org.sqlite.JDBC"
URL: "jdbc:sqlite:db_file_path","user","password"
More info  
Microsoft SQL Server
Driver : "com.microsoft.jdbc.sqlserver.SQLServerDriver"
URL: "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=databasename","user","password"
More info , Read More
SAP MaxDB
Driver : "com.sap.dbtech.jdbc.DriverSapDB"
URL: "jdbc:sapdb://localhost:3306/databasename","user","password"
More info
Informix
Driver : "com.informix.jdbc.IfxDriver"
URL: "jdbc:informix-sqli://localhost:3306/databasename","user","password"
HypersonicSQL
Driver : "org.hsqldb.jdbcDriver"
URL: "jdbc:hsqldb:directoryname/filename","user","password"
Ingres
Driver : "com.ingres.jdbc.IngresDriver"
URL: "jdbc:ingres://localhost:117/databasename","user","password"
MonetDB
Driver : "nl.cwi.monetdb.jdbc.MonetDriver"
URL: "jdbc:monetdb://localhost/database", "monetdb", "monetdb"
More info 
SmallSQL
Driver : "smallsql.database.SSDrive"
URL: "jdbc:smallsql:db1","user","password"
FireBird
Driver : "org.firebirdsql.jdbc.FBDriver"
URL: "jdbc:firebirdsql://localhost:10007/dbname.fdb","user","password"
Pointbase
Driver : "com.pointbase.jdbc.jdbcUniversalDriver"
URL: ""jdbc:pointbase:server://localhost/databasename","user","password"
FrontBase
Driver : "jdbc.FrontBase.FBJDriver"
URL: "jdbc:FrontBase://localhost/databasename","user","password"

Struts Simple Example

Here is a simple example of Struts2.

Directory hierarchy 
your-application
│   result1.jsp

└───WEB-INF
           │         web.xml
           │
           └───classes
                                struts.xml

First of all, configure strut2 filter into web.xml of your application

<web-app>

    <display-name>Struts 2 eg 1</display-name>

    <filter>

        <filter-name>struts2</filter-name>

        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

    </filter>

    <filter-mapping>

        <filter-name>struts2</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>



</web-app>


Now, in struts.xml file which is located into classes folder of you web application, write following contetns
<web-app>

    <display-name>Struts 2 eg 1</display-name>

    <filter>

        <filter-name>struts2</filter-name>

        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

    </filter>

    <filter-mapping>

        <filter-name>struts2</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>



</web-app>


Here contastant element is used to set some properties of struts. We used struts.devMode property value to true. this enable us to view all information like errors, exception and warning at the time of  execution.


Element package-name defines the name of package that can be used to group diffrent action into a specific namespace. The attribute namespace defines relative path/pattern to be followed while invoking these actions.


Elenment action declare action to be executed for specified url-pattern . Here is "/hello" url pattern for which this action will be executed.


Element result inside action element declare the resultant view to be returned to client after successful execution of this action. Here we created result1.jsp page to be returned to view.


result1.jsp
this file contains only following message


This is test application



Now deploy this aplication into server and write following address into address bar of web browser.
http://localhost:8080/your-application/hello


You will get following output.


This is test application


Resources: struts2, Apache tomcat

Popular Posts