Monday 17 November 2014

Mouse Pointer info in java

Suppose you move your mouse pointer in entire desktop area and want to know the exact position of the mouse. then use listed below code. by this code you can get the real mouse position X and Y .




import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
class ShowMyMouse extends Thread {
    public ShowMyMouse(String str) {
        super(str);
    }
    public void run() {
        while(true){
        PointerInfo info = MouseInfo.getPointerInfo();
        Point pp=info.getLocation();
        System.out.println(pp);
            try {
                sleep((int)(Math.random() * 1000));
            } catch (InterruptedException e) {}
        }
       
    }
}
public class MyMouse{
    public static void main(String[] ss) {
        new ShowMyMouse("Mouse Pointer info").start();
    }
}

Incompatible type required: org.hibernate.Session found

Incompatible type required: org.hibernate.Session found: javax.mail.Session Java mail struts and hibernate at the same time


How to use Java mail struts and hibernate at the same time?

Answer:

When you work with hibernate in java and want to use java email then you will face
the error, incompatible type required: org.hibernate.Session found: javax.mail.Session
This is because Session is in both package, so you needed to explicit declaration.
Use the listed below email code in java hibernate and you will not face the above error.
------------------------------------------------------

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import org.hibernate.Query;
public void sendEmailToAll(String toEmail){
        String ffrom = "POP@mail.com";
        String tto = toEmail;
        String ssubject = "My subject" + new Date();
        String msgText = "My text message ";
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "my email ip");
        javax.mail.Session ss = javax.mail.Session.getDefaultInstance(properties,null);
        try {
            MimeMessage message = new MimeMessage(ss);
            message.setFrom(new InternetAddress(ffrom));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(tto));
            message.setSubject(ssubject);
            message.setSentDate(new Date());
            MimeBodyPart messagePart = new MimeBodyPart();
            messagePart.setText(msgText);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messagePart);
            message.setContent(multipart);
            Transport.send(message);
        } catch (MessagingException e) {
            System.out.println(e.toString());
        }
    }
 

How to Terminate JSP Process

How to Terminate JSP Process

Some time you want to debug your JSP code for this you want to terminate JSP page process. To achieve this use simple one line code:

out.close();

How to generate .XLS file in Java using Apache POI

How to generate .XLS file in Java using Apache POI


String contextName = request.getContextPath().substring(1);
HttpSession hs = request.getSession();
String path = hs.getServletContext().getRealPath("/" + contextName);
char pathSep = new File(path).separatorChar;
path = path.substring(0, path.lastIndexOf(pathSep + contextName));
path = path + pathSep;
 //String filename = "c:\\Send\\text.xls";
String filename = path+"text.xls";
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
int width = 30;
sheet.setAutobreaks(true);
sheet.setDefaultColumnWidth(width);
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((int) 0).setCellValue("SR No.");
rowhead.createCell((int) 1).setCellValue("Name");
rowhead.createCell((int) 2).setCellValue("Code");
rowhead.createCell((int) 3).setCellValue("Salary");
rowhead.createCell((int) 4).setCellValue("City");
rowhead.createCell((int) 5).setCellValue("State");
int i = 0,index=0;
for(i=0;i<6;i++) {
            index++;
            HSSFRow row = sheet.createRow((short) index);
            row.createCell((int) 0).setCellValue(index);
            row.createCell((int) 1).setCellValue("Name -- "+index);
            row.createCell((int) 2).setCellValue("12345 -- "+index);
            row.createCell((int) 3).setCellValue("4500"+index);
            row.createCell((int) 4).setCellValue("City -- "+index);
            row.createCell((int) 5).setCellValue("State -- "+index);
}
       
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
String disHeader = "Attachment;Filename=\"Report.xls\"";
response.setHeader("Content-Disposition", disHeader);
File desktopFile = new File(filename);
PrintWriter pw = response.getWriter();
FileInputStream fileInputStream = new FileInputStream(desktopFile);
int j;
//pw.flush();
while ((j = fileInputStream.read()) != -1) {
            pw.write(j);
}
fileInputStream.close();
response.flushBuffer();
pw.flush();

pw.close();

How to generate .XLSX file in Java using Apache POI

How to generate .XLSX file in Java using Apache POI

First you need to download from apache site:
Extract zip file and copy listed below file in you Libraries folder under NetBeans.
1)      poi-3.9-20121203.jar
2)      poi-examples-3.9-20121203.jar
3)      poi-excelant-3.9-20121203.jar
4)      poi-ooxml-3.9-20121203.jar
5)      poi-ooxml-schemas-3.9-20121203.jar
6)      poi-scratchpad-3.9-20121203.jar
7)      xmlbeans-2.3.0.jar
8)      dom4j-1.6.1.jar
Create “excel.jsp” as listed below file:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Excel Page</title>
    </head>
    <body>
        <h1>Excel!</h1>
        <form name="excelform" id="excelform"  action="/MyTest/TestExcel"   method="post">
            <input type="submit" value="submit"/>
        </form>    
    </body>
</html>
Create a servlet “TestExcel.java” as listed below file:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestExcel extends HttpServlet {
    //Processes requests for both HTTP
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String contextName = request.getContextPath().substring(1);
        HttpSession hs = request.getSession();
        String path = hs.getServletContext().getRealPath("/" + contextName);
       
        char pathSep = new File(path).separatorChar;
        path = path.substring(0, path.lastIndexOf(pathSep + contextName));
        path = path + pathSep;
        //String filename = "c:\\Send\\text.xlsx";
        String filename = path+"text.xlsx";
        String sheetName = "Sheet1";
        XSSFWorkbook wb= new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet(sheetName) ;
        int width = 30;
        sheet.setAutobreaks(true);
        sheet.setDefaultColumnWidth(width);
       
        XSSFRow rowHead = sheet.createRow((short) 0);
        rowHead.createCell((int) 0).setCellValue("SR No.");
        rowHead.createCell((int) 1).setCellValue("Name");
        rowHead.createCell((int) 2).setCellValue("Code");
        rowHead.createCell((int) 3).setCellValue("Salary");
        rowHead.createCell((int) 4).setCellValue("City");
        rowHead.createCell((int) 5).setCellValue("State");
       
        int i = 0,index=0;
        for(i=0;i<6;i++) {
            index++;
            XSSFRow row = sheet.createRow((short) index);
            row.createCell((int) 0).setCellValue(index);
            row.createCell((int) 1).setCellValue("Name -- "+index);
            row.createCell((int) 2).setCellValue("12345 -- "+index);
            row.createCell((int) 3).setCellValue("4500"+index);
            row.createCell((int) 4).setCellValue("City -- "+index);
            row.createCell((int) 5).setCellValue("State -- "+index);
        }
        FileOutputStream fileOut = new FileOutputStream(filename);
        wb.write(fileOut);
        fileOut.close();
        String disHeader = "Attachment;Filename=\"Report.xlsx\"";
        response.setHeader("Content-Disposition", disHeader);
        File desktopFile = new File(filename);
        PrintWriter pw = response.getWriter();
        FileInputStream fileInputStream = new FileInputStream(desktopFile);
        int j;
        //pw.flush();
        while ((j = fileInputStream.read()) != -1) {
            pw.write(j);
        }
        fileInputStream.close();
        response.flushBuffer();
        pw.flush();
        pw.close();
       
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    public String getServletInfo() {
        return "Short description";
    }

}

Html to pdf in java struts

Html to pdf in java struts


import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.html.
simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.codec.Base64;

import java.util.ArrayList;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.validator.DynaValidatorForm;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import plugins.HibernateSessionFactory;


String contextName = request.getContextPath().substring(1);
HttpSession hs = request.getSession();
String path = hs.getServletContext().getRealPath("/" + contextName);

char pathSep = new File(path).separatorChar;

path = path.substring(0, path.lastIndexOf(pathSep + contextName));
path = path + pathSep + "MyForms";


Document pdfDoc = new Document(PageSize.A4, 50, 50, 1, 50);
Reader htmlReader = new BufferedReader(new InputStreamReader(new FileInputStream(path+"\\newRegistrn.html")));
ByteArrayOutputStream byteAOS = new ByteArrayOutputStream();
PdfWriter.getInstance(pdfDoc, byteAOS);
pdfDoc.open();
StyleSheet stylez = new StyleSheet();
stylez.loadTagStyle("body", "font", "Tahoma");
ArrayList arrayElementList = HTMLWorker.parseToList(htmlReader, stylez);
for (int i = 0; i < arrayElementList.size(); ++i) {
    Element e = (Element) arrayElementList.get(i);
    pdfDoc.add(e);
}
pdfDoc.close();
       
DateFormat dff = new SimpleDateFormat("dd_MMMM_yyyy");
DateFormat tf = new SimpleDateFormat("hhmmss");
String dateString = dff.format(new java.util.Date());
String timeString = tf.format(new java.util.Date());
String pdfStoredFileName = "\\newRegistrn_" + dateString + timeString + "__" + ".pdf";

byte[] byt = byteAOS.toByteArray();
String pdfBase64 = Base64.encodeBytes(byt);
File pdfFile = new File(path+pdfStoredFileName);
FileOutputStream out = new FileOutputStream(pdfFile);
out.write(byt);
out.close();
htmlReader.close();



String fileToDownload =pdfStoredFileName;
String disHeader = "Attachment;Filename=" + fileToDownload;
response.setHeader("Content-Disposition", disHeader);
File desktopFile = new File(path+pdfStoredFileName);
PrintWriter pw = response.getWriter();
FileInputStream fileInputStream = new FileInputStream(desktopFile);
int j;
pw.flush();
while ((j = fileInputStream.read()) != -1) {
   pw.write(j);
}
fileInputStream.close();
response.flushBuffer();
pw.flush();
pw.close();

File fileToDel = new File(path+pdfStoredFileName);
  if(fileToDel.delete()){
    System.out.println("\n "+fileToDel.getName() + " is deleted!");
  } else {
    System.out.println("\n Delete operation is failed.");
  }

Post multiple and return values from JSON in JSP

Post multiple and return values from JSON in JSP

JSON is very lightweight than XML. Here is the some hard JSON example with multiple values post and
multiple return values.
I have used "json-simple-1.1.1.jar" , so you need to download it.

index.jsp
---------------------
<%@ page import="org.json.JSONObject"%>
<%@ page import="java.io.PrintWriter"%>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<input type="button" value="send" onclick="dook();"/>
<script>
function dook() {
    var article = new Object();
    article.title = "Title Name";
    article.url = "Url Name";
    article.categories ="Categories  Name";
    article.tags = "Tags Name";
    var jsonobj=JSON.stringify(article);
    $.ajax({
        data: {para:jsonobj},
        dataType: 'json',
        url: 'newjsp1.jsp',
        type: 'POST',
        success: function(jsonObj){
            alert(jsonObj.title);
            alert(jsonObj.url);
            alert(jsonObj.categories);
            alert(jsonObj.tags);
            alert(jsonObj.rate); 
        },
        error: function() {
            alert('readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
        }
    });
}
</script>



newjsp1.jsp
=======================
<%@ page import="java.io.PrintWriter"%>
<%@ page import="org.json.simple.JSONObject"%>
<%@ page import="org.json.simple.JSONValue"%>
<%
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter outt = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
String title=jsonObj.get("title").toString();
String url=jsonObj.get("url").toString();
String categories=jsonObj.get("categories").toString();
String tags=jsonObj.get("tags").toString();
String rate="450.00";
System.out.println(jsonObj.get("title"));
JSONObject obj = new JSONObject();
obj.put("title", title);
obj.put("url", url);
obj.put("categories", categories);
obj.put("tags", tags);
obj.put("rate", rate);
out.print(obj);
%>

Simple JSON in JSP

Simple JSON in JSP



JSON is very lightweight than XML.Here is the simple example of JSON with java.
I have used "json-simple-1.1.1.jar" , so you need to download it.

index.jsp
---------------------
<%@ page import="org.json.JSONObject"%>
<%@ page import="javax.json.Json"%>
<%@ page import="java.io.PrintWriter"%>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<input type="button" value="send" onclick="dook();"/>
<script>
function dook() {
    var datas = ({"msg":'Test Message'});
    var jsonobj=JSON.stringify(datas);
    $.ajax({
        data: {para:jsonobj},
        dataType: 'json',
        url: 'newjsp.jsp',
        type: 'POST',
        success: function(ans){
            alert(ans.res);    
        },
        error: function() {
            alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
        }
    });
}
</script>


newjsp.jsp
-------------------
<%@ page import="java.io.PrintWriter"%>
<%@ page import="org.json.simple.JSONObject"%>
<%@ page import="org.json.simple.JSONValue"%>
<%
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter outt = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
System.out.println(jsonObj.get("msg"));
JSONObject obj = new JSONObject();
obj.put("res", "hello...");
out.print(obj);
%>

Show records without class in hibernate and struts

Show records without class in hibernate and struts

Struts and Hibernate if you need to show all records from database table then you need to create a pojo class...in some cases you not need to use pojo class then how can you achieve to show all records? I have faced the same problem and overcome it with listed below code.


In query.hbm.xml file
<sql-query name="TestTestTest">
select user_name, user_id, password, cd, user_status,CAST(from_dt AS CHAR) as from_date from user_info
</sql-query>

In your action class

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.
HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.*;
import plugins.HibernateSessionFactory;

Session ssn = null;
ssn = HibernateSessionFactory.getSession();
ssn.setCacheMode(CacheMode.GET);
Query qry = ssn.getNamedQuery("TestTestTest");
List <Object[]>containerResults = qry.list();
for(java.lang.Object[] result : containerResults) {
    System.out.print("\n"+result[0]+"======"+result[1]+"======"+result[2]+"======"+result[3]+"======"+result[4]+"======"+result[5]);
}

ALTERNATE OF OR ANY OTHER LOGIC TAG IN STRUTS

ALTERNATE OF OR ANY OTHER LOGIC TAG IN STRUTS


ALTERNATE OF <logic:equal> OR ANY OTHER LOGIC TAG IN STRUTS
----------------------------------------------------------------------------------------
We need to write very much <logic:equal name> if there are lot of if conditions in you page...so how we use native if condition in struts. I have faced the same problem and find the solution. the solution is in listed below code.


==============================

Using  <logic:equal name> 

<logic:notEmpty name="myProductList" scope="request">
<table>
<logic:iterate id="prodIterateId" name="myProductList">
<tr>
    <logic:equal name="prodIterateId" property="catId" value="1">
        <td  align="center"><html:text name="prodIterateId" property="catId" value="DESKTOP COMPUTER"/></td>
    </logic:equal>
    <logic:equal name="prodIterateId" property="catId" value="2">
        <td align="center"><html:text name="prodIterateId" property="catId" value="LAPTOP"/></td>
    </logic:equal>
    <logic:equal name="prodIterateId" property="catId" value="3">
        <td  align="center"><html:text name="prodIterateId" property="catId" value="PAMTOP"/></td>
    </logic:equal>
     <logic:equal name="prodIterateId" property="catId" value="4">
        <td  align="center"><html:text name="prodIterateId" property="catId" value="PAD"/></td>
    </logic:equal>
        <td  align="center"><html:text name="prodIterateId" property="productName" readonly="true" size="33"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productPrice" readonly="true" size="33"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productCode" readonly="true" size="33"/></td>
    </tr>
    </logic:iterate>
    </table>
</logic:notEmpty>
============================================================

Using native IF condition

<logic:notEmpty name="myProductList" scope="request">
<table>
    <logic:iterate id="prodIterateId" name="myProductList">
        <tr>
            <bean:define id="catId_Value" name="prodIterateId" property="catId"  type="java.lang.Integer" />
            <%
                int c_id=catId_Value.intValue();
                String cat_Name="";
                if(c_id==1) {cat_Name="DESKTOP COMPUTER";}
                if(c_id==2) {cat_Name="LAPTOP"; }
                if(c_id==3) {cat_Name="PAMTOP"; }
                if(c_id==4) {cat_Name="PAD"; }
            %>
        <td  align="center"><html:text name="prodIterateId" property="catId" value="<%=cat_Name%>"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productName" readonly="true" size="33"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productPrice" readonly="true" size="33"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productCode" readonly="true" size="33"/></td>
    </tr>
    </logic:iterate>
    </table>
</logic:notEmpty>

java.lang.OutOfMemoryError: PermGen space in netbeans

java.lang.OutOfMemoryError: PermGen space in netbeans

java.lang.OutOfMemoryError: PermGen space in netbeans

How to solve it in netbeans:
1- Right click on server
2- properties
3- select platform
4-in VM option paste as : -Xmx512m -Xms512m -XX:MaxPermSize=512m


java.lang.OutOfMemoryError: PermGen space in netbeans

Ajax in struts

Ajax in struts

How to use ajax in struts and hibernate.

Ajax is very important in website coding.
Here I am demonstrating how to use jquery ajax in struts and hibernate.


struts-config.xml
--------------------------
<action input="/" path="/amittest" scope="request" type="com.test.actions.AmitTestAction" parameter="method">
<forward name="success" path="/Webs/Input/amittest.jsp"/>
</action>
====================================================


query.hbm.xml
-----------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <sql-query cache-mode="ignore" cacheable="false" flush-mode="always" name="chkBook"> SELECT COUNT(*) FROM book_master WHERE code_id=:code AND serial_id>=:serial </sql-query>
</hibernate-mapping>
====================================================

MyUtilDao.java
------------------------------
package dao;
import org.hibernate.CacheMode;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import plugins.HibernateSessionFactory;
public class MyUtilDao {
    public int chkBook(int code,int serial){
        Session ssn = null;
        ssn = HibernateSessionFactory.getSession();
        ssn.setCacheMode(CacheMode.GET);
        Query qry = ssn.getNamedQuery("chkBook");
        qry.setParameter("code", code);
        qry.setParameter("serial", serial);
        Object tot = qry.uniqueResult();
        int total = 0;
        if (tot != null) {
            total = Integer.parseInt(tot.toString());
        } else {
            total = 0;
        }
        return total;
    }
 
}
====================================================

AmitTestAction.java
-------------------------
package mytest.actions;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import dao.MyUtilDao;
import plugins.HibernateSessionFactory;

public class AmitTestAction  extends org.apache.struts.actions.DispatchAction {
     private final static String SUCCESS = "success";
     public ActionForward showForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
       
         MyUtilDao myUtiDaoObj=new MyUtilDao();
       
         String ffor= request.getParameter("ffor");
         if(ffor.compareTo("chkBook")==0) {
            int code= Integer.parseInt(request.getParameter("code"));
            int erial= Integer.parseInt(request.getParameter("serial"));
            int total=myUtiDaoObj.chkBook(code,serial);
            request.setAttribute("total", total);
            request.setAttribute("ffor", "chkBook");
         }
         return mapping.findForward(SUCCESS);
      }
}
====================================================
amittest.jsp
<%
if(request.getAttribute("ffor")!=null) {
    if(request.getAttribute("ffor").toString().compareTo("chkBook")==0) {
        out.print(request.getAttribute("total"));
    }
}
%>
====================================================
BookAdd.jsp

<input type="button" name="btn1" value="Button" onclick="dotest();"/>
<html:button property="button" value="Save" onclick="do_save()"/>
<script>

 var code=222;
var serial=111;
function do_save() {
        var ajaxans="";
        $.ajax({
                    url: "amittest.do?method=showForm",
                    type: "POST",
                    async: false,
                    cache: false,
                    data:   { 'ffor':'chkBook',
                              'code':code,
                              'serial':serial},
                    success: function(html) {
                             ajaxans=html;
                            }
                }
             );
       if(ajaxans=="1" || parseInt(ajaxans)==1) {
           alert("This is already exists");
           return;
       }    
        var r=confirm("Do you want to save?");
        if (r==true) {
            document.forms[0].action="BookMasterAdd.do?method=processForm";
            document.forms[0].submit();
        }
    }

   function dotest() {
       /*$.post("http://localhost:8080/mytest/amittest.do?method=showForm",{'method':'showForm'},function(ans) {
alert(ans);
});*/
      /*// done
       *$.post("amittest.do?method=showForm",{'method':'showForm'},function(ans) {
alert(ans);
});*/
      /* done
       * $.post("amittest.do?method=showForm",function(ans) {
alert(ans);
});*/
      /* $.get("amittest.do?method=showForm",function(ans) {
alert(ans);
});*/
     
      /* $.get("amittest.do?method=showForm",{'val1':'Hi'},function(ans) {
alert(ans);
});*/  
   
      /*   $.post("amittest.do?method=showForm",{'val1':'Hi'},function(ans) {
alert(ans);
});*/
    /*  $.post("amittest.do?method=showForm",{'ffor':'chkExistReceiptBookMaster',
                                            'zone_code':'8004500',
                                            'frm_serial':'11'
                                           },function(ans) {
alert(ans);
});*/
}
</script>

DispatchMapping does not define a handler property

DispatchMapping does not define a handler property

You may face this error while working on java struts:
"DispatchMapping[/login] does not define a handler property"

Answer of this issue is "parameter attribute mention in struts-config for method of Action class"

Cannot retrieve definition for form bean on action

Cannot retrieve definition for form bean on action

javax.servlet.jsp.JspException: Cannot retrieve definition for form bean stdname on action regist

Ans: spelling mistake in tags, so check it and correct it in struts-config.xml file

Action missing resource in key method map

Action missing resource in key method map


Ans:It means the you have put some spaces in .properties file or missing some property key and its value

Cannot find ActionMappings or ActionFormBeans collection

Cannot find ActionMappings or ActionFormBeans collection


org.apache.jasper.JasperException: javax.servlet.
ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
root cause
javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
root cause
javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection


Ans: One of the most common error is that .. that you have missed struts-config file path in web.xml file.

for Ex: <param-value>/WEB_INF/struts-config.xml</param-value>
so change it as <param-value>/WEB-INF/struts-
config.xml</param-value>

message No action instance for path / could be created error in struts

message No action instance for path / could be created error in struts


Message No action instance for path /getcity could be created in struts
description The server encountered an internal error (No action instance for path /getcity could be created) that prevented it from fulfilling this request.

Ans: it means that you miss-spelled class information just see [type="con.test.action.DoLogin"] it must be
type="com.test.action.DoLogin"

<action name="logform" path="/getcity" type="con.test.action.DoLogin" scope="request" parameter="action">
<forward name="cityyyy" path="/city_confirm.jsp"/>
</action>

Action does not contain specified method (check logs)

Action does not contain specified method (check logs)

javax.servlet.ServletException: java.lang.
NoSuchMethodException: Action[/salary] does not contain specified method (check logs)
java.lang.NoSuchMethodException: Action[/salary] does not contain specified method (check logs)

Ans: This means "salary" method must be a text in the .jsp file:
public ActionForward salary(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
LoginForm lfm=(LoginForm)form;
request.setAttribute("empName", lfm.getAname());
return mapping.findForward("salary");
}

<html:form action="/salary" method="post">
Salary: <html:text property="salary"/><br/>
Emp code <html:text property="empcode"/><br/>
<html:submit value="salary" property="action"/>
</html:form>struts-config.xml

Cannot find message resources under key org.apache.struts.action.MESSAGE

Cannot find message resources under key org.apache.struts.action.MESSAGE


javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.
MESSAGE
javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.MESSAGE

Ans:
1- create a package: com.test.properties
2- under that package create a "Common.properties" file with this contents or just empty it:

#common module error message
error.common.name.required = Name is required.

#common module label message
label.common.name = UserName
label.common.button.submit = Submit
label.common.button.reset = Reset

3- just add the message-resource tag in struts-config.xml file as listed below:
<message-resources parameter="com.test.properties.Common"></message-
resources>

Post Xml data without form in JSP and receive output

Post Xml data without form in JSP and receive output


How to post xml data in JSP page without form field and get it's data
in the next JSP page.

The first file post-data.jsp is just taking xml data form xml file and
sending xml data as a post to the get-post.jsp page.

first file is:

post-data.jsp
--------------
< %@ page import="java.net.*" % >
< %@ page import="java.io.*" % >
< %@ page import="java.util.*" % >
< %@ page import="java.text.*" % >
< %
try
{
URL u;
u = new URL("http://localhost:9292/post/get-post.jsp");
// get the xml data from xml file which you want to post
String inputFileName="C:\\temp1.xml";
FileReader filereader =new FileReader(inputFileName);
BufferedReader bufferedreader=new BufferedReader(filereader);
String initial=bufferedreader.readLine();
String finalData=new String();
while(initial!=null)
{
finalData=finalData+initial;
initial=bufferedreader.readLine();
}
String s=(finalData.toString());
HttpURLConnection uc = (HttpURLConnection)u.openConnection();
uc.setRequestMethod("POST");
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\"");
uc.setAllowUserInteraction(false);
DataOutputStream dstream = new DataOutputStream(uc.getOutputStream());
dstream.writeBytes(s);
dstream.close();
InputStream in = uc.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine())!=null) {
buf.append(line);
}
in.close();
out.println(buf.toString());
}
catch (IOException e)
{
out.println(e.toString());
}
% >


Second file is:

get-post.jsp
-----------------

< %@ page import="java.util.*" % >
< %
String postedData = request.getReader().readLine();
///// perform here your operation for postedData
out.println("Posted Data is ");
out.println(postedData);
% > 

Time in 24 Hours format in Java

Time in 24 Hours format in Java

How to show time in 24 Hours format.

Listed below the code; how to show time in 24 format in java

import java.io.*;
import java.util.*;
import java.util.Calendar;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Tm {
    public static void main(String[] args) {
        Date date = new Date();
    SimpleDateFormat simpDate;

    simpDate = new SimpleDateFormat("kk:mm:ss");
    System.out.println(simpDate.
format(date));


    }
}

Get cookies in java

Get cookies in java

import java.io.*;
import java.net.*;
public class CO {
    public static void main(String ss[]) {
     try {
             String url="http://www.mywebsite.com/anything.do";
              HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        System.out.println("\n[HTTP GET RESPONSE]");
        System.out.println("==== Response Headers =====");
        String serverCookies = conn.getHeaderField("Set-Cookie");
        if(serverCookies != null) {
                    String[] cookies = serverCookies.split(";");
                    for(String s : cookies){
                        s = s.trim();
                        if(s.split("=")[0].equals("JSESSIONID")){
                                String J_SESSION_ID = s.split("=")[1];
                                System.out.println(" Session ID Found: " + J_SESSION_ID);
                            }
            }
        }
    } catch(Exception ee) {
        System.out.println(ee.toString());
    }
    }
}

Show TIFF File in java

Show TIFF File in java

If you have a multiple pages TIFF file and want to see it in java then listed below code will help you.


import java.io.File;
import java.io.IOException;
import java.awt.Frame;
import java.awt.image.RenderedImage;
import javax.media.jai.widget.ScrollingImagePanel;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;

public class ReadTiff extends Frame {
    ScrollingImagePanel panel;
    public ReadTiff(String filename) throws IOException {
        setTitle("ReadTiff");
        File file = new File(filename);
        SeekableStream s = new FileSeekableStream(file);
        TIFFDecodeParam param = null;
        ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
        System.out.println("Number of images in this TIFF: " +
                           dec.getNumPages());
        // 0 means the first, 1 for second and so on.
        int imageToLoad = 0;
        RenderedImage op =
            new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
                            null,
                            OpImage.OP_IO_BOUND,
                            null);
        panel = new ScrollingImagePanel(op, 800, 800);
        add(panel);
    }

    public static void main(String [] args) {
        String filename = "C:\\java\\tiff\\car1.tif";
        try {
            ReadTiff window = new ReadTiff(filename);
            window.pack();
            window.show();
        } catch (java.io.IOException ioe) {
            System.out.println(ioe);
        }
    }
}

Extract Corrupt Zip File By Java

Java Extract Corrupt Zip File By Java


I received an zip file from customer. I have tried to extract with WinZip, but unable to extract zip file because that zip file was corrupt.

So I have tried to extract with Java Zip API and got the success. The code is listed below:

I am sure that the zip file having 5% to 10% part corrupt will be unzip with this code, but if it is having more corrupt then the code will not work.


import java.io.*;
import java.util.zip.*;

class ExtractCorruptZip {
public void extractZipFiles(String fileName) {
try {
String zipDir = "c:\\zip\\";
//String zipDir = "/home/usr/amit/zip/";
byte[] by = new byte[2048];
ZipInputStream ziStream = null;
ZipEntry zipEntry;
ziStream = new ZipInputStream(new FileInputStream(fileName));

zipEntry = ziStream.getNextEntry();
int count=1;
while (zipEntry != null) {
String entry = zipDir + zipEntry.getName();
entry = entry.replace('/', File.separatorChar).replace('\\', File.separatorChar);
int n;
FileOutputStream fOTStream;
File newFile = new File(entry);
if (zipEntry.isDirectory()) {
if (!newFile.mkdirs()) {
break;
}
zipEntry = ziStream.getNextEntry();
continue;
}
fOTStream = new FileOutputStream(entry);
while ((n = ziStream.read(by, 0, 2048)) > -1) {
fOTStream.write(by, 0, n);
}
System.out.println("Working....."+(++count));
fOTStream.close();
ziStream.closeEntry();
zipEntry = ziStream.getNextEntry();
}
ziStream.close();
System.out.println("DONE!!!!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}

public static void main(String[] ss) {
try {
String fileName = "w1.zip";
ExtractCorruptZip extractCorruptZip = new ExtractCorruptZip();
extractCorruptZip.extractZipFiles(fileName);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}