001    /*
002     * Copyright 2011 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 1.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl1.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package edu.sampleu.kew.krad.controller;
017    
018    import java.io.File;
019    import java.io.FileOutputStream;
020    import java.io.IOException;
021    import java.util.ArrayList;
022    import java.util.Collection;
023    import java.util.List;
024    
025    import javax.servlet.http.HttpServletRequest;
026    import javax.servlet.http.HttpServletResponse;
027    
028    import org.apache.commons.lang.StringUtils;
029    import org.apache.commons.lang.exception.ExceptionUtils;
030    import org.kuali.rice.core.api.CoreApiServiceLocator;
031    import org.kuali.rice.core.api.impex.xml.CompositeXmlDocCollection;
032    import org.kuali.rice.core.api.impex.xml.FileXmlDocCollection;
033    import org.kuali.rice.core.api.impex.xml.XmlDoc;
034    import org.kuali.rice.core.api.impex.xml.XmlDocCollection;
035    import org.kuali.rice.core.api.impex.xml.ZipXmlDocCollection;
036    import org.kuali.rice.krad.util.GlobalVariables;
037    import org.kuali.rice.krad.web.controller.UifControllerBase;
038    import org.kuali.rice.krad.web.form.UifFormBase;
039    import org.springframework.stereotype.Controller;
040    import org.springframework.validation.BindingResult;
041    import org.springframework.web.bind.annotation.ModelAttribute;
042    import org.springframework.web.bind.annotation.RequestMapping;
043    import org.springframework.web.bind.annotation.RequestMethod;
044    import org.springframework.web.multipart.MultipartFile;
045    import org.springframework.web.servlet.ModelAndView;
046    
047    import edu.sampleu.kew.krad.KEWConstants;
048    import edu.sampleu.kew.krad.form.IngesterForm;
049    
050    /**
051     * This is a description of what this class does - Venkat don't forget to fill this in. 
052     * 
053     * @author Kuali Rice Team (rice.collab@kuali.org)
054     *
055     */
056    @Controller
057    @RequestMapping(value = "/ingester")
058    public class IngesterController extends UifControllerBase {
059    
060            @Override
061        protected IngesterForm createInitialForm(HttpServletRequest request) {
062            return new IngesterForm();
063        }
064    
065            @Override
066            @RequestMapping(params = "methodToCall=start")
067            public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
068                            HttpServletRequest request, HttpServletResponse response) {
069    
070                    IngesterForm ingesterForm = (IngesterForm)form;
071                    
072    //              checkAuthorization(form,"");
073                    return super.start(ingesterForm, result, request, response);
074            }
075    
076            @RequestMapping(method = RequestMethod.POST, params = "methodToCall=upload")
077            public ModelAndView upload(@ModelAttribute("KualiForm") IngesterForm ingesterForm, BindingResult result,
078                            HttpServletRequest request, HttpServletResponse response) {
079                    
080                    List<File> tempFiles = new ArrayList<File>();
081                    
082                    try {
083                            
084                            List<XmlDocCollection> collections = new ArrayList<XmlDocCollection>();
085                            
086                            for (MultipartFile file : ingesterForm.getFiles())
087                    {
088                        if (file == null || StringUtils.isBlank(file.getOriginalFilename())) {
089                                            continue;
090                                    }
091                        
092                        // ok, we have to copy it to *another* file because Struts doesn't give us a File
093                        // reference (which itself is not a bad abstraction) and XmlDocs based on ZipFile
094                        // can't be constructed without a file reference.
095                        FileOutputStream fos = null;
096                        File temp = null;
097                        try{
098                            temp = File.createTempFile("ingester", null);
099                            tempFiles.add(temp);
100                            fos = new FileOutputStream(temp);
101                            fos.write(file.getBytes());
102                        } catch (IOException ioe) {
103                            GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID,KEWConstants.ERROR_INGESTER_COPY_FILE , file.getOriginalFilename(), ExceptionUtils.getFullStackTrace(ioe));
104                            continue;
105                        } finally{
106                            if (fos != null) {
107                                                    try{
108                                                        fos.close();
109                                                    } catch (IOException ioe){
110            //                                          //LOG.error("Error closing temp file output stream: " + temp, ioe);
111                                                    }
112                                            }
113                        }
114                        if (file.getOriginalFilename().toLowerCase().endsWith(".zip"))
115                        {
116                            try {
117                                collections.add(new ZipXmlDocCollection(temp));
118                            } catch (IOException ioe) {
119                                GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_LOAD_FILE, file.getOriginalFilename());
120                            }
121                        } else if (file.getOriginalFilename().endsWith(".xml")) {
122                            collections.add(new FileXmlDocCollection(temp, file.getOriginalFilename()));
123                        } else {
124                            GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_EXTRANEOUS_FILE, file.getOriginalFilename());
125                        }
126                    }
127            
128                    if (collections.size() == 0) {
129                        String message = "No valid files to ingest";
130                        GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_NO_VALID_FILES);
131                    } else {
132                        // wrap in composite collection to make transactional
133                        CompositeXmlDocCollection compositeCollection = new CompositeXmlDocCollection(collections);
134                        int totalProcessed = 0;
135                        List<XmlDocCollection> c = new ArrayList<XmlDocCollection>(1);
136                        c.add(compositeCollection);
137                        try {
138                            Collection<XmlDocCollection> failed = CoreApiServiceLocator.getXmlIngesterService().ingest(c, GlobalVariables.getUserSession().getPrincipalId());
139                            boolean txFailed = failed.size() > 0;
140                            if (txFailed) {
141                                    GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_FAILED);
142                            }
143                            for (XmlDocCollection collection1 : collections)
144                            {
145                                List<? extends XmlDoc> docs = collection1.getXmlDocs();
146                                for (XmlDoc doc1 : docs)
147                                {
148                                    if (doc1.isProcessed())
149                                    {
150                                        if (!txFailed)
151                                        {
152                                            totalProcessed++;
153                                            GlobalVariables.getMessageMap().putInfoForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.INFO_INGESTER_SUCCESS, doc1.getName(),doc1.getProcessingMessage());
154    //                                      messages.add("Ingested xml doc: " + doc1.getName() + (doc1.getProcessingMessage() == null ? "" : "\n" + doc1.getProcessingMessage()));
155                                        } else
156                                        {GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_ROLLEDBACK, doc1.getName(),doc1.getProcessingMessage());
157    //                                      messages.add("Rolled back doc: " + doc1.getName() + (doc1.getProcessingMessage() == null ? "" : "\n" + doc1.getProcessingMessage()));
158                                        }
159                                    } else
160                                    {GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_FAILED_XML, doc1.getName(),doc1.getProcessingMessage());
161    //                                  messages.add("Failed to ingest xml doc: " + doc1.getName() + (doc1.getProcessingMessage() == null ? "" : "\n" + doc1.getProcessingMessage()));
162                                    }
163                                }
164                            }
165                        } catch (Exception e) {
166    //                      String message = "Error during ingest";
167                            //LOG.error(message, e);
168    //                      messages.add(message + ": " + e  + ":\n" + ExceptionUtils.getFullStackTrace(e));
169                            GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_DURING_INJECT, ExceptionUtils.getFullStackTrace(e));
170                        }
171                        if (totalProcessed == 0) {
172    //                      String message = "No xml docs ingested";
173                            GlobalVariables.getMessageMap().putErrorForSectionId(KEWConstants.INGESTER_SECTION_ID, KEWConstants.ERROR_INGESTER_NO_XMLS);
174                        }
175                    }
176                } finally {
177                    if (tempFiles.size() > 0) {
178                        for (File tempFile : tempFiles)
179                        {
180                            if (!tempFile.delete())
181                            {
182                                //LOG.warn("Error deleting temp file: " + tempFile);
183                            }
184                        }
185                    }
186                }
187                    
188    //          request.setAttribute("messages", messages);
189                return getUIFModelAndView(ingesterForm, ingesterForm.getViewId());
190            }
191            
192            @RequestMapping(method = RequestMethod.POST, params = "methodToCall=close")
193            public ModelAndView close(@ModelAttribute("KualiForm") IngesterForm ingesterForm, BindingResult result,
194                            HttpServletRequest request, HttpServletResponse response) {
195    
196                    return null;
197            }
198    
199    }