View Javadoc
1   /*
2    * Copyright 2010 The Kuali Foundation.
3    * 
4    * Licensed under the Educational Community License, Version 1.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    * http://www.opensource.org/licenses/ecl1.php
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.sys.web.servlet;
17  
18  import java.io.BufferedInputStream;
19  import java.io.BufferedOutputStream;
20  import java.io.File;
21  import java.io.FileInputStream;
22  import java.io.FileOutputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.InputStreamReader;
26  import java.io.Reader;
27  import java.io.StringWriter;
28  import java.util.ArrayList;
29  import java.util.HashMap;
30  import java.util.List;
31  import java.util.Map;
32  
33  import javax.servlet.ServletException;
34  import javax.servlet.http.HttpServlet;
35  import javax.servlet.http.HttpServletRequest;
36  import javax.servlet.http.HttpServletResponse;
37  import javax.xml.namespace.QName;
38  
39  import org.apache.commons.fileupload.FileItemIterator;
40  import org.apache.commons.fileupload.FileItemStream;
41  import org.apache.commons.fileupload.FileUploadException;
42  import org.apache.commons.fileupload.servlet.ServletFileUpload;
43  import org.apache.commons.lang.StringUtils;
44  import org.kuali.ole.sys.FinancialSystemModuleConfiguration;
45  import org.kuali.ole.sys.context.SpringContext;
46  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
47  import org.kuali.rice.kim.api.identity.AuthenticationService;
48  import org.kuali.rice.kim.api.identity.Person;
49  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
50  import org.kuali.rice.krad.bo.ModuleConfiguration;
51  import org.kuali.rice.krad.document.DocumentAuthorizer;
52  import org.kuali.rice.krad.service.DocumentDictionaryService;
53  import org.kuali.rice.krad.service.KualiModuleService;
54  import org.kuali.rice.krad.service.ModuleService;
55  
56  public class BatchFileUploadServlet extends HttpServlet {
57      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BatchFileUploadServlet.class);
58  
59      protected void checkAuthorization( HttpServletRequest request ) {
60          boolean authorized = false;
61          String principalName = ((AuthenticationService) GlobalResourceLoader.getResourceLoader().getService(new QName("kimAuthenticationService"))).getPrincipalName(request);
62          if ( LOG.isInfoEnabled() ) {
63              LOG.info("Logged In User: " + principalName);
64          }
65          if ( StringUtils.isNotBlank(principalName) ) {
66              Person person = KimApiServiceLocator.getPersonService().getPersonByPrincipalName(principalName);
67              if ( person != null ) {
68                  String principalId = person.getPrincipalId();
69                  Map<String,String> permissionDetails = new HashMap<String,String>();
70                  DocumentAuthorizer da = SpringContext.getBean(DocumentDictionaryService.class).getDocumentAuthorizer("GLCP");
71                  if ( da != null ) {
72                      authorized = da.canInitiate("GLCP", person);
73                  }
74                  if ( !authorized ) {
75                      da = SpringContext.getBean(DocumentDictionaryService.class).getDocumentAuthorizer("LLCP");
76                      if ( da != null ) {
77                          authorized = da.canInitiate("LLCP", person);
78                      }
79                  }
80              }
81          }
82          if ( !authorized ) {
83              throw new RuntimeException( "You must be able to initiate the GLCP or LLCP documents to use this page.  (Backdoor users are not recognized.)" );
84          }
85      }
86      
87      @Override
88      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
89          checkAuthorization(request);
90          request.setAttribute("directories", getBatchDirectories());
91          request.getRequestDispatcher("/WEB-INF/jsp/batchFileUpload.jsp").forward(request, response);
92      }
93  
94      @Override
95      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
96          checkAuthorization(request);
97          ServletFileUpload upload = new ServletFileUpload();
98  
99          String destPath = null;
100         String fileName = null;
101         String tempDir = System.getProperty("java.io.tmpdir");
102         // Parse the request
103         try {
104             FileItemIterator iter = upload.getItemIterator(request);
105             while (iter.hasNext()) {
106                 FileItemStream item = iter.next();
107                 fileName = item.getName();
108                 LOG.info("Processing Item: " + item.getFieldName());
109                 if (item.isFormField()) {
110                     if (item.getFieldName().equals("uploadDir")) {
111                         Reader str = new InputStreamReader(item.openStream());
112                         StringWriter sw = new StringWriter();
113                         char buf[] = new char[100];
114                         int len;
115                         while ((len = str.read(buf)) > 0) {
116                             sw.write(buf, 0, len);
117                         }
118                         destPath = sw.toString();
119                     }
120                 } else {
121                     InputStream stream = item.openStream();
122                     fileName = item.getName();
123                     LOG.info("Uploading to Directory: " + tempDir );
124                     // Process the input stream
125                     FileOutputStream fos = new FileOutputStream(new File(tempDir, fileName));
126                     BufferedOutputStream bos = new BufferedOutputStream(fos, 1024 * 1024);
127                     byte buf[] = new byte[10240];
128                     int len;
129                     while ((len = stream.read(buf)) > 0) {
130                         bos.write(buf, 0, len);
131                     }
132                     bos.close();
133                     stream.close();
134                 }
135             }
136             LOG.info("Copying to Directory: " + destPath);
137             
138             if ( !getBatchDirectories().contains(destPath) ) {
139                 new File(tempDir, fileName).delete();
140                 throw new RuntimeException( "Illegal Attempt to upload to an unauthorized path: '" + destPath + "'" );
141             }
142             
143             BufferedInputStream bis = new BufferedInputStream( new FileInputStream( new File(tempDir, fileName) ) ); 
144             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(destPath, fileName)), 1024 * 1024);
145             byte buf[] = new byte[10240];
146             int len;
147             while ((len = bis.read(buf)) > 0) {
148                 bos.write(buf, 0, len);
149             }
150             bos.close();
151             bis.close();
152         }
153         catch (FileUploadException ex) {
154             LOG.error("Problem Uploading file", ex);
155         }
156         if (fileName != null) {
157             request.setAttribute("message", "Successfully uploaded " + fileName + " to " + destPath);
158         }
159         else {
160             request.setAttribute("message", "Upload Failed");
161         }
162         doGet(request, response);
163     }
164 
165     protected List<String> getBatchDirectories() {
166         List<String> dirs = new ArrayList<String>();
167         for (ModuleService moduleService : SpringContext.getBean(KualiModuleService.class).getInstalledModuleServices()) {
168             ModuleConfiguration moduleConfiguration = moduleService.getModuleConfiguration();
169             if (moduleConfiguration instanceof FinancialSystemModuleConfiguration) {
170                 List<String> batchFileDirectories = ((FinancialSystemModuleConfiguration) moduleConfiguration).getBatchFileDirectories();
171                 for (String batchFileDirectoryName : batchFileDirectories) {
172                     String directory = new File(batchFileDirectoryName).getAbsolutePath();
173                     if ( new File( directory, "originEntry" ).isDirectory() ) {
174                         dirs.add( new File( directory, "originEntry" ).getAbsolutePath() );
175                     }
176                 }
177             }
178         }
179         return dirs;
180     }
181 
182 }