Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: org/acs/damsel/client/ingestionClient/IngestionClientUploadExcelAction.java


1   package org.acs.damsel.client.ingestionClient;
2   
3   import java.io.*;
4   import java.sql.*;
5   import java.util.Vector;
6   import java.util.StringTokenizer;
7   import javax.servlet.http.*;
8   
9   import org.acs.damsel.client.*;
10  import org.acs.damsel.srvr.*;
11  import org.acs.damsel.srvr.asset.*;
12  import org.apache.log4j.*;
13  import org.apache.struts.action.*;
14  import org.apache.struts.upload.*;
15  import org.acs.damsel.srvr.collection.*;
16  import org.acs.damsel.srvr.user.*;
17  import org.acs.damsel.srvr.db.*;
18  
19  public class IngestionClientUploadExcelAction
20      extends Action {
21  
22    private static Logger log = Logger.getLogger(IngestionClientUploadExcelAction.class);
23  
24    public IngestionClientUploadExcelAction() {
25      BasicConfigurator.resetConfiguration();
26      PropertyConfigurator.configure(Config.instance().getLogPropertiesFileName());
27    }
28  
29    public ActionForward execute(ActionMapping actionMapping,
30                                 ActionForm actionForm,
31                                 HttpServletRequest httpServletRequest,
32                                 HttpServletResponse httpServletResponse) {
33      /**@todo make more descriptive errors in application.properties
34       * @todo if this class gets too long, move data validation to
35       * IngestionClientUploadExcelForm.validate()
36       */
37  
38      IngestionClientUploadExcelForm ingestionClientUploadExcelForm = (
39          IngestionClientUploadExcelForm) actionForm;
40  
41      ActionErrors errors;
42          /*assetFileNames is used to collect the filenames supplied in the tab-delimited
43           file... ingestionClientUploadZipAction will use these fileNames to determine
44            whether or not to add a file to the assets folder*/
45      Vector assetFileNames = new Vector();
46      String fileName = null;
47      FormFile excelFile = ingestionClientUploadExcelForm.getExcelFile();
48      String excelFileName = excelFile.getFileName();
49      String collectionSelect = ingestionClientUploadExcelForm.
50          getCollectionSelect();
51      File file;
52      User user = (User) httpServletRequest.getSession().getAttribute("User");
53  
54      /*Check for an empty fileName */
55      if (excelFile == null || excelFileName.trim().equals("")) {
56        errors = new ActionErrors();
57        errors.add("ingestionClient", new ActionError("no.file.name"));
58        this.saveErrors(httpServletRequest, errors);
59        return actionMapping.findForward("failure");
60      }
61  
62      /*Upload File*/
63      try {
64        int lastSlash = excelFileName.lastIndexOf("\\");
65        if (lastSlash == -1)
66          lastSlash = excelFileName.lastIndexOf("/");
67        fileName = excelFileName.substring(lastSlash + 1);
68        file = this.doUpload(excelFile, fileName);
69      }
70      catch (Exception ex3) {
71        /*Tell the user the file could not be uploaded */
72        log.warn("Upload did not succeed: " + ex3.getMessage());
73        errors = new ActionErrors();
74        errors.add("ingestionClient", new ActionError("upload.failed"));
75        this.saveErrors(httpServletRequest, errors);
76        return actionMapping.findForward("failure");
77      }
78  
79      try {
80        /*read in the file */
81        BufferedReader br = new BufferedReader(new FileReader(file));
82        try {
83          /*validate the file by checking that the first line contains the
84               "FileName" tag... this is mandatory! all other tags are optional */
85          String line = br.readLine();
86          String temp;
87          StringTokenizer st = new StringTokenizer(line, "\t", true);
88          Vector metadataTags = new Vector();
89          boolean wasLastBlank = false;
90  
91          while (st.hasMoreTokens()) {
92            /*Add each metadatatag to a collection */
93            temp = st.nextToken();
94            if (temp.equals("\t")) {
95              /*Complain if the user gave a tab-delimited file with blank metadata columns */
96              if (wasLastBlank) {
97                errors = new ActionErrors();
98                errors.add("ingestionClient", new ActionError("empty.columns"));
99                this.saveErrors(httpServletRequest, errors);
100               return actionMapping.findForward("failure");
101             }
102             wasLastBlank = true;
103           }
104           else
105             wasLastBlank = false;
106           metadataTags.add(temp);
107 
108         }
109         /*shout at the user if the metadata tags in their excel file do
110            not contain the "FileName" tag*/
111         if (!metadataTags.contains("FileName")) {
112           br.close();
113           file.delete();
114           return this.saveExcelFileNameNotIncluded(httpServletRequest,
115               actionMapping);
116         }
117 
118         /*Now we can pull out each line and add each asset descriptor to a new
119                  asset, and add the asset to the database */
120         Asset asset;
121         line = br.readLine();
122         AssetDescriptorCollection adc;
123         while (line != null) { //while we have more lines in the file to examine
124           if (!line.trim().equals("")) { //if we are not looking at an empty line
125             st = new StringTokenizer(line, "\t", true);
126             /*Populate the asset descriptors */
127             adc = new AssetDescriptorCollection();
128             /*We need to iterate through the data AND the empty tabs so we can
129                  tell what fields have been left blank. Now, if we come across an empty
130                  field we will actually skip over it (it is not really there), we will
131                  really just iterate over the blank tabs around it. In this case we
132                  use wasLastBlank. if the last token we looked at was a blank, and the
133                  current one we are looking at is also blank, we have found an empty
134                        field and need to increment i*/
135             wasLastBlank = false;
136             boolean isFirst = true;
137             boolean hasFileName = true;
138             int fileNameIndex = metadataTags.indexOf("FileName");
139             int i = 0;
140 
141             while (st.hasMoreTokens()) {
142               temp = st.nextToken();
143               temp = temp.toLowerCase();
144               temp = DBUtils.encode(temp);
145               if  (((String)metadataTags.elementAt(i)).indexOf("FileName") != -1)
146                   temp = temp.replaceAll("'", "");
147               if (!temp.trim().equals("")) {
148                 /*Add fileNames to our fileNames collection (see assetFileNames
149                                  declaration comment above) */
150                 if (i == fileNameIndex)
151                   assetFileNames.add(temp);
152                 wasLastBlank = false;
153                 adc.addAssetDescriptor(new AssetDescriptor( (String)
154                     metadataTags.elementAt(i),
155                     temp));
156               }
157               else {
158                     /*If the asset has no fileName, we can't add it! So break out of
159                      the for loop and set hasFileName to false, so that we dont add
160                        this asset and can move on to the next one*/
161                 if (i == fileNameIndex) {
162                   hasFileName = false;
163                   break;
164                 }
165                 if (wasLastBlank || isFirst)
166                   i++;
167                 wasLastBlank = true;
168               }
169               i++;
170               isFirst = false;
171             }
172             /*Rip out ' */
173 
174             /*Set the webFileName to FileName if the user didnt supply it */
175             String webFileNameValue = adc.getValue("WebFileName");
176             if (webFileNameValue == null) {
177               adc.addAssetDescriptor(new AssetDescriptor("WebFileName",
178                   adc.getValue("FileName")));
179             }
180             /*Add WebFileName to assetFileNames vector */
181             else {
182               assetFileNames.add(webFileNameValue);
183             }
184             /*Set up permissionID, OwnerName and GroupName */
185             Collection collection = null;
186               collection = ClientApp.instance().getCollectionMgr().getCollection(collectionSelect);
187 
188             if (collection != null) {
189               if (adc.getValue("PermissionID") == null)
190             adc.addAssetDescriptor(new AssetDescriptor("PermissionID", "79"));
191           if (adc.getValue("OwnerName") == null)
192             adc.addAssetDescriptor(new AssetDescriptor("OwnerName", user.getUserName()));
193           if (adc.getValue("GroupName") == null)
194             adc.addAssetDescriptor(new AssetDescriptor("GroupName", collection.getGroupName()));
195             }
196 
197             /*Create the asset with new ADs if it has a file name */
198             if (hasFileName) {
199               asset = new Asset();
200               asset.setAssetDescriptors(adc);
201               /*Add the asset to the user specified collection */
202               try {
203                 ClientApp.instance().getRepositoryMgr().addAsset(asset,
204                     collectionSelect);
205                 if (!collectionSelect.equals("AllAssets")) {
206                   /*If collection is private, remove from AllAssets */
207                   if (ClientApp.instance().getCollectionMgr().
208                       isCollectionPrivate(collectionSelect))
209                     ClientApp.instance().getRepositoryMgr().
210                         removeAssetFromCollection(asset, "AllAssets");
211                 }
212               }
213               catch (SQLException ex2) {
214                 log.warn("Unexpected SQLException while trying to add an asset in IngestionClientUploadExcelAction");
215               }
216             }
217           }
218           /*Go on to the next line in our file */
219           line = br.readLine();
220         }
221         br.close();
222       }
223       catch (IOException ex1) {
224         /*Shout at the user if their file was not the correct format */
225         try {
226           br.close();
227         }
228         catch (IOException ex4) {
229         }
230         file.delete();
231         return this.saveExcelFileBadError(httpServletRequest, actionMapping);
232       }
233     }
234     catch (FileNotFoundException ex) {
235       /*Shout at the user if the file was not found */
236       errors = new ActionErrors();
237       errors.add("ingestionClient", new ActionError("file.not.found"));
238       this.saveErrors(httpServletRequest, errors);
239       return actionMapping.findForward("failure");
240     }
241     /*Attach the assetsFileNames to the session */
242     httpServletRequest.getSession().setAttribute("assetsFileNames",
243                                                  assetFileNames);
244 
245     /*Destroy the uploaded file! */
246     file.delete();
247 
248     return actionMapping.findForward("success");
249   }
250 
251   /*Private helper method to shout at the user if their excel file is bad */
252   private ActionForward saveExcelFileBadError(HttpServletRequest
253                                               httpServletRequest,
254                                               ActionMapping actionMapping) {
255     ActionErrors errors = new ActionErrors();
256     errors.add("ingestionClient", new ActionError("excel.file.bad"));
257     this.saveErrors(httpServletRequest, errors);
258     return actionMapping.findForward("failure");
259   }
260 
261   /*Private helper method to shout at the user if their excel file is bad */
262   private ActionForward saveExcelFileNameNotIncluded(HttpServletRequest
263       httpServletRequest,
264       ActionMapping actionMapping) {
265     ActionErrors errors = new ActionErrors();
266     errors.add("ingestionClient",
267                new ActionError("excel.file.fileName.not.included"));
268     this.saveErrors(httpServletRequest, errors);
269     return actionMapping.findForward("failure");
270   }
271 
272   // this method writes the uploaded file to a new file with the given fileName
273   public File doUpload(FormFile theFile, String fileName) throws IOException {
274     log.info("About to write: " + theFile.getFileSize() + " bytes to " +
275              Config.instance().getUploadPrefix() + fileName);
276     File file = new File(Config.instance().getUploadPrefix() + fileName);
277     FileOutputStream out = new FileOutputStream(file);
278     out.write(theFile.getFileData(), 0, theFile.getFileSize());
279     out.close();
280     return file;
281   }
282 
283 }