Ignore:
Timestamp:
Sep 24, 2014, 9:34:21 PM (11 years ago)
Author:
dmik
Message:

icedtea-web: Merge version 1.5.1 from vendor to trunk.

Location:
trunk/icedtea-web/tests/test-extensions
Files:
13 edited
13 copied

Legend:

Unmodified
Added
Removed
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/ContentReader.java

    r418 r429  
    3535exception statement from your version.
    3636 */
    37 
    3837package net.sourceforge.jnlp;
    3938
     
    4241import java.io.InputStreamReader;
    4342import java.io.Reader;
     43import java.util.ArrayList;
     44import java.util.List;
    4445
    4546/**
    46  * Class to read content of stdout/stderr of process, and to cooperate with its running/terminated/finished statuses.
     47 * Class to read content of stdout/stderr of process, and to cooperate with its
     48 * running/terminated/finished statuses.
    4749 */
    4850class ContentReader implements Runnable {
     
    5153    private final InputStream is;
    5254    private boolean done;
    53     ContentReaderListener listener;
     55    final List<ContentReaderListener> listeners = new ArrayList<ContentReaderListener>(1);
    5456
    5557    public String getContent() {
     
    6365    public ContentReader(InputStream is, ContentReaderListener l) throws IOException {
    6466        this.is = is;
    65         this.listener = l;
     67        if (l != null) {
     68            this.listeners.add(l);
     69        }
    6670    }
    6771
    68     public void setListener(ContentReaderListener listener) {
    69         this.listener = listener;
     72    public ContentReader(InputStream is, List<ContentReaderListener> l) throws IOException {
     73        this.is = is;
     74        if (l != null) {
     75            this.listeners.addAll(l);
     76        }
    7077    }
    7178
    72     public ContentReaderListener getListener() {
    73         return listener;
     79    public void addListener(ContentReaderListener listener) {
     80        this.listeners.add(listener);
     81    }
     82
     83    public List<ContentReaderListener> getListener() {
     84        return listeners;
    7485    }
    7586
     
    97108                int s = br.read();
    98109                if (s < 0) {
    99                     if (line.length() > 0 && listener != null) {
    100                         listener.lineReaded(line.toString());
     110                    if (line.length() > 0 && listeners != null) {
     111                        for (ContentReaderListener listener : listeners) {
     112                            if (listener != null) {
     113                                listener.lineReaded(line.toString());
     114                            }
     115                        }
    101116                    }
    102117                    break;
     
    106121                line.append(ch);
    107122                if (ch == '\n') {
    108                     if (listener != null) {
    109                         listener.lineReaded(line.toString());
     123                    if (listeners != null) {
     124                        for (ContentReaderListener listener : listeners) {
     125                            if (listener != null) {
     126                                listener.lineReaded(line.toString());
     127                            }
     128                        }
    110129                    }
    111130                    line = new StringBuilder();
    112131                }
    113                 if (listener != null) {
    114                     listener.charReaded(ch);
     132                if (listeners != null) {
     133                    for (ContentReaderListener listener : listeners) {
     134                        if (listener != null) {
     135                            listener.charReaded(ch);
     136                        }
     137                    }
    115138                }
    116139            }
    117             //do not want to bother output with terminations
    118             //mostly compaling when assassin kill the process about StreamClosed
    119             //do not want to bother output with terminations
    120             //mostly compaling when assassin kill the process about StreamClosed
    121         } catch (Exception ex) {
     140        } catch (NullPointerException ex) {
     141            ex.printStackTrace();
     142        }
     143        //do not want to bother output with terminations
     144        //mostly compaling when assassin kill the process about StreamClosed
     145        catch (Exception ex) {
    122146            // logException(ex);
     147            //ex.printStackTrace();
    123148        } finally {
    124149            try {
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/LoggingBottleneck.java

    r418 r429  
    4646import java.io.Writer;
    4747import java.lang.reflect.Method;
     48import java.util.Collections;
    4849import java.util.HashMap;
    4950import java.util.Map;
     
    8182     * class.testMethod.logs
    8283     */
    83     final Map<String, Map<String, TestsLogs>> processLogs = new HashMap<String, Map<String, TestsLogs>>(100);
     84    final Map<String, Map<String, TestsLogs>> processLogs = Collections.synchronizedMap(new HashMap<String, Map<String, TestsLogs>>(1000));
    8485    private boolean added = false;
    8586
    86     public static LoggingBottleneck getDefaultLoggingBottleneck() {
     87    synchronized public static LoggingBottleneck getDefaultLoggingBottleneck() {
    8788        if (loggingBottleneck == null) {
    8889            loggingBottleneck = new LoggingBottleneck();
     
    102103    }
    103104
    104     void writeXmlLog() throws FileNotFoundException, IOException {
     105   synchronized void writeXmlLog() throws FileNotFoundException, IOException {
    105106        writeXmlLog(DEFAULT_LOG_FILE);
    106107    }
    107108
    108     void writeXmlLog(File f) throws FileNotFoundException, IOException {
     109    synchronized void writeXmlLog(File f) throws FileNotFoundException, IOException {
     110        writeXmlLog(f, Collections.unmodifiableMap(processLogs));
     111    }
     112       
     113    synchronized static void writeXmlLog(File f, Map<String, Map<String, TestsLogs>> processLogs) throws FileNotFoundException, IOException {
    109114        Writer w = new OutputStreamWriter(new FileOutputStream(f));
    110115        Set<Entry<String, Map<String, TestsLogs>>> classes = processLogs.entrySet();
     
    118123                String testLogs = testLog.getValue().toString();
    119124                w.write("<" + TESTLOG_ELEMENT + " " + TESTMETHOD_ATTRIBUTE + "=\"" + testName + "\" " + FULLID_ATTRIBUTE + "=\"" + className + "." + testName + "\"  >");
    120                 w.write(testLogs);
     125                w.write(clearChars(testLogs));
    121126                w.write("</" + TESTLOG_ELEMENT + ">");
    122127            }
     
    128133    }
    129134
    130     void addToXmlLog(String message, boolean printToOut, boolean printToErr, StackTraceElement ste) {
     135    synchronized  void addToXmlLog(String message, boolean printToOut, boolean printToErr, StackTraceElement ste) {
    131136        Map<String, TestsLogs> classLog = processLogs.get(ste.getClassName());
    132137        if (classLog == null) {
     
    158163    }
    159164
    160     public String modifyMethodWithForBrowser(String methodBrowseredName, String className) {
     165   synchronized public String modifyMethodWithForBrowser(String methodBrowseredName, String className) {
    161166        try {
    162             Class clazz = Class.forName(className);
     167            Class<?> clazz = Class.forName(className);
    163168            /*
    164169             * By using this isAssignable to ensure corect class before invocation,
     
    181186    }
    182187
    183     public void setLoggedBrowser(String loggedBrowser) {
     188   synchronized public void setLoggedBrowser(String loggedBrowser) {
    184189        this.loggedBrowser = loggedBrowser;
    185190    }
    186191
    187     public void logIntoPlaintextLog(String message, boolean printToOut, boolean printToErr) {
     192  synchronized  public void logIntoPlaintextLog(String message, boolean printToOut, boolean printToErr) {
    188193        try {
    189194            if (printToOut) {
     
    202207        DEFAULT_STDOUT_WRITER.write(idded);
    203208        DEFAULT_STDOUT_WRITER.newLine();
     209        DEFAULT_STDOUT_WRITER.flush();
    204210    }
    205211
     
    207213        DEFAULT_STDERR_WRITER.write(idded);
    208214        DEFAULT_STDERR_WRITER.newLine();
     215        DEFAULT_STDERR_WRITER.flush();
    209216    }
    210217
     
    212219        DEFAULT_STDLOGS_WRITER.write(idded);
    213220        DEFAULT_STDLOGS_WRITER.newLine();
     221        DEFAULT_STDLOGS_WRITER.flush();
     222    }
     223   
     224   synchronized public  static String clearChars(String ss) {
     225        StringBuilder s = new StringBuilder(ss);
     226        for (int i = 0; i < s.length(); i++) {
     227            char q = s.charAt(i);
     228            if (q == '\n') {
     229                continue;
     230            }
     231            if (q == '\t') {
     232                continue;
     233            }
     234            int iq = (int) q;
     235            if ((iq <= 31 || iq > 65533)||(iq >= 64976 && iq <= 65007)) {
     236                s.setCharAt(i, 'I');
     237                s.insert(i + 1, "NVALID_CHAR_" + iq);
     238                i--;
     239            }
     240        }
     241        return s.toString();
    214242    }
    215243}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/ProcessAssasin.java

    r418 r429  
    4040import java.util.ArrayList;
    4141import java.util.List;
     42import net.sourceforge.jnlp.browsertesting.ReactingProcess;
    4243
    4344/**
    44  * class which timeout any ThreadedProcess. This killing of 'thread with process' replaced not working process.destroy().
     45 * class which timeout any ThreadedProcess. This killing of 'thread with
     46 * process' replaced not working process.destroy().
    4547 */
    46 class ProcessAssasin extends Thread {
     48public class ProcessAssasin extends Thread {
    4749
    4850    long timeout;
     
    5153    private boolean canRun = true;
    5254    private boolean wasTerminated = false;
     55    //signifies that assasin have been summoned
     56    private volatile boolean killing = false;
     57    //signifies that assasin have done its job
     58    private volatile boolean killed = false;
    5359    /**
    54      * if this is true, then process is not destroyed after timeout, but just left to its own destiny.
    55      * Its stdout/err is no longer recorded, and it is leaking system resources until it dies by itself
    56      * The contorl is returned to main thread with all informations recorded  untill now.
    57      * You will be able to listen to std out from listeners still
     60     * if this is true, then process is not destroyed after timeout, but just
     61     * left to its own destiny. Its stdout/err is no longer recorded, and it is
     62     * leaking system resources until it dies by itself The contorl is returned
     63     * to main thread with all informations recorded untill now. You will be
     64     * able to listen to std out from listeners still
    5865     */
    5966    private boolean skipInstedOfDesroy = false;
     67    private ReactingProcess reactingProcess;
    6068
    6169    public ProcessAssasin(ThreadedProcess p, long timeout) {
     
    98106        return skipInstedOfDesroy;
    99107    }
     108
     109    void setTimeout(long timeout) {
     110        this.timeout = timeout;
     111    }
     112
    100113
    101114    @Override
     
    119132                                try {
    120133                                    if (!skipInstedOfDesroy) {
    121                                         destroyProcess(p);
     134                                        destroyProcess();
    122135                                    }
    123136                                } catch (Throwable ex) {
     
    161174    }
    162175
    163     public static void destroyProcess(ThreadedProcess pp) {
     176    public void destroyProcess() {
     177        try {
     178            killing = true;
     179            destroyProcess(p, reactingProcess);
     180        } finally {
     181            killed = true;
     182        }
     183    }
     184
     185    public boolean haveKilled() {
     186        return killed;
     187    }
     188
     189    public boolean isKilling() {
     190        return killing;
     191    }
     192
     193
     194
     195    public static void destroyProcess(ThreadedProcess pp, ReactingProcess reactingProcess) {
    164196        Process p = pp.getP();
    165197        try {
     
    167199            f.setAccessible(true);
    168200            String pid = (f.get(p)).toString();
     201            if (reactingProcess != null) {
     202                reactingProcess.beforeKill(pid);
     203            };
    169204            sigInt(pid);
    170205            //sigTerm(pid);
     
    174209        } finally {
    175210            p.destroy();
     211            if (reactingProcess != null) {
     212                reactingProcess.afterKill("");
     213            };
    176214        }
    177215    }
     
    189227    }
    190228
    191     public static void kill(String pid,String signal) throws InterruptedException, Exception {
     229    public static void kill(String pid, String signal) throws InterruptedException, Exception {
    192230        List<String> ll = new ArrayList<String>(4);
    193231        ll.add("kill");
     
    199237        Thread.sleep(1000);
    200238    }
     239
     240    void setReactingProcess(ReactingProcess reactingProcess) {
     241        this.reactingProcess = reactingProcess;
     242    }
     243
     244    public static void closeWindow(String pid) throws Exception {
     245        List<String> ll = new ArrayList<String>(2);
     246        ll.add(ServerAccess.getInstance().getDir().getParent() + "/softkiller");
     247        ll.add(pid);
     248        ServerAccess.executeProcess(ll); //sync, but  acctually release
     249        //before affected application "close"
     250        Thread.sleep(100);
     251
     252    }
     253
     254    public static void closeWindows(String s) throws Exception {
     255        closeWindows(s, 10);
     256    }
     257   
     258    public static void closeWindows(String s, int count) throws Exception {
     259        //each close closes just one tab...
     260        for (int i = 0; i < count; i++) {
     261            ProcessAssasin.closeWindow(s);
     262        }
     263    }
     264
     265
    201266}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/ServerAccess.java

    r418 r429  
    11/* ServerAccess.java
    2 Copyright (C) 2011 Red Hat, Inc.
     2Copyright (C) 2011, 2012 Red Hat, Inc.
    33
    44This file is part of IcedTea.
     
    5656import java.util.ArrayList;
    5757import java.util.List;
     58import net.sourceforge.jnlp.ProcessResult;
    5859import net.sourceforge.jnlp.browsertesting.Browser;
    5960import net.sourceforge.jnlp.browsertesting.BrowserFactory;
    6061import net.sourceforge.jnlp.browsertesting.Browsers;
     62import net.sourceforge.jnlp.closinglisteners.AutoErrorClosingListener;
     63import net.sourceforge.jnlp.closinglisteners.AutoOkClosingListener;
     64import net.sourceforge.jnlp.util.FileUtils;
     65import net.sourceforge.jnlp.util.logging.OutputController;
    6166import org.junit.Assert;
    6267
     
    7883public class ServerAccess {
    7984
     85    public static enum AutoClose {
     86
     87        CLOSE_ON_EXCEPTION, CLOSE_ON_CORRECT_END, CLOSE_ON_BOTH
     88    }
     89
    8090    public static final long NANO_TIME_DELIMITER=1000000l;
    8191    /**
     
    132142        } else {
    133143            int port = 44321;
    134             if (args.length > 0) {
    135                 port=new Integer(args[0]);
     144            if (args.length > 0 && args[0].equalsIgnoreCase("randomport")) {
     145                port = findFreePort();
     146            } else if (args.length > 0) {
     147                port = new Integer(args[0]);
    136148            }
    137149            getIndependentInstance(port);
     
    157169    }
    158170    public static final  String HEADLES_OPTION="-headless";
    159     public static final  String VERBOSE_OPTION="-verbose ";
     171    public static final  String VERBOSE_OPTION="-verbose";
    160172
    161173    /**
     
    260272       List<String> l1=this.currentBrowser.getComaptibilitySwitches();
    261273       List<String> l2=this.currentBrowser.getDefaultSwitches();
    262        List<String> l= new ArrayList();
     274       List<String> l= new ArrayList<String>();
    263275       if (l1!=null)l.addAll(l1);
    264276       if (l2!=null)l.addAll(l2);
     
    409421     * @throws IOException if connection can't be established or resource does not exist
    410422     */
    411     public static String getContentOfStream(InputStream is,String encoding) throws IOException {
    412         try {
    413             BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
    414             StringBuilder sb = new StringBuilder();
    415             while (true) {
    416                 String s = br.readLine();
    417                 if (s == null) {
    418                     break;
    419                 }
    420                 sb.append(s).append("\n");
    421 
    422             }
    423             return sb.toString();
    424         } finally {
    425             is.close();
    426         }
    427 
     423    public static String getContentOfStream(InputStream is, String encoding) throws IOException {
     424        return FileUtils.getContentOfStream(is, encoding);
    428425    }
    429426
     
    436433     */
    437434    public static String getContentOfStream(InputStream is) throws IOException {
    438         return getContentOfStream(is, "UTF-8");
    439 
     435        return FileUtils.getContentOfStream(is);
    440436    }
    441437
     
    483479     */
    484480    public static void saveFile(String content, File f) throws IOException {
    485         saveFile(content, f, "utf-8");
     481        FileUtils.saveFile(content, f);
    486482    }
    487483    public static void saveFile(String content, File f,String encoding) throws IOException {
    488         Writer output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),encoding));
    489         output.write(content);
    490         output.flush();
    491         output.close();
     484        FileUtils.saveFile(content, f, encoding);
    492485    }
    493486
     
    546539        return executeJavaws(null, resource,stdoutl,stderrl);
    547540    }
     541
     542    public net.sourceforge.jnlp.ProcessResult executeBrowser(String string, AutoClose autoClose) throws Exception {
     543        ClosingListener errClosing = null;
     544        ClosingListener outClosing = null;
     545        if (autoClose == AutoClose.CLOSE_ON_BOTH || autoClose == AutoClose.CLOSE_ON_EXCEPTION){
     546            errClosing=new AutoErrorClosingListener();
     547        }
     548        if (autoClose == AutoClose.CLOSE_ON_BOTH || autoClose == AutoClose.CLOSE_ON_CORRECT_END){
     549            outClosing=new AutoOkClosingListener();
     550        }
     551        return executeBrowser(string, outClosing, errClosing);
     552    }
     553   
     554
    548555    public ProcessResult executeBrowser(String resource) throws Exception {
    549556        return executeBrowser(getBrowserParams(), resource);
    550557    }
    551558    public ProcessResult executeBrowser(String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
     559        return executeBrowser(getBrowserParams(), resource, stdoutl, stderrl);
     560    }
     561
     562    public ProcessResult executeBrowser(String resource, List<ContentReaderListener> stdoutl, List<ContentReaderListener> stderrl) throws Exception {
    552563        return executeBrowser(getBrowserParams(), resource, stdoutl, stderrl);
    553564    }
     
    572583
    573584    public ProcessResult executeBrowser(List<String> otherargs, String resource) throws Exception {
    574         return executeProcessUponURL(getBrowserLocation(), otherargs, getUrlUponThisInstance(resource));
    575     }
    576     public ProcessResult executeBrowser(List<String> otherargs, String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
    577         return executeProcessUponURL(getBrowserLocation(), otherargs, getUrlUponThisInstance(resource),stdoutl,stderrl);
    578     }
    579 
    580      public ProcessResult executeBrowser(Browser b,List<String> otherargs, String resource) throws Exception {
    581         return executeProcessUponURL(b.getBin(), otherargs, getUrlUponThisInstance(resource));
    582     }
    583     public ProcessResult executeBrowser(Browser b,List<String> otherargs, String resource,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
    584         return executeProcessUponURL(b.getBin(), otherargs, getUrlUponThisInstance(resource),stdoutl,stderrl);
     585        return executeBrowser(otherargs, getUrlUponThisInstance(resource));       
     586    }
     587   
     588     public ProcessResult executeBrowser(List<String> otherargs, URL url) throws Exception {
     589        ProcessWrapper rpw = new ProcessWrapper(getBrowserLocation(), otherargs, url);
     590        rpw.setReactingProcess(getCurrentBrowser());//current browser may be null, but it does not metter
     591        return rpw.execute();
     592    }
     593
     594    public ProcessResult executeBrowser(List<String> otherargs, String resource, ContentReaderListener stdoutl, ContentReaderListener stderrl) throws Exception {
     595        ProcessWrapper rpw = new ProcessWrapper(getBrowserLocation(), otherargs, getUrlUponThisInstance(resource), stdoutl, stderrl, null);
     596        rpw.setReactingProcess(getCurrentBrowser());//current browser may be null, but it does not metter
     597        return rpw.execute();
     598    }
     599
     600    public ProcessResult executeBrowser(List<String> otherargs,    String resource, List<ContentReaderListener> stdoutl, List<ContentReaderListener> stderrl) throws Exception {
     601        ProcessWrapper rpw = new ProcessWrapper(getBrowserLocation(), otherargs, getUrlUponThisInstance(resource), stdoutl, stderrl, null);
     602        rpw.setReactingProcess(getCurrentBrowser());// current browser may be null, but it does not matter
     603        return rpw.execute();
     604    }
     605
     606    public ProcessResult executeBrowser(Browser b, List<String> otherargs, String resource) throws Exception {
     607        ProcessWrapper rpw = new ProcessWrapper(b.getBin(), otherargs, getUrlUponThisInstance(resource));
     608        rpw.setReactingProcess(b);
     609        return rpw.execute();
     610    }
     611
     612    public ProcessResult executeBrowser(Browser b, List<String> otherargs, String resource, ContentReaderListener stdoutl, ContentReaderListener stderrl) throws Exception {
     613        ProcessWrapper rpw = new ProcessWrapper(b.getBin(), otherargs, getUrlUponThisInstance(resource), stdoutl, stderrl, null);
     614        rpw.setReactingProcess(b);
     615        return rpw.execute();
     616    }
     617
     618    public ProcessResult executeBrowser(Browser b, List<String> otherargs, String resource, List<ContentReaderListener> stdoutl, List<ContentReaderListener> stderrl) throws Exception {
     619        ProcessWrapper rpw = new ProcessWrapper(b.getBin(), otherargs, getUrlUponThisInstance(resource), stdoutl, stderrl, null);
     620        rpw.setReactingProcess(b);
     621        return rpw.execute();
     622    }
     623
     624    /**
     625     * Create resource on http, on 'localhost' on port on which this cached instance is running
     626     * @param resource
     627     * @return
     628     * @throws MalformedURLException
     629     */
     630    public URL getUrlUponThisInstance(String resource) throws MalformedURLException {
     631        getInstance();
     632        return getUrlUponInstance(server, resource);
    585633    }
    586634
     
    591639     * @throws MalformedURLException
    592640     */
    593     public URL getUrlUponThisInstance(String resource) throws MalformedURLException {
    594         if (!resource.startsWith("/")) {
    595             resource = "/" + resource;
    596         }
    597         return new URL("http", server.getServerName(), getPort(), resource);
     641    public static URL getUrlUponInstance(ServerLauncher instance,String resource) throws MalformedURLException {
     642       return instance.getUrl(resource);
    598643    }
    599644
     
    623668     */
    624669    public static ProcessResult executeProcessUponURL(String toBeExecuted, List<String> otherargs, URL u) throws Exception {
    625         return executeProcessUponURL(toBeExecuted, otherargs, u,null,null);
    626     }
    627 
    628     public static ProcessResult executeProcessUponURL(String toBeExecuted, List<String> otherargs, URL u,ContentReaderListener stdoutl,ContentReaderListener stderrl) throws Exception {
    629         return executeProcessUponURL(toBeExecuted, otherargs, u, stdoutl, stderrl, null);
    630     }
    631     public static ProcessResult executeProcessUponURL(String toBeExecuted, List<String> otherargs, URL u,ContentReaderListener stdoutl,ContentReaderListener stderrl,String[] vars) throws Exception {
    632         Assert.assertNotNull(u);
    633         Assert.assertNotNull(toBeExecuted);
    634         Assert.assertTrue(toBeExecuted.trim().length() > 1);
    635         if (otherargs == null) {
    636             otherargs = new ArrayList<String>(1);
    637         }
    638         List<String> urledArgs = new ArrayList<String>(otherargs);
    639         urledArgs.add(0, toBeExecuted);
    640         urledArgs.add(u.toString());
    641         return executeProcess(urledArgs, stdoutl, stderrl,vars);
     670        return new ProcessWrapper(toBeExecuted, otherargs, u).execute();
     671    }
     672
     673    public static ProcessResult executeProcessUponURL(String toBeExecuted, List<String> otherargs, URL u, ContentReaderListener stdoutl, ContentReaderListener stderrl) throws Exception {
     674        return new ProcessWrapper(toBeExecuted, otherargs, u, stdoutl, stderrl, null).execute();
     675    }
     676
     677    public static ProcessResult executeProcessUponURL(String toBeExecuted, List<String> otherargs, URL u, ContentReaderListener stdoutl, ContentReaderListener stderrl, String[] vars) throws Exception {
     678        return new ProcessWrapper(toBeExecuted, otherargs, u, stdoutl, stderrl, vars).execute();
    642679    }
    643680
     
    671708    }
    672709
    673     private static String createConnectionMessage(ThreadedProcess t) {
    674         return "Connecting " + t.getCommandLine();
    675     }
    676 
    677710    /**
    678711     * Proceed message s to logging with request to reprint to System.err
     
    699732    }
    700733
    701     private static void log(String message, boolean printToOut, boolean printToErr) {
     734    static void log(String message, boolean printToOut, boolean printToErr) {
    702735        String idded;
    703736        StackTraceElement ste = getTestMethod();
     
    726759    }
    727760    public static void logException(Throwable t, boolean print){
    728         try{
    729         StringWriter sw = new StringWriter();
    730         PrintWriter pw = new PrintWriter(sw);
    731         t.printStackTrace(pw);
    732         log(sw.toString(), false, print);
    733         pw.close();
    734         sw.close();
    735         }catch(Exception ex){
    736            throw new RuntimeException(ex);
    737         }
     761        log(OutputController.exceptionToString(t), false, print);
    738762    }
    739763
     
    744768    private static StackTraceElement getTestMethod(StackTraceElement[] stack) {
    745769        //0 is always thread
    746         //1 is net.sourceforge.jnlp.ServerAccess
     770        //1 is net.sourceforge.jnlp.*
     771        //we need to get out of all  of classes from this package or pick last of it
    747772        StackTraceElement result = stack[1];
    748773        String baseClass = stack[1].getClassName();
     
    750775        for (; i < stack.length; i++) {
    751776            result = stack[i];//at least moving up
    752             if(stack[i].getClassName().contains("$")){
     777            if (stack[i].getClassName().contains("$")) {
    753778                continue;
    754779            }
    755             if (!baseClass.equals(stack[i].getClassName())) {
    756                 break;
     780            //probablky it is necessary to get out of net.sourceforge.jnlp.
     781            //package where are right now all test-extensions
     782            //for now keeping exactly the three classes helping you  access the log
     783            try {
     784                Class<?> clazz = Class.forName(stack[i].getClassName());
     785                String path = null;
     786                try {
     787                    path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
     788                } catch (NullPointerException ex) {
     789                    //silently ignoring and continuing with null path
     790                }
     791                if (path != null && path.contains("/tests.build/")) {
     792                    if (!path.contains("/test-extensions/")) {
     793                        break;
     794                    }
     795                } else {
     796                    //running from ide
     797                    if (!stack[i].getClassName().startsWith("net.sourceforge.jnlp.")) {
     798                        break;
     799                    }
     800                }
     801            } catch (ClassNotFoundException ex) {
     802                ///should not happen, searching  only for already loaded class
     803                ex.printStackTrace();
    757804            }
    758805        }
     
    760807        //so the target method is the highest form it and better to return it
    761808        //rather then die to ArrayOutOfBounds
    762         if(i >= stack.length){
     809        if (i >= stack.length) {
    763810            return result;
    764811        }
    765         //now we are out of net.sourceforge.jnlp.ServerAccess
     812        //now we are out of test-extensions
    766813        //method we need (the test)  is highest from following class
    767814        baseClass = stack[i].getClassName();
     
    783830
    784831    }
    785     public static ProcessResult executeProcess(final List<String> args, File dir, ContentReaderListener stdoutl, ContentReaderListener stderrl,String[] vars) throws Exception {
    786         ThreadedProcess t = new ThreadedProcess(args, dir,vars);
    787         if (PROCESS_LOG) {
    788             String connectionMesaage = createConnectionMessage(t);
    789             log(connectionMesaage, true, true);
    790         }
    791         ProcessAssasin pa = new ProcessAssasin(t, PROCESS_TIMEOUT);
    792         pa.start();
    793         t.start();
    794         while (t.getP() == null && t.deadlyException == null) {
    795             Thread.sleep(100);
    796         }
    797         if (t.deadlyException != null) {
    798             pa.setCanRun(false);
    799             return new ProcessResult("", "", null, true, Integer.MIN_VALUE, t.deadlyException);
    800         }
    801         ContentReader crs = new ContentReader(t.getP().getInputStream(),stdoutl);
    802         ContentReader cre = new ContentReader(t.getP().getErrorStream(),stderrl);
    803 
    804         OutputStream out = t.getP().getOutputStream();
    805         if (out != null) {
    806             out.close();
    807         }
    808 
    809         new Thread(crs).start();
    810         new Thread(cre).start();
    811         while (t.isRunning()) {
    812             Thread.sleep(100);
    813         }
    814 
    815         while (!t.isDestoyed()) {
    816             Thread.sleep(100);
    817         }
    818         pa.setCanRun(false);
    819         // ServerAccess.logOutputReprint(t.getP().exitValue()); when process is killed, this throws exception
    820 
    821         ProcessResult pr=new ProcessResult(crs.getContent(), cre.getContent(), t.getP(), pa.wasTerminated(), t.getExitCode(), null);
    822         if (PROCESS_LOG) {
    823             log(pr.stdout, true, false);
    824             log(pr.stderr, false, true);
    825         }
    826         return pr;
    827     }
    828 
    829     /**
    830      * this is temprary solution until refactoring is fully done
    831      * Use  net.sourceforge.jnlp.ProcessResult instead
    832      */
    833     @Deprecated
    834     public static class ProcessResult extends net.sourceforge.jnlp.ProcessResult {
    835 
    836         public ProcessResult(String stdout, String stderr, Process process, boolean wasTerminated, Integer r, Throwable deadlyException) {
    837             super(stdout, stderr, process, wasTerminated, r, deadlyException);
    838         }
    839     }
    840     }
     832    public static ProcessResult executeProcess(final List<String> args, File dir, ContentReaderListener stdoutl, ContentReaderListener stderrl, String[] vars) throws Exception {
     833        return new ProcessWrapper(args, dir, stdoutl, stderrl, vars).execute();
     834    }
     835
     836}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/ServerLauncher.java

    r418 r429  
    5757    private final Integer port;
    5858    private final File dir;
     59    private ServerSocket serverSocket;
     60    private boolean supportingHeadRequest = true;
    5961
     62    public void setSupportingHeadRequest(boolean supportsHead) {
     63        this.supportingHeadRequest = supportsHead;
     64    }
     65
     66    public boolean isSupportingHeadRequest() {
     67        return supportingHeadRequest;
     68    }
     69
     70   
     71   
    6072    public String getServerName() {
    6173        return serverName;
     
    100112        running = true;
    101113        try {
    102             ServerSocket s = new ServerSocket(port);
     114            serverSocket = new ServerSocket(port);
    103115            while (running) {
    104                 new TinyHttpdImpl(s.accept(), dir, port);
     116                TinyHttpdImpl server = new TinyHttpdImpl(serverSocket.accept(), dir, false);
     117                server.setSupportingHeadRequest(isSupportingHeadRequest());
     118                server.start();
    105119            }
    106120        } catch (Exception e) {
    107             e.printStackTrace();
     121            ServerAccess.logException(e);
    108122        } finally {
    109123            running = false;
     
    112126
    113127    public URL getUrl(String resource) throws MalformedURLException {
     128        if (resource == null) {
     129            resource = "";
     130        }
     131        if (resource.trim().length() > 0 && !resource.startsWith("/")) {
     132            resource = "/" + resource;
     133        }
    114134        return new URL("http", getServerName(), getPort(), resource);
    115135    }
     
    118138        return getUrl("");
    119139    }
     140
     141    public void stop() {
     142        this.running = false;
     143        if (serverSocket != null) {
     144            try {
     145                serverSocket.close();
     146            } catch (Exception ex) {
     147                ServerAccess.logException(ex);
     148            }
     149        }
     150    }
    120151}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/ThreadedProcess.java

    r418 r429  
    4646 * Process builder caused some unexpected and weird behavior :/
    4747 */
    48 class ThreadedProcess extends Thread {
     48public class ThreadedProcess extends Thread {
    4949
    5050    Process p = null;
     
    6060     */
    6161    private boolean destoyed = false;
     62    private ProcessAssasin assasin;
    6263
    6364    public boolean isDestoyed() {
     
    118119        } catch (Exception ex) {
    119120            ex.printStackTrace();
    120         } finally {
    121             return commandLine;
    122121        }
     122        return commandLine;
    123123    }
    124124
     
    144144                exitCode = p.waitFor();
    145145                Thread.sleep(500); //this is giving to fast done proecesses's e/o readers time to read all. I would like to know better solution :-/
     146                while(assasin.isKilling() && !assasin.haveKilled()){
     147                    Thread.sleep(100);
     148                };
    146149            } finally {
    147150                destoyed = true;
     
    164167        }
    165168    }
     169
     170    void setAssasin(ProcessAssasin pa) {
     171        this.assasin=pa;
     172    }
    166173}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/TinyHttpdImpl.java

    r418 r429  
    4343import java.io.FileInputStream;
    4444import java.io.InputStreamReader;
     45import java.io.UnsupportedEncodingException;
     46import java.net.HttpURLConnection;
    4547import java.net.Socket;
    4648import java.net.SocketException;
     
    5658 * is returned, but its delivery is delayed
    5759 */
    58 class TinyHttpdImpl extends Thread {
    59 
    60     Socket c;
    61     private final File dir;
    62     private final int port;
     60public class TinyHttpdImpl extends Thread {
     61
     62    private static final String CRLF = "\r\n";
     63    private static final String HTTP_NOT_IMPLEMENTED = "HTTP/1.0 " + HttpURLConnection.HTTP_NOT_IMPLEMENTED + " Not Implemented" + CRLF;
     64    private static final String HTTP_NOT_FOUND = "HTTP/1.0 " + HttpURLConnection.HTTP_NOT_FOUND + " Not Found" + CRLF;
     65    private static final String HTTP_OK = "HTTP/1.0 " + HttpURLConnection.HTTP_OK + " OK" + CRLF;
     66    private static final String XSX = "/XslowX";
     67
     68    private Socket socket;
     69    private final File testDir;
    6370    private boolean canRun = true;
    64     private static final String XSX = "/XslowX";
    65 
    66     public TinyHttpdImpl(Socket s, File f, int port) {
    67         c = s;
    68         this.dir = f;
    69         this.port = port;
    70         start();
     71    private boolean supportingHeadRequest = true;
     72
     73    public TinyHttpdImpl(Socket socket, File dir) {
     74        this(socket, dir, true);
     75    }
     76
     77    public TinyHttpdImpl(Socket socket, File dir, boolean start) {
     78        this.socket = socket;
     79        this.testDir = dir;
     80        if (start) {
     81            start();
     82        }
    7183    }
    7284
     
    7587    }
    7688
     89    public void setSupportingHeadRequest(boolean supportsHead) {
     90        this.supportingHeadRequest = supportsHead;
     91    }
     92
     93    public boolean isSupportingHeadRequest() {
     94        return this.supportingHeadRequest;
     95    }
     96
    7797    public int getPort() {
    78         return port;
     98        return this.socket.getPort();
    7999    }
    80100
     
    82102    public void run() {
    83103        try {
    84             BufferedReader i = new BufferedReader(new InputStreamReader(c.getInputStream()));
    85             DataOutputStream o = new DataOutputStream(c.getOutputStream());
     104            BufferedReader reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
     105            DataOutputStream writer = new DataOutputStream(this.socket.getOutputStream());
    86106            try {
    87107                while (canRun) {
    88                     String s = i.readLine();
    89                     if (s.length() < 1) {
     108                    String line = reader.readLine();
     109                    if (line.length() < 1) {
    90110                        break;
    91111                    }
    92                     if (s.startsWith("GET")) {
    93                         StringTokenizer t = new StringTokenizer(s, " ");
    94                         t.nextToken();
    95                         String op = t.nextToken();
    96                         String p = op;
    97                         if (p.startsWith(XSX)) {
    98                             p = p.replace(XSX, "/");
    99                         }
    100                         ServerAccess.logNoReprint("Getting: " + p);
    101                         p = URLDecoder.decode(p, "UTF-8");
    102                         ServerAccess.logNoReprint("Serving: " + p);
    103                         p = (".".concat((p.endsWith("/")) ? p.concat("index.html") : p)).replace('/', File.separatorChar);
    104                         File pp = new File(dir, p);
    105                         int l = (int) pp.length();
    106                         byte[] b = new byte[l];
    107                         FileInputStream f = new FileInputStream(pp);
    108                         f.read(b);
    109                         String content = "";
    110                         String ct = "Content-Type: ";
    111                         if (p.toLowerCase().endsWith(".jnlp")) {
    112                             content = ct + "application/x-java-jnlp-file\n";
    113                         } else if (p.toLowerCase().endsWith(".html")) {
    114                             content = ct + "text/html\n";
    115                         } else if (p.toLowerCase().endsWith(".jar")) {
    116                             content = ct + "application/x-jar\n";
    117                         }
    118                         o.writeBytes("HTTP/1.0 200 OK\nConten" + "t-Length:" + l + "\n" + content + "\n");
    119                         if (op.startsWith(XSX)) {
    120                             byte[][] bb = splitArray(b, 10);
     112
     113                    StringTokenizer t = new StringTokenizer(line, " ");
     114                    String request = t.nextToken();
     115
     116                    boolean isHeadRequest = request.equals("HEAD");
     117                    boolean isGetRequest = request.equals("GET");
     118
     119                    if (isHeadRequest && !isSupportingHeadRequest()) {
     120                        ServerAccess.logOutputReprint("Received HEAD request but not supported");
     121                        writer.writeBytes(HTTP_NOT_IMPLEMENTED);
     122                        continue;
     123                    }
     124
     125                    if (!isHeadRequest && !isGetRequest) {
     126                        ServerAccess.logOutputReprint("Received unknown request type " + request);
     127                        continue;
     128                    }
     129
     130                    String filePath = t.nextToken();
     131                    boolean slowSend = filePath.startsWith(XSX);
     132
     133                    if (slowSend) {
     134                        filePath = filePath.replace(XSX, "/");
     135                    }
     136
     137                    ServerAccess.logOutputReprint("Getting- " + request + ": " + filePath);
     138                    filePath = urlToFilePath(filePath);
     139
     140                    File resource = new File(this.testDir, filePath);
     141
     142                    if (!(resource.isFile() && resource.canRead())) {
     143                        ServerAccess.logOutputReprint("Could not open file " + filePath);
     144                        writer.writeBytes(HTTP_NOT_FOUND);
     145                        continue;
     146                    }
     147                    ServerAccess.logOutputReprint("Serving- " + request + ": " + filePath);
     148
     149                    int resourceLength = (int) resource.length();
     150                    byte[] buff = new byte[resourceLength];
     151                    FileInputStream fis = new FileInputStream(resource);
     152                    fis.read(buff);
     153                    fis.close();
     154
     155                    String contentType = "Content-Type: ";
     156                    if (filePath.toLowerCase().endsWith(".jnlp")) {
     157                        contentType += "application/x-java-jnlp-file";
     158                    } else if (filePath.toLowerCase().endsWith(".jar")) {
     159                        contentType += "application/x-jar";
     160                    } else {
     161                        contentType += "text/html";
     162                    }
     163                    writer.writeBytes(HTTP_OK + "Content-Length:" + resourceLength + CRLF + contentType + CRLF + CRLF);
     164
     165                    if (isGetRequest) {
     166                        if (slowSend) {
     167                            byte[][] bb = splitArray(buff, 10);
    121168                            for (int j = 0; j < bb.length; j++) {
    122169                                Thread.sleep(2000);
    123170                                byte[] bs = bb[j];
    124                                 o.write(bs, 0, bs.length);
     171                                writer.write(bs, 0, bs.length);
    125172                            }
    126173                        } else {
    127                             o.write(b, 0, l);
     174                            writer.write(buff, 0, resourceLength);
    128175                        }
    129176                    }
     
    132179                ServerAccess.logException(e, false);
    133180            } catch (Exception e) {
    134                 o.writeBytes("HTTP/1.0 404 ERROR\n\n\n");
     181                writer.writeBytes(HTTP_NOT_FOUND);
    135182                ServerAccess.logException(e, false);
     183            } finally {
     184                reader.close();
     185                writer.close();
    136186            }
    137             o.close();
    138187        } catch (Exception e) {
    139188            ServerAccess.logException(e, false);
     
    172221        return array;
    173222    }
     223
     224    /**
     225    * This function transforms a request URL into a path to a file which the server
     226    * will return to the requester.
     227    * @param url - the request URL
     228    * @return a String representation of the local path to the file
     229    * @throws UnsupportedEncodingException
     230    */
     231    public static String urlToFilePath(String url) throws UnsupportedEncodingException {
     232        url = URLDecoder.decode(url, "UTF-8"); // Decode URL encoded charaters, eg "%3B" becomes ';'
     233        if (url.startsWith(XSX)) {
     234            url = url.replace(XSX, "/");
     235        }
     236        url = url.replaceAll("\\?.*", ""); // Remove query string from URL
     237        url = ".".concat(url); // Change path into relative path
     238        if (url.endsWith("/")) {
     239            url += "index.html";
     240        }
     241        url = url.replace('/', File.separatorChar); // If running on Windows, replace '/' in path with "\\"
     242        url = stripHttpPathParams(url);
     243        return url;
     244    }
     245
     246    /**
     247     * This function removes the HTTP Path Parameter from a given JAR URL, assuming that the
     248     * path param delimiter is a semicolon
     249     * @param url - the URL from which to remove the path parameter
     250     * @return the URL with the path parameter removed
     251     */
     252    public static String stripHttpPathParams(String url) {
     253        if (url == null) {
     254            return null;
     255        }
     256
     257        // If JNLP specifies JAR URL with .JAR extension (as it should), then look for any semicolons
     258        // after this position. If one is found, remove it and any following characters.
     259        int fileExtension = url.toUpperCase().lastIndexOf(".JAR");
     260        if (fileExtension != -1) {
     261            int firstSemiColon = url.indexOf(';', fileExtension);
     262            if (firstSemiColon != -1) {
     263                url = url.substring(0, firstSemiColon);
     264            }
     265        }
     266        return url;
     267    }
    174268}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/annotations/KnownToFail.java

    r418 r429  
    4242import java.lang.annotation.RetentionPolicy;
    4343import java.lang.annotation.Target;
     44import net.sourceforge.jnlp.browsertesting.Browsers;
    4445
    4546/**
     
    5354 * implemented.
    5455 * </p>
     56 * <p>
     57 * The meaning of optional parameter failsIn is either a list of
     58 * browsers where the test fails, or a default value - an empty array {},
     59 * default value means that the test fails always.
     60 * </p>
    5561 */
    5662
     
    5864@Retention(RetentionPolicy.RUNTIME)
    5965public @interface KnownToFail {
    60    
     66    public Browsers[] failsIn() default {};
    6167}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/browsertesting/Browser.java

    r418 r429  
    4343 * interface which represents individual browsers
    4444 */
    45 public interface Browser {
     45public interface Browser extends ReactingProcess{
    4646    public String getDefaultBin();
    4747    public String getDefaultPluginExpectedLocation();
     
    5353    public List<String> getDefaultSwitches();
    5454
    55 
    5655}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/browsertesting/browsers/Epiphany.java

    r418 r429  
    3535exception statement from your version.
    3636 */
    37 
    3837package net.sourceforge.jnlp.browsertesting.browsers;
    3938
     39import java.util.Arrays;
     40import java.util.List;
    4041import net.sourceforge.jnlp.browsertesting.Browsers;
    4142
    4243public class Epiphany extends MozillaFamilyLinuxBrowser {
     44
     45   
     46    String[] cs = {};
    4347
    4448    public Epiphany(String bin) {
     
    4751
    4852    @Override
     53    public List<String> getComaptibilitySwitches() {
     54        return Arrays.asList(cs);
     55    }
     56
     57    @Override
    4958    public Browsers getID() {
    5059        return Browsers.epiphany;
    5160    }
    52 
    53 
    54    
    5561}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/browsertesting/browsers/Firefox.java

    r418 r429  
    3535exception statement from your version.
    3636 */
    37 
    3837package net.sourceforge.jnlp.browsertesting.browsers;
    3938
    4039import java.util.Arrays;
    4140import java.util.List;
     41import net.sourceforge.jnlp.ProcessAssasin;
     42import net.sourceforge.jnlp.ServerAccess;
    4243import net.sourceforge.jnlp.browsertesting.Browsers;
     44import net.sourceforge.jnlp.browsertesting.browsers.firefox.FirefoxProfilesOperator;
    4345
    4446public class Firefox extends MozillaFamilyLinuxBrowser {
     47
     48    private static final FirefoxProfilesOperator firefoxProfilesOperatorSingleton = new FirefoxProfilesOperator();
    4549
    4650    public Firefox(String bin) {
    4751        super(bin);
    4852    }
    49 
    50     String[] cs={"-new-tab"};
     53    String[] cs = {"-new-tab"};
    5154
    5255    @Override
     
    6063    }
    6164
     65    @Override
     66    public void beforeProcess(String s) {
     67        try {
     68            firefoxProfilesOperatorSingleton.backupProfiles(); //assuming firefox is not in  safemode already
     69        } catch (Exception ex) {
     70            throw new RuntimeException("Firefox profile backup failed", ex);
     71        }
     72    }
    6273
     74    @Override
     75    public void afterProcess(String s) {
     76    }
    6377
     78    @Override
     79    public void beforeKill(String s) {
     80        try {
     81            ProcessAssasin.closeWindows(s);
     82        } catch (Exception ex) {
     83            throw new RuntimeException(ex);
     84        }
     85    }
    6486
    65    
     87    @Override
     88    public void afterKill(String s) {
     89        try {
     90            firefoxProfilesOperatorSingleton.restoreProfiles();
     91        } catch (Exception ex) {
     92            throw new RuntimeException("Firefox profile restoration failed", ex);
     93        }
     94
     95    }
    6696}
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/browsertesting/browsers/LinuxBrowser.java

    r418 r429  
    9393    }
    9494
     95    @Override
     96    public void beforeProcess(String s) {
     97       
     98    }
     99
     100    @Override
     101    public void afterProcess(String s) {
     102       
     103    }
     104
     105    @Override
     106    public void beforeKill(String s) {
     107
     108    }
     109
     110    @Override
     111    public void afterKill(String s) {
     112       
     113    }
    95114
    96115   
  • trunk/icedtea-web/tests/test-extensions/net/sourceforge/jnlp/browsertesting/browsers/Midory.java

    r418 r429  
    5151    }
    5252
    53 
     53     
    5454   
    5555}
Note: See TracChangeset for help on using the changeset viewer.