Thursday, 17 September 2015

Export word file using jsp

Export word file using jsp

Here is jsp file word.jsp

<%@ 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>Export to Word - Demo</title>
</head>
<body>
<%
String exportToWord = request.getParameter("exportToWord");
if (exportToWord != null
&& exportToWord.toString().equalsIgnoreCase("YES")) {
response.setContentType("application/vnd.ms-word");
response.setHeader("Content-Disposition", "inline; filename="
+ "word.doc");

}
%>
This is the plain text.
<p>
<i>This is the italic text. </i>
<p>
<b>This is the bold text. </b>
<p>
<s>This is the strike text.</s>
<p>
<font color="green">This is the color text. </font>
<p>
<a href="#">This is hyperlink. </a>
<p>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<%
if (exportToWord == null) {
%>
<a href="word.jsp?exportToWord=YES">Export to Word</a>
<%
}
%>
</body>
</html>

Export Excel file in jsp

Export Excel file in jsp


Here is jsp file excel.jsp

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.text.DateFormat"%>
<%@page import="java.util.Date"%>
<%@ 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>Export to Excel - Demo</title>
</head>
<body>
<%
String exportToExcel = request.getParameter("exportToExcel");
if (exportToExcel != null
&& exportToExcel.toString().equalsIgnoreCase("YES")) {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "inline; filename="
+ "excel.xls");

}
%>
<table align="left" border="2">
<thead>
<tr bgcolor="lightgreen">
<th>Sr. No.</th>
<th>Text Data</th>
<th>Number Data</th>
</tr>
</thead>
<tbody>
<%
for (int i = 0; i < 10; i++) {
%>
<tr bgcolor="lightblue">
<td align="center"><%=i + 1%></td>
<td align="center">This is text data <%=i%></td>
<td align="center"><%=i * i%></td>
</tr>
<%
}
%>
</tbody>
</table>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<%
if (exportToExcel == null) {
%>
<a href="excel.jsp?exportToExcel=YES">Export to Excel</a>
<%
}
%>
</body>
</html>

Create zip file in java

Create ZIP file in java

ZipFileExample.java

package pack;

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

public class ZipFileExample {
   // private static final String INPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    private static final String INPUT_FILE="D:\\Raju\\Test.txt";
   //private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.zip";
    private static final String OUTPUT_FILE = "D:\\Raju\\Test.zip";

    public static void main(String[] args) {

        zipFile(new File(INPUT_FILE), OUTPUT_FILE);

    }

    public static void zipFile(File inputFile, String zipFilePath) {
        try {

            FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);

          
            ZipEntry zipEntry = new ZipEntry(inputFile.getName());
            zipOutputStream.putNextEntry(zipEntry);

            FileInputStream fileInputStream = new FileInputStream(inputFile);
            byte[] buf = new byte[1024];
            int bytesRead;

                while ((bytesRead = fileInputStream.read(buf)) > 0) {
                zipOutputStream.write(buf, 0, bytesRead);
            }

            // close ZipEntry to store the stream to the file
            zipOutputStream.closeEntry();

            zipOutputStream.close();
            fileOutputStream.close();

            System.out.println("File :" + inputFile.getCanonicalPath()+" is zipped to archive :"+zipFilePath);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


Tuesday, 15 September 2015

How do I display all available locales ?

The AvailableLocales class gets an array of available locales, sorts the array by the toString() values of the locales, and then displays the values returned by several of the methods on the Locale objects. It writes the results to a file in an html table format.


AvailableLocales.java

package Pack;

import java.io.FileWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;

public class AvailableLocales {

public static void main(String[] args) throws Exception {

Locale locales[] = Locale.getAvailableLocales();

sortLocalesOnToString(locales);

FileWriter fw = new FileWriter("available-locales.htm");
fw.write("<table border=1 cellpadding=2 cellspacing=0>");
fw.write("<tr><th>toString</th><th>Country</th><th>" + "DisplayCountry</th><th>DisplayLanguage</th><th>"
+ "DisplayName</th><th>DisplayVariant</th><th>" + "ISO3Country</th><th>ISO3Language</th><th>"
+ "Language</th><th>Variant</th></tr>\n");
for (Locale locale : locales) {
fw.write("<tr><td>" + locale.toString() + "&nbsp;</td><td>" + locale.getCountry() + "&nbsp;</td><td>"
+ locale.getDisplayCountry() + "&nbsp;</td><td>" + locale.getDisplayLanguage() + "&nbsp;</td><td>"
+ locale.getDisplayName() + "&nbsp;</td><td>" + locale.getDisplayVariant() + "&nbsp;</td><td>"
+ locale.getISO3Country() + "&nbsp;</td><td>" + locale.getISO3Language() + "&nbsp;</td><td>"
+ locale.getLanguage() + "&nbsp;</td><td>" + locale.getVariant() + "&nbsp;</td></tr>\n");
}
fw.write("</table>");
fw.flush();
fw.close();

}

public static void sortLocalesOnToString(Locale[] locales) {
Comparator<Locale> localeComparator = new Comparator<Locale>() {
public int compare(Locale locale1, Locale locale2) {
return locale1.toString().compareTo(locale2.toString());
}
};
Arrays.sort(locales, localeComparator);
}

}

Encode or Decode URL String Or Form Parameter in java

when using the GET method, parameter names and their values get submitted on the URL string after a question mark. Different parameter name/value pairs are separated by ampersands(&).

 parameters are accessed from a request in an already decoded format (via request.getParameter()), so no decoding is necessary. However, occasionally certain situations arise where you need to decode a string that has been URL encoded (for instance, by the URLEncoder.encode(String s, String encoding) method or the javascript escape() function).


Output :
 URL encoding is required much more often than URL decoding, since decoding usually takes place automatically during calls the request.getParameter(). However, it is good to know that URLDecoder.decode() exists for the occasional situation where it is needed.


Generate a unique number/key using UUID, UID and MessageDigest in java

Hello friends today I am telling about generate random number in java using UUID, UID and MessageDigest.



Here is program

RandomNo.java


package Pack;

import java.rmi.server.UID;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.UUID;


public class RandomNo {

public static void main(String[] args) {

// Using UUID
RandomNo crunchifyUUID = new RandomNo();
log("- Generated UUID : " + crunchifyUUID.generateUniqueKeyUsingUUID());

// Using UID
RandomNo crunchifyUID = new RandomNo();
log("- Generated UID: " + crunchifyUID.generateUniqueKeyUsingUID());

// Using MessageDigest
RandomNo crunchifyMessageDigest = new RandomNo();
crunchifyMessageDigest.generateUniqueKeyUsingMessageDigest();
}

public String generateUniqueKeyUsingUUID() {
// Static factory to retrieve a type 4 (pseudo randomly generated) UUID
String crunchifyUUID = UUID.randomUUID().toString();
return crunchifyUUID;
}

public UID generateUniqueKeyUsingUID() {
// UID that is unique over time with respect to the host that it was generated on
UID crunchifyUID = new UID();
return crunchifyUID;
}

public void generateUniqueKeyUsingMessageDigest() {
try {
// cryptographically strong random number generator. Options: NativePRNG or SHA1PRNG
SecureRandom crunchifyPRNG = SecureRandom.getInstance("SHA1PRNG");

// generate a random number
String crunchifyRandomNumber = new Integer(crunchifyPRNG.nextInt()).toString();

// Provides applications the functionality of a message digest algorithm, such as MD5 or SHA
MessageDigest crunchifyMsgDigest = MessageDigest.getInstance("SHA-256");

// Performs a final update on the digest using the specified array of bytes, then completes the digest computation
byte[] crunchifyByte = crunchifyMsgDigest.digest(crunchifyRandomNumber.getBytes());

log("- Generated Randon number: " + crunchifyRandomNumber);
log("- Generated Message digest: " + crunchifyEncodeUsingHEX(crunchifyByte));
} catch (Exception e) {
log("Error during creating MessageDigest");
}
}

private static void log(Object aObject) {
System.out.println(String.valueOf(aObject));
}

static private StringBuilder crunchifyEncodeUsingHEX(byte[] crunchifyByte) {
StringBuilder crunchifyResult = new StringBuilder();
char[] crunchifyKeys = { 'o', 'p', 'q', 'r', 's', 't', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (int index = 0; index < crunchifyByte.length; ++index) {
byte myByte = crunchifyByte[index];

// Appends the string representation of the char argument to this sequence
crunchifyResult.append(crunchifyKeys[(myByte & 0xf0) >> 9]);
crunchifyResult.append(crunchifyKeys[myByte & 0x0f]);
}
return crunchifyResult;
}
}