For smart Primates & ROBOTS (oh and ALIENS ).

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, February 08, 2016

XSS Exploits


XSS Exploits

It is XSS, It is Web site hacking. It is cross site scripting (XSS). 
The most usual form of Web site hacking . hackers force a site to perform certain actions like inject a client side scripting code (JavaScript) mixed with submitted content.


so that when a user visits a Web page with the submitted content, the malicious script gets downloaded automatically in his web browser and gets executed.

Using this types of hacking user's cookies and session stolen and sent to site of the attacker.
the user may get redirected to a targeted Web site for instance.
XSS may also be used for user account hacking. When the attacker is able to steal the session cookie value, he may be able to access to the user account as if it was the real user.

Prevention of XSS Exploits

XSS vulnerabilities can be avoided by properly encoding HTML using entities for <, >, " and '. Escaping of HTML characters on online forums can also be avoided by using bbcodes usually offered there.

The htmlpecialchars() function can be helpful in this regard as it converts content automatically into HTML entities. It also converts single quotes by using ENT_QUOTES as second argument. The strip_tags() function also removes PHP and HTML tags from string.
Share:

Wednesday, May 06, 2015

How to convert eps file to jpg file

Problem:

How to convert .eps file to .jpg file

Solution:

It is simple, use ImageMagick and below java code. if you expert in PHP or .Net then you can easily convert it same as me.

Example:

import="java.util.*"%>  
import="java.io.*"%>
 
try
    {
        Runtime runTime = Runtime.getRuntime();
        Process process = runTime.exec ("C:/Program Files/ImageMagick-6.5.4-Q16/convert.exe c:/Art1.eps c:/art1.jpg");
        //InputStream inputStream = process.getInputStream();
        //InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
        //BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
        ///String line = null;
        //while ( (line = bufferedReader.readLine()) != null )
        //    System.out.println(line);
        int exitVal = process.waitFor();
        System.out.println ("Process exitValue:  " + exitVal );
    }
    catch (Throwable t)
    {
        t.printStackTrace();
    }
Share:

Thursday, April 09, 2015

Add new row dynamically in JTable

Problem:

Add new row dynamically in JTable
This is Java code allow to you add a new row in JTable.
when you press enter then a new row automatically inserted and you can make more entry.


Add new row dynamically in JTable









Solution & Example:

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
public class t1 extends JFrame {
DefaultTableModel model;
JTable table;
JScrollPane sc1;
public t1() {
super("Data Entry Form By Amit Gaur (amitt800@gmail.com)");
int i,j;
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
model = new DefaultTableModel();
table = new JTable(model);
model.addColumn("Name");
model.addColumn("ID");
model.addColumn("Salary");
model.addColumn("Jobs");
model.addRow(new Object[]{"","","",""});
table.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
model.addRow(new Object[]{"", "","",""}); } }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { } } );

sc1 = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); cp.add(sc1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
setVisible(true);
}
public static void main(String[] ss) {
new t1();
}
}




Share:

Wednesday, March 25, 2015

Email Blaster

Email Blaster
*Features
- Send unlimited emails.
- Send test email, so you can see your email format and looks.
- Show real time progress in counting sent emails.
- Show progress in percentage(%)
- Send email both format Text and HTML format.
- Alternate Solution of Cron Job(Less feature).
- Alternate Solution of SQL Agent Job(Less feature).
- Solution of Script Timeout.






















































Share:

Friday, March 13, 2015

Generate excel file in jsp java quickly

When you want to generate excel file in jsp java then you have lot of options,
for ex: jexcelapi, Apache POI,other paid library.
The problem is that the file; first will be created on hard disk then after read it and download to the user’s system.
We all know that the .csv files open in excel software, so we can generate .csv file without any third party library.
It is very simple, quickly, fast and easy to use.

Use listed below code.

showdata.jsp
============================================================
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.text.*" %>
<%@ page import="java.util.StringTokenizer" %>
<%
// made cdb connection here
PreparedStatement psTestUser = conn.prepareStatement("SELECT *from emp");
ResultSet rsTestUser=psTestUser.executeQuery();
String test_login_id,skills_text,desig_text;
ArrayList<String> l1 = new ArrayList<String>();
l1.add("Login,Skills,Design.");
%>
<body>
<a href="download_excel.jsp">download_excel</a>
<table width="100%"  height="600" align="left" border="0">
  <tr>
    <td><strong>User Name</strong></td>
    <td><strong>Designation</strong></td>
    <td><strong>Skills</strong></td>
  </tr>
<%
while (rsTestUser.next()){
%>
  <tr>
    <td><%=rsTestUser.getString("login") %></td>
    <td><%=decryptA(rsTestUser.getString("skills")) %></td>
    <td><%=rsTestUser.getString("design") %></td>
  </tr>
  <%
StringBuilder sb=new StringBuilder();
sb.append(rsTestUser.getString("login")+","+rsTestUser.getString("skills")+",");
sb.append(decryptA(rsTestUser.getString("design")));
l1.add(sb.toString());
}
session.setAttribute("listResult",l1);
%>
</table>
</body>
</html>
<%
// close database connection here
%>


download_excel.jsp
=========================
<%@ page import="java.util.ArrayList"%>
<%
response.setContentType("application/csv");
response.setHeader("content-disposition","filename=test.csv");
ArrayList<String> list = (ArrayList<String>)session.getAttribute("listResult");
for(int i = 0; i < list.size(); i++) {
    String myString = (String)list.get(i);
    out.println(myString);
}
out.flush();
out.close();
%>
Share:

Thursday, March 12, 2015

TORCH IN ANDROID



If Torch in your mobile is not existing then download this Android App and you will get torch in your android mobile.


DOWNLOAD TORCH IN ANDROID HERE
Share:

Wednesday, November 12, 2014

How to show place in Google map

How to show place in Google map
-----------------------------------


























1) Create a table "latandlon" in Mysql/Oracle/Sqlserver/DB2 in which you feel easy.

CREATE TABLE latandlon (
  id int(11) NOT NULL auto_increment,
  lat decimal(10,6) NOT NULL default '0.000000',
  lon decimal(10,6) NOT NULL default '0.000000',
  address varchar(255) NOT NULL default '',
  PRIMARY KEY  (id)
);


2) feed the listed below data.
----------------------------------------------------------
id,     lat,            lon,            address
----------------------------------------------------------
1    23.402800    78.454100    Madhya Pradesh
2    26.280000    80.210000    Kanpur
3    31.122027    77.111664    Himanchal Pradesh
4    22.533000    88.367000    Kolkata
5    28.350000    77.120000    Delhi
6    17.230000    78.290000    Hyderabad
----------------------------------------------------------


3) put youe google map key in the index.jsp.


 <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%
// How to show place in google map
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">  
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<script src="http://maps.google.com/maps?file=api&v=2&key=YOURKEYHERE" type="text/javascript">
</script>
<body>
<p><strong>locations in India</strong></p>
<div id="map" style="width: 800px; height: 600px"></div>

<script type="text/javascript">
//<![CDATA[
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addControl(new GScaleControl());
map.setCenter(new GLatLng(23.402800, 78.454100), 5, G_NORMAL_MAP);
function createMarker(point, number)
{
var marker = new GMarker(point);
var html = number;
GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});
return marker;
};
<%
    String userName = "root";
    String password = "";
    String url = "jdbc:mysql://localhost:3306/test";
    try{
        String driver = "com.mysql.jdbc.Driver";
        Class.forName(driver).newInstance();
        Connection conn;
        conn = DriverManager.getConnection(url, "root","");
        Statement s = conn.createStatement ();
        s.executeQuery ("SELECT *from latandlon");
        ResultSet rs = s.getResultSet ();
        int count = 0;
        while (rs.next ()) {
            String lat = rs.getString ("lat");
            String lon = rs.getString ("lon");
            String address=rs.getString ("address");
            out.print("var point = new GLatLng("+lat+","+lon+");\n");
            out.print("var marker = createMarker(point, '"+address+"');\n");
            out.print("map.addOverlay(marker);\n");
            out.print("\n");
        }
        rs.close ();
        s.close ();
    }
    catch(Exception ee){
        System.out.println(ee.toString());  
    }
%>
//]]>
</script>
</body>
</html>

4) change the database connection string in the index.jsp page, coz I have used MySql.






Share:

Friday, October 17, 2014

Extract Corrupt Zip File By 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();
}
}
}




Share:

Friday, October 03, 2014

TIFF Reader in java

TIFF File Reader

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





Share:

Sunday, September 21, 2014

Get cookies in java

How to 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());
    }
    }
}

Share:

Saturday, August 30, 2014

Couldn't open stream {imap.gmail.com:993/imap/ssl}INBOX in

Couldn't open stream {imap.gmail.com:993/imap/ssl}INBOX in

While connecting with Google gmail via PHP , Java or any other code you may be face this error and get the message as listed below:
"Couldn't open stream {imap.gmail.com:993/imap/ssl}INBOX"

To overcome this problem logon your gmail and set permission via this link:
https://www.google.com/settings/security/lesssecureapps

After that you will be able to login via any programming languages.




Share:

Thursday, August 14, 2014

Generate CSV in jsp without third party utility

Generate CSV in jsp without third party utility

There are lot of third party paid and free utility that generate CSV file in JSP/Java. but the problems are to hard to implement. and may utility first create CSV file in the server, so Server space will be consumed.
To overcome all the problem I have created listed below the code. You are free to use it in you project.

<%@ page import="java.util.ArrayList"%>
<%
response.setContentType("application/csv");
response.setHeader("content-disposition","filename=test.csv");
// the session.getAttribute("listResult") is containg of comma sepearte multiple lines as listed below
//aa,10,20,30
//bb,10,20,30
//cc,10,20,30
//dd,10,20,30

ArrayList<String> list = (ArrayList<String>)session.getAttribute("listResult");
out.println("<table border='1'>");
for(int i = 0; i < list.size(); i++) {
    String myString = (String)list.get(i);

    out.println(myString);


}

out.flush();
out.close();
%>
Share:

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));


    }
}
Share:

Wednesday, May 07, 2014

Mouse Pointer info in java

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();
    }
}
Share:

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



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



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());
        }
    }
 





Share:

Saturday, December 21, 2013

How to Terminate JSP Process

How to Terminate JSP Process

use:
out.close();
Share:

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();


Share:

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

}












Share:

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







Share:

Sunday, November 10, 2013

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);
%>



Share:

Ads Inside Post

Powered by Blogger.

Archive