View Javadoc
1   /**
2    * This Source Code Form is subject to the terms of the Mozilla Public
3    * License, v. 2.0. If a copy of the MPL was not distributed with this
4    * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5    *
6    * If it is not possible or desirable to put the notice in a particular
7    * file, then You may include the notice in a location (such as a LICENSE
8    * file in a relevant directory) where a recipient would be likely to look
9    * for such a notice.
10  
11   * 
12   */
13   
14  /*  ---------------------------------------------------------------------------
15   *  U.S. Government, Department of the Army
16   *  Army Materiel Command
17   *  Research Development Engineering Command
18   *  Communications Electronics Research Development and Engineering Center
19   *  ---------------------------------------------------------------------------
20   */
21  
22  package org.miloss.fgsms.services.reporting;
23  
24  import java.io.ByteArrayInputStream;
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.sql.Connection;
28  import java.sql.PreparedStatement;
29  import java.sql.ResultSet;
30  import java.util.Calendar;
31  import java.util.GregorianCalendar;
32  import javax.servlet.ServletException;
33  import javax.servlet.ServletOutputStream;
34  import javax.servlet.http.HttpServlet;
35  import javax.servlet.http.HttpServletRequest;
36  import javax.servlet.http.HttpServletResponse;
37  import javax.xml.bind.JAXBContext;
38  import javax.xml.bind.JAXBElement;
39  import javax.xml.bind.Unmarshaller;
40  import javax.xml.stream.XMLInputFactory;
41  import javax.xml.stream.XMLStreamReader;
42  import org.miloss.fgsms.common.AuditLogger;
43  import org.miloss.fgsms.common.Utility;
44  import org.apache.log4j.Level;
45  import org.miloss.fgsms.common.Logger;;
46  import org.miloss.fgsms.common.DBUtils;
47  import org.miloss.fgsms.services.interfaces.automatedreportingservice.ReportDefinition;
48  
49  /**
50   * This little servlet will attempt to fetched a zipped csv/html report from the fgsms database. These reports are scheduled by the 
51   * Automated Reporting Service and are generated by the fgsms.ReportGenerator
52   * @author AO
53   * @since 6.2
54   */
55  public class ReportFetch extends HttpServlet {
56  
57      /**
58       * Processes requests for both HTTP
59       * <code>GET</code> and
60       * <code>POST</code> methods.
61       *
62       * @param request servlet request
63       * @param response servlet response
64       * @throws ServletException if a servlet-specific error occurs
65       * @throws IOException if an I/O error occurs
66       */
67      protected void processRequest(HttpServletRequest request, HttpServletResponse response)
68              throws ServletException, IOException {
69          String user = null;
70          if (request.getUserPrincipal() != null) {
71              user = request.getUserPrincipal().getName();
72          }
73          if (user==null)
74              user="anonymouse";
75          String reportid = request.getParameter("reportid");
76          ServletOutputStream out = response.getOutputStream();
77          Connection con = Utility.getPerformanceDBConnection();
78          PreparedStatement cmd =null;
79          ResultSet rs=null;
80          try {
81  
82  
83              if (Utility.stringIsNullOrEmpty(user)) {
84                  response.sendError(401, "Authorization Required");
85              } else if (Utility.stringIsNullOrEmpty(user)) {
86                  response.sendError(400, "Bad request, a report id is required");
87              } else {
88  
89  //arsjobs.owninguser=? and
90                  cmd = con.prepareStatement("select hasextrapermissions, reportdef, owninguser, reportcontents, arsjobs.jobid as JOB from arsjobs, arsreports where arsjobs.jobid=arsreports.jobid and  arsreports.reportid=? ");
91  //                cmd.setString(1, user);
92                  cmd.setString(1, reportid);
93                  rs = cmd.executeQuery();
94                  if (rs.next()) {
95                      boolean accessCheck = false;
96                      boolean accesscontrolrules = rs.getBoolean("hasextrapermissions");
97                      if (user.equalsIgnoreCase(rs.getString("owninguser"))) {
98                          accessCheck = true;
99                      }
100                     if (accesscontrolrules) {
101                         ReportDefinition def = null;
102                         //load the job from xml   ReportDefinition ret = null;
103                         JAXBContext GetARSSerializationContext = Utility.getARSSerializationContext();
104                         Unmarshaller u = GetARSSerializationContext.createUnmarshaller();
105                         byte[] s = rs.getBytes("reportdef");
106                         ByteArrayInputStream bss = new ByteArrayInputStream(s);
107                         XMLInputFactory xf = XMLInputFactory.newInstance();
108                         XMLStreamReader r = xf.createXMLStreamReader(bss);
109                         JAXBElement<ReportDefinition> foo = (JAXBElement<ReportDefinition>) u.unmarshal(r, ReportDefinition.class);
110                         if (foo != null && foo.getValue() != null) {
111                             def = foo.getValue();
112                         }
113 
114                         if (def != null) {
115                             for (int i = 0; i < def.getAdditionalReaders().size(); i++) {
116                                 if (def.getAdditionalReaders().get(i).equalsIgnoreCase(user)) {
117                                     accessCheck = true;
118                                 }
119                             }
120                         }
121                     }
122                     if (accessCheck) {
123                         AuditLogger.logItem("ServletReportFetcher", "GET (access a stored report)", user, "Report id " + reportid + " Job id " + rs.getString("JOB"), "unspecified", null);
124                         response.setHeader("contentType", "application/zip");
125                         response.setHeader("Cache-Control", "no-cache");
126                         response.setHeader("Content-disposition", "attachment; filename=\"report"
127                                 + GregorianCalendar.getInstance().get(Calendar.YEAR)
128                                 + (GregorianCalendar.getInstance().get(Calendar.MONTH) + 1)
129                                 + GregorianCalendar.getInstance().get(Calendar.DATE) + "-" + reportid + ".zip\"");
130                         response.setStatus(200);
131                         response.setCharacterEncoding("UTF-8");
132                         byte[] buffer = new byte[1024];
133                         InputStream binaryStream = rs.getBinaryStream("reportcontents");
134                         int x = binaryStream.read(buffer);
135 
136 
137                         while (x > 0) {
138                             out.write(buffer, 0, x);
139                             x = binaryStream.read(buffer);
140                         }
141 
142                         binaryStream.close();
143                     } else {
144                         AuditLogger.logItem("ServletReportFetcher", "GET (access a stored report)", user, "ACCESS DENIED Report id " + reportid + " Job id " + rs.getString("JOB"), "unspecified", null);
145                         response.sendError(403, "Access Denied");
146                     }
147                 } else {
148                     response.sendError(404, "Report Not Found");
149 
150                 }
151                 rs.close();
152                 cmd.close();
153             }
154 
155             con.close();
156         } catch (Exception ex) {
157             Logger.getLogger("report fetcher").log(Level.FATAL, null, ex);
158             AuditLogger.logItem("ServletReportFetcher", "GET (access a stored report)", user, "ERROR Report id " + reportid + " " + ex.getMessage(), "unspecified", null);
159             response.sendError(500);
160         } finally {
161             out.close();
162             DBUtils.safeClose(rs);
163             DBUtils.safeClose(cmd);
164             DBUtils.safeClose(con);
165         }
166     }
167 
168 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
169     /**
170      * Handles the HTTP
171      * <code>GET</code> method.
172      *
173      * @param request servlet request
174      * @param response servlet response
175      * @throws ServletException if a servlet-specific error occurs
176      * @throws IOException if an I/O error occurs
177      */
178     @Override
179     protected void doGet(HttpServletRequest request, HttpServletResponse response)
180             throws ServletException, IOException {
181         processRequest(request, response);
182     }
183 
184     /**
185      * Handles the HTTP
186      * <code>POST</code> method.
187      *
188      * @param request servlet request
189      * @param response servlet response
190      * @throws ServletException if a servlet-specific error occurs
191      * @throws IOException if an I/O error occurs
192      */
193     @Override
194     protected void doPost(HttpServletRequest request, HttpServletResponse response)
195             throws ServletException, IOException {
196         processRequest(request, response);
197     }
198 
199     /**
200      * Returns a short description of the servlet.
201      *
202      * @return a String containing servlet description
203      */
204     @Override
205     public String getServletInfo() {
206         return "fgsms Report Fetcher";
207     }// </editor-fold>
208 }