Monday 22 December 2014

Simple Java HttpClient


import java.io.*;
import java.net.*;


 public void myjavaclient() throws Exception {
      URL url = new URL("http://localhost:9292/Iitaccess/testpost.jsp");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setDoOutput(true);
      PrintWriter out = new PrintWriter(connection.getOutputStream());
      String name = "name="+URLEncoder.encode("myname", "UTF-8");
      String email = "email="+URLEncoder.encode("email@email.com", "UTF-8");
      out.println(name+"&"+email);
      out.close();
      BufferedReader in = new BufferedReader(
        new InputStreamReader(connection.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
         System.out.println(line);
      }
      in.close();
   }


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.");
  }