Sunday, February 26, 2012

FileUpload using jersey

today i learnt to implement file uploading using jersey

@Path("fileupload")
public class FileUploadResource {

@POST
@Produces("text/plain")
public String loadFile(@Context HttpServletRequest request) {
String resultStatus="fail";
String fileRepository="d:\\"; //the files u choose to upload will be uploaded to this d. directory
//servlet file upload handles multiple files in a html widget

if (ServletFileUpload.isMultipartContent(request)) {//checks if the servlet request contains multipart data.
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items=null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {

e.printStackTrace();
}
if(items!=null) {
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
    if(!item.isFormField() && item.getSize() > 0) {
    String fileName = processFileName(item.getName());
    try {
item.write(new File(fileRepository+fileName));
//the write methodn writes uploaded file into the disk
} catch (Exception e) {
e.printStackTrace();
}
        resultStatus="ok";
    }
}
}
}
return resultStatus;
}

private String processFileName(String fileNameInput) {
String fileNameOutput=null;
fileNameOutput = fileNameInput.substring(fileNameInput.lastIndexOf("\\")+1,fileNameInput.length());
//extracts the name of the file
return fileNameOutput;
}
ur file will be uploaded to the directory

Saturday, February 25, 2012

JAXB (JAVA ARCHITECTURE FOR XML BINDING)

java objects are created to and from XML.the different annotations will be described in the program below.
1)Book.java(a class with getter setter methods)

XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = {"name", "id"})  //the order of output in XML.
public class Book {

    String name;
    int id;
    // If you like the variable name, e.g. "name", you can easily change this
    // name for your XML-Output:

    @XmlElement(name = "bookName")//will see the change when u see the XML as output
2)BookStore.java(a class with an arraylist and getter setter methods)

//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "jaxb implementation")//when u say namespace that means root element of XML.
public class BookStore {
// XmLElementWrapper generates a wrapper element around XML representation

    @XmlElementWrapper(name = "bookList")
    // XmlElement sets the name of the entities
    @XmlElement(name = "book")
    private ArrayList<Book> bookList;
    private String name;
    private String location;
3)BookMain.java the main class
set the values and include the book class object in the arraylist.also .
class x{
private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";
public static void main(){

// create JAXB context and instantiate marshaller
        JAXBContext context = JAXBContext.newInstance(BookStore.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(bookstore, System.out);

        Writer w = null;
        try {
            w = new FileWriter(BOOKSTORE_XML);
            m.marshal(bookstore, w);
        } finally {
            try {
                w.close();
            } catch (Exception e) {
            }
            // get variables from our xml file, created before
            System.out.println();
            System.out.println("Output from our XML File: ");
            Unmarshaller um = context.createUnmarshaller();
     
          BookStore bookstore2 =  (BookStore) um.unmarshal(new FileReader(
                    BOOKSTORE_XML));

           for (int i = 0; i < bookstore2.getBooksList().toArray().length; i++) {
                System.out.println("Book " + (i + 1) + ": "
                      +"id:"  + bookstore2.getBooksList().get(i).getId()+ " "
                     +"author"+":"+ bookstore2.getBooksList().get(i).getName()+"location"+":"+bookstore2.getLocation());
            }

        }
    }
output:-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:bookStore xmlns:ns2="jaxb implementation">//see the rootelement
    <bookList>
        <book>
            <name>sougata</name>
            <bookName>6974</bookName>//see the name change"bookname"
        </book>
    </bookList>
    <location>Frankfurt Airport</location>
    <name>Fraport Bookstore</name>
</ns2:bookStore>

Output from our XML File:
Book 1: id:6974 author:sougata location:Frankfurt Airport

Java Restful API

Rest is an architecture(not a technology mind it) where everything is a resource.now the resource is accessed via some HTTP methods.
here there is a rest server as well as a rest client.same as old ways.the server provides access to the resources and the client makes access to resource as well as can modify the resources.resources are identified by global ids.rest allows resources have different representations.client can get different outputs.(i.e xml,html,json).methods that are supported are get,post,delete,put.
Java defines standard REST support via JAX-RS (The Java API for RESTful Web Services)

@Path("/test")
public class testjersey {
// This method is called if TEXT_PLAIN is request 
@GET
//the class registers its methods for the get request using @GET annotation.Using the @Produces annotation, it defines that it can deliver several MIME types, text, XML and HTML. 
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersaey";
}

// This method is called if XML is request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersddddey" + "</hello>";
}

// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jeffrsey" + "</title>"
+ "<body><h1>" + "Hello Jerseay" + "</body></h1>" + "</html> ";
}
}
the url to access the webapp is like this( http://localhost:8080/resources/test)
see resources is the servlet mapping in web.xml and test is the name of path(base- uri) in the resource.the browser requests the html representation of your resource.so the output will be: Hello Jerseay 

Wednesday, February 22, 2012

Integrate IBM DB2 with netbeans

I have always loved working with mysql databases.but this time as i was making an attempt for IBM -TGMC ,i had to strictly use IBM tools..so IBM DB2 caused much problems initially.but finally got over it.
below are some snapshots to integrate DB2 with IBM
1.first as the old way go to Drivers->right click-new driver








2)













when u click add browse for the db2jcc.jar and db2jcc4.jar where u have db2 installed.db2/sqllib/java(here u will find those jara).now clicking ok the new ibm2 universal driver gets installed.
now again the old way create a new connection as shown in the snapshot below

Tuesday, February 21, 2012

Mouse Not working??

my USB optical mouse was not working for the past 6 months.i hardly cared.but for the past few days my fingers are feeling the pain of touch pad.so today morning i decided to make my mouse work.made restarts didnt work.

so what i did-
go to control panel->performance and maintenance ->system->hardware->device manager

now find the human interface device.expand and find update the USB human interface driver.
as it got updated the mouse started working flawlessly.:))

Saturday, February 18, 2012

Dealing with the netbeans and eclipse error.

Sometimes we often see errors like deployement error port already in use,while we were doing some useful work.i searched throughout the internet.people said do this,do that.really i tried all but didnt help.and so i had to wait for my luck that when will the error go.sometimes it worked on with a restart sometimes it took days.

the best answer is:download a TCP view software.now look for ports which you saw in the error msg.


run tcp view and close the necessary ports.then run your program again.this will ceratainly do.

Friday, February 17, 2012

Working on security for my final year project.(Testing )

Filters:Little bit on life cycle
The init() method is used to initialize any code that is used by Filter. Also note that, init() method will get an object of FilterConfig which contains different Filter level information as well as init parameters which is passed from Web.xml (Deployment descriptor).

The doFilter() method will do the actual logging of information. You can modify this method and add your code which can modify request/session/response, add any attribute in request etc.
The destroy() method is called by the container when it wants to garbage collect the filter. This is usually done when filter is not used for long time and server wants to allocate memory for other applications.
Tested a very simple web project.
web.xml(only the flter configuration showed)
    <filter>
        <filter-name>LogFilter</filter-name>
        <filter-class>com.in.Filter.LogFilter</filter-class>
        <init-param>
            <param-name>test-param</param-name>
            <param-value>This is for testing</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>LogFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
     </web-app>

the FILTER
public class LogFilter implements Filter {
    private static final boolean debug = true;
    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;
    public LogFilter() {
    }
    private void doBeforeProcessing(ServletRequest request, ServletResponse response)//abstract methods
            throws IOException, ServletException {
    }

    private void doAfterProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        RequestDispatcher rd = null;
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        rd = getFilterConfig().getServletContext().getRequestDispatcher("/LoginServlet");
        if (rd != null) {
            rd.include(req, res);
        }
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        Throwable problem = null;
        try {
            chain.doFilter(request, response);
        } catch (Throwable t) {
            // If an exception is thrown somewhere down the filter chain,
            // we still want to execute our after processing, and then
            // rethrow the problem after that.
            problem = t;
            t.printStackTrace();
        }
        // If there was a problem, we want to rethrow it if it is
        // a known type, otherwise log it.
        if (problem != null) {
            if (problem instanceof ServletException) {
                throw (ServletException) problem;
            }
            if (problem instanceof IOException) {
                throw (IOException) problem;
            }
            sendProcessingError(problem, response);
        }
        //Get the IP address of client machine.
        String ipAddress = request.getRemoteAddr();

        //Log the IP address and current timestamp.
        System.out.println("IP " + ipAddress + ", Time "
                + new Date().toString());
   HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String name=req.getParameter("user");
        System.out.println(""+name);//as it is a filter and in xml see the mapping.the url pattern is /*.so after     //getting the servlet i again shows the value in the filter.from this we can know abut any unauthorized //access.

        doAfterProcessing(request, response);
        chain.doFilter(request, response);
    }

    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter 
     */
    public void destroy() {
    }

    /**
     * Init method for this filter 
     */
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        
        //Get init parameter
        String testParam = filterConfig.getInitParameter("test-param");

        //Print the init parameter
        System.out.println("Test Param: " + testParam);
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        if (filterConfig == null) {
            return ("LogFilter()");
        }
        StringBuffer sb = new StringBuffer("LogFilter(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }

    private void sendProcessingError(Throwable t, ServletResponse response) {
    }

    public static String getStackTrace(Throwable t) {
        String stackTrace = null;
        try {
        } catch (Exception ex) {
        }
        return stackTrace;
    }

    public void log(String msg) {
        filterConfig.getServletContext().log(msg);
    }
}