Showing posts with label Back To School. Show all posts
Showing posts with label Back To School. Show all posts

Friday, March 27, 2009

How to Unzip a File

Follow the steps given below to Unzip a file on Server:

1. Create a File object from the uplodaded data - If you have used Struts framwork to upload a Zip file, then first get the FormFile object (org.apache.struts.upload.FormFile).

FormFile formFile = form.getFileProperties();

From FormFile object get the InputStream.

InputStream inputStream = formFile.getInputStream();

In case we are getting the data within a hidden field in base-64 / zipped format, FormFile is null. In that case get the byte[] data using: sun.misc.BASE64Decoder().decodeBuffer() method if Enctype is *B64*

if(form.getEnctype().equals("*B64*"))
byte[] rawData = sun.misc.BASE64Decoder().decodeBuffer(form.Data());


Create ByteArryaIntputStream from byte[] data.

InputStream inputStream = new ByteArrayInputStream(rawData);

Now create a File object in which you want to read the InputStream.

File fileObj = new File("test.zip");

Create a FileOutputStream from the File object.

OutputStream outputStream = new FileOutputStream(fileObj);

Now read the IntputStream and write it to OutputStream.

2. Once the File object is created, next is to create a ZipFile (java.util.zip.ZipFile) object from it.

ZipFile zipFile = new ZipFile(fileObject);

3. Iterate through the ZipFile to read the zip and extract its contents.

Below is the complete soure code.

import org.apache.struts.upload.*;

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

public class unzipUtility
{
public static final String B64String = "*B64*";

public void unzipFile(ActionForm form)
{
InputStream inputStream = null;
OutputStream outputStream = null;

File fileObj = new File("test.zip");

FormFile formFile = form.getFormFile();// not the standard method

if(formFile!=null)
{
inputStream = formFile.getInputStream();
}
else
{
byte[] rawData = null;

if(form.getEnctype().equals(B64String))
{
rawData = new sun.misc.BASE64Decoder().decodeBuffer(form.getData());
}

inputStream = new ByteArrayInputStream(
rawData);
}

outputStream = FileOutputStream(fileObj);
copyStream(inputStream, outputStream);
}

private byte[] getRawData(String content)
{

}// getRawData()

private void copyStream(InputStream input, OutputStream output)
{
int size;
byte[] buffer = new byte[1024];

while((size=input.read(buffer))>=0)
{
output.write(buffer, 0, size);
}//while

input.close();
output.close();
}//copyStream()

public void unzip(File fileObj)
{
Enumeration entries;
ZipFile zipFile;

try {
zipFile = new ZipFile(fileObj);

entries = zipFile.entries();

while(entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();

if(entry.isDirectory()) {
// Assume directories are stored parents first then children.
System.err.println("Extracting directory: " + entry.getName());
// This is not robust, just for demonstration purposes.
(new File(entry.getName())).mkdir();
continue;
}

System.err.println("Extracting file: " + entry.getName());
copyInputStream(zipFile.getInputStream(entry),
new BufferedOutputStream(new FileOutputStream(entry.getName())));
}

zipFile.close();
} catch (IOException ioe) {
System.err.println("Unhandled exception:");
ioe.printStackTrace();
return;
}
}

}

Friday, May 25, 2007

What is Encapsulation?

Encapsulation refers to the bundling of data with the methods that operate on that data. Often that definition is misconstrued to mean that the data is somehow hidden. In Java, you can have encapsulated data that is not hidden at all.

Encapsulation or equivalently information hiding refers to the practice of including within an object everything it needs, and furthermore doing this in such a way that no other object need ever be aware of this internal structure.

What is Abstraction?

Here are couple of definitions of Abstraction -

Abstraction (from the Latin abs, meaning away from and trahere, meaning to draw) is the process of taking away or removing characteristics from something in order to reduce it to a set of essential characteristics. In object-oriented programming, abstraction is one of three central principles (along with encapsulation and inheritance). Through the process of abstraction, a programmer hides all but the relevant data about an object in order to reduce complexity and increase efficiency. In the same way that abstraction sometimes works in art, the object that remains is a representation of the original, with unwanted detail omitted. The resulting object itself can be referred to as an abstraction, meaning a named entity made up of selected attributes and behavior specific to a particular usage of the originating entity. Abstraction is related to both encapsulation and data hiding.

Abstraction is the process of hiding the details and exposing only the essential features of a particular concept or object.

A view of a problem that extracts the essential information relevant to a particular purpose and ignores the remainder of the information.

The essence of abstraction is to extract essential properties while omitting inessential details.

Tuesday, May 8, 2007

What is the difference between <%@ include file="abc.jsp" %> and <jsp:include page="abc.jsp" %> ?

The <%@include file="abc.jsp"%> directive acts like C "#include", pulling in the text of the included file and compiling it as if it were part of the including file. The included file can be any type (including HTML or text).

The <jsp:include page="abc.jsp"> tag compiles the file as a separate JSP file, and embeds a call to it in the compiled JSP.

Some JSP engines support the non-standard tags <!--#include file="data.inc"--> (NCSA-, or .shtml-style) and <%@ vinclude="data.inc" %> (JRun-style), but these are not defined in the JSP spec and thus cannot be relied on.

Wednesday, March 21, 2007

Java Core

Upcasting and Downcasting

A super class reference can be converted into a subclass reference but thissubclass reference is not useful to call the methods of any of the classes. This convention is known as Downcasting.

We can convert the subclass reference to a superclass reference without using the cast poeration compiler because it will internally take care of the casting. This is known as Upcasting.





Use Content-Disposition to Send a File

While we're on the subject of magic header incantations, servlet developers often struggle with finding the right header combination to send a browser a file that's intended for saving rather than viewing and thus triggers a "Save As" dialog. For the solution to this problem, I have some good news and some bad news.

The bad news is that although the HTTP specification provides a mechanism for file downloads (see HTTP/1.1, Section 19.5.1), many browsers second-guess the server's directives and do what they think is best rather than what they're told. These browsers--including Microsoft Internet Explorer and Opera--look at the file extension and "sniff" the incoming content. If they see HTML or image content, they inline-display the file contents instead of offering a Save As dialog.[3] Turns out there's no 100% reliable way to download a file across all browsers. Perhaps, with this effort, programmers are more like alchemists than magicians, trying in vain to turn lead into gold.

The good news is that the right combination of headers will download files well enough to be practical. With these special headers set, a compliant browser will open a Save As dialog, while a noncompliant browser will open the dialog for all content except HTML or image files. For these types it will display the content inline, where a user can use the menu to save the content. Example-1 shows the best technique for sending files.

Example-1: Sending a file for download // Set the headers.

res.setContentType("application/x-download");
res.setHeader("Content-Disposition", "attachment; filename=" + filename);
// Send the file.
OutputStream out = res.getOutputStream( );
returnFile(filename, out); // Shown earlier in the chapter


First, set the Content-Type header to a nonstandard value such as application/x-download. It's very important that this header is something unrecognized by browsers because browsers often try to do something special when they recognize the content type.[4] Then set the Content-Disposition header to the value attachment; filename=foo, in which foo is substituted with the filename to be used by default in the Save As dialog. Finally, send the file content as bytes. The bytes can come from the filesystem or be dynamically generated.

Using these headers, the file content in the response will be saved by most browsers or, in worst cases, displayed inline where the user can save the file. There's no standard way to download multiple files in one response.

Finally, it can be useful to include the download file's name as extra path information to the servlet. The servlet can use the filename to learn which file to download, or it can ignore the extra path info. Either way, it's useful because the name appears to the browser as the name of the resource being retrieved, and browsers often use that name in the Save As dialog prompt. For example, instead of serving content from /servlet/FileDownload?fileid=5, serve it from /servlet/FileDownload/inventory.pdf?fileid=5.




In which .jar file Object.class resides?

Object.class file is packed in rt.jar, which is available at \jre\lib. All the core class libraries that come with the JDK are stored in a file named "rt.jar".