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