View Javadoc
1   /**
2    * Copyright 2005-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.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/ecl2.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.rice.kew.batch;
17  
18  import org.apache.struts.action.ActionForward;
19  import org.apache.struts.action.ActionMapping;
20  import org.apache.struts.upload.FormFile;
21  import org.junit.Test;
22  import org.kuali.rice.core.api.util.ClasspathOrFileResourceLoader;
23  import org.kuali.rice.core.web.impex.IngesterAction;
24  import org.kuali.rice.core.web.impex.IngesterForm;
25  import org.kuali.rice.kew.test.KEWTestCase;
26  import org.kuali.rice.kew.test.web.MockFormFile;
27  import org.kuali.rice.kew.test.web.WorkflowServletRequest;
28  import org.kuali.rice.krad.web.filter.UserLoginFilter;
29  import org.kuali.rice.krad.UserSession;
30  import org.kuali.rice.krad.util.GlobalVariables;
31  import org.kuali.rice.krad.util.KRADConstants;
32  import org.springframework.core.io.Resource;
33  import org.springframework.mock.web.MockHttpServletResponse;
34  
35  import javax.servlet.FilterChain;
36  import javax.servlet.ServletRequest;
37  import javax.servlet.ServletResponse;
38  import java.io.File;
39  import java.util.Iterator;
40  import java.util.LinkedList;
41  import java.util.List;
42  import java.util.Map;
43  import java.util.Properties;
44  import java.util.regex.Pattern;
45  
46  import static org.junit.Assert.*;
47  
48  /**
49   * Tests workflow Struts IngesterAction
50   * @author Kuali Rice Team (rice.collab@kuali.org)
51   */
52  public class IngesterActionTest extends KEWTestCase {
53  
54  	private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(IngesterActionTest.class);
55  
56      private static final String TRANSACTION_FAILED_REGEX = "(?i)^Ingestion failed$";
57      private static final String SUCCESS_MESSAGE_REGEX_PRE = "(?ism)^Ingested xml doc.*";
58      private static final String SUCCESS_MESSAGE_REGEX_POST = ".*";
59      private static final String FAILURE_MESSAGE_REGEX_PRE = "(?ism)^((Failed to ingest xml doc)|(Rolled back doc)).*";
60      private static final String FAILURE_MESSAGE_REGEX_POST = ".*";
61  
62      private static final String escape(String fileName) {
63          return fileName.replaceAll("\\.", "\\\\.");
64      }
65  
66      private static final String getSuccessRegex(String fileName) {
67          return SUCCESS_MESSAGE_REGEX_PRE + escape(fileName) + SUCCESS_MESSAGE_REGEX_POST;
68      }
69  
70      private static final String getFailureRegex(String fileName) {
71          return FAILURE_MESSAGE_REGEX_PRE + escape(fileName) + FAILURE_MESSAGE_REGEX_POST;
72      }
73  
74      private boolean findMessage(List messages, String regex) {
75          Pattern p = Pattern.compile(regex);
76          Iterator it = messages.iterator();
77          LOG.error(regex);
78          while (it.hasNext()) {
79              String message = (String) it.next();
80              LOG.error(message);
81              if (p.matcher(message).matches()) {
82                  return true;
83              }
84          }
85          return false;
86      }
87  
88      @Test public void testSuccessfulIngestion() throws Exception {
89          testIngestion("IngesterActionTest_success.txt", true);
90      }
91  
92      @Test public void testFailedIngestion() throws Exception {
93          testIngestion("IngesterActionTest_failure.txt", false);
94      }
95  
96      @SuppressWarnings("unchecked")
97  	private void testIngestion(String config, boolean shouldSucceed) throws Exception {
98          IngesterForm form = new IngesterForm();
99          Properties filesToIngest = new Properties();
100         filesToIngest.load(getClass().getResourceAsStream(config));
101         List shouldPass = new LinkedList();
102         List shouldFail = new LinkedList();
103 
104         ClasspathOrFileResourceLoader rl = new ClasspathOrFileResourceLoader();
105 
106         // add all test files to form
107         Iterator entries = filesToIngest.entrySet().iterator();
108         int i = 0;
109         while (entries.hasNext()) {
110             Map.Entry entry = (Map.Entry) entries.next();
111             Resource resource = rl.getResource(entry.getKey().toString());
112             File resourceFile = resource.getFile();
113             String fileName = resourceFile.getName();
114             if (Boolean.valueOf(entry.getValue().toString()).booleanValue()) {
115                 shouldPass.add(fileName);
116             } else {
117                 shouldFail.add(fileName);
118             }
119             FormFile file = new MockFormFile(resourceFile);
120             form.setFile(i, file);
121             assertTrue(form.getFiles().size() == i+1);
122             i++;
123         }
124 
125         assertTrue(form.getFiles().size() > 0);
126 
127         // invoke action
128         IngesterAction action = new IngesterAction();
129         ActionMapping mapping = new ActionMapping();
130         mapping.addForwardConfig(new ActionForward("view", "/nowhere", false));
131         WorkflowServletRequest request = new WorkflowServletRequest();
132         MockHttpServletResponse response = new MockHttpServletResponse();
133         request.setUser("admin");
134         // add the user to the session
135         new UserLoginFilter().doFilter(request, response, new FilterChain() {
136             public void doFilter(ServletRequest req, ServletResponse res) {
137             }
138         });
139         request.setMethod("post");
140         try {
141         	UserSession userSession = (UserSession)request.getSession().getAttribute(KRADConstants.USER_SESSION_KEY);
142         	assertNotNull("UserSession should have been established.", userSession);
143         	GlobalVariables.setUserSession(userSession);
144         	action.execute(mapping, form, request, response);
145         } finally {
146         	GlobalVariables.setUserSession(null);
147         }
148 
149         // test result
150         List messages = (List) request.getAttribute("messages");
151         assertNotNull(messages);
152 
153         Iterator it = shouldFail.iterator();
154         while (it.hasNext()) {
155             String file = it.next().toString();
156             LOG.error("file: " + file);
157             LOG.error("file replaced: " + escape(file));
158             assertTrue(findMessage(messages, getFailureRegex(file)));
159         }
160 
161 
162         // test that the global transaction failure message was emitted
163         boolean failed = shouldFail.size() > 0;
164         if (failed && shouldSucceed) {
165             fail("Ingestation failed but should have succeeded");
166         } else if (!failed && !shouldSucceed) {
167             fail("Ingestation succeeded but should have failed");
168         }
169 
170         if (failed) {
171             assertTrue(findMessage(messages, TRANSACTION_FAILED_REGEX));
172         }
173 
174         it = shouldPass.iterator();
175         while (it.hasNext()) {
176             if (failed) {
177                 assertTrue(findMessage(messages, getFailureRegex(it.next().toString())));
178             } else {
179                 assertTrue(findMessage(messages, getSuccessRegex(it.next().toString())));
180             }
181         }
182     }
183 }