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 edu.sampleu.admin;
017
018import org.apache.commons.io.IOUtils;
019import org.openqa.selenium.By;
020
021import java.io.File;
022import java.io.FileOutputStream;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.net.URL;
026import java.net.URLDecoder;
027import java.util.ArrayList;
028import java.util.Collections;
029import java.util.Enumeration;
030import java.util.HashSet;
031import java.util.List;
032import java.util.Set;
033import java.util.jar.JarEntry;
034import java.util.jar.JarFile;
035
036/**
037 * @author Kuali Rice Team (rice.collab@kuali.org)
038 */
039
040public abstract class EdocLiteXmlIngesterBase extends AdminTmplMthdAftNavBase {
041    // values set by default for repeatable testing; left as configurable for load tests
042    protected List<File> fileUploadList;
043
044    @Override
045    protected String getBookmarkUrl() {
046        return null; // no bookmark test yet
047    }
048
049    /**
050     * This overridden method ...
051     *
052     * @see edu.sampleu.common.NavTemplateMethodAftBase#getLinkLocator()
053     */
054    @Override
055    protected String getLinkLocator() {
056        return "XML Ingester";
057    }
058
059    /**
060     * Performs Ingesting files to fileupload component and asserts succesful ingestion.
061     *
062     */
063    private void fileIngester(List<File> fileToUpload) throws Exception {
064        int cnt = 0;
065
066        for (File file : fileToUpload) {
067            String path = file.getAbsolutePath().toString();
068            driver.findElement(By.name("file[" + cnt + "]")).sendKeys(path);
069            cnt++;
070        }
071
072        waitAndClickById("imageField");
073    }
074
075    /**
076     * Divides fileUploadList from resources into sublists to match the maximum number of file
077     * upload components available on XML Ingester Screen
078     *
079     */
080    private List<List<File>> getSubListsForFile(List<File> fileList, final int L) {
081        List<List<File>> subLists = new ArrayList<List<File>>();
082        final int N = fileList.size();
083        for (int i = 0; i < N; i += L) {
084            subLists.add(new ArrayList<File>(fileList.subList(i, Math.min(N, i + L))));
085        }
086
087        return subLists;
088    }
089
090    protected void setUpResourceDir(String resourceDir) {
091        try {
092            setUpFiles("src/it/resources/" + resourceDir);
093        } catch (Exception e) {
094            System.out.println("Problem loading files from filesystem ( " + e.getMessage() + "). If running from Intellij make sure working directory is rice-middleware/sampleapp attempt to load as resource.");
095            try {
096                setUpResourceFiles(resourceDir);
097            } catch (Exception e1) {
098                e1.printStackTrace();
099                jiraAwareFail("Problems loading files as resources " + e1.getMessage());
100            }
101        }
102    }
103
104    protected void setUpResourceFiles(String resourceDir) throws Exception {
105        String[] resources = getResourceListing(getClass(), resourceDir);
106        fileUploadList = new ArrayList<File>();
107
108        for (String resource : resources) {
109            InputStream inputStream = getClass().getResourceAsStream(resource);
110            File file = new File(System.getProperty("java.io.tmpdir") + File.separator + resource);
111            OutputStream outputStream = new FileOutputStream(file);
112            IOUtils.copy(inputStream, outputStream);
113            outputStream.close();
114            fileUploadList.add(file);
115        }
116        Collections.sort(fileUploadList);
117    }
118
119    protected String[] getResourceListing(Class clazz, String pathStartsWith) throws Exception {
120        String classPath = clazz.getName().replace(".", "/")+".class";
121        URL dirUrl = clazz.getClassLoader().getResource(classPath);
122
123        if (!"jar".equals(dirUrl.getProtocol())) {
124            throw new UnsupportedOperationException("Cannot list files for URL " + dirUrl);
125        }
126
127        String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); //strip out only the JAR file
128        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
129        Enumeration<JarEntry> entries = jar.entries();
130        Set<String> result = new HashSet<String>();
131
132        while(entries.hasMoreElements()) {
133            String entry = entries.nextElement().getName();
134            if (entry.startsWith(pathStartsWith) && !entry.endsWith("/")) { //filter according to the pathStartsWith skipping directories
135                result.add(entry);
136            }
137        }
138
139        return result.toArray(new String[result.size()]);
140    }
141
142    protected void setUpFiles(String path) throws Exception {
143        fileUploadList = new ArrayList<File>();
144
145        File dir = new File(path);
146
147        if (dir != null && dir.listFiles().length > 0) {
148            Integer i = 1;
149            for (File file : dir.listFiles()) {
150                if (file.getName().endsWith(".xml") && !file.getName().equalsIgnoreCase("sample-app-config.xml")) {
151                    fileUploadList.add(file);
152                }
153                i++;
154            }
155            Collections.sort(fileUploadList);
156        } else {
157            throw new Exception("----Resources not found----");
158        }
159    }
160
161    protected void testEdocLiteIngestion() throws Exception {
162        testXmlIngesterSuccessfulFileUpload();
163
164        Thread.sleep(2000);
165        driver.switchTo().defaultContent();
166        waitAndClickByLinkText("Main Menu");
167        waitAndClickByLinkText("eDoc Lite");
168
169        selectFrameIframePortlet();
170        waitIsVisible(By.cssSelector("input.tinybutton:nth-child(1)")); // why name methodToCall.search fails?
171        waitAndClick(By.cssSelector("input.tinybutton:nth-child(1)"));
172        Thread.sleep(2000);
173        driver.switchTo().defaultContent();
174        Thread.sleep(1000);
175        waitIsVisible(By.className("exportlinks"));
176        selectFrameIframePortlet();
177    }
178
179    /**
180     * Uploads file available from fileUploadList through XML Ingester.
181     * Uploads each sublist from main fileUploadList if size greater than 10.
182     *
183     */
184    public void testXmlIngesterSuccessfulFileUpload() throws Exception {
185        if (fileUploadList == null && fileUploadList.isEmpty()) {
186            return;
187        }
188
189        if (fileUploadList.size() > 10) {
190            List<List<File>> subLists = getSubListsForFile(fileUploadList, 10);
191            for (List<File> fileSet : subLists) {
192                fileIngester(fileSet);
193                for (File file : fileSet) {
194                    checkMessages(file);
195                }
196            }
197        } else {
198            fileIngester(fileUploadList);
199            for (File file : fileUploadList) {
200                checkMessages(file);
201            }
202        }
203    }
204
205    private void checkMessages(File file) throws InterruptedException {
206        waitIsVisible(By.className("error")); // messages appear in error too.
207        if (!isTextPresent("without allowOverwrite set")) { // docs should still be present
208            // from previous run, if not we'll fail when we assert they exist.
209            // xml ingestion can take a long, long time
210            waitForTextPresent("Ingested xml doc: " + file.getName(), 360);
211        }
212    }
213}