Saturday, September 6, 2014

HTML Minifier using JSP taglib

HtmlCompressor is a small, fast and very easy to use Java library that minifies given HTML or XML source by removing extra whitespaces, comments and other unneeded characters without breaking the content structure.

Bad Practices

  • Don't feed the compressor actual templates (php, jsp, etc). This most likely won't work, even if it does it would be a bad idea anyway as you will lose their readability and further development will be very inconvenient. Instead of compressing templates you should consider compressing resulting html after a template is merged. If you absolutely have to compress templates, you need to set custom block preservation rules for HTML Compressor.
  • If your site is in pure HTML, always keep original files and only compress their copies that will be served to the client. If you compress your only sources, again your further development will be very hard and there is no easy way to decompress pages back. 

Known Issues

  • When <script> tag contains some custom preserved block (for example <?php>), enabling inline javascript compression will fail. Such <script> tags could be skipped by wrapping them with <!-- {{{ -->...<!-- }}} --> comments (skip blocks).
  • Removing intertag spaces might break text formatting, for example spaces between words surrounded with <b> will be removed. Such spaces might be preserved by replacing them with &#20; or &nbsp;.

Compressing selective content in JSP pages

If you install the compressor taglib, you will be able to use <compress:html>, <compress:xml>, <compress:js> and <compress:css> tags in your JSP pages to mark selective code blocks that need to be compressed.

Taglib installation procedure

  1. Download .jar file of the current release and put it into your lib directory
  2. Add the following taglib directive to your JSP pages:
  3. <%@ taglib uri="http://htmlcompressor.googlecode.com/taglib/compressor" prefix="compress" %>
    
Please note that JSP 2.0 or above is required.

Using compressor taglib

Now you can wrap parts of JSP pages that need to be compressed with corresponding tags:

<%@ taglib uri="http://htmlcompressor.googlecode.com/taglib/compressor" prefix="compress" %>
<html>
        Compressor Example
        
                
                        

Header

Link
</html>
Each tag supports all attributes from corresponding compressors, so you have full control over their options, for example:



<compress:js> and <compress:css> tags call corresponding compressors directly bypassing HtmlCompressor, so they should be used only for actual JavaScript and Css content. If you need to wrap mixed content use <compress:html> with required attributes. For the complete list of available attributes see taglib or javadocs.

Thursday, May 29, 2014

Hello World program in Web Service in Java using NetBeans IDE

Hi Guys,
Today i am going to describe you how to write a simple hello world program in web services using java in NetBeans IDE.

First we need to create the service.

For that, first create a new "Web Project" from "Java EE".

Then create an Interface class file named IHelloWOrld.java and write the below code
package com.hello;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException
@WebService
public interface IHelloWorld{
@WebMethod
public String hello() throws WebServiceException;
}
Then, create another class file named HelloWorld.java

Then write the code below


package com.hello; import javax.jws.WebMethod; import javax.jws.WebService; import javax.xml.ws.WebServiceException; @WebService public class HelloWorld implements IHelloWorld{ @WebMethod public String hello() throws WebServiceException{ return "Hello World"; } }
After that, create another project either standalone or a web project for service consumer/client side.
Here I am describing as a standalone application.
Then create a Web Service Client file and give the project name of the above service provider and package same as the above which we gave as "com.hello" and click on finish.
Then the stubs are generated for u to develop the consumer code or application.
Then create a class file and write the below code.
import com.java.HelloWorldService;
import com.java.HelloWorldPort;

public class HelloWorldClient{
public static void main(String args[]){
HelloWorldService service=new HelloWorldService();
HelloWorldPort port=service.getHelloWorldPort();
String hello=port.hello();
System.out.println(hello);
}
}

Online Libraries for Students, Teachers and Researchers

Have you grown tired asking Google to find eBooks for you? Then why not directly go to online libraries with thousands and millions of collections entirely focused for books? That’s the reason why I gathered the 8 best online libraries that students, teachers, and researches can use freely. Millions of books, hundreds of categories, and definitely for free! Enjoy!

1. Project Gutenberg

To start our list, Project Gutenberg was founded by Michael S. Hart, inventor of the now popular eBook, a project that seeks to provide free information on the internet with the use of eBooks. The early contents of the project were mostly typed by Hart, and now a large community is behind its continuing success. Being the first eBook library, it may also have the largest collection.

2. The Free Library

The Free Library contains several millions of articles and books, with the topic of Business having over 15 million articles and books in their library. Other categories include Law, Recreation, Humanities, Health, Science, Entertainment, Communications, and a lot more.

3. Planet eBook

 Although Planet eBook is not really a large library of free books, it makes up for it by focusing on classic books and novels ranging from George Orwell’s 1984 to Emily Bronte’s Wuthering Heights. In total Planet eBook has 82 free classic books and novels that you can download and read.

4. LibriVox

LibriVox is a one-of-a-kind project going around online, it is run by volunteers who read and record books so that people who are more acquainted with listening can enjoy the resources available in their catalog. All of the resources in LibriVox are in the public domain, meaning they’re free for use for most purposes.

5. Wikibooks

Yep, Wikibooks is one of Wikipedia’s sister sites, and is run completely ad-free and mostly by volunteers. Unlike other online libraries, Wikibooks only lists instructional books and both fiction and non-fiction are not allowed. If you are a student, or a teacher, then Wikibooks will prove very useful to you. While Wikibooks does not cater novels, it certainly does provide free information about mathematics, languages, sciences, engineering, and a lot more.

6. Scribd

Scribd is a different way of reading online, since it fuses reading with social media (Facebook, Twitter, and others). Scribd has a large collection of free books which range from novels down to amateur-written books, instructables, music sheets, and just about anything that can be read. You can also keep track of the things you read, share them to your friends via Facebook, and learn what’s entertaining and useful based on user reccomendations

7. Ibiblio

Ibiblio presents a wide variety of topics such as art, science, history, culture, and many more. All of the books, and software, are free for use. Ibiblio proclaims itself as the largest “collections of collections” on the internet.

8. GetCited

 GetCited is an online academic resource that teachers, students, and researchers can use to find a wide range of academic papers, reviews, conference papers, book chapters, and journals.

 

Sunday, March 9, 2014

20 Things Every Java Developer Must Know!

The term 'java developer' covers a wide range of individuals. It starts with fresh graduates looking for jobs and goes up till experienced Java Enterprise Edition developers. There are a wide range of concepts and skills that Java developers must posses in order to be important in the industry. It is highly advisable to know the language fundamentals thoroughly, rather than specific frameworks or syntax.
College Graduates:
A college graduate with no job experience is a fresh mind waiting to become a true Java developer. There are certain things that you need to understand as a fresher in the industry to get your dream job.
  1. College graduates must know how a Java Virtual Machine works for starters. Concepts like Platform Independence, Garbage Collection, class files etc must be clearly understood. 
  2. They must be aware of the many Object Oriented Programming Concepts implemented in Java. 
  3. They must know what is multi-threading. 
  4. Basic understanding of data types and java.lang classes such as String, Math, System etc. is advisable. 
  5. They must understand the concept of Swing/AWT event based programming. 
  6. Knowledge of Java Collection framework. 
  7. They must be clear in the concepts of servlets and JSP.
Java Developers:
You may be a professional Java developer, but that doesn’t firmly guarantee you a job.
  1. You must understand design patterns and its usage in Java.
  2. You must understand improvements on language from major version changes such as Generics, Annotations, Enums etc.
  3. Must know coding conventions.
  4. Understand the concepts of Build tool (Ant) and Project Management Tool (Maven).
  5. Understand version control systems, for instance CVS, SVN, Perforce, Clearcase etc.
  6. You must know about Apache common libraries among other open source libraries.
  7. Understand Unit testing and Continuous Integration Tools.
  8. Highly advisable to have fundamental understanding of XML.
You must also understand business layer frameworks like Spring.

Circular Queue ADT using Linked Lists.

Hi guys here is a code on Circular Linked List in Java! Program :

import java.util.Scanner;
interface CllAdt{
public void insert();
public void delete();
public void display();
public int len();
}
class CNode{
int data;
CNode link;
}
public class CQSll extends CNode implements CllAdt{
CNode first;
Scanner s=new Scanner(System.in);
public CQSll(){
first=null;
}

public void insert(){
System.out.println("Enter the position to insert a node :");
int pos=s.nextInt();
System.out.println("Enter the data into a node :");
int ele=s.nextInt();

CNode p=new CNode();
p.data=ele;
p.link=null;
CNode temp;
if(pos<1 || pos>len()+1)
System.out.println("Invalid position and insertion is not possible");
else if(pos==1&&len()==0)
{
first=p;
first.link=first;
System.out.println("Entered position is(1st):"+pos);
}
else if((pos==1)&&(len()!=0)){
temp=first.link;
while(temp.link!=first)
temp=temp.link;
p.link=first;
first=p;
temp.link=first;
System.out.println("Entered position is(1st):"+pos);
}
else if(pos==len()+1){
temp=first;
while(temp.link!=first)
temp=temp.link;
temp.link=p;
p.link=first;
System.out.println("Entered position is(Last) :"+pos);
}
else
{
temp=first;
for(int i=1;i<pos-1;i++)
temp=temp.link;

p.link=temp.link;
temp.link=p;
System.out.println("Entered position is:"+pos);
}
}

public void delete(){
System.out.println("Enter the position to delete a node :");
int pos=s.nextInt();
CNode p,temp;
if(pos<1||(pos>len()+1)||(len()==0))
System.out.println("Invalid position and deletion is not possible");
else if(pos==1&& len()==1){
temp=first;
first=null;
System.out.println("Only one i.e. Deleted item:"+temp.data);
}
else if(pos==1&&len()!=1){
temp=first.link;
while(temp.link!=first)
temp=temp.link;
p=first;
first=p.link;
temp.link=first;
System.out.println("From begininning i.e. Deleted item :"+p.data);
}
else if(pos==len()){
temp=first;
for(int i=1;i<pos-1;i++)
temp=temp.link;
p=temp.link;
temp.link=first;
System.out.println("From Ending i.e. Deleted item :"+p.data);
}
else{
temp=first;
for(int i=1;i<pos-1;i++)
temp=temp.link;
p=temp.link;
temp.link=p.link;
System.out.println("Deleted item :"+p.data);
}
}

public void display(){
CNode temp;
if(first==null)
System.out.println("Circular Linked list is empty :");
else{
System.out.println("List of elements :");
System.out.println("First->");
temp=first;
System.out.println(temp.data+"-->");
temp=first.link;
while(temp!=first){
System.out.println(temp.data+"-->");
temp=temp.link;
}
System.out.println("End");
}
}
@Override
public int len(){
int count=1;
CNode temp=first;
if(temp==null) return(0);
else if(temp.link==first) return(1);
else{
while(temp.link!=first){
count++;
temp=temp.link;
}
return count;
}
}
public static void main(String args[]){
System.out.println("Circular Linked List ADT");
Scanner s=new Scanner(System.in);
CQSll c=new CQSll();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("\n CLL Operations :");
System.out.println("1. Insert 2. Delete 3. Display 4. Length 5. Exit :");
System.out.println("Enter the option :");
int opt=s.nextInt();
switch(opt){
case 1: c.insert();break;
case 2: c.delete();break;
case 3: c.display();break;
case 4: System.out.println("Length of CLL is :"+c.len());
case 5: System.exit(0);
case 6: System.out.println("Invalid option!");
}
System.out.println("\nDo you want to continue(y/n)");
ch=s.next();
}
}
}

Saturday, March 8, 2014

Linear Queue ADT using Single Linked List

Program :

package adsa;
import java.util.Scanner;
/**
*
* @author sudeep
*/
interface LQSll{
void insert();
void delete();
void display();
}
class QNode{
int data;
QNode link;
}
class QueueSll extends QNode implements LQSll{
QNode front,rear;
Scanner s=new Scanner(System.in);
public QueueSll(){
front=rear=null;
}
public void insert(){
System.out.println("Insert the element into the linear Queue :");
int ele=s.nextInt();
QNode p=new QNode();
p.data=ele;
p.link=null;
if(front==null)
front=p;
else rear.link=p;
rear=p;
}
public void delete()
{
//QNode temp;
if(front==null)
System.out.println("Linear Queue is empty");
else
{
//temp=front;
System.out.println("Deleted item :"+front.data);
front=front.link;
}
}
public void display(){
QNode temp;
if(front==null)
System.out.println("Linear Queue is empty");
else{
System.out.println("Queue elements are:");
for(temp=front;temp!=null;temp=temp.link)
System.out.println("-->"+temp.data);
}
}

public static void main(String[] args){
System.out.println("Single Linked List Linear Queue ADT");
Scanner s=new Scanner(System.in);
QueueSll q=new QueueSll();
String ch="y";
while(ch.equalsIgnoreCase("y")){
System.out.println("\n Linear Queue ooperations :");
System.out.println("1. Insert 2.Delete 3. Display 4.Exit");
System.out.println("Enter the option :");
int opt=s.nextInt();
switch(opt){
case 1:q.insert();break;
case 2:q.delete();break;
case 3:q.display();break;
case 4:System.exit(0);
default:System.out.println("Invalid option ");
}
System.out.println("Do you want to continue");
ch=s.next();
}
}
}

Stack ADT using Sinlgle Linked List

Program :
import java.util.Scanner;
interface SStackADT{
    void push();
    void pop();
    void display();
}
class Ssnode{
    int data;
    Ssnode link;
}
public class StackSll extends Ssnode implements SStackADT{
    Ssnode top;
    Scanner s=new Scanner(System.in);
    public StackSll(){
        top=null;
    }
    public void push(){
        System.out.print("Insert the element into the stack :");
        int ele=s.nextInt();
        Ssnode p=new Ssnode();
        p.data=ele;
        p.link=top;
        top=p;
    }
    public void pop(){
        if(top==null)
            System.out.println("Stack is empty");
        else{
            System.out.println("Popped item :"+top.data);
            top=top.link;
        }
    }
    public void display(){
        Ssnode temp;
        if(top==null)
            System.out.println("Stack is empty");
        else{
            System.out.println("Stack elements are :");
            for(temp=top;temp!=null;temp=temp.link)
                System.out.println("-->"+temp.data);
        }
    }
    public static void main(String args[]){
        System.out.println("Single Linked List Stack ADT");
        Scanner s=new Scanner(System.in);
        StackSll s1=new StackSll();
        String ch="y";
        while(ch.equalsIgnoreCase("y")){
            System.out.println("\n Stack operations:\n1.Push 2.Pop 3.Display 4.Exit\nEnter the option :");
            int opt=s.nextInt();
            switch(opt){
                case 1:s1.push();break;
                case 2:s1.pop();break;
                case 3:s1.display();break;
                case 4:System.exit(0);
                default:System.out.println("Invalid input");
            }
            System.out.println("Do you want to continue");
            ch=s.next();
        }
    }
}

Differences Between C++ and Java

Are you having a tough time differentiating between C++ and Java? Do you keep using the semicolon when you're not supposed to? While the two languages are similar, there are certain syntactical differences that can be confusing. Here’s something that will come in handy.

The main function

C++

int main( int X, char* Y[])
{
printf( "Hello, world" );
}

Java

Every function in Java has to be made a part of a class. So, the main function also has to be a part of a class. Moreover, in Java there is one main() function for every class. This can come in handy when writing unit tests for the class.

class HelloWorld
{
public static void main(String X[])
{
System.out.println( "Hello, World" );
}
}

Compiling

C++

In C++, you will be compiling as,
g++ X.cc -o outfile

This will then be run with,

./outfile

Java
In Java, you will compile the classes in X.java.

javac X.java

You have to run this by invoking the static main method.

Class declarations

While C++ requires a semicolon at the end of class declarations, Java does not have any such requirement.

C++

class X{};

Java

class X{}

Method declarations

A method declaration in Java must be a part of a class always. Otherwise, both the languages are quite the same syntactically on this front. You can also use the public, private and protected access specifications in Java.

Constructors and destructors

In the case of constructors, the syntax in both C++ and Java is the same. Java though has no exact replacement for destructors.

Static members

Static members (variables and functions) are also declared in the same way in both the languages. But, Java allows for static initialisation blocks in order to initialise static variables.

class Foo
{
static private int x;
// static initialization block
{ x = 5; }
}

Scoop static namespaces and methods

C++

In C++, you will use the Class::method form in order to scoop static methods.

class MyClass
{
public:
static do();
};

Use this by,
MyClass::do();

Java

In Java, on the other hand, scooping comes with the use of the .again parameter. This is similar to accessing the fields of a class.

class MyClass
{
public static do()
{
// do something
}
}

To use the static method.
MyClass.doStuff();

Accessing fields from various objects

C++

In order to access fields from classes and other such objects, the programmer has to use dots.

myClass x;
x.field;

If a pointer is involved, then the narrow operator (->) has to be used.

myClass x = new MyClass();
x->field;

Java
In Java, only the dot is used. Since we always use references in Java, even pointers are accessed using the dot.

myClass x = new MyClass();
x.field;

Protection levels

They are specified in a different manner.

C++

public:
void X();
void Y();

Java

public void X();
public void Y();

Virtual functions

C++

virtual int X();

Virtual functions can also be used non virtually. You can simply say into X().

Java
int foo(); // or, final int foo();

In Java, functions are always virtual by default. You use ‘final’ in order to avoid them from being overridden.

Abstract Classes

C++

All you need to do is include public virtual functions.

class X{ public: virtual void X() = 0; };

Java
In Java the syntax allows the programmer to be explicit.

abstract class X{ public abstract void X(); }

If you want to specify an interface, then say,

interface X{ public void foo(); }

In that case though, you will have to implement it by,

class Y implements X
{
public void M() { /* do something */ }
}

Memory management

This is also pretty much the same in both the languages, except that Java has garbage collection, so no delete for Java.

Tuesday, March 4, 2014

Print Calender in Java

Hi guys, in this post i am going to give u Print Calender Month code using Java.
import java.util.Scanner;

public class PrintCalendar {

/** Main method */

public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println(" Calender ");
System.out.println("");
//Prompt the user to enter year
System.out.print("Enter full year (YYYY): ");
int year = scan.nextInt();

// Prompt the user to enter month
System.out.print("Enter month in number between 1 and 12(MM): ");

int month = scan.nextInt();

// Print calendar for the month of the year
if (month < 1 || month > 12 || year < 1980)
System.out.println("Wrong input!");
else
printMonth(year, month);

}
/** Print the calendar for a month in a year */

static void printMonth(int year, int month) {

//Print the headings of the calendar
printMonthTitle(year, month);

//Print the body of the calendar
printMonthBody(year, month);
}

/** Print the month title, e.g., May, 1999 */

static void printMonthTitle(int year, int month) {

System.out.println(" " + getMonthName(month) + " " + year);
System.out.println(" ");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");

}

/** Get the English name for the month */
static String getMonthName(int month) {
String monthName = null;
switch (month) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December";
}
return monthName;
}

/** Print month body */
static void printMonthBody(int year, int month) {

// Get start day of the week for the first date in the month
int startDay = getStartDay(year, month);

// Get number of days in the month
int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);

// Pad space before the first day of the month
int i = 0;
for (i = 0; i < startDay; i++)
System.out.print(" ");
for (i = 1; i <= numberOfDaysInMonth; i++) {
if (i < 10)
System.out.print(" " + i);
else
System.out.print(" " + i);
if ((i + startDay) % 7 == 0)
System.out.println();
}
System.out.println();
}

/** Get the start day of the first day in a month */

static int getStartDay(int year, int month) {

//Get total number of days since 1/1/1800
int startDay1800 = 3;
int totalNumberOfDays = getTotalNumberOfDays(year, month);

//Return the start day
return (totalNumberOfDays + startDay1800) % 7;
}

/** Get the total number of days since January 1, 1800 */

static int getTotalNumberOfDays(int year, int month) {
int total = 0;

//Get the total days from 1800 to year - 1
for (int i = 1800; i < year; i++)
if (isLeapYear(i))
total = total + 366;
else
total = total + 365;

//Add days from January to the month prior to the calendar month
for (int i = 1; i < month; i++)
total = total + getNumberOfDaysInMonth(year, i);

return total;
}

/** Get the number of days in a month */

static int getNumberOfDaysInMonth(int year, int month) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
return 31;

if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;

if (month == 2) return isLeapYear(year) ? 29 : 28;

return 0; // If month is incorrect
}

/** Determine if it is a leap year */
static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
}
Output :
Calender Output

Sunday, March 2, 2014

Differences between XML and HTML

XML HTML

eXtensible Markup Language
Hyper Text Markup Language
Markup language defines a set of rules for encoding documents that can be read by both humans and machines. Designed with focus on storing and transporting data.
Markup language for displaying web pages in a web browser. Designed to display data with focus on how the data looks
It is used to Transport data between the application and the database and to develop other mark up languages.
It is used to display a web page
User defined tags
Predefined tags
Tags are case sensitive
Tags are not case sensitive
XML is dynamic type
HTML is of static type
Infine set of tags
Limited no of tags
Every start tag must have end tag
Every start tag need not have end tag
XML focuses on what data is
HTML focuses on how data looks
XML attribute must be enclosed within Quotation marks.
Attribute value can be presented without Quotation marks
Cannot be used as a subtype of a sql_variant instance. Does not support casting or converting to either text or ntext. Does not support the following column and table constraints. XML provides its own encoding. Collations apply to string types only. Cannot be compared or sorted. Cannot be used in Distributed Partitioned Views. Not well supported by browsers
Data does not know itself very well. Data cannot change in response to environment. Data cannot be easily maintained. Cannot store or call on variables. Lacks the capability to define new structures by defining relationships between classes. Tags are not useful for exchanging the document between applications.

Introduction to xml

In this post i am going to give an Introduction of XML technology.

What is XML?


  • XML stands for eXtensible Markup Language.
  • XML is designed to transport and store data.
  • It is not a programming language, i's a markup language.
  • It is a specification of W3C(World Wide Web Consortium)
Markup : Enclosing textual content with in textual code(tags) is nothing but markup.

Purpose :  
  • Used to exchange the information
  • XML documents are used as deployment discriptors
  • Used as textual databases.

Syntax with example :

<?xml version="1.0" encoding="utf-8"?>
<student>
   <sno>10</sno>
   <sname>sudeep</sname>
   <sage>18</sage>
</student>

Well-Formness
It indicates the readability nature of an XML document.
  1. XML Document start with PROLOG.
  2. Start tag must have a matching end tag.
  3. Root element.
  4. Level constraint.
  5. Attribute values must be quoted.
  6. Elements are case sensitive.
XML Element.

1. Start element <eleementname>
2. End element </elementname>
An element can contain
  1. Other elements
  2. Text
  3. Attribute
  4. Mix of all

XML Attribute

If you want to add supplementary information attah to an element, instead of having another element.
  1. Attribute is unique in xml
  2. It can occur in any order.

Avoid using attributes.
  1. It can not contain multiple values.
  2. More difficult to manipulate code
Entities :
                &lt;                           :                  <
                &gt;                          :                  >
                &amp;                      :                  &
                &quot;                      :                  "
                &apos;                     :                   '
                &copy;                     :                   c

Naming Rules :

  1. names can contain letters, numbers and other characters.
  2. name cannot start with number or punctuation characters.
  3. Names cannot start wiht the letters xml.

Best Practices :

  1. Make names descriptive.
  2. Names should be short and simple.
  3. Avoid using hyphen(-), period(.) and colon(:) in the code.

 Validating XML :

If an xml document is developed accorrding to rules specified in DTD/XSD.
Validating xml can be done by :
  1. XML Parsers.
  2. XML Editors.

XML Parser :

It's an API that enables XML applications to work with xml document. It performs
  1. Reading the XML document.
  2. Checking the well-formedness
  3. Verify its validity. 
  4. Making XML data available to XML applications.

XML Editors :

XML Editors are just like text editors which have the feature to check well-formness of our XML document and to validate the same.

The best one is Altova XMLSpy. You can download a windows version here. Unfortunately Altova doesn't provide Linux version for XMLSpy. 

IDE's also have the feature of validating and checking the well-formedness of xml document.

Thursday, February 27, 2014

Sending e-Mail with GMail using SSL connection

To run this application you need mail.jar library. Download JavaMail.jar of new version available here and extract the file, where you will mail.jar file. Add mail.jar to the CLASSPATH.
package sendmail;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username@gmail.com","password");
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-address@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-address@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Testing through SSL");

Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

Sending e-Mail with GMail using TLS

Send an Email via Gmail SMTP server using TLS connection.
To run this application you need mail.jar library. Download JavaMail.jar of new version available here and extract the file, where you will mail.jar file. Add mail.jar to the CLASSPATH.
package sendmail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
*
* @author sudeep
*/
public class SendMailTLS {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
final String username = "username@gmail.com";
final String password = "password";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

Session session;
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-address.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-address@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");

Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

 

Wednesday, February 26, 2014

Implementing Sinlge Linked List in Java

Linked List :

Linked list is a dynamic data structure whose length can be increased or decreased at run time.
How Linked lists are different from arrays? Consider the following points :
  • An array is a static data structure. This means the length of array cannot be altered at run time. While, a linked list is a dynamic data structure.
  • In an array, all the elements are kept at consecutive memory locations while in a linked list the elements (or nodes) may be kept at any location but still connected to each other. 
The figure below shows representation of Single Linked List
Single Linked List

    When to prefer linked lists over arrays?

    Linked lists are preferred mostly when you don’t know the volume of data to be stored. For example, In an employee management system, one cannot use arrays as they are of fixed length while any number of new employees can join. In scenarios like these, linked lists (or other dynamic data structures) are used as their capacity can be increased (or decreased) at run time (as an when required).

    How linked lists are arranged in memory?

    Linked list basically consists of memory blocks that are located at random memory locations. 


    A node class in Java can be created as :
    class Node
    {
    int data;
    Node link;

    Operations on Single Linked List :

    • Insert : Add/Insert node into the list.
    • Delete : Delete a node/element from the list
    • Search : Search for an element in the list
    • Display : Display the list
    • Sort : Sort the list.
    • Length : Finding the length of the list i.e., number of elements in the list.

    import java.util.Scanner;
    interface SllAdt{
    public void insert();
    public void delete();
    public void display();
    public int len();
    public void search();
    public void sort();
    }
    class SNode{
    int data;
    SNode link;
    }
    public class SLL extends SNode implements SllAdt {
    SNode first;
    Scanner s=new Scanner(System.in);
    public SLL(){
    first=null;
    }
    public void insert(){
    System.out.println("Enter the position to insert a node: ");
    int pos=s.nextInt();
    System.out.println("Enter the data into a node");
    int ele=s.nextInt();

    SNode p=new SNode();
    p.data=ele;
    p.link=null;

    if(pos<&eq;1||pos>len()+1)
    System.out.println("Invalid position and insertion is not possible");
    else if(pos==1){
    p.link=first;
    System.out.println("found at position 1 and p.link is :"+p.link+" and first is :"+first);
    first=p;
    System.out.println("now first is :"+first);
    System.out.println("Entered position is(1st):"+pos);
    }
    else{
    SNode temp;
    temp=first;
    for(int i=1;i<pos-1;i++)
    temp=temp.link;
    p.link=temp.link;
    temp.link=p;
    System.out.println("ENtered position is:"+pos);

    }
    }

    public void delete(){
    System.out.println("Enter the positon to delete a node:");
    int pos=s.nextInt();
    SNode p,temp;
    if(pos<1||pos>len()+1)
    System.out.println("Invalid position and deletion is not possible");
    else if(pos==1){
    temp=first;
    first=first.link;
    System.out.println("Deleted element is :"+temp.data);
    }
    else{
    temp=first;
    for(int i=1;i < pos-1;i++)
    temp=temp.link;
    p=temp.link;
    temp.link=p.link;
    System.out.println("Deleted element is :"+p.data);
    }
    }
    public void display(){
    SNode temp;
    if(first==null)
    System.out.println("Linked list is empty:");
    else{
    System.out.println("List of elements:");
    System.out.print("First->");
    for(temp=first;temp!=null;temp=temp.link)
    System.out.print(temp.data+"-->");
    System.out.print("End");
    }
    }
    public int len(){
    int count=0;
    SNode temp;
    for(temp=first;temp!=null;temp=temp.link)
    count++;
    return count;
    }
    public void search(){
    System.out.println("Enter the element to search :");
    int ele=s.nextInt();
    int pos=1;
    SNode temp;
    for(temp=first;temp!=null;temp=temp.link){
    if(temp.data==ele)
    System.out.println("Element "+ele+" is found at position: "+pos);
    else
    System.out.println("Element "+ele+" is not found");
    pos++;
    }
    }
    public void sort(){
    SNode temp1,temp2;
    for(temp1=first;temp1!=null;temp1=temp1.link)
    for(temp2=temp1.link;temp2!=null;temp2=temp2.link)
    {
    if(temp1.data>temp2.data)
    {
    int t=temp1.data;
    temp1.data=temp2.data;
    temp2.data=t;
    }
    }
    }

    public static void main(String[] args){
    System.out.println("Single Linked List ADT");
    Scanner s=new Scanner(System.in);
    SLL s1=new SLL();
    String ch="y";
    while(ch.equalsIgnoreCase("y")){
    System.out.println("\nStack Operations:\n1. Insert 2. Delete 3. Display 4. Length 5. Search 6. Sort 7. Exit :");
    System.out.println("Enter the option :");
    int opt=s.nextInt();
    switch(opt){
    case 1:s1.insert();break;
    case 2:s1.delete();break;
    case 3:s1.display();break;
    case 4: System.out.println("Length of SLL is :"+s1.len());break;
    case 5:s1.search();break;
    case 6:s1.sort();break;
    case 7:System.exit(0);
    default:System.out.println("Invalid option");
    }
    }
    }
    }

    Introduction to Web Services!

    What are Web Services?

    Web service is a way of communication that allows interoperability between different applications on different platforms, for example, a java based application on Windows can communicate with a .Net based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.

    Web services are browsers and operating system independent service, which means it can run on any browser without the need of making any changes. Web Services take Web-applications to the Next Level.

    The World Wide Web Consortium (W3C) has defined the web services. According to W3C, “Web Services are the message-based design frequently found on the Web and in enterprise software. The Web of Services is based on technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and others.”

    A web service has special behavioral characteristics:
    XML Based

    By using XML as the data representation layer for all web services protocols and technologies that are created, these technologies can be interoperable at their core level. As a data transport, XML eliminates any networking, operating system, or platform binding that a protocol has.

    Loosely coupled

    A consumer of a web service is not tied to that web service directly; the web service interface can change over time without compromising the client's ability to interact with the service. A tightly coupled system implies that the client and server logic are closely tied to one another, implying that if one interface changes, the other must also be updated. Adopting a loosely coupled architecture tends to make software systems more manageable and allows simpler integration between different systems.

    Coarse-grained

    Object-oriented technologies such as Java expose their services through individual methods. An individual method is too fine an operation to provide any useful capability at a corporate level. Building a Java program from scratch requires the creation of several fine-grained methods that are then composed into a coarse-grained service that is consumed by either a client or another service. Businesses and the interfaces that they expose should be coarse-grained. Web services technology provides a natural way of defining coarse-grained services that access the right amount of business logic.

    Ability to be synchronous or asynchronous

    Synchronicity refers to the binding of the client to the execution of the service. In synchronous invocations, the client blocks and waits for the service to complete its operation before continuing. Asynchronous operations allow a client to invoke a service and then execute other functions. Asynchronous clients retrieve their result at a later point in time, while synchronous clients receive their result when the service has completed. Asynchronous capability is a key factor in enabling loosely coupled systems.

    Supports Remote Procedure Calls (RPCs)

    Web services allow clients to invoke procedures, functions, and methods on remote objects using an XML-based protocol. Remote procedures expose input and output parameters that a web service must support. Component development through Enterprise JavaBeans (EJBs) and .NET Components has increasingly become a part of architectures and enterprise deployments over the past couple of years. Both technologies are distributed and accessible through a variety of RPC mechanisms. A web service supports RPC by providing services of its own, equivalent to those of a traditional component, or by translating incoming invocations into an invocation of an EJB or a .NET component.

    Supports document exchange

    One of the key advantages of XML is its generic way of representing not only data, but also complex documents. These documents can be simple, such as when representing a current address, or they can be complex, representing an entire book or RFQ. Web services support the transparent exchange of documents to facilitate business integration.

    Web Services Technologies

    Simple Object Access Protocol

    SOAP is a communication protocol which is used to exchange messages between applications over the Internet, irrespective of the platforms and the technology the applications are built on.

    Web Service Description Language (WSDL)

    WSDL is an XML technology that describes the interface of a web service in a standardized way. WSDL standardizes how a web service represents the input and output parameters of an invocation externally, the function's structure, the nature of the invocation (in only, in/out, etc.), and the service's protocol binding. WSDL allows disparate clients to automatically understand how to interact with a web service.

    Universal Description, Discovery, and Integration (UDDI)

    It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery. UDDI provides a worldwide registry of web services for advertisement, discovery, and integration purposes.

    Monday, February 24, 2014

    Dequeue (Double Ended Queue) using Arrays ADT

    Double Ended Queue :

    Program :


    package adsa;

    import java.util.Scanner;
    interface DQArrADT{
    void linsert();
    void rinsert();
    void ldelete();
    void rdelete();
    void display();
    }
    public class DQArr implements DQArrADT{
    int dq[],size,front,rear;
    Scanner s=new Scanner(System.in);

    public DQArr() throws Exception
    {
    System.out.println("Enter the Deque size");
    size=s.nextInt();
    dq=new int[size];
    front=-1;rear=-1;
    }

    public void linsert()
    {
    if(((front==0)&&(rear==dq.length-1))||(rear==front-1))
    System.out.println("Deque is full");
    else if(front==-1)
    {
    front=0;
    rear=0;
    }
    else if(front==0)
    front=(dq.length-1);
    else
    front=front-1;
    System.out.println("Enter the element into deque at left end :");
    int item=s.nextInt();
    dq[front]=item;
    }

    public void rinsert()
    {
    if(((front==0)&&rear==dq.length-1)||(rear==front-1))
    System.out.println("Deque is full");
    else if(front==-1)
    {
    front=0;
    rear=0;
    }
    else if(rear==dq.length-1){
    rear=0;
    System.out.println("rear is changed to "+rear);}
    else
    rear=rear+1;

    System.out.println("Enter the element into the Deque at right end :");
    int item=s.nextInt();
    dq[rear]=item;
    }

    public void ldelete()
    {
    if(front==-1)
    System.out.println("Deque underflow");
    else
    {
    System.out.println("Deleted item at leftend is :"+dq[front]);
    if(front==rear)//one element
    {
    front=-1;rear=-1;
    }
    else if(front==dq.length-1)
    front=0;
    else front=front+1;
    }
    }
    public void rdelete(){
    if(front==-1)System.out.println("Deque underflow");
    else
    {
    System.out.println("Deleted item at right end :"+dq[rear]);
    if(front==rear){//one element
    front=-1;rear=-1;
    }
    else if(rear==0){
    rear=dq.length-1;
    }
    else rear=rear-1;
    }
    }


    public void display()
    {
    if(front==-1)
    System.out.println("Deque empty");
    System.out.println("Deque elements are:");
    if(front<=rear)
    {
    for(int i=front;i<=rear;i++)
    System.out.print(" "+dq[i]);
    }
    else{
    for(int i=front;i<dq.length;i++)
    System.out.print(" "+dq[i]);
    for(int i=0;i<=rear;i++)
    System.out.print(" "+dq[i]);
    }
    }

    public static void main(String args[]) throws Exception{
    System.out.println("Linear Dequeu Array ADT");
    Scanner s=new Scanner(System.in);
    DQArr d=new DQArr();
    String ch="y";
    while(ch.equalsIgnoreCase("y")){
    System.out.println("Deque operations :");
    System.out.println("1. DQ LInsert 2. DQ RInsert 3. DQ LDelete 4. DQ RDelete 5. Display 6.Exit :");
    System.out.println("Enter the option :");
    int opt=s.nextInt();
    switch(opt){
    case 1: d.linsert();
    break;
    case 2:d.rinsert();
    break;
    case 3:d.ldelete();
    break;
    case 4:d.rdelete();
    break;
    case 5:d.display();
    break;
    case 6:System.exit(0);
    default:System.out.println("Invalid option!!!");
    }
    System.out.println("Do you want to continue(y/N) :");
    ch=s.next();
    }
    }
    }

    Sunday, February 23, 2014

    Enhanced for loop (for each loop) in Java

    Enhanced for loop java: Enhanced for loop is useful when scanning the array instead of using for loop. Syntax of enhanced for loop is:
    for (data_type variable: array_name)
    Here array_name is the name of array.

    Java enhanced for loop integer array

    class EnhancedForLoop
    {
        public static void main(String[] args)
        {
              int even[]= { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
              for(int t: even)
              {
                    System.out.println(t);
              }
        }
    }

    Circular Queue ADT using arrays in Java!

    Circular Queue :

    Circular Queue is a linear data structure. It follows FIFO principle.
    • In Circular Queue the last node is connected back to the first node to make a circle.
    • Elements are added at the rear and deleted at front of the queue.
    • Both the front and rear pointers point to the beginning of the array.
    • Circular Queue is also called as Ring Buffer.
    • Items can be inserted and deleted from a queue in O(1) time.

     Circular Queue can be created in three ways they are :
    • Using arrays (In this post)
    • Using single linked list
    • Using double linked list
    I'll be covering Circular Queue using Arrays and remaining two in next posts.


    Program :


    interface CQArrAdt{
    void insert();
    void delete();
    void display();
    }
    class CQArr1 implements CQArrAdt{
    int cq[],size,front,rear;
    Scanner s=new Scanner(System.in);
    public CQArr1()throws Exception{
    System.out.println("Enter the size of the Circular Queue :");
    size=s.nextInt();
    cq=new int[size];
    front=-1;rear=-1;
    }

    @Override
    public void insert() {
    if(((front==0) && (rear==cq.length-1))||(rear==front-1)){
    System.out.println("Circular Queue is full!!!");
    }
    else if(front==-1){front=0;rear=0;}
    else if(rear==cq.length-1)rear=0;//rotate/override cq
    else
    rear++;
    System.out.println("Enter the element into the circular queue :");
    int ele=s.nextInt();
    cq[rear]=ele;
    System.out.println("At this point rear= "+rear++);
    }

    @Override
    public void delete() {
    if(front==-1)
    System.out.println("CQ is underflow!!");
    else
    {
    System.out.println("Deleted item is :"+cq[front]);
    if(front==rear)//array contains only one element
    {
    front=rear=-1;
    }
    else if(front==cq.length-1){//rotate in the array!!!
    front=0;
    }
    else
    front--;
    }
    }

    @Override
    public void display() {
    if(front==-1){
    System.out.println("CQ is empty");
    }
    else if(front<=rear){
    for(int i=front;i<=rear;i++)
    System.out.print(" a"+cq[i]);
    }
    else{
    for(int i=front;i<cq.length;i++)
    System.out.print(" b"+cq[i]);
    for(int i=0;i<=rear;i++)
    System.out.print(" c"+cq[i]);
    }
    }

    }
    public class CQArr{
    public static void main(String args[]) throws Exception{
    System.out.println("Circular Queue ADT");
    Scanner s=new Scanner(System.in);
    CQArr1 c=new CQArr1();
    String ch="y";
    while(ch.equalsIgnoreCase("y")){
    System.out.println("Circular Queue operations\n1. Insert 2. Delete 3. Display 4. Exit\nEnter your choice :");
    int opt=s.nextInt();
    switch(opt){
    case 1:c.insert();break;
    case 2:c.delete();
    break;
    case 3:c.display();break;
    case 4:System.exit(0);
    default :System.out.println("Invalid operation!!!");
    }
    System.out.println("Do you want to continue (y/N):");
    ch=s.next();
    }
    }

    }

    Linear Queue ADT using Arrays!

    Queue :

    A queue is a linear collection, where something to be added to the queue must be placed at the end of the queue. Items are removed from the queue from the front. To keep with the analogy, when you walk into the bank you go to the end of the queue. When the teller is ready to help the next person, the person at the beginning of the queue is removed from the queue. Each person then moves one position closer to the beginning of the queue. Eventually, you will be the first person in the queue and the teller will call you up causing you to be removed from the queue.

    A queue is referred to as a FIFO data structure: First In, First Out.

    Operations on Queue :

    enqueue : Add an element to the end of the queue.
    dequeue : Remove the element from the front of the queue
    peek       : Retrieve an item at front of queue.
    isEmpty  : Determines whether the Queue is empty or not.
    isFull      : Determines whether the queue is full or not.

    Applications :

    • For implementing any "natural" FIFO service, like telephone enquiries, reservation requests, traffic flow, etc.
    • For implementing any "computational" FIFO service, for instance, to access some resources. Examples: printer queues, disk queues, etc.
    • For searching in special data structures (breadth-first search in graphs and trees).
    • For handling scheduling of processes in a multitasking operating system.

    Program :

    package adsa;
    import java.util.Scanner;

    interface LQueADT{
    void insert() throws Exception;
    void delete();
    void display();
    }
    public class QueueArr implements LQueADT {
    int q[],size;
    int front,rear;
    Scanner s=new Scanner(System.in);

    public QueueArr() throws Exception {
    System.out.println("Enter the size of the Linear Queue :");
    size=s.nextInt();
    q=new int[size];
    front=-1;rear=-1;
    }

    public void insert() throws Exception {
    if(rear==q.length-1){
    System.out.println("Linear Queue overflow");
    }
    else{
    System.out.println("Enter the element into the queue :");
    int ele=s.nextInt();
    rear++;
    q[rear]=ele;
    if(front==-1) front=0;
    }
    }

    public void delete() {
    if(front==-1 || front>rear){
    System.out.println("Linear Queue underflow");
    }
    else{
    System.out.println("Deleted Element is :"+q[front]);
    front++;
    }
    }

    public void display() {
    if(front==-1 || front>rear){
    System.out.println("Linear Queue is Empty");
    }
    else{
    System.out.println("Linear Queue elements are....");
    for(int i=front;i<=rear;i++)
    System.out.println(""+q[i]);
    }
    }

    public static void main(String args[]) throws Exception{
    System.out.println("Linear Queue Array ADT ");
    Scanner s=new Scanner(System.in);
    QueueArr qa=new QueueArr();
    String ch="y";
    while(ch.equalsIgnoreCase("y")){
    System.out.println("Linear Queue operations :\n1. Insert 2. Delete 3. Display 4. Exit\nEnter the option :");
    int opt=s.nextInt();
    switch(opt){
    case 1:qa.insert();break;
    case 2:qa.delete();break;

    case 3:qa.display();break;
    case 4:System.exit(0);
    default : System.out.println("Invalid Option");
    }
    System.out.println("Do you want to continue (y/N):");
    ch=s.next();
    }
    }

    }

    Stack Program using Arrays in Java!

    Stack :

    A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations are allowed: pushthe item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top.

    Applications :

    1. The simplest application of a stack is to reverse a word. You push a given    word to stack - letter by letter - and then pop letters from the stack.
    2. Another application is an "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack.
    3. Infix to Postfix conversion.

    Operations :

    1. Push : To push an element into the stack.
    2. Pop   : To pop an element from the stack.
    3. Peek  : Shows the top most element in the stack.
    4. isEmpty : Determines whether the stack is empty or not.

    Java Program!

    package adsa;
    import java.util.Scanner;
    interface StackAdt{
    void push() throws Exception;
    void pop();
    void display();
    }
    public class StackArr implements StackAdt{
    int top;
    int stack[];
    int size;
    Scanner s=new Scanner(System.in);
    public StackArr() throws Exception{
    System.out.println("Enter the stack size :");
    size=s.nextInt();
    stack=new int[size];
    top=-1;
    }
    public void push() throws Exception{
    if(top==stack.length-1)
    System.out.println("Stack is full!!");
    else{
    System.out.println("Enter the element into the stack :");
    int ele=s.nextInt();
    top++;
    stack[top]=ele;
    }
    }
    public void pop(){
    if(top==-1)
    System.out.println("Stack underflow!!");
    else{
    System.out.println("Popped item is :"+stack[top]);
    top--;
    }

    }
    public void display(){
    System.out.println("The elements in the stack are...");
    if(top==-1){
    System.out.println("No elements to display!!");
    }else
    {
    for(int i=top;i>=0;i--){
    System.out.print(stack[i]);
    }
    }System.out.println();
    }
    public static void main(String args[])throws Exception{
    Scanner s=new Scanner(System.in);
    StackArr st=new StackArr();
    String ch="y";
    while(ch.equalsIgnoreCase("y")){
    System.out.println("1. Push 2. Pop 3. Display 4. Exit\n Enter the option :");
    int opt=s.nextInt();
    switch(opt){
    case 1:st.push();
    break;
    case 2: st.pop();
    break;
    case 3:st.display();
    break;
    case 4:System.exit(0);
    default:System.out.println("Invalid input");
    }
    System.out.println("Do you want to continue (y/N):");
    ch=s.next();
    }
    }
    }