Pages

Saturday, June 29, 2013

Spring MVC - Utility Project To Download files - Access log files from restricted environments

In development as well as maintenance projects you may have to access the log files to see what went wrong. However in some environments the developers may not have access to these log files. The developers has to request for these log files and it is a time consuming process. So if accessing log files implemented as part of the application itself it will save lot of time for the development team members.

However please note, this functionality should be used only when it is appropriate.

Technologies & Tools used

1. STS
2. Maven

Step 1:

Create Spring MVC project using the steps given here

Step 2:

Add showLogs and handleFileDownload method as shown below.

1:  package com.ravi.springmvc;  
2:  import java.io.File;  
3:  import java.io.FileInputStream;  
4:  import java.text.DateFormat;  
5:  import java.util.Date;  
6:  import java.util.Locale;  
7:  import javax.servlet.http.HttpServletResponse;  
8:  import org.slf4j.Logger;  
9:  import org.slf4j.LoggerFactory;  
10:  import org.springframework.stereotype.Controller;  
11:  import org.springframework.ui.Model;  
12:  import org.springframework.util.FileCopyUtils;  
13:  import org.springframework.validation.BindingResult;  
14:  import org.springframework.web.bind.annotation.ModelAttribute;  
15:  import org.springframework.web.bind.annotation.RequestMapping;  
16:  import org.springframework.web.bind.annotation.RequestMethod;  
17:  import org.springframework.web.servlet.ModelAndView;  
18:  /**  
19:   * Handles requests for the application home page.  
20:   */  
21:  @Controller  
22:  public class HomeController {  
23:       private static final Logger logger = LoggerFactory  
24:                 .getLogger(HomeController.class);  
25:       @ModelAttribute("logFile")  
26:       public LogFile getLogFile() {  
27:            return new LogFile();  
28:       }  
29:       /**  
30:        * Simply selects the home view to render by returning its name.  
31:        */  
32:       @RequestMapping(value = "/", method = RequestMethod.GET)  
33:       public String home(Locale locale, Model model) {  
34:            logger.info("Welcome home! The client locale is {}.", locale);  
35:            Date date = new Date();  
36:            DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,  
37:                      DateFormat.LONG, locale);  
38:            String formattedDate = dateFormat.format(date);  
39:            model.addAttribute("serverTime", formattedDate);  
40:            return "home";  
41:       }  
42:       @RequestMapping("/showlogs")  
43:       public ModelAndView showLogs() {  
44:            return new ModelAndView("logs", "command", new LogFile());  
45:       }  
46:       @RequestMapping(value = "/logs")  
47:       public void handleFileDownload(@ModelAttribute("log") LogFile log,  
48:                 BindingResult result, HttpServletResponse res) throws Exception {  
49:            try {  
50:                 String fn = log.getLogFileLocation();  
51:                 File f = new File(fn);  
52:                 System.out.println("Loading file " + fn + "(" + f.getAbsolutePath()  
53:                           + ")");  
54:                 if (f.exists()) {  
55:                      res.setContentType("application/text");  
56:                      res.setContentLength(new Long(f.length()).intValue());  
57:                      res.setHeader("Content-Disposition",  
58:                                "attachment; filename=Test.log");  
59:                      FileCopyUtils.copy(new FileInputStream(f),  
60:                                res.getOutputStream());  
61:                 } else {  
62:                      System.out.println("File" + fn + "(" + f.getAbsolutePath()  
63:                                + ") does not exist");  
64:                 }  
65:            } catch (Exception e) {  
66:                 System.out.println(e.getMessage());  
67:                 throw e;  
68:            }  
69:       }  
70:  }  

Step 3

Add the JSP file which allows the user to download to specific log file.

1:  <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
2:  <html>  
3:  <head>  
4:       <title>Spring 3 MVC - Log Manager</title>  
5:  </head>  
6:  <body>  
7:  <h2>Log Manager</h2>  
8:  <form:form method="post" action="logs.html">  
9:       <table>  
10:       <tr>  
11:            <td><form:label path="logFileLocation">Log File Location</form:label></td>  
12:            <td><form:input path="logFileLocation" /></td>   
13:       </tr>  
14:       <tr>  
15:       </tr>  
16:       <tr>  
17:            <td colspan="2">  
18:                 <input type="submit" value="Fetch Log"/>  
19:            </td>  
20:       </tr>  
21:  </table>       
22:  </form:form>  
23:  </body>  
24:  </html>  

Step 4

Run the application and the application can be accessed in the url http://localhost:8080/springmvc/showlogs


Step 5

Your log files will be downloaded as shown below.










This tutorial is for illustration purposes only. Do not use this in real life scenario without adding specific security measurements as this application will allow you to download all the files for which the user has access to.

No comments:

Post a Comment

 
Blogger Templates