<commit_before>/*
 * Copyright 2006 Wyona
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.wyona.org/licenses/APACHE-LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.wyona.yanel.impl.resources;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.dom.DOMSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Category;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.PatternSet;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.taskdefs.optional.junit.JUnitTask;
import org.apache.tools.ant.taskdefs.optional.junit.BatchTest;

import org.wyona.yanel.core.Path;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.ViewableV1;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yarep.core.NoSuchNodeException;
import org.wyona.yarep.core.Repository;
import org.wyona.yarep.core.RepositoryFactory;
import org.wyona.yarep.util.RepoPath;
import org.wyona.yarep.util.YarepUtil;

/**
 * 
 */
public class TestingControlResource extends Resource implements ViewableV1 {

    private static final String JUNIT_JAR = "yanel-JunitTests.jar";
    private static final String HTMLUNIT_JAR = "yanel-HtmlUnitTests.jar";
    private static Category log = Category.getInstance(TestingControlResource.class);

    private File JunitJarLocation;
    private File HtmlunitJarLocation;
    private File tmpResultDir;
    private String errorMessage;

    public TestingControlResource() {
    }

    public ViewDescriptor[] getViewDescriptors() {
        return null;
    }

    public View getView(Path path, String viewId) {
        View defaultView = new View();
        defaultView.setMimeType("application/xml");
        StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
        defaultView.setInputStream(new java.io.StringBufferInputStream(sb.toString()));
        return defaultView;
    }

    public View getView(HttpServletRequest request, String viewId) throws Exception {
        Path path = new Path(request.getServletPath());

        // the junit and htmlunit jars
        String WEBINFPath = request.getSession().getServletContext().getRealPath("WEB-INF");
        HtmlunitJarLocation = new File(WEBINFPath + File.separator + "lib" + File.separator
                + HTMLUNIT_JAR);
        JunitJarLocation = new File(WEBINFPath + File.separator + "lib" + File.separator
                + JUNIT_JAR);

        if (!HtmlunitJarLocation.exists()) {
            errorMessage = errorMessage + "\n HtmlUnit-Tests not found.";
        }
        if (!JunitJarLocation.exists()) {
            errorMessage = errorMessage + "\n JUnit-Tests not found.";
        }

        // create tmp-directory to write the tests
        if (!new File(request.getSession().getServletContext().getRealPath("tmp")).exists()) {
            if (!new File(request.getSession().getServletContext().getRealPath("tmp")).mkdir()) {
                errorMessage = errorMessage + "\n Creation of tmp directory faild.";
            }
        }

        String submit = request.getParameter("submit");
        String type = request.getParameter("type");
        String archivedResults = request.getParameter("archived-results");
        String[] testnames = request.getParameterValues("testnames");

        View defaultView = new View();
        if (errorMessage != null) {
            return error();
        }
        if(request.getSession().getAttribute("tmpResultDir") != null){
            return showProgress(path, defaultView);
        }
        if (submit != null) {
            if (testnames != null) {
                return executeTests(path, defaultView, testnames);
            }
            if (archivedResults != null) {
                return showArchive(path, defaultView, archivedResults);
            }
            return plainRequest(path, defaultView);
        } else {

            return plainRequest(path, defaultView);
        }
    }

    private View plainRequest(Path path, View defaultView) throws Exception,
            TransformerConfigurationException, TransformerFactoryConfigurationError,
            NoSuchNodeException, TransformerException {
        Repository contentRepo;
        RepoPath rp = contentRepo(path);
        contentRepo = rp.getRepo();

        StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
        sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        sb.append("<head>");
        sb.append("<title>Testing Control</title>");
        sb.append("</head>");
        sb.append("<body>");

        sb.append("<ul id=\"htmlunit\">");
        String[] allHtmlUnitTestNames = getAllTestNames("htmlunit");

        for (int i = 0; i < allHtmlUnitTestNames.length; i++) {
            sb.append("<li title=\""
                    + allHtmlUnitTestNames[i].substring(allHtmlUnitTestNames[i].lastIndexOf("/") + 1)
                    + "\">" + allHtmlUnitTestNames[i] + "</li>");
        }

        sb.append("</ul>");
        sb.append("<ul id=\"junit\">");
        String[] allJUnitTestNames = getAllTestNames("junit");
        for (int i = 0; i < allJUnitTestNames.length; i++) {
            sb.append("<li title=\""
                    + allJUnitTestNames[i].substring(allJUnitTestNames[i].lastIndexOf("/") + 1)
                    + "\">" + allJUnitTestNames[i] + "</li>");
        }
        sb.append("</ul>");

        // sb.append("<form method=\"post\">");
        // sb.append("<br/>Archived Test-Results: <select name=\"archived-results\">");
        // try {
        // org.wyona.yarep.core.Path testResultArchivePath = new
        // org.wyona.yarep.util.YarepUtil().getRepositoryPath(new
        // org.wyona.yarep.core.Path(path.getParent()
        // .toString()
        // + "/test-results-archive/"),
        // getRepositoryFactory())
        // .getPath();
        // org.wyona.yarep.core.Path[] children = contentRepo.getChildren(testResultArchivePath);
        // for (int i = 0; i < children.length; i++) {
        // if (contentRepo.isResource(children[i])
        // && children[i].getName()
        // .matches("[\\d]{4,4}[-][\\d]{2,2}[-][\\d]{2,2}[-][\\d]{2,2}[-][\\d]{2,2}[-][\\d]{2,2}[-]tests\\.xml"))
        // {
        // sb.append("<option value=\"" + children[i] + "\">" + children[i].getName()
        // + "</option>");
        // }
        // }
        // } catch (Exception e) {
        // log.error(e);
        // }
        // sb.append("</select>");
        // sb.append("<input type=\"submit\" name=\"submit\" value=\"Show\"/>");
        // sb.append("</form>");

        sb.append("</body>");
        sb.append("</html>");

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        File result2htmlXsltFile = org.wyona.commons.io.FileUtil.file(rtd.getConfigFile()
                .getParentFile()
                .getAbsolutePath(), "xslt" + File.separator + "chooseTest.xsl");
        Transformer transResult2html = TransformerFactory.newInstance()
                .newTransformer(new StreamSource(result2htmlXsltFile));
        transResult2html.transform(new StreamSource(new java.io.StringBufferInputStream(sb.toString())),
                new StreamResult(byteArrayOutputStream));

        Transformer transformer = globalTransformer(path, contentRepo);
        // TODO: Is this the best way to generate an InputStream from an
        // OutputStream?
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        transformer.transform(new StreamSource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())),
                new StreamResult(baos));

        defaultView.setMimeType("application/xhtml+xml");<commit_msg>code cleanup. see bug #5161<commit_after>/*
 * Copyright 2006 Wyona
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.wyona.org/licenses/APACHE-LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.wyona.yanel.impl.resources;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.dom.DOMSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Category;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.PatternSet;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.taskdefs.optional.junit.JUnitTask;
import org.apache.tools.ant.taskdefs.optional.junit.BatchTest;

import org.wyona.yanel.core.Path;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.ViewableV1;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yarep.core.NoSuchNodeException;
import org.wyona.yarep.core.Repository;
import org.wyona.yarep.core.RepositoryFactory;
import org.wyona.yarep.util.RepoPath;
import org.wyona.yarep.util.YarepUtil;

/**
 * 
 */
public class TestingControlResource extends Resource implements ViewableV1 {

    private static final String JUNIT_JAR = "yanel-JunitTests.jar";
    private static final String HTMLUNIT_JAR = "yanel-HtmlUnitTests.jar";
    private static Category log = Category.getInstance(TestingControlResource.class);

    private File JunitJarLocation;
    private File HtmlunitJarLocation;
    private File tmpResultDir;
    private String errorMessage;

    public TestingControlResource() {
    }

    public ViewDescriptor[] getViewDescriptors() {
        return null;
    }

    public View getView(Path path, String viewId) {
        View defaultView = new View();
        defaultView.setMimeType("application/xml");
        StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
        defaultView.setInputStream(new java.io.StringBufferInputStream(sb.toString()));
        return defaultView;
    }

    public View getView(HttpServletRequest request, String viewId) throws Exception {
        Path path = new Path(request.getServletPath());

        // the junit and htmlunit jars
        String WEBINFPath = request.getSession().getServletContext().getRealPath("WEB-INF");
        HtmlunitJarLocation = new File(WEBINFPath + File.separator + "lib" + File.separator
                + HTMLUNIT_JAR);
        JunitJarLocation = new File(WEBINFPath + File.separator + "lib" + File.separator
                + JUNIT_JAR);

        if (!HtmlunitJarLocation.exists()) {
            errorMessage = errorMessage + "\n HtmlUnit-Tests not found.";
        }
        if (!JunitJarLocation.exists()) {
            errorMessage = errorMessage + "\n JUnit-Tests not found.";
        }

        // create tmp-directory to write the tests
        if (!new File(request.getSession().getServletContext().getRealPath("tmp")).exists()) {
            if (!new File(request.getSession().getServletContext().getRealPath("tmp")).mkdir()) {
                errorMessage = errorMessage + "\n Creation of tmp directory faild.";
            }
        }

        String submit = request.getParameter("submit");
        String type = request.getParameter("type");
        String archivedResults = request.getParameter("archived-results");
        String[] testnames = request.getParameterValues("testnames");

        View defaultView = new View();
        if (errorMessage != null) {
            return error();
        }
        if(request.getSession().getAttribute("tmpResultDir") != null){
            return showProgress(path, defaultView);
        }
        if (archivedResults != null) {
            return showArchive(path, defaultView, archivedResults);
        }
        if (submit != null) {
            if (testnames != null) {
                return executeTests(path, defaultView, testnames);
            }
            return plainRequest(path, defaultView);
        } else {

            return plainRequest(path, defaultView);
        }
    }

    private View plainRequest(Path path, View defaultView) throws Exception,
            TransformerConfigurationException, TransformerFactoryConfigurationError,
            NoSuchNodeException, TransformerException {
        Repository contentRepo;
        RepoPath rp = contentRepo(path);
        contentRepo = rp.getRepo();

        StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
        sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        sb.append("<head>");
        sb.append("<title>Testing Control</title>");
        sb.append("</head>");
        sb.append("<body>");
        sb.append("<ul id=\"htmlunit\">");
        String[] allHtmlUnitTestNames = getAllTestNames("htmlunit");

        for (int i = 0; i < allHtmlUnitTestNames.length; i++) {
            sb.append("<li title=\""
                    + allHtmlUnitTestNames[i].substring(allHtmlUnitTestNames[i].lastIndexOf("/") + 1)
                    + "\">" + allHtmlUnitTestNames[i] + "</li>");
        }

        sb.append("</ul>");
        sb.append("<ul id=\"junit\">");
        String[] allJUnitTestNames = getAllTestNames("junit");
        for (int i = 0; i < allJUnitTestNames.length; i++) {
            sb.append("<li title=\""
                    + allJUnitTestNames[i].substring(allJUnitTestNames[i].lastIndexOf("/") + 1)
                    + "\">" + allJUnitTestNames[i] + "</li>");
        }
        sb.append("</ul>");
        sb.append("</body>");
        sb.append("</html>");

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        File result2htmlXsltFile = org.wyona.commons.io.FileUtil.file(rtd.getConfigFile()
                .getParentFile()
                .getAbsolutePath(), "xslt" + File.separator + "chooseTest.xsl");
        Transformer transResult2html = TransformerFactory.newInstance()
                .newTransformer(new StreamSource(result2htmlXsltFile));
        transResult2html.transform(new StreamSource(new java.io.StringBufferInputStream(sb.toString())),
                new StreamResult(byteArrayOutputStream));

        Transformer transformer = globalTransformer(path, contentRepo);
        // TODO: Is this the best way to generate an InputStream from an
        // OutputStream?
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        transformer.transform(new StreamSource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())),
                new StreamResult(baos));

        defaultView.setMimeType("application/xhtml+xml");
{'fraction_non_alphanumeric': 0.12778240685632664, 'fraction_numerical': 0.004463754314962504, 'mean_word_length': 2.96671388101983, 'pattern_counts': {'":': 0, '<': 52, '<?xml version=': 4, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 31}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4269362', 'n_tokens_mistral': 4776, 'n_tokens_neox': 4662, 'n_words': 970}