001/**
002 * Copyright 2005-2016 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.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/ecl2.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 */
016package org.kuali.rice.testtools.selenium;
017
018import org.apache.commons.io.FileUtils;
019import org.junit.After;
020import org.junit.Before;
021import org.junit.Test;
022import org.openqa.selenium.By;
023import org.openqa.selenium.Keys;
024import org.openqa.selenium.NoSuchWindowException;
025import org.openqa.selenium.WebDriver;
026import org.openqa.selenium.WebElement;
027import org.openqa.selenium.firefox.FirefoxDriver;
028import org.openqa.selenium.firefox.FirefoxProfile;
029import org.openqa.selenium.remote.DesiredCapabilities;
030
031import java.io.File;
032import java.io.FilenameFilter;
033import java.io.IOException;
034import java.util.HashMap;
035import java.util.LinkedList;
036import java.util.List;
037import java.util.Map;
038import java.util.Set;
039import java.util.StringTokenizer;
040import java.util.concurrent.TimeUnit;
041
042/**
043 * -Dcas.username=casusername -Dcas.password=caspassword
044 * -Djira.input.dir=/Users/eghm/Desktop/JenkinsResults-2.5-IT-05-12/JiraGroups -Djira.summary.start=IT_Failure
045 * @author Kuali Rice Team (rice.collab@kuali.org)
046 */
047public class JiraIssueCreation {
048
049    WebDriver driver;
050    String jiraBase;
051    List<File> jiraDataDirs = new LinkedList();
052    boolean passed = false;
053    Map<String, String> jiraMap = new HashMap<String, String>();
054    Map<String, Map<String, String>> jiraMaps = new HashMap<String, Map<String, String>>();
055
056    @Before
057    public void setUp() throws IOException, InterruptedException {
058        jiraMap.put("project-field", System.getProperty("jira.project", "Kuali Rice Development"));
059        jiraMap.put("jira.versions", System.getProperty("jira.versions", "2.5").replaceAll(",", " "));
060        jiraMap.put("jira.fixVersions", System.getProperty("jira.fixVersions", "").replaceAll(",", " "));
061        jiraMap.put("issuetype-field", System.getProperty("jira.issuetype", "Bug Fix"));
062        jiraMap.put("jira.component", System.getProperty("jira.component", "Regression,Development").replaceAll(",", " "));
063        jiraMap.put("jira.priority", System.getProperty("jira.priority", "Critical"));
064
065        jiraBase = System.getProperty("jira.base.url", "https://jira.kuali.org");
066        File inputDir = new File(System.getProperty("jira.input.dir", "."));
067        File listDir[] = inputDir.listFiles();
068        for (int i = 0; i < listDir.length; i++) {
069            if (listDir[i].isDirectory()) {
070                jiraDataDirs.add(listDir[i]);
071            }
072        }
073
074        createJiraMaps();
075        dumpJiraMaps();
076        login();
077
078        passed = true;
079    }
080
081    private void dumpJiraMaps() {
082        for (Map<String, String> jiraMapped : jiraMaps.values()) {
083            for (String key : jiraMapped.keySet()) {
084                System.out.println(key + " = " + jiraMapped.get(key));
085            }
086            System.out.println("\n\n\n\n\n\n\n\n");
087        }
088    }
089
090    private void login() throws InterruptedException {DesiredCapabilities capabilities = new DesiredCapabilities();
091        FirefoxProfile profile = new FirefoxProfile();
092        profile.setEnableNativeEvents(false);
093        capabilities.setCapability(FirefoxDriver.PROFILE, profile);
094
095        driver = new FirefoxDriver(capabilities);
096        driver.manage().timeouts().implicitlyWait(WebDriverUtils.configuredImplicityWait(), TimeUnit.SECONDS);
097        driver.get(jiraBase + "/secure/Dashboard.jspa");
098
099        WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.className("login-link"),
100                this.getClass().toString()).click();
101
102        // CAS
103        WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("username"),
104                this.getClass().toString());
105        driver.findElement(By.id("username")).sendKeys(System.getProperty("cas.username"));
106        driver.findElement(By.id("password")).sendKeys(System.getProperty("cas.password"));
107        driver.findElement(By.name("submit")).click();
108    }
109
110    @After
111    public void tearDown() {
112//        closeAndQuitWebDriver(); // don't close yet, doing the submit manually
113    }
114
115    public void createJiraMaps() throws InterruptedException, IOException {
116        List<JiraData> jiraDatas = new LinkedList();
117        String summary;
118
119        for (File dir: jiraDataDirs) {
120
121            File[] inputFiles = dir.listFiles(new FilenameFilter() {
122                @Override
123                public boolean accept(File dir, String name) {
124                    return name.endsWith(".jira");
125                }
126            });
127
128            for (int i = 0, s = inputFiles.length; i < s; i++) {
129                jiraDatas.add(parseJiraData(inputFiles[i]));
130            }
131
132            String testClass = jiraDatas.get(0).fullTestName.substring(0, jiraDatas.get(0).fullTestName.lastIndexOf("."));
133            testClass = testClass.replace("org.kuali.rice.", "");
134            testClass = testClass.replace("edu.sampleu.", "");
135            summary = System.getProperty("jira.summary.start", "").replaceAll("_", " ") + " "  + testClass;
136
137            if (jiraDatas.size() == 1) {
138                summary += " " + jiraDatas.get(0).testDetails;
139            }
140
141            summary = summary.replace("java.lang.AssertionError: ", "");
142            summary = summary.replace("org.eclipse.persistence.exceptions.DatabaseException: \nInternal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: ", "");
143            if (summary.indexOf("\n") > -1) {
144                summary = summary.substring(0, summary.indexOf("\n")).trim();
145            } else if (summary.indexOf("\t") > -1) {
146                summary = summary.substring(0, summary.indexOf("\t")).trim();
147            }
148
149            if (summary.length() > 180) {
150                summary = summary.substring(0, 179);
151            }
152
153            jiraMap.put("jira.summary", summary);
154
155            StringBuilder description = new StringBuilder(summary).append(" ").append(System.getProperty("jira.description.start", "").replaceAll("_", " ")).append("\n");
156
157            for (JiraData jiraData : jiraDatas) {
158                if (!"".equals(jiraData.aftSteps)) {
159                    description.append("\n").append(jiraData.aftSteps);
160                }
161                description.append("\n").append(jiraData.fullTestName).append(" ( ").append(jiraData.shortTestName).append(" ) - ");
162                description.append(jiraData.testUrl).append("\n");
163                description.append("\n{code}\n\n").append(jiraDatas.get(0).testDetails).append("\n\n{code}\n");
164            }
165
166            jiraMap.put("jira.description", description.toString());
167            jiraMaps.put(dir.getName(), new HashMap<String, String>(jiraMap));
168        }
169    }
170
171    @Test
172    public void testCreateJira() throws InterruptedException, IOException {
173        for (Map<String, String> jiraMap : jiraMaps.values()) {
174
175            // Jira
176            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("create_link"), this.getClass().toString());
177            driver.get(jiraBase + "/secure/CreateIssue!default.jspa");
178
179            // Project
180            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("project-field"),
181                    this.getClass().toString()).sendKeys(jiraMap.get("jira.project"));
182
183            // Issue type
184            WebElement issue = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id(
185                    "issuetype-field"), this.getClass().toString());
186            issue.click();
187            issue.sendKeys(Keys.BACK_SPACE);
188            issue.sendKeys(jiraMap.get("jira.issuetype"));
189//            issue.sendKeys(Keys.ARROW_DOWN);
190            issue.sendKeys(Keys.TAB);
191
192            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("issue-create-submit"),
193                    this.getClass().toString()).click();
194
195            // Summary // TODO remove things that look like java object references
196            // TODO if the error messages are the same for all jiras then include it in the summary
197            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("summary"),
198                    this.getClass().toString()).sendKeys(jiraMap.get("jira.summary"));
199
200            // Components
201            WebElement component = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id(
202                    "components-textarea"), this.getClass().toString());
203            String components = jiraMap.get("jira.component");
204            StringTokenizer tokens = new StringTokenizer(components);
205            while (tokens.hasMoreElements()) {
206                component.click();
207                component.sendKeys(tokens.nextToken());
208//                component.sendKeys(Keys.ARROW_DOWN);
209                component.sendKeys(Keys.TAB);
210            }
211
212            // Description
213            WebElement descriptionElement = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("description"),
214                    this.getClass().toString());
215            descriptionElement.click();
216            descriptionElement.sendKeys(jiraMap.get("jira.description"));
217
218            // Priority
219            WebElement priority = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("priority-field"),
220                    this.getClass().toString());
221            priority.click();
222            priority.sendKeys(Keys.BACK_SPACE);
223            priority.sendKeys(jiraMap.get("jira.priority"));
224//            priority.sendKeys(Keys.ARROW_DOWN);
225            priority.sendKeys(Keys.TAB);
226
227            // Version
228            WebElement version = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("versions-textarea"),
229                    this.getClass().toString());
230            version.click();
231            version.sendKeys(jiraMap.get("jira.versions"));
232//            version.sendKeys(Keys.ARROW_DOWN);
233            version.sendKeys(Keys.TAB);
234
235            // Fix version
236            WebElement fixVersion = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("fixVersions-textarea"),
237                    this.getClass().toString());
238            fixVersion.click();
239            fixVersion.sendKeys(jiraMap.get("jira.fixVersions"));
240//            fixVersion.sendKeys(Keys.ARROW_DOWN);
241            fixVersion.sendKeys(Keys.TAB);
242
243            // Release notes unchecked
244            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("customfield_11621-1"),
245                    this.getClass().toString()).click();
246
247            WebDriverUtils.waitFor(driver, 8, By.id("issue-create-submit"), this.getClass().toString());
248
249//            WebDriverUtils.acceptAlertIfPresent(driver); // Dialog present when running Se.....
250        }
251    }
252
253    protected JiraData parseJiraData(File inputFile) throws IOException {
254        String rawData = FileUtils.readFileToString(inputFile, (String)null);
255        JiraData jiraData = new JiraData();
256        try {
257            jiraData.aftSteps = rawData.substring(rawData.indexOf("AFT Step:"), rawData.indexOf("Abbreviated test name: "));
258        } catch (IndexOutOfBoundsException ioobe) {
259            // ignore only AFTs have AFT steps
260        }
261        jiraData.shortTestName = rawData.substring(rawData.indexOf("Abbreviated test name: ") + 23, rawData.indexOf("Full test name: ")).trim(); // Abbreviated test name:
262        jiraData.fullTestName = rawData.substring(rawData.indexOf("Full test name: ") + 16, rawData.indexOf("Test results url: ")).trim();
263        jiraData.testUrl = rawData.substring(rawData.indexOf("Test results url: ") + 18, rawData.indexOf("Error Message: ")).trim();
264        jiraData.errorMessage = rawData.substring(rawData.indexOf("Error Message: ") + 15, rawData.indexOf("Test Details: ")).trim();
265        jiraData.testDetails = rawData.substring(rawData.indexOf("Test Details: ") + 14, rawData.length()).trim().replace("\t", "       ");
266        return jiraData;
267    }
268
269    private void closeAndQuitWebDriver() {
270        if (driver != null) {
271            if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(passed)) {
272                try {
273                    driver.close();
274                } catch (NoSuchWindowException nswe) {
275                    System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
276                } finally {
277                    if (driver != null) {
278                        driver.quit();
279                    }
280                }
281            }
282        } else {
283            System.out.println("WebDriver is null for " + this.getClass().toString());
284        }
285    }
286
287    class JiraData {
288        String aftSteps = ""; // only AFTs have AFT Steps
289        String shortTestName;
290        String fullTestName;
291        String testUrl;
292        String errorMessage;
293        String testDetails;
294    }
295}