This is an automated email from the ASF dual-hosted git repository.

matthiasblaesing pushed a commit to branch release100
in repository https://gitbox.apache.org/repos/asf/incubator-netbeans.git

commit c30835744e91d98f671678466d8cf7977bf7fa87
Author: Matthias Bläsing <mblaes...@doppel-helix.eu>
AuthorDate: Tue Nov 27 21:20:35 2018 +0100

    Switch to Rhino as PAC evaluator
---
 platform/core.network/arch.xml                     |  12 +-
 platform/core.network/nbproject/project.xml        |   9 +
 .../proxy/pac/datetime/PacUtilsDateTime.java       |  13 +-
 .../proxy/pac/impl/ClassFilterPacHelpers.java      |  42 ---
 .../proxy/pac/impl/NbPacScriptEvaluator.java       | 283 +++++++++------------
 .../test/unit/data/pacFiles/wpad space.dat         |  22 --
 .../core/network/proxy/pac/PacEngineTest.java      |  23 ++
 7 files changed, 162 insertions(+), 242 deletions(-)

diff --git a/platform/core.network/arch.xml b/platform/core.network/arch.xml
index 59da865..2f0d5c5 100644
--- a/platform/core.network/arch.xml
+++ b/platform/core.network/arch.xml
@@ -104,9 +104,7 @@
       which clients are supposed to download and execute in order to find 
       out which proxy to use. This is known as <a 
href="https://en.wikipedia.org/wiki/Proxy_auto-config";>Proxy Auto-Config</a>
       (or PAC). This module provides a pluggable PAC evaluation environment
-      based on Nashorn. However, it will gracefully degrade to any other 
JavaScript
-      which may be installed in the JVM. Execution of the downloaded
-      JavaScript code is sandboxed. (only true for Nashorn)
+      based on Rhino. Execution of the downloaded JavaScript code is sandboxed.
   </p>
   <p>
       If you don't like the PAC evaluation environment provided
@@ -733,14 +731,6 @@
 -->
  <answer id="exec-reflection">
   <p>
-   Yes. It detects the presence of Nashorn (as opposed to say Rhino) by way 
-      of reflection. In particular it needs to know if the Java version is
-      Java 8u40 as Nashorn was greatly enhanced in that update and was more
-      or less useless (for our purpose) before this time. The use of reflection
-      means the code will gracefully 'degrade' to whatever script engine is
-      available if we are not on Java 8u40 or later.
-  </p>
-  <p>
    For testing only a dirty hack is used in our <code>FakeDns</code> class.
    This installs itself as a preferred name service in Java. This is done
    via reflection. It also uses proprietary <code>sun.*</code> package.
diff --git a/platform/core.network/nbproject/project.xml 
b/platform/core.network/nbproject/project.xml
index 0fe2742..57af864 100644
--- a/platform/core.network/nbproject/project.xml
+++ b/platform/core.network/nbproject/project.xml
@@ -62,6 +62,15 @@
                     </run-dependency>
                 </dependency>
                 <dependency>
+                    <code-name-base>org.netbeans.libs.rhino</code-name-base>
+                    <build-prerequisite/>
+                    <compile-dependency/>
+                    <run-dependency>
+                        <release-version>1</release-version>
+                        <specification-version>1.7.10</specification-version>
+                    </run-dependency>
+                </dependency>
+                <dependency>
                     
<code-name-base>org.netbeans.modules.keyring</code-name-base>
                     <build-prerequisite/>
                     <compile-dependency/>
diff --git 
a/platform/core.network/src/org/netbeans/core/network/proxy/pac/datetime/PacUtilsDateTime.java
 
b/platform/core.network/src/org/netbeans/core/network/proxy/pac/datetime/PacUtilsDateTime.java
index e08d2ce..4d224ad 100644
--- 
a/platform/core.network/src/org/netbeans/core/network/proxy/pac/datetime/PacUtilsDateTime.java
+++ 
b/platform/core.network/src/org/netbeans/core/network/proxy/pac/datetime/PacUtilsDateTime.java
@@ -260,7 +260,7 @@ public class PacUtilsDateTime {
     
     
     private static int getInteger(Object obj) throws PacDateTimeInputException 
{
-        if (obj instanceof Integer || obj instanceof Long) {
+        if (obj instanceof Number) {
             return ((Number) obj).intValue();
         }
         if (obj instanceof String) {
@@ -320,8 +320,9 @@ public class PacUtilsDateTime {
      * {@link PacHelperMethodsNetscape#weekdayRange(java.lang.Object...) 
weekdayRange()}
      * 
      * <p>
-     * Note: In Nashorn, JavaScript function arguments that are not used in the
-     * call will have a type of {@code Undefined}.
+     * Note: In Rhino, JavaScript function arguments that are not used in the
+     * call will have a type of {@code java.lang.String} and the value will be
+     * 'undefined'.
      *
      * @param objs
      * @return 
@@ -337,7 +338,8 @@ public class PacUtilsDateTime {
             }
             // Only parameters of type CharSequence (String) and 
             // Number (Integer, Long, etc) are relevant.
-            if ((obj instanceof Number) || (obj instanceof CharSequence)) {
+            // Rhino converts javascript undefined to the string "undefined"
+            if ((obj instanceof Number) || (obj instanceof CharSequence && (! 
"undefined".equals(obj)))) {
                 params++;
             }
         }
@@ -351,6 +353,9 @@ public class PacUtilsDateTime {
      */
     public static boolean usesGMT(Object... args) {
         int params = getNoOfParams(args);
+        if(params == 0) {
+            return false;
+        }
         if (args[params - 1] instanceof CharSequence) {
             String p = args[params - 1].toString();
             if (p.equals("GMT")) {
diff --git 
a/platform/core.network/src/org/netbeans/core/network/proxy/pac/impl/ClassFilterPacHelpers.java
 
b/platform/core.network/src/org/netbeans/core/network/proxy/pac/impl/ClassFilterPacHelpers.java
deleted file mode 100644
index 7c5a742..0000000
--- 
a/platform/core.network/src/org/netbeans/core/network/proxy/pac/impl/ClassFilterPacHelpers.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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.apache.org/licenses/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.netbeans.core.network.proxy.pac.impl;
-
-import jdk.nashorn.api.scripting.ClassFilter;
-import org.netbeans.core.network.proxy.pac.PacHelperMethods;
-
-/**
- * Nashorn class filter which helps us create a sandboxed JavaScript execution
- * environment which only has access to the Helper methods, nothing more.
- * 
- * <p>Note that the ClassFilter feature is specific to Nashorn (Rhino had the
- * {@code ClassShutter} class for this purpose), but the feature did not 
appear 
- * until Java 8u40.
- * 
- * @author lbruun
- */
-class ClassFilterPacHelpers implements ClassFilter {
-
-    @Override
-    public boolean exposeToScripts(String string) {
-        // The only Java class the PAC script is allowed to
-        // make use of is the PAC Helpers, nothing more. 
-        return string.equals(PacHelperMethods.class.getName());
-    }
-}
diff --git 
a/platform/core.network/src/org/netbeans/core/network/proxy/pac/impl/NbPacScriptEvaluator.java
 
b/platform/core.network/src/org/netbeans/core/network/proxy/pac/impl/NbPacScriptEvaluator.java
index 55f09b6..334d982 100644
--- 
a/platform/core.network/src/org/netbeans/core/network/proxy/pac/impl/NbPacScriptEvaluator.java
+++ 
b/platform/core.network/src/org/netbeans/core/network/proxy/pac/impl/NbPacScriptEvaluator.java
@@ -21,7 +21,6 @@ package org.netbeans.core.network.proxy.pac.impl;
 import java.net.InetSocketAddress;
 import java.net.Proxy;
 import java.net.URI;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
@@ -30,21 +29,19 @@ import java.util.logging.Level;
 import java.util.logging.Logger;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-import javax.script.Bindings;
-import javax.script.Invocable;
-import javax.script.ScriptContext;
-import javax.script.ScriptEngine;
-import javax.script.ScriptEngineFactory;
-import javax.script.ScriptEngineManager;
-import javax.script.ScriptException;
-import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
-import jdk.nashorn.api.scripting.ScriptObjectMirror;
+import org.mozilla.javascript.ClassShutter;
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.ContextFactory;
+import org.mozilla.javascript.EvaluatorException;
+import org.mozilla.javascript.Function;
+import org.mozilla.javascript.RhinoException;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.ScriptableObject;
 import org.netbeans.core.network.utils.SimpleObjCache;
 import org.netbeans.core.network.proxy.pac.PacHelperMethods;
 import org.netbeans.core.network.proxy.pac.PacJsEntryFunction;
 import org.netbeans.core.network.proxy.pac.PacValidationException;
 import org.netbeans.core.network.proxy.pac.PacParsingException;
-import org.openide.util.Exceptions;
 import org.netbeans.core.network.proxy.pac.PacScriptEvaluator;
 import org.netbeans.core.network.proxy.pac.PacUtils;
 import org.openide.util.Lookup;
@@ -180,14 +177,27 @@ import org.openide.util.Lookup;
 public class NbPacScriptEvaluator implements PacScriptEvaluator {
 
     private static final Logger LOGGER = 
Logger.getLogger(NbPacScriptEvaluator.class.getName());
-
+    // The execution limits are in place as a last resort. In general it is
+    // expected, that a PAC comes from a trusted source
+    private static final SandboxedContextFactory SANDBOXED_CONTEXT_FACTORY = 
new SandboxedContextFactory(
+            100_000,
+            5 * 1000,
+            new ClassShutter() {
+                @Override
+                public boolean visibleToScripts(String string) {
+                    return 
"org.netbeans.core.network.proxy.pac.impl.NbPacHelperMethods".equals(string)
+                            || "java.lang.String".equals(string);
+                }
+            }
+    );
 
     private static final String JS_HELPER_METHODS_INSTANCE_NAME = 
"jsPacHelpers";
     
     private final boolean canUseURLCaching;
-    private final PacScriptEngine scriptEngine;
+    private final Scriptable scriptEngine;
     private final SimpleObjCache<URI,List<Proxy>> resultCache;
-    
+    private final PacJsEntryFunction entryFunctionInfo;
+    private final Function entryFunction;
     private static final String PAC_PROXY = "PROXY";
     private static final String PAC_DIRECT = "DIRECT";
     private static final String PAC_SOCKS = "SOCKS";
@@ -195,20 +205,41 @@ public class NbPacScriptEvaluator implements 
PacScriptEvaluator {
     private static final String PAC_SOCKS5_FFEXT = "SOCKS5"; // Mozilla 
Firefox extension. Not part of original Netscape spec.
     private static final String PAC_HTTP_FFEXT = "HTTP"; // Mozilla Firefox 
extension. Not part of original Netscape spec.
     private static final String PAC_HTTPS_FFEXT = "HTTPS"; // Mozilla Firefox 
extension. Not part of original Netscape spec.
-    private final boolean nashornJava8u40Available;
     private final String pacScriptSource;
 
 
     public NbPacScriptEvaluator(String pacSourceCocde) throws 
PacParsingException {
         this.pacScriptSource = pacSourceCocde;
-        nashornJava8u40Available = getNashornJava8u40Available();
-        scriptEngine = getScriptEngine(pacSourceCocde);
         canUseURLCaching = !usesTimeDateFunctions(pacSourceCocde);
         if (canUseURLCaching) {
             resultCache = new SimpleObjCache<>(100);
         } else {
             resultCache = null;
         }
+        Context cx = SANDBOXED_CONTEXT_FACTORY.enterContext();
+        try {
+            String helperJSScript = getHelperJsScriptSource();
+            LOGGER.log(Level.FINER, "PAC Helper JavaScript :\n{0}", 
helperJSScript);
+
+            scriptEngine = cx.initSafeStandardObjects();
+
+            PacHelperMethods pacHelpers = 
Lookup.getDefault().lookup(PacHelperMethods.class);
+            if (pacHelpers == null) { // this should be redundant but we take 
no chances
+                pacHelpers = new NbPacHelperMethods();
+            }
+
+            ScriptableObject.putProperty(scriptEngine, 
JS_HELPER_METHODS_INSTANCE_NAME, pacHelpers);
+
+            cx.evaluateString(scriptEngine, pacSourceCocde, "PAC Source", 0, 
null);
+            cx.evaluateString(scriptEngine, helperJSScript, "JS Helper", 0, 
null);
+
+            entryFunctionInfo = testScriptEngine(scriptEngine, false);
+            entryFunction = (Function) 
ScriptableObject.getProperty(scriptEngine, 
entryFunctionInfo.getJsFunctionName());
+        } catch (RhinoException ex) {
+            throw new  PacParsingException(ex);
+        } finally {
+            Context.exit();
+        }
     }
 
     @Override
@@ -223,20 +254,18 @@ public class NbPacScriptEvaluator implements 
PacScriptEvaluator {
                 return jsResultAnalyzed;
             }
         }
+
+        Context cx = SANDBOXED_CONTEXT_FACTORY.enterContext();
         try {
-            Object jsResult = 
scriptEngine.findProxyForURL(PacUtils.toStrippedURLStr(uri), uri.getHost()); 
+
+            Object jsResult = entryFunction.call(cx, scriptEngine, null, new 
Object[] {PacUtils.toStrippedURLStr(uri), uri.getHost()});
             jsResultAnalyzed = analyzeResult(uri, jsResult);
             if (canUseURLCaching && (resultCache != null)) {
                 resultCache.put(uri, jsResultAnalyzed);   // save the result 
in the cache
             }
             return jsResultAnalyzed;
-        } catch (NoSuchMethodException ex) {
-            // If this exception occur at this time it is really, really 
unexpected. 
-            // We already gave the function a test spin in the constructor.
-            Exceptions.printStackTrace(ex);
-            return Collections.singletonList(Proxy.NO_PROXY);
-        } catch (ScriptException ex) {
-            LOGGER.log(Level.WARNING, "Error when executing PAC script 
function " + scriptEngine.getJsMainFunction().getJsFunctionName() + " : ", ex);
+        } catch (RhinoException ex) {
+            LOGGER.log(Level.WARNING, "Error when executing PAC script 
function " + entryFunctionInfo.getJsFunctionName() + " : ", ex);
             return Collections.singletonList(Proxy.NO_PROXY);
         } catch (Exception ex) {  // for runtime exceptions
             if (ex.getCause() != null) {
@@ -247,8 +276,10 @@ public class NbPacScriptEvaluator implements 
PacScriptEvaluator {
                 }
             }
             // other unforseen errors
-            LOGGER.log(Level.WARNING, "Error when executing PAC script 
function " + scriptEngine.getJsMainFunction().getJsFunctionName() + " : ", ex);
+            LOGGER.log(Level.WARNING, "Error when executing PAC script 
function " + entryFunctionInfo.getJsFunctionName() + " : ", ex);
             return Collections.singletonList(Proxy.NO_PROXY);
+        } finally {
+            Context.exit();
         }
     }
 
@@ -259,89 +290,29 @@ public class NbPacScriptEvaluator implements 
PacScriptEvaluator {
 
     @Override
     public String getJsEntryFunction() {
-        return scriptEngine.getJsMainFunction().getJsFunctionName();
+        return entryFunctionInfo.getJsFunctionName();
     }
 
     @Override
     public String getEngineInfo() {
-        ScriptEngineFactory factory = 
scriptEngine.getScriptEngine().getFactory();
-        return factory.getEngineName() + " version " + 
factory.getEngineVersion();
+        Context cx = Context.enter();
+        try {
+            return cx.getImplementationVersion();
+        } finally {
+            Context.exit();
+        }
     }
 
     @Override
     public String getPacScriptSource() {
         return this.pacScriptSource;
     }
-    
-    
 
-    private PacScriptEngine getScriptEngine(String pacSource) throws 
PacParsingException {
-
-        try {
-            String helperJSScript = getHelperJsScriptSource();
-            LOGGER.log(Level.FINER, "PAC Helper JavaScript :\n{0}", 
helperJSScript);
-            
-            ScriptEngine engine;
-            if (nashornJava8u40Available) {
-                engine = getNashornJSScriptEngine();
-            } else {
-                engine = getGenericJSScriptEngine();
-            }
-            
-            LOGGER.log(Level.FINE, "PAC script evaluator using:  {0}", 
getEngineInfo(engine));
-            
-            
-            PacHelperMethods pacHelpers = 
Lookup.getDefault().lookup(PacHelperMethods.class);
-            if (pacHelpers == null) { // this should be redundant but we take 
no chances
-                pacHelpers = new NbPacHelperMethods();
-            }
-            Bindings b = engine.createBindings();
-            b.put(JS_HELPER_METHODS_INSTANCE_NAME, pacHelpers);
-            engine.setBindings(b, ScriptContext.ENGINE_SCOPE);
-            
-            engine.eval(pacSource);
-            engine.eval(helperJSScript);
-
-            // Do some minimal testing of the validity of the PAC Script.
-            final PacJsEntryFunction jsMainFunction;
-            if (nashornJava8u40Available) {
-                jsMainFunction = testScriptEngine(engine, true);
-            } else {
-                jsMainFunction = testScriptEngine(engine, false);
-            }
-            
-            return new PacScriptEngine(engine, jsMainFunction);
-        } catch (ScriptException ex) {
-            throw new  PacParsingException(ex);
-        }
-    }
-    
-    private boolean getNashornJava8u40Available() {
-        try {
-            Class<?> klass = 
Class.forName("jdk.nashorn.api.scripting.NashornScriptEngineFactory");
-        } catch (ClassNotFoundException ex) {
-            return false;
-        }
-        return true;
-    }
-    
-    private ScriptEngine getNashornJSScriptEngine() {
-        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
-        return factory.getScriptEngine(new ClassFilterPacHelpers());
-    }
-    
-    private ScriptEngine getGenericJSScriptEngine() {
-        // The result of the statements below may be Rhino, but more likely
-        // - since Java 8 - it will be a Nashorn engine.
-        ScriptEngineManager factory = new ScriptEngineManager();
-        return factory.getEngineByName("JavaScript");
-    }
-    
     /**
      * Test if the main entry point, function 
FindProxyForURL()/FindProxyForURLEx(), 
      * is available.
      */
-    private PacJsEntryFunction testScriptEngine(ScriptEngine eng, boolean 
doDeepTest) throws PacParsingException {
+    private PacJsEntryFunction testScriptEngine(Scriptable eng, boolean 
doDeepTest) throws PacParsingException {
         if (isJsFunctionAvailable(eng, 
PacJsEntryFunction.IPV6_AWARE.getJsFunctionName(), doDeepTest)) {
             return PacJsEntryFunction.IPV6_AWARE;
         }
@@ -351,30 +322,9 @@ public class NbPacScriptEvaluator implements 
PacScriptEvaluator {
         throw new PacParsingException("Function " + 
PacJsEntryFunction.STANDARD.getJsFunctionName() + " or " + 
PacJsEntryFunction.IPV6_AWARE.getJsFunctionName() + " not found in PAC 
Script.");
     }
 
-    private boolean isJsFunctionAvailable(ScriptEngine eng, String 
functionName, boolean doDeepTest) {
-        // We want to test if the function is there, but without actually 
-        // invoking it.        
-        Object obj = eng.get(functionName);
-        
-        if (!doDeepTest && obj != null) {  
-            // Shallow test. We've established that there's
-            // "something" in the ENGINE_SCOPE with a name like
-            // functionName, and we *hope* it is a function, but we really 
don't
-            // know, therefore we call it a shallow test.
-            return true;
-        }
-        
-        // For Nashorn post JDK8u40 we can do even deeper validation
-        // using the ScriptObjectMirror class. This will not work for Rhino.
-        if (doDeepTest && obj != null) {
-            if (obj instanceof ScriptObjectMirror) {
-                    ScriptObjectMirror  som = (ScriptObjectMirror) obj;
-                    if (som.isFunction()) {
-                        return true;
-                    }
-            }
-        }        
-        return false;
+    private boolean isJsFunctionAvailable(Scriptable eng, String functionName, 
boolean doDeepTest) {
+        Object o = ScriptableObject.getProperty(eng, functionName);
+        return o instanceof Function;
     }
     
 
@@ -399,26 +349,6 @@ public class NbPacScriptEvaluator implements 
PacScriptEvaluator {
         return matcher.matches();
     }
 
-    private String getEngineInfo(ScriptEngine engine) {
-        StringBuilder sb = new StringBuilder();
-        ScriptEngineFactory f = engine.getFactory();
-        sb.append("LanguageName=");
-        sb.append("\"").append(f.getLanguageName()).append("\"");
-        sb.append(" ");
-        sb.append("LanguageVersion=");
-        sb.append("\"").append(f.getLanguageVersion()).append("\"");
-        sb.append(" ");
-        sb.append("EngineName=");
-        sb.append("\"").append(f.getEngineName()).append("\"");
-        sb.append(" ");
-        sb.append("EngineNameAliases=");
-        sb.append(Arrays.toString(f.getNames().toArray(new 
String[f.getNames().size()])));
-        sb.append(" ");
-        sb.append("EngineVersion=");
-        sb.append("\"").append(f.getEngineVersion()).append("\"");
-        return sb.toString();
-    }
-
     /**
      * Translates result from JavaScript into list of java proxy types.
      * 
@@ -498,34 +428,61 @@ public class NbPacScriptEvaluator implements 
PacScriptEvaluator {
         
         return new Proxy(proxyType, new InetSocketAddress(host, portNo));
     }
-    
-    
-    private static class PacScriptEngine  {
-        private final ScriptEngine scriptEngine;
-        private final PacJsEntryFunction jsMainFunction;
-        private final Invocable invocable;
-
-        public PacScriptEngine(ScriptEngine scriptEngine, PacJsEntryFunction 
jsMainFunction) {
-            this.scriptEngine = scriptEngine;
-            this.jsMainFunction = jsMainFunction;
-            this.invocable = (Invocable) scriptEngine;
-        }
 
-        public PacJsEntryFunction getJsMainFunction() {
-            return jsMainFunction;
-        }
+    /**
+     * SandboxedContextFactory provides an Rhino execution context, that can
+     * limit executed instructions, execution time and exposed java classes
+     */
+    private static final class SandboxedContextFactory extends ContextFactory {
+        private final long maxExecutionTimeMS;
+        private final long maxInstructionCount;
+        private final ClassShutter classShutter;
 
-        public ScriptEngine getScriptEngine() {
-            return scriptEngine;
+        public SandboxedContextFactory(long maxInstructionCount, long 
maxExecutionTimeMS, ClassShutter classShutter) {
+            this.classShutter = classShutter;
+            this.maxInstructionCount = maxInstructionCount;
+            this.maxExecutionTimeMS = maxExecutionTimeMS;
         }
 
-        public Invocable getInvocable() {
-            return invocable;
-        }
-        
-        public Object findProxyForURL(String url, String host) throws 
ScriptException, NoSuchMethodException {
-            return 
invocable.invokeFunction(jsMainFunction.getJsFunctionName(), url, host);
-        }
+       @Override
+       protected Context makeContext() {
+           return new SandboxedContext(this, classShutter, 
maxInstructionCount, maxExecutionTimeMS);
+       }
+
+    }
+
+    private static final class SandboxedContext extends Context {
+        private final long maxInstructionCount;
+        private final long maxExecutionTimeMS;
+       private final long executionStart = System.currentTimeMillis();
+       private long instructionCounter = 0;
+
+       public SandboxedContext(SandboxedContextFactory factory, ClassShutter 
classShutter, long maxInstructionCount, long maxExecutionTimeMS) {
+           super(factory);
+            this.maxExecutionTimeMS = maxExecutionTimeMS;
+            this.maxInstructionCount = maxInstructionCount;
+           setClassShutter(classShutter);
+           setGenerateObserverCount(true);
+           setInstructionObserverThreshold(1);
+       }
+
+       @Override
+       protected void observeInstructionCount(int instructionCount) {
+           instructionCounter += instructionCount;
+           long executionTime = System.currentTimeMillis() - executionStart;
+           if(instructionCounter > maxInstructionCount || executionTime > 
maxExecutionTimeMS) {
+               throw new ExecutionLimitsExceeded(executionTime, 
maxExecutionTimeMS, instructionCounter, maxInstructionCount);
+           }
+       }
+    }
+
+    private static class  ExecutionLimitsExceeded extends EvaluatorException {
+
+       public ExecutionLimitsExceeded(long executionTime, long 
maxExecutionTime, long intructionCount, long maxInstructionCount) {
+           super(String.format("Exceeded execution limits (Execution Time 
(current/max): %dms / %dms, Instruction Count (current/max): %d / %d)",
+                   executionTime, maxExecutionTime,
+                   intructionCount, maxInstructionCount));
+       }
+
     }
-        
 }
diff --git a/platform/core.network/test/unit/data/pacFiles/wpad space.dat 
b/platform/core.network/test/unit/data/pacFiles/wpad space.dat
deleted file mode 100644
index 3310e6a..0000000
--- a/platform/core.network/test/unit/data/pacFiles/wpad space.dat      
+++ /dev/null
@@ -1,22 +0,0 @@
-/* 
- * 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.apache.org/licenses/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.
- */
-
-function FindProxyForURL(url, host)
-{
-    // Make everything lower case.
-    url = url.toLowerCase();
-    host = host.toLowerCase();
-    if (isPlainHostName(host)) return "DIRECT";
-    return "PROXY www-proxy.us.oracle.com:80";
-};
diff --git 
a/platform/core.network/test/unit/src/org/netbeans/core/network/proxy/pac/PacEngineTest.java
 
b/platform/core.network/test/unit/src/org/netbeans/core/network/proxy/pac/PacEngineTest.java
index 7d109a7..cba6cc7 100644
--- 
a/platform/core.network/test/unit/src/org/netbeans/core/network/proxy/pac/PacEngineTest.java
+++ 
b/platform/core.network/test/unit/src/org/netbeans/core/network/proxy/pac/PacEngineTest.java
@@ -15,6 +15,7 @@ package org.netbeans.core.network.proxy.pac;
 
 import java.io.File;
 import java.io.IOException;
+import java.net.InetSocketAddress;
 import java.net.Proxy;
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -75,6 +76,28 @@ public class PacEngineTest extends NbTestCase {
         testPacFile2("pac-test4.js", factory);
     }
 
+    @Test
+    public void testEngine2() throws IOException, PacParsingException, 
URISyntaxException, PacValidationException {
+
+        File pacFilesDir = new File(getDataDir(), "pacFiles");
+        byte[] b = Files.readAllBytes((new File(pacFilesDir, 
"wpad.dat")).toPath());
+        String pacSource = new String(b, StandardCharsets.UTF_8);
+
+        PacScriptEvaluatorFactory factory = new NbPacScriptEvaluatorFactory();
+        PacScriptEvaluator evaluator = 
factory.createPacScriptEvaluator(pacSource);
+
+        List<Proxy> proxiesFQDN = evaluator.findProxyForURL(new 
URI("https://www.heise.de";));
+        assertNotNull(proxiesFQDN);
+        assertEquals(1, proxiesFQDN.size());
+        assertEquals(Proxy.Type.HTTP, proxiesFQDN.get(0).type());
+        assertEquals("www-proxy.us.oracle.com", ((InetSocketAddress) 
proxiesFQDN.get(0).address()).getHostString());
+        assertEquals(80, ((InetSocketAddress) 
proxiesFQDN.get(0).address()).getPort());
+        List<Proxy> simpleName = evaluator.findProxyForURL(new 
URI("https://localserver";));
+        assertNotNull(simpleName);
+        assertEquals(1, simpleName.size());
+        assertEquals(Proxy.Type.DIRECT, simpleName.get(0).type());
+    }
+
     private String getPacSource(String pacFileName) throws IOException {
         File pacFilesDir = new File(getDataDir(), "pacFiles2");
         byte[] b = Files.readAllBytes((new File(pacFilesDir, 
pacFileName)).toPath());


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@netbeans.apache.org
For additional commands, e-mail: commits-h...@netbeans.apache.org

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists

Reply via email to