Saturday, August 9, 2014

Initialize and access Spring in Web Application

---------------------------------------------------------- 
Initialize Spring  in web.xml
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/application-context.xml</param-value>
</context-param>
----------------------------------------------------------
Get Access to Spring Container
- getRequiredWebApplicationContext()
- getWebApplicationContext() of WebApplicationContextUtils:
----------------------------------------------------------

Saturday, August 2, 2014

Browsing File System Using Servlet

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jini.FileList;

public class FileServlet extends HttpServlet {
      
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       
            String path = (String) request.getParameter("path");
            System.out.println("PATH => " + path);
           
             ServletContext context = request.getServletContext();
             String realPath = context.getRealPath("/");
             StringBuilder realPathBuilder = new StringBuilder();
             realPathBuilder.append(realPath);
             realPathBuilder.append("<br/>");
             System.out.println("ACTUAL PATH were this servlet exists => " + realPath);
           
            if(null != path && path.length() == 0 ){
                existOnError(response);
                return;
            }
           
            File[] fileList= FileList.FileList(path);
            if(fileList == null){
                existOnError(response);
                return;
            }
           
            System.out.println("File List .................... "  );
            StringBuilder filebuilder= new StringBuilder();
            for(int i=0; i<fileList.length;i++){
                File file = fileList[i];
                // System.out.println(file.toString());
                filebuilder.append("<a href=\"");
                filebuilder.append(file.toString());
                filebuilder.append("\">");
                filebuilder.append(file.toString());
                filebuilder.append("</a>");
                filebuilder.append("<br/>");
                //<a href="url">Link text</a>
            } // end of for
            filebuilder.append("<br/>");
          System.out.println("Directory List ....................... "  );
          StringBuilder dirbuilder= new StringBuilder();
          fileList= FileList.DirectoryList(path);
            for(int i=0; i<fileList.length;i++){
                File file = fileList[i];
                // System.out.println(file.toString());
                dirbuilder.append(file.toString());
                dirbuilder.append("<br/>");
            } // end of for
           
              // Set response content type
              response.setContentType("text/html");
              PrintWriter out = response.getWriter();
              out.println("================== SERVLET ACTUAL PATH ==================" + "<br/>");
              out.println(realPathBuilder.toString());
              out.println("=================== FILE LIST ==================" + "<br/>");
              out.println(filebuilder.toString());
              out.println("=================== DIRECTORY LIST ==================" + "<br/>");
              out.println(dirbuilder.toString());
       
    } // end of doGet()
   
    void existOnError(HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("=================== Invalid or Empty Path  ==================" + "<br/>");

    }
}

=============================
  <servlet>
      <servlet-name>FileServlet</servlet-name>
    <servlet-class>com.jini.FileServlet</servlet-class>
  </servlet>
   <servlet-mapping>
    <servlet-name>FileServlet</servlet-name>
    <url-pattern>/filelist</url-pattern>
  </servlet-mapping>
============================

File List Util

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;

public class FileList {

    public static File[] FileList(String directoryName) {
        File dir = new File(directoryName);
        // // Filter files, not to return any files that start with `.'.
        // FilenameFilter filter = new FilenameFilter() {
        // public boolean accept(File dir, String name) {
        // return !name.startsWith(".");
        // }
        // };
        // This filter only returns directories
        FileFilter fileFilter = new FileFilter() {
            public boolean accept(File file) {
                return file.isFile();
            }
        };
        File[] files = dir.listFiles(fileFilter);
        return files;
    } // end of method

    public static File[] DirectoryList(String directoryName) {
        File dir = new File(directoryName);
        // This filter only returns directories
        FileFilter fileFilter = new FileFilter() {
            public boolean accept(File file) {
                return file.isDirectory();
            }
        };
        File[] files = dir.listFiles(fileFilter);
        return files;
    } // end of method

    public static String getCurrentDirPath() {
        File dir1 = new File(".");
        String currentDir = null;
        try {
            currentDir = dir1.getCanonicalPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currentDir;
    } // end of getCurrentDir()

    public static String getParent() {
        File dir1 = new File("..");
        String parrentDir = null;
        try {
            parrentDir = dir1.getCanonicalPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return parrentDir;
    } // end of getParrentDir()

    public static void createDirectoryIfNotExist(String directoryName) {
        File theDir = new File(directoryName);
          // if the directory does not exist, create it
          if (!theDir.exists())
          {
            boolean result = theDir.mkdir();
            if(result)            {  
               System.out.println("Directory created ... ");
             } // end of if
          }
        } // end of createDirectory()
   
    public static void main(String[] args) {
        String path = "C:\\";
        File[] fileList = FileList(path);
        System.out.println("File List .................... ");
        for (int i = 0; i < fileList.length; i++) {
            File file = fileList[i];
            System.out.println(file.toString());
        } // end of for

        System.out.println("Directory List ....................... ");
        fileList = DirectoryList(path);
        for (int i = 0; i < fileList.length; i++) {
            File file = fileList[i];
            System.out.println(file.toString());
        } // end of for

        System.out.println("Current Directory Path ....................... "
                + getCurrentDirPath());

        System.out
                .println("Parent Path ....................... " + getParent());
    } // end of main

} // end of class