December 31, 2013

Struts application in java


Java struts login page application source code


This application is for beginner. copy paste the code to respective folder.  The application shows you how login  with struts work.

Login page

Login.jsp

Java struts login page application source code


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>

<title> Java struts web application source code </title>
</head>
<body>

<h2>Sample web application</h2>

<s:actionerror />

<s:form action="login.action" method="post">
    <s:textfield name="username" key="label.username" />
    <s:password name="password" key="label.password" />
    <s:submit method="execute" key="label.login" align="center" />
</s:form>

</body>
</html>

This jsp teach you how struts tag works

<%@ taglib prefix="s" uri="/struts-tags"%> adding a struts tag to jsp page

<s:form action="login.action" method="post">  as like form in html. once you submit the form the corresponding login action in struts.xml is called.

key="label.login" will be defined in application.properties

Welcome page.jsp   ( Second page)


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> struts JSP jquery application</title>
</head>
<body>
<h2> Welcome to java lazy blog, Java web application </h2>
</body>
</html>


Web.xml


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

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

   
    <display-name>Struts2 application</display-name>

    <filter>
        <filter-name>StrutsNew</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>StrutsNew</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>Login.jsp</welcome-file>
    </welcome-file-list>

</web-app>

---

    <filter>
        <filter-name>StrutsNew</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>StrutsNew</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Through this filter class in struts.xml we are re directing each every url [ <url-pattern>/*</url-pattern>]  through filterdispatcher <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>



Jar file needed. you have to put this in lib folder






LoginAction.java inside src folder


package com.blazy.strutsSpringapplication;
/*
* Action class in struts
*/
public class LoginAction {
   
    private String username = null;
    private String password = null;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
   
    public String execute()
    {
        if(username.equals("u") & (password.equals("p")))
           // code for validation
        {
            System.out.println(" Struts frame work example download "+username + password);
        return "success";
        }
        else
            return "error";
       
    }

}

--

public class LoginAction  implements ......

ApplicationResources.properties file inside resources folder


label.username = username
label.password = password
label.login = Login
error.login = Invalid user try again later



Struts.xml file  inside resource folder


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />

    <package name="default" extends="struts-default" namespace="/">
     <action name="login" class="com.org.strutsNew.LoginAction" converter="" method="save">
            <result name="success">Welcome.jsp</result>
            <result name="error">Login.jsp</result>
        </action>
     </package>
</struts>

we have created the login class above
<action name="login" class="com.org.strutsNew.LoginAction" converter="" method="save">

This is only a small program. please try this.

Wish you a Happy New year

+Deepu A.B.


Similar posts

  1. Java spring model view and controller - hello world example



https://javabelazy.blogspot.in

December 25, 2013

Cryptography in java

Java Cryptography



 import javax.crypto.Cipher;
   import javax.crypto.BadPaddingException;
   import javax.crypto.IllegalBlockSizeException;
   import javax.crypto.KeyGenerator;
   import java.security.Key;
   import java.security.InvalidKeyException;

   public class LocalEncrypter {

        private static String algorithm = "DESede";
        private static Key key = null;
        private static Cipher cipher = null;

        private static void setUp() throws Exception {
            key = KeyGenerator.getInstance(algorithm).generateKey();
            cipher = Cipher.getInstance(algorithm);
        }

        public static void main(String[] args)
           throws Exception {
            setUp();
            if (args.length !=1) {
                System.out.println(
                  "USAGE: java LocalEncrypter " +
                                         "[String]");
                System.exit(1);
            }
            byte[] encryptionBytes = null;
            String input = args[0];
            System.out.println("Entered: " + input);
            encryptionBytes = encrypt(input);
            System.out.println(
              "Recovered: " + decrypt(encryptionBytes));
        }

        private static byte[] encrypt(String input)
            throws InvalidKeyException,
                   BadPaddingException,
                   IllegalBlockSizeException {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] inputBytes = input.getBytes();
            return cipher.doFinal(inputBytes);
        }

        private static String decrypt(byte[] encryptionBytes)
            throws InvalidKeyException,
                   BadPaddingException,
                   IllegalBlockSizeException {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] recoveredBytes =
              cipher.doFinal(encryptionBytes);
            String recovered =
              new String(recoveredBytes);
            return recovered;
          }
   }

Merry Christmas and happy new year wishes to all visitors +belazy


Up helly aa fire festival

http://belazy.blog.com/

December 18, 2013

To check whether a number is prime or not in java

How to find Prime Number in java

How to determine a prime number in java :This program will check whether the given input is either prime number or not. it will return true or false.
copy and paste the code to notepad. compile it with javac and run it...

Instead of bufferedStream class you can use scanner class.  The logic i used is divide the given number from 2 to half of the number. if any one is divisible i stopped the loop and concluded it as not prime. if it successfully passed through all loop with out a division, then its a prime


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Ramanujan s number 1729
 */

/**
 * @author Proximotech Java lazy
 *
 */


public class PrimeOrNot {

    /**
     * @param lazy java
     */
      static int i,num,flag=0;
   
    public static void main(String[] vadassery) {
        // TODO Auto-generated method stub
   
        System.out.println("enter the integer no:");
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       try {
         num=Integer.parseInt(br.readLine());
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       for(i=2;i<num/2;i++){
           if(num%2==0)
           {
               flag=1;break;
           }
       }
       if(flag==1)
           System.out.println("The given number is a prime number");
       else
           System.out.println("The above number is not a prime number"); 
    }

}

write a program in java to check the given number is prime or not


Checking the program with ramanujans number 1729 (smallest prime number which can be expressed as the sum of the cubes of two numbers in two ways )

out put : The given number is prime

Remember the smallest prime number is 2

To print all prime number in java


Alternative method to check a number is prime or not


public class JavaPrimeNumberCheck {
    public boolean isPrimeNumber(int number){
         
        for(int i=2; i<=number/2; i++){
            if(number % i == 0){
                return false;
            }
        }
        return true;
    }
     
    public static void main(String a[]){
        JavaPrimeNumberCheck pc = new JavaPrimeNumberCheck();
        System.out.println("Is 17 prime number? "+pc.isPrimeNumber(17));
        System.out.println("Is 19 prime number? "+pc.isPrimeNumber(19));
        System.out.println("Is 15 prime number? "+pc.isPrimeNumber(15));
    }
}

 Number to word convertor in java



public
class Test {
public static void main(String[] args) {
String []a = {"","one","two","three","four","five"};
String []b = {"","ten","twenty","thirty","fourty"};
int number = 432;
int i = number;
int d = i/100;
int r = i%100;
int t = r/10;
int tr = r% 10;
System.out.println(a[d]+" Hundered and "+b[t]+" "+a[tr]);
}
}



Are you looking for prime factor in java click here

http://belazy.blog.com/

December 16, 2013

ActionListeners example in java

ActionListeners example in java


 import java.awt.*;
import java.awt.event.*;

class click extends Frame implements ActionListener
{
Button b,p;

click()
{
this.setLayout(null);
b= new Button("pink");
p= new Button("blue");
b.setBounds(100,299,70,20);
p.setBounds(200,299,70,20);
this.add(p);
this.add(b);
b.addActionListener(this);
p.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==p)
setBackground(Color.pink);
if(ae.getSource()==b)
setBackground(Color.blue);
}

public static void main(String a[])
{
click c=new click();
c.setTitle("adding button");
c.setSize(500,500);
c.setVisible(true);
}

}


Decimal to Binary calculation in java


//import java.io.*;

class dectobin
{

public static void main(String arg[])
{

int b;

//int a=Integer.parseInt(10);
int a=10;


while(a<=0)
{

b=a%2;
a=a/2;
System.out.print(b);
}

System.out.println(" Binary to decimal convertor in java source code");

}
}


Creating A frame in java

import java.awt.*;
class demoframe extends Frame
{
public static void main(String arg[])
{
demoframe f=new demoframe();
f.setSize(300,300);
f.setVisible(true);
f.setTitle("Dallas cowboy xkeycode");

}
}

Ceaser Encryption in java


import java.awt.*;
import java.awt.event.*;
//import java.awt.text.*;
import java.lang.*;



public class encryp extends Frame implements ActionListener

{

Label l1,l2,l3;
TextField t;
TextField t2,k;
String s1;


Button b,e;

encryp()
{
this.setLayout(null);

l1=new Label("Input :");
l1.setBounds(350,50,50,20);
this.add(l1);
//l1.addActionListener(this);
l2=new Label("key :");
l2.setBounds(350,100,50,20);
this.add(l2);
l3=new Label("Output :");
l3.setBounds(350,350,50,20);
this.add(l3);




t=new TextField(4);
t.setBounds(400,50,100,20);
this.add(t);
t.addActionListener(this);

k=new TextField(4);
k.setBounds(400,100,100,20);
this.add(k);
k.addActionListener(this);



t2=new TextField(4);
t2.setBounds(400,350,100,20);
this.add(t2);
t2.addActionListener(this);

b=new Button("Ceaser");
b.setBounds(300,140,50,30);
this.add(b);
b.addActionListener(this);

e=new Button("exit");
e.setBounds(410,300,50,30);
this.add(e);
e.addActionListener(this);



}

public void work()
{
System.out.println(" work ");
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b)
{
s1=t.getText();
StringBuffer s=new StringBuffer(s1);
System.out.println(t.getText());

//s.reverse();
System.out.println(s);
t2.setText(s.reverse());
}

if(ae.getSource()==e)
{
System.exit(0);
}

}

public void textChanged(TextEvent te)
{
System.out.println(" java source code  ");
}

public static void main(String arg[])
{

encryp e=new encryp();
e.setTitle(" encryption ");
e.setSize(900,600);
e.setVisible(true);
}


Simple applications, copy paste and run it...



http://belazy.blog.com/

December 13, 2013

Method Overriding example in java


This is a small example for overriding in java.


Method Overriding : Implementation in sub class with same parameters and type signature Overrides the implementation in super class. Call of overriding is resolved through dynamic binding by JVM. JVM only deals with overriding.


Base class


public class Base {
   
    public void area()
    {
        System.out.println(" area inside base class ");
    }

}

November 06, 2013

Sending email with pdf as attachment in google spreadsheet

How to create an automatic email with attachment sending code in google spreadsheet



 This is a small

Google script code

that send mail periodically (by setting timer) by having an attached pdf copy to a sender mail.
Thanks to +bithesh soubhagya


 function myFunction() {
// convert spread sheet to portable document format (pdf) with google spreadsheet
     var sheetToPdf = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheet/ccc?key=7AuhngraNMxhdFpxT24WEJjN0FzMjMDEEP1AMzRYXRZNVE&usp=drive_web#gid=9");
     Logger.log(" sheet name :::: "+SpreadsheetApp.getActiveSheet().getName());
     MailApp.sendEmail('belazy1987atgmail.com', 'Testing automatic email with google spreadsheet ', 'Hi, this is subject automatic email sender in google spreadsheet script running', {
     name: 'Google , Spreadsheet ',
     attachments: sheetToPdf
     });
     Logger.log(" Email sent successfully !!! ");
}


Here is a small google script (.gs) function. the above code will sent the google spreadsheet as pdf document through mail. you can specify receivers mail id, subject etc in MailApp.sendEmail function.

Then, if you want to invoke the function automatically use timer button.

Sending alert while opening a file using  google script

function sentOnOpen() {
  var sheetToPdf = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheet/ccc?key=0AuhngraNMxhdFJnMANKALIGNBUnVUbTJVg2dE05Y0UEE&usp=drive_web#gid=0");
 
   var todayDate = new Date();
   Logger.log(" inside date "+todayDate);
   var htmlBody = sheetToPdf.getViewers()+" opened the Report on "+todayDate;
   var subject = " Report " ;
   var optAdvancedArgs = {name: "VIPIN", htmlBody: htmlBody};
   MailApp.sendEmail("belazy1987atgmaildotcom", subject , "Email Body" , optAdvancedArgs);
   Logger.log(" Sending email ");
 
}

you can set the timer. The timer option available on the script page. run it.


The full source code available here, you can run the script and check the result
click here to run the script


http://javabelazy.blogspot.in/

October 15, 2013

Sending screenshot from client to Server through socket in java


How to send screen shot from client to server automatically in java

Did you ever think of getting screen shot from all computers in a network to a server. This code will helps you to do so....This code will capture the current desktop screen shot and sent it to server computer. This application is very useful to network administrator to track what other are doing in the computer at your organization.

ClientApp.java : is a client program that takes screen shot in regular interval.  The sendScreen function will help you to know how java program takes screen shot at intervals and sends to server machine. Here i used ImageIO class to create image buffer. There are other options too... The file is sent through a socket. the port number i used here is 1729. Server Name here used is loop back ip, where you need to specify the server computer name or ip  address.

On the Other hand
SeverApp.java will always listen to the port 1729. if any request comes there, it will catch request and save to the folder 


ClientApp.java


import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


import javax.imageio.ImageIO;


/**
 * @author lou reed
 *
 */
public class ClientApp implements Runnable {

    private static long nextTime = 0;
    private static ClientApp clientApp = null;
    private String serverName = "127.0.0.1"; //loop back ip
    private int portNo = 1729;
    //private Socket serverSocket = null;
   
    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        clientApp = new ClientApp();
        clientApp.getNextFreq();
        Thread thread = new Thread(clientApp);
        thread.start();
    }

    private void getNextFreq() {
        long currentTime = System.currentTimeMillis();
        Random random = new Random();
        long value = random.nextInt(180000); //1800000
        nextTime = currentTime + value;
        //return currentTime+value;
    }

    @Override
    public void run() {
        while(true){
            if(nextTime < System.currentTimeMillis()){
                System.out.println(" get screen shot ");
                try {
                    clientApp.sendScreen();
                    clientApp.getNextFreq();
                } catch (AWTException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch(Exception e){
                    e.printStackTrace();
                }
               
            }
            //System.out.println(" statrted ....");
        }
       
    }

    private void sendScreen()throws AWTException, IOException {
           Socket serverSocket = new Socket(serverName, portNo);
             Toolkit toolkit = Toolkit.getDefaultToolkit();
             Dimension dimensions = toolkit.getScreenSize();
                 Robot robot = new Robot();  // Robot class
                 BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
                 ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
                 serverSocket.close();
    }
}




Web Browsers Tips and Tricks

How to remove or hide an address bar from a web browser

cómo quitar la barra de direcciones de un navegador web

كيفية إزالة شريط العنوان من مستعرض الويب

wie Adressleiste von einem Webbrowser entfernen

como remover barra de endereços do navegador de internet

как удалить адресную строку из веб-браузера

วิธีการเอาแถบที่อยู่จากเว็บเบราว์เซอร์

如何从Web浏览器中删除地址栏

How to remove address bar from Internet Explorer web browser

  • Open run (win + r) then type " regedit " to open registry editor
  • Navigate to HKEY_LOCAL_MACHINE >> software >> policies >> Microsoft , Right click then select New >> Key to create a subkey named " Internet Explorer " under " Microsoft "
  • Right click on "Internet Explorer" then select New >> Key to create another key named " Toolbars " under " Internet Explorer "
  • Right click on " Toolbars " then select New >> Key to create another key named " Restrictions " under " Toolbars "
  • The hierarchy looks as follows HKEY_LOCAL_MACHINE >> software >> policies >> Microsoft >> Internet Explorer >> Toolbars >> Restrictions
  • On the right side you can two columns name and type. right click in the open area select New >> DWORD value create the name " NoAddressBar "
  • Right click on " NoAddressBar " then select Modify and Enter the value 1 in the Textbox and click "OK"

How to remove address bar from Google chrome web browser

  • Type "about:flag" in the address bar of google chrome and hit enter
  • Scroll down to "compact navigation" and enable it
  • Once browser restarted, click on the tab and select " hide the tool bar " from context menu

+Vipin Cp

http://javabelazy.blogspot.in/

October 10, 2013

Example in java to read and write an excel sheet

How to read and write an excel sheet in java



/**
* Developed for ..... Account Section (For ...),
*/

package reader;

import java.io.File;

import java.io.IOException;

import java.security.acl.LastOwnerException;

import java.util.Vector;

import writer.WriteExcel;

import jxl.Cell;

import jxl.CellType;

import jxl.Sheet;

import jxl.Workbook;

import jxl.read.biff.BiffException;

import jxl.write.WriteException;

public class ReadExcel {

  private String inputFile;

  private double openingBalDL =130.95;

  private double openingBalCL =0.00; // Credit Last

  private double openingBalDN =0.00; // Debit New

  private double openingBalCN =0.00;

  private double allDebits = 0.00;

  private double allCredits = 0.00;

  private String dateLast = "4/3/12";

  private String dateNew = null;

  private Vector array = new Vector();

  public void setInputFile(String inputFile) {
    this.inputFile = inputFile;
  }

  public void read() throws IOException  {
    File inputWorkbook = new File(inputFile);
    Workbook w;
    try {
      w = Workbook.getWorkbook(inputWorkbook);
      // Get the first sheet
      Sheet sheet = w.getSheet(0);
      // Loop over first 10 column and lines
      System.out.println(" no of rows "+sheet.getRows());
      System.out.println(" no of col "+sheet.getColumns());
      int totCols = sheet.getColumns();
      int totRows = sheet.getRows();
      Cell cell = sheet.getCell(0, 1);  // col,row
      System.out.println(cell.getContents());
      if(cell.getContents().equalsIgnoreCase("Opening Balance B/D")){
          System.out.println(" --------------- true ---------------- ");
      }
    
              double debit = 0.00;
              double credit = 0.00;
              double openingBalDb = 130.95;
              double openingBalCr = 0.00;
              double balanceTotDb = 0.00;
              double balanceTotCr = 0.00;
              double closingBalCr = 0.00;
              double closingBalDb = 0.00;
              Vector value = null;
          for(int row =1; row               value = new Vector();
              Cell dateCell = sheet.getCell(0, row);
              Cell refCell = sheet.getCell(1, row);
              Cell partCell = sheet.getCell(2, row);
              Cell debCell = sheet.getCell(3, row);
              Cell crdCell = sheet.getCell(4, row);
              value.add(dateCell.getContents());
              value.add(refCell.getContents());
              value.add(partCell.getContents());
              if(!dateCell.getContents().equalsIgnoreCase("")){  // date ( all debit, credit0
                   debit = debit + Double.parseDouble(debCell.getContents());
                   credit = credit + Double.parseDouble(crdCell.getContents());
                   value.add(debCell.getContents());
                   value.add(crdCell.getContents());
                   System.out.println(" Row : "+row + " Debit : "+debit + " Credit : "+credit);
              } else{ // Balance total , closing balance , grant total, Opeining bala
                      if(partCell.getContents().equalsIgnoreCase("Balance Total")){
                          balanceTotDb = openingBalDb + debit;
                          balanceTotCr = credit;
                          System.out.println(" Balance Total Db : "+balanceTotDb + " Balance Total Cr :"+balanceTotCr);
                          openingBalDb = balanceTotDb;
                          value.add(balanceTotDb);
                          value.add(balanceTotCr);
                      }
                      if(partCell.getContents().equalsIgnoreCase("Closing Balance C/D")){
                          closingBalCr = 0.00;
                          closingBalDb = 0.00;
                        
                          if(balanceTotDb >= balanceTotCr){ //+ credit
                              closingBalCr = balanceTotDb - balanceTotCr;
                          }else{ // - debit
                              closingBalDb = balanceTotCr - balanceTotDb;
                          }
                          System.out.println(" Closing Balance Db "+closingBalDb + " Closing Balance Cr "+closingBalCr);
                          value.add(closingBalDb);
                          value.add(closingBalCr);
                      }if(partCell.getContents().equalsIgnoreCase("Grand Total")){
                          double grantTotalDb = balanceTotDb + closingBalDb;
                          double grantTotalCr = balanceTotCr + closingBalCr;
                          System.out.println(" Grant Total Db : "+grantTotalDb + " Grant Total Cr : "+grantTotalCr);
                          value.add(grantTotalDb);
                          value.add(grantTotalCr);
                      }
                      if(partCell.getContents().equalsIgnoreCase("Opening Balance B/D")){
                          double opBalDb = closingBalCr;
                          double opBalCr = closingBalDb;
                          System.out.println(" Opening Balance Db : " + opBalDb + " Opening Balance Cr : "+opBalCr);
                          value.add(opBalDb);
                          value.add(opBalCr);
                          debit = 0.00;
                        credit = 0.00;  
                        balanceTotDb = 0.00;
                        balanceTotCr = 0.00;
                        closingBalDb = 0.00;
                        closingBalCr = 0.00;
                      }
              }
              array.add(value);
              //Cell cell = sheet.getCell(col, row);
             // System.out.println(cell.getContents());
          }
  
       System.out.println(" array size "+array.size());
       WriteExcel test = new WriteExcel();
       test.setOutputFile("D:/Nijesh/Report.xls",array);
       try {
        test.write();
    } catch (WriteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 
    } catch (BiffException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) throws IOException {
    ReadExcel test = new ReadExcel();
    test.setInputFile("D:/Jerin/Ultron/CashBook.xls");
    test.read();
  }

}

-----------------------

package writer;

import java.io.File;

import java.io.IOException;

import java.util.Locale;

import java.util.Vector;

import jxl.CellView;

import jxl.Workbook;

import jxl.WorkbookSettings;

import jxl.format.UnderlineStyle;

import jxl.write.Formula;

import jxl.write.Label;

import jxl.write.Number;

import jxl.write.WritableCellFormat;

import jxl.write.WritableFont;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;

public class WriteExcel {

  private WritableCellFormat timesBoldUnderline;

  private WritableCellFormat times;

  private String inputFile;

  private Vector array = null;


  public void setOutputFile(String inputFile) {
      this.inputFile = inputFile;
  }

  public void setOutputFile(String inputFile, Vector array) {
      this.inputFile = inputFile;
      this.array = array;  
    }

  public void write() throws IOException, WriteException {
    File file = new File(inputFile);
    WorkbookSettings wbSettings = new WorkbookSettings();

    wbSettings.setLocale(new Locale("en", "EN"));

    WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
    workbook.createSheet("Report", 0);
    WritableSheet excelSheet = workbook.getSheet(0);
    createLabel(excelSheet);
    createContent(excelSheet);

    workbook.write();
    workbook.close();
  }

  private void createLabel(WritableSheet sheet)
      throws WriteException {
    // Lets create a times font
    WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
    // Define the cell format
    times = new WritableCellFormat(times10pt);
    // Lets automatically wrap the cells
    times.setWrap(true);

    // Create create a bold font with unterlines
    WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,
        UnderlineStyle.SINGLE);
    timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
    // Lets automatically wrap the cells
    timesBoldUnderline.setWrap(true);

    CellView cv = new CellView();
    cv.setFormat(times);
    cv.setFormat(timesBoldUnderline);
    cv.setAutosize(true);

    // Write a few headers
    addCaption(sheet, 0, 0, "Date");
    addCaption(sheet, 1, 0, "Reference");
    addCaption(sheet, 2, 0, "Particulars");
    addCaption(sheet, 3, 0, "Debit");
    addCaption(sheet, 4, 0, "Credit");
  

  }

  private void createContent(WritableSheet sheet) throws WriteException,
      RowsExceededException {
    
      int size = array.size();
    
      for(int row = 0; row < size; row ++){
          Vector val = array.get(row);
          for(int col =0; col<5 data-blogger-escaped-br="" data-blogger-escaped-col="">              addValues(sheet,col, row, val.get(col));
          }
        }
    
    
    
    
      /*
    for (int i = 1; i < 10; i++) {
      // First column
      addNumber(sheet, 0, i, i + 10);
      // Second column
      addNumber(sheet, 1, i, i * i);
    }
    */

  }

  private void addCaption(WritableSheet sheet, int column, int row, String s)
      throws RowsExceededException, WriteException {
    Label label;
    label = new Label(column, row, s, timesBoldUnderline);
    sheet.addCell(label);
  }

  private void addNumber(WritableSheet sheet, int column, int row,
      Integer integer    ) throws WriteException, RowsExceededException {
  
    Number number;
    number = new Number(column, row, integer, times);
    sheet.addCell(number);
  
  
  }

  private void addValues(WritableSheet sheet, int column, int row, Object obj)
          throws WriteException, RowsExceededException {
        Label label;
        label = new Label(column, row, obj.toString(), times);
        sheet.addCell(label);
      }

  private void addLabel(WritableSheet sheet, int column, int row, String s)
      throws WriteException, RowsExceededException {
    Label label;
    label = new Label(column, row, s, times);
    sheet.addCell(label);
  }

  public static void main(String[] args) throws WriteException, IOException {
    WriteExcel test = new WriteExcel();
    test.setOutputFile("D:/Akshara/Report.xls");
    test.write();
    System.out
        .println("Please check the result file under E:/Bithesh/consumerfed.xls ");
  }


}

--------------

You have to download jxl.jar to download this apps

The above program calculate balance total, closing balance, opening balance, grant total from given ledger entries in excels sheet...



Read : How to copy all images (resource) from ms word document?

October 07, 2013

How to redirect to second page from first page through servlet

Servlet Mapping example in deployment descriptor


This java server page (jsp) example shows how to redirect from a page another page in jsp, the request from jsp page will pass through a servlet and from the servlet to second . the following java code will decide which page the request should be directed : page.response.sendRedirect("secondPage.jsp");

web.xml file



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Artificial intelligence</display-name>
  <welcome-file-list>
    <welcome-file>newPage.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description>An example for servlet mapping in jsp servlet</description>
    <display-name>Beyonce superbowl</display-name>
    <servlet-name>Beyonce</servlet-name>
    <servlet-class>com.NeuralNetwork.servlet.EvasiOn</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Beyonce</servlet-name>
    <url-pattern>/NeuralNetwork.jsp</url-pattern>
  </servlet-mapping>
</web-app>



October 04, 2013

Java code to get screen shot

How to get screen shot in java



 /**
 * @author Jim Brown
 *
 */

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ScreenShotCapture {
   
    private static final String DIR_NAME = "SouthPark";

    public static void main(String[] shutdown)  {
        ScreenShotCapture captureSS = new ScreenShotCapture();
        captureSS.createDirectory(DIR_NAME);
        try {
            captureSS.getScreen();
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void createDirectory(String dirName) {
        File newDir = new File("D:\\"+dirName);
        if(!newDir.exists()){
            boolean isCreated = newDir.mkdir();
        }
}

    private void getScreen()throws AWTException, IOException {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension dimensions = toolkit.getScreenSize();
        Robot robot = new Robot();  // Robot class
        BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
        ImageIO.write(screenshot, "png", new File("D:\\"+DIR_NAME+"\\Gravity.png"));
   
   }
}

Hi Friends,

         This is a small program named Xkeycode  that enables you to capture system screen. Once you run the code it will capture the screen and save  and png image in your system. so please try it out..


September 30, 2013

How to create javadoc using eclipse ide

How to create developer documentation for a java project


Documentation Comments are essential for every source code in industrial projects. Documentation comments represented by ( /** … */) are unique to java. You can create html developer document for your project once you properly comment your code. Here ,i am going to show you how to create javadoc for your project.

Create a java project in eclipse, Copy and paste the below code to your source folder
/**
* Filename :  ArithmeticOperations.java
* Author   :  belazy1987atgmail.com
* Date      :  September 19 1987
* Description : A java program that shows Basic Arithmetic Operations
*/

/**@author nick +Karthick Rajendran 
 * @version 1.0
*/
public class ArithmeticOperations {
/**  To store answers with double DataType
 */
private double answerDouble = 0.0d;
/**
 *   To store answers with float DataType
 */
private float answerFloat = 0.0f;
/** To store answers with int DataType
 */
private int ansInt = 1;
/** addition() is used to add two variables
 *  @param value_one  first parameter
 *  @param value_two  second parameter
 *  @return answerDouble  returns the sum of value_one and value_two
 */
private double addition(double value_one, double value_two) {
 answerDouble = value_one + value_two;
 return answerDouble;
}

/** subtraction() is used to subtract and return the result
 *  @param value_one first parameter
 *  @param value_two second parameter
 *  @return answerFloat returns the difference of value_one and value_two
 */
private float subtraction(float value_one, float value_two) {
 answerFloat = value_one - value_two;
 return answerFloat;
}

/** multiplication() is used to multiply two values
 *  and return the result
 *  @param value_one first parameter
 *  @param value_two second parameter
 *  @return ansInt returns the product of value_one and value_two
 */
private int multiplication(int value_one, int value_two) {
 ansInt = value_one * value_two;
 return ansInt;
}

/**division() is used to division
 *  and return the result
 *  @param value_one first parameter
 *  @param value_two second parameter
 *  @return ansInt returns the quotient after dividing value_one with value_two
 */
private int division(int value_one, int value_two) {
 ansInt = value_one / value_two;
 return ansInt;
}

/** showDetails() is used to display the output
 *  @param ansAdd  Output of addition
 *  @param ansSub  Output of subtraction
 *  @param ansMul  Output of multiplication
 *  @param ansDiv  Output of Division
 */
private void showDetails(double ansAdd, float ansSub, int ansMul, int ansDiv) {
 System.out.println(" Addition : " +ansAdd);
 System.out.println(" Subtraction : " +ansSub);
 System.out.println(" Multiplication : " +ansMul);
 System.out.println(" Division : "+ansDiv);
}

/**
 * main() function
 * @param str user can pass parameters to main through command prompt
 */
public static void main(String[] str) {
 ArithmeticOperations arithmeticOperation = new ArithmeticOperations();
 double ansAdd = arithmeticOperation.addition(10.0,20.0);
 float ansSub = arithmeticOperation.subtraction(20.8f,12.3f);
 int ansMul = arithmeticOperation.multiplication(200,10);
 int ansDiv = arithmeticOperation.division(100,10);
 arithmeticOperation.showDetails(ansAdd,ansSub,ansMul,ansDiv);
}

/**
 *  belazy1987atgmaildotcom
 */
}

read more 
 
 
Created a html document for the project you had coded 
 
 Thanking you.........

September 27, 2013

How to add css to struts2

 How to add css to struts2
Adding css file to struts

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
<link href="<s:url value ="/css/Theme.css"/>" rel="stylesheet" type="text/css"/>
</head>

September 19, 2013

How to reduce coupling in java

 

How to reduce coupling in java

 Description : This examples shows how the concept of interface in java helps to reduce the coupling between classes/ decoupling the classes, Inversion of control, Removing dependency injection

uml diagram example in java- How to reduce coupling
UML Diagram

The concept is very simple. We are just removing the dependencies of class in another class. Let us check how will do this. By doing this project maintenance will be very easy since there is no dependencies. so please try this code

Copy and paste this source code :
This program shows interface example in java

EmployeeInterface.java
/**
* FileName : EmployeeInterface.java
* Author : belazy1987atgmailcomcom
* Date : September 19 1987
* Description : Interface of the project
*/
package com.nick.Interface;
/**
* @author Oscar
* Implementing Employee Interface to types of employees in java
*/
public interface EmployeeInterface {
/**
* basic salary of the employee
*/
int BASICS = 5000;
/**
* house rent allowance for an employee
*/
int HR = 3000;
/**
* Traveling allowance for an employee
*/
int TA = 2000;
/**
*
*/
int DA = 4000;
/**
* @return int
* abstract method for getting the salary
*/
public int getSalary();
/**
*
* @return String
* abstract method for finding the desingation of employee
*/
public String getDesignation();
}
HumanResourceManager.java
/**
* FileName : HumanResourceManager.java
* Author : belazy1987@gmail.com
* Date : September 29 1987
* Description : Represents the details of Human Resource Manager
*/
package com.nick.Interface;
/**
* @author Oscar
*
*/
public class HumanResourceManager implements EmployeeInterface {
/**
* @return string
* Defines the desingation of the employee
*/
@Override
public String getDesignation() {
String designation = ” HumanResourceManager”;
return designation;
}
/**
* @return int
* calculate the salary of the employee (basic + hr)
*/
@Override
public int getSalary() {
int salary = BASICS + HR;
return salary;
}
}
BusinessAnalyst.java
/**
* FileName : BusinessAnalyst.java
* Author : menijesh@gmail.com
* Date : September 29 1987
* Description : MainClass of project
*/
package com.nick.Interface;
/**
* @author Oscar
*
*/
public class BusinessAnalyst implements EmployeeInterface{
/**
* @return string
* defines the designation of the employee
*/
@Override
public String getDesignation() {
String designation = “BusinessAnalyst”;
return designation;
}
/**
* @return int
* calculate the salary of the employee (basic + hr + da)
*/
@Override
public int getSalary() {
int salary = BASICS + HR + DA ;
return salary;
}
}
MarketingStaff.java
/**
* FileName : MarketingStaff.java
* Author : menijesh@gmail.com
* Date : September 29 1987
* Description : Represent the details of marketting staff
*/
package com.nick.Interface;
/**
* @author Oscar
*
*/
public class MarketingStaff implements EmployeeInterface {
/**
* @return string
* defines the designation of the employee
*/
@Override
public String getDesignation() {
String designation = “Marketing”;
return designation;
}
/**
* @return int
* calculate the salary of the employee (basic + hr + ta)
*/
@Override
public int getSalary() {
int salary = BASICS + HR + TA;
return salary;
}
}
MainClass.java
/**
* FileName : MainClass.java
* Author : menijesh@gmail.com
* Date : September 29 1987
* Description : MainClass of project
* Main Idea of the project is to describe how
* interface works and how to reduce coupling
*/
package com.nick.Interface;
/**
* @author belazy1987@gmail.com
* Working with interface in java
*/
public class MainClass {
/**
* @param cmdArg
*/
public static void main(String[] computerScience) {
EmployeeInterface employeeInterface = null;
employeeInterface = new HumanResourceManager();
System.out.println(“Designation :”+employeeInterface.getDesignation() +” and Salary :”+employeeInterface.getSalary());
employeeInterface = new BusinessAnalyst();
System.out.println(“Designation :”+employeeInterface.getDesignation() +” and Salary :”+employeeInterface.getSalary());
employeeInterface = new MarketingStaff();
System.out.println(“Designation :”+employeeInterface.getDesignation() +” and Salary :”+employeeInterface.getSalary());
}
}

The Above program is an example for interface in java. Why java doesnt support multiple inheritence?

This example shows how to reduce couple or enable loose coupling through concept of interface in java. 

 



August 29, 2013

Excel Formulae : How to convert text to date in Excel 2010 (fomat dd/MM/yyyy)

How to  convert a text data cell to date cell in Excel 2010

For Example the format of text file is given below .....
23/04/2012 12:00:00 AM
17/08/2012 12:00:00 AM
20/10/2012 12:00:00 AM
22/10/2012 12:00:00 AM
29/12/2012 12:00:00 AM

Me Nexus?

For this we have to convert the text to serial number.

the date value function returns the text date to serial number ( calculated as on jan 01 1990)

mid function is use to substring the text

apply the below formula

=DATEVALUE(CONCATENATE(MID(B1,7,4),"/",MID(B1,4,2),"/",MID(B1,1,2)))

after that format the cell as date



Hi Friends,

       Here you can find some Microsoft excel formula that could apply to your excel sheets. Please reply once you tried it out. mail me at  :: belazy1987atgmaildotcom

If you are unable to copy images or any resources from ms document file(.doc/.docx) format try this : java-lazy blog

+joseph james 
+Vipin Cp


Thanks +deepajayaprakash payyanakkal  for her support



http://belazy.blog.com/

August 15, 2013

Software keys


AVG 8

key

VDCST-JDNDZ-BABPA-S8EBG-P7KK4-ZMNX



DREAMWEAVER MX


Sl No: WPD700-58202-88194-29915

4C85-200E-4005-0004-0000-3M00-0800-35X3-0000-404C-EXCC-1451  nero:7


Windows xp


Q7Q6W Q3846 RGDBM 6R883 3736G

YFKBB G996G VWGXY 2V3X8

Q7Q6W Q3846 RGDBM 6R883 3736G

Windows Vista


Ffp3t htkf2 4xymp kf8x9 mghkt

Photoshop CS

serial key
1131-1028-1537-2956-7072-0359

Microsoft Office


KGFVY-7733B-8WCK9-KTG64-BC7D8

Microsoft Office 2007 Product key

FOR OFFICE STANDARD 2007

CTKXX-M97FT-89PW2-DHKD3-74MYJ
KCBJJ-67B9Q-KQXF2-VQV2V-6TXJ3
4NJ39-D83K0-2HNS0-39OKD-4ZHJ8

FOR OFFICE HOME and STUDENT 2007

PHXQ7-GMKQ3-XPYRB-YXTVM-XXT73
B4MKP-KP9YP-7TBQ4-7T4XF-MTGWY
DDY79-433JV-2RXGX-MQFQP-PFDH8
KGFVY-7733B-8WCK9-KTG64-BC7D8
DDY79-433JV-2RXGX-MQFQP-PFDH8
WRGJQ-2J2HB-8XP8D-6J2YK-BMFFD
HX2HC-MJM6Q-4487F-23FMP-9VKV8
HX2DJ-36TJX-CRVRJ-C72Q8-CJTBQ
V82W3-BM72R-XRHWG-CP69F-4FPMT
VHGFG-FVMY3-HHP46-RXVDJ-8R6BY
TC2QP-QBCP7-WQ62V-WBF92-WWG73
WQ27D-PY77P-R9CQK-MCPPB-QGJYQ

FOR OFFICE PROFESSIONAL 2007

MTP6Q-D868F-448FG-B6MG7-3DBKT
T3PVR-XX42X-T49DW-WGBG6-9FT73
TT3M8-H3469-V89G6-8FWK7-D3Q9Q
RVRY7-9H6W3-VBGF7-M7GQF-2X7TB
BHFYK-9RTKR-RV3J6-X669J-XQ3Q8
GM3C4-HQQJV-4TGMX-3R8CP-G928Q
KGFVY-7733B-8WCK9-KTG64-BC7D8
XC84W-M642D-2QDWY-YTKMM-RWJQW
TQ7MT-BQTJD-V4MJ6-J6KT8-RP2VW
HCFPT-K86VV-DCKH3-87CCR-FM6HW
V9mtg-3gx8p-d3y4r-68bq8-4q8vd
KGFVY-7733B-8WCK9-KTG64-BC7D8
GM3C4-HQQJV-4TQMX-3R8CP-G928Q
MTP6Q-D868F-448FG-B6MG7-3DBKT
kxfdr-7ptmk-ykyhd-c8fwv-bbpvw

FOR OFFICE ENTERPRISE 2007

VCWD4-Q2HTM-VKT6B-7V8J3-28K38
M2BX2-HQKQF-Q9Q7K-F2JQH-MDGHW
FXDKB-XJKJP-9B79T-8CMPB-QG938
KGFVY-7733B-8WCK9-KTG64-BC7D8
D8Y66-3Y4GK-G6Y3C-8G7R9-JTDQ8
V9MTG-3GX8P-D3Y4R-68BQ8-4Q8VD
KGFVY-7733B-8WCK9-KTG64-BC7D8
W2jjw-4kydp-2ymkw-fx36h-qyvd8
Vb48g-h6vk9-wj93d-9r6rm-vp7gt
Hcfpt-k86vv-dckh3-87ccr-fm6hw

OFFICE ULTIMATE 2007

J67F8-BB7GM-8VPH2-8YMXP-K49QQ
M247G-3Y738-69GD7-V6CF8-9KH4G
M2QKF-KDQ4R-YHQKD-M4YYK-GPWVD
WRWWX-G9MMD-X4B8X-7JQP3-CMD93
RYC22-PRMXB-8HP8W-384PD-GXHX3
VM98J-C9X4C-MM7YX-93G64-BJMK3



avast : W3083976R9962A0912-ZZT6LA5J
download avast 2014


Corel Draw
download

http://belazy.blog.com/

August 05, 2013

Billing (inventory) system for shops

Billing system for medium size shops




This system can help the company to avoid overstocking. When an organisation overstocks, money is wasted since procuring, storing, and accounting for unneeded items require time, space, and money which could have been used on more critical assets. Likewise, when under stocking occurs the organisation will more likely to only partly meet their mission or possibly not meet the mission at all. Also, a weak inventory control system is more prone to errors and fraud.
      Having advanced systems on sales and inventories makes the company more productive, efficient and convenient both to the company and its client. The system is meant to help people show to customers more relevant items, hoping to expedite   and increase the sales and most importantly to increase the profit of the company. With the aid of sales and inventory systems, management can easily make consistent, reliable, and timely decisions.
Our inventory software is designed for any business that desires a complete control over stock levels and inventory tracking. This inventory software can be used either as a simple inventory control system or a complete manufacturing solution.
The main modules are the following
·         Purchase Module
·         Sales Module
·         Inventory Module
·         Report Module
·         User Module (Employee, Customer and Vendor management)

There will be two types of user (on the basis privilege).

1.      Administrator :

2.      Employees :
billing system login page
log in screen







Please visit our site  proximoTech 

Offical fb page : Trade

Java Fx Login page example


Facebook comments