You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ro...@apache.org on 2019/06/13 09:37:09 UTC

[sling-whiteboard] branch master updated (1b101fd -> a75f55a)

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

rombert pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git.


    from 1b101fd  Prevent NPE in test
     new 19a195b  Added support for okhttp
     new c45de91  Simplify output parsing logic
     new a32efe6  Simplify classpath building for ITs
     new c21af56  Simplify handling of client type specifics in the AgentIT
     new 1a63417  Explicitly look for the default contructors when needed instead of relying on the declaration order.
     new 7ad74c4  Only print headers in case of success
     new 2536515  Correct usage examples in README
     new a75f55a  Reduced duplication in the transformer implementations

The 8 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 url-connection-agent/README.md                     |  8 +-
 url-connection-agent/pom.xml                       |  6 ++
 .../main/java/org/apache/sling/uca/impl/Agent.java |  3 +-
 .../uca/impl/HttpClient4TimeoutTransformer.java    | 46 +----------
 .../sling/uca/impl/OkHttpTimeoutTransformer.java}  | 23 ++++--
 ...dateFieldsInConstructorTimeoutTransformer.java} | 35 ++++----
 .../java/org/apache/sling/uca/impl/AgentIT.java    | 95 +++++++++++++---------
 .../apache/sling/uca/impl/HttpClientLauncher.java  | 53 ++++++------
 8 files changed, 132 insertions(+), 137 deletions(-)
 copy url-connection-agent/src/{test/java/org/apache/sling/uca/impl/MisbehavingServerControl.java => main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java} (54%)
 copy url-connection-agent/src/main/java/org/apache/sling/uca/impl/{HttpClient4TimeoutTransformer.java => UpdateFieldsInConstructorTimeoutTransformer.java} (67%)


[sling-whiteboard] 02/08: Simplify output parsing logic

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git

commit c45de91c13b23d763c4b6e3bb714f8db88a998d1
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Wed Jun 12 16:52:38 2019 +0200

    Simplify output parsing logic
---
 .../src/test/java/org/apache/sling/uca/impl/AgentIT.java             | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
index 8ea2b52..7a6c0bc 100644
--- a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
+++ b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
@@ -147,7 +147,7 @@ public class AgentIT {
             throw new RuntimeException("Command terminated successfully. That is unexpected.");
         } else {
             return Files.lines(STDERR)
-                .filter( l -> l.startsWith("Exception in thread \"main\""))
+                .filter( l -> l.startsWith(EXCEPTION_MARKER))
                 .map( l -> newRecordedThrowable(l) )
                 .findFirst()
                 .orElseThrow(() -> new RuntimeException("Exit code was zero but did not find any exception information in stderr.txt"));
@@ -205,9 +205,6 @@ public class AgentIT {
 
     private RecordedThrowable newRecordedThrowable(String line) {
         
-        if ( !line.startsWith(EXCEPTION_MARKER) )
-            return null;
-     
         line = line.replace(EXCEPTION_MARKER, "");
 
         String className = line.substring(0, line.indexOf(':'));


[sling-whiteboard] 05/08: Explicitly look for the default contructors when needed instead of relying on the declaration order.

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git

commit 1a63417217c60810ee8135a9539d0b84ecd211ce
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Wed Jun 12 18:02:59 2019 +0200

    Explicitly look for the default contructors when needed instead of relying on the declaration order.
---
 .../java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java  | 3 +--
 .../main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java  | 3 +--
 2 files changed, 2 insertions(+), 4 deletions(-)

diff --git a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java
index 230c1db..d389518 100644
--- a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java
+++ b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java
@@ -56,8 +56,7 @@ public class HttpClient4TimeoutTransformer implements ClassFileTransformer {
                 ClassPool defaultPool = ClassPool.getDefault();
                 CtClass cc = defaultPool.get(Descriptor.toJavaName(className));
                 
-                // TODO - access the default constructor explicitly in case it changes
-                CtConstructor noArgCtor =  cc.getConstructors()[0];
+                CtConstructor noArgCtor = cc.getConstructor(Descriptor.ofConstructor(new CtClass[0]));
                 CtField connectTimeout = cc.getDeclaredField("connectTimeout");
                 CtField socketTimeout = cc.getDeclaredField("socketTimeout");
                 noArgCtor.insertAfter("this." + connectTimeout.getName() + " = " + connectTimeoutMillis + ";");
diff --git a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
index a93e223..22a660e 100644
--- a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
+++ b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
@@ -54,8 +54,7 @@ public class OkHttpTimeoutTransformer implements ClassFileTransformer {
                 ClassPool defaultPool = ClassPool.getDefault();
                 CtClass cc = defaultPool.get(Descriptor.toJavaName(className));
                 
-                // TODO - access the default constructor explicitly in case it changes
-                CtConstructor noArgCtor =  cc.getConstructors()[0];
+                CtConstructor noArgCtor = cc.getConstructor(Descriptor.ofConstructor(new CtClass[0]));
                 CtField connectTimeout = cc.getDeclaredField("connectTimeout");
                 CtField readTimeout = cc.getDeclaredField("readTimeout");
                 noArgCtor.insertAfter("this." + connectTimeout.getName() + " = " + connectTimeoutMillis + ";");


[sling-whiteboard] 04/08: Simplify handling of client type specifics in the AgentIT

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git

commit c21af56ee23439d1b7c52b26f0693fb1fac54dfd
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Wed Jun 12 17:57:31 2019 +0200

    Simplify handling of client type specifics in the AgentIT
---
 .../java/org/apache/sling/uca/impl/AgentIT.java    | 72 ++++++++++++----------
 1 file changed, 40 insertions(+), 32 deletions(-)

diff --git a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
index ec420e5..f8ea7c7 100644
--- a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
+++ b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
@@ -17,6 +17,11 @@
 package org.apache.sling.uca.impl;
 
 import static java.time.Duration.ofSeconds;
+import static java.util.Objects.requireNonNull;
+import static org.apache.sling.uca.impl.HttpClientLauncher.ClientType.HC3;
+import static org.apache.sling.uca.impl.HttpClientLauncher.ClientType.HC4;
+import static org.apache.sling.uca.impl.HttpClientLauncher.ClientType.JavaNet;
+import static org.apache.sling.uca.impl.HttpClientLauncher.ClientType.OkHttp;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertTimeout;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -31,8 +36,10 @@ import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.EnumMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
@@ -62,7 +69,16 @@ public class AgentIT {
     private static final Path STDERR = Paths.get("target", "stderr.txt");
     private static final Path STDOUT = Paths.get("target", "stdout.txt");
     private static final Logger LOG = LoggerFactory.getLogger(AgentIT.class);
-
+    
+    private static Map<ClientType, ErrorDescriptor> errorDescriptors = new EnumMap<>(ClientType.class);
+    static {
+        errorDescriptors.put(JavaNet, new ErrorDescriptor(SocketTimeoutException.class, "connect timed out", "Read timed out"));
+        errorDescriptors.put(HC3, new ErrorDescriptor(ConnectTimeoutException.class, "The host did not accept the connection within timeout of 3000 ms", "Read timed out"));
+        errorDescriptors.put(HC4, new ErrorDescriptor(org.apache.http.conn.ConnectTimeoutException.class, 
+                "Connect to repo1.maven.org:81 \\[.*\\] failed: connect timed out", "Read timed out"));
+        errorDescriptors.put(OkHttp, new ErrorDescriptor(SocketTimeoutException.class, "connect timed out", "timeout"));
+    }
+    
     /**
      * Validates that connecting to a unaccessible port on an existing port fails with a connect 
      * timeout exception
@@ -78,36 +94,12 @@ public class AgentIT {
     @EnumSource(HttpClientLauncher.ClientType.class)
     public void connectTimeout(ClientType clientType) throws IOException {
 
+        ErrorDescriptor ed =  requireNonNull(errorDescriptors.get(clientType), "Unhandled clientType " + clientType);
         RecordedThrowable error = assertTimeout(ofSeconds(5),  () -> runTest("http://repo1.maven.org:81", clientType));
         
-        Class<?> expectedClass;
-        String expectedMessageRegex;
-        
-        switch ( clientType ) {
-            case JavaNet:
-                expectedClass= SocketTimeoutException.class;
-                expectedMessageRegex = "connect timed out";
-                break;
-            case HC3:
-                expectedClass = ConnectTimeoutException.class;
-                expectedMessageRegex = "The host did not accept the connection within timeout of 3000 ms";
-                break;
-            case HC4:
-                expectedClass = org.apache.http.conn.ConnectTimeoutException.class;
-                expectedMessageRegex = "Connect to repo1.maven.org:81 \\[.*\\] failed: connect timed out";
-                break;
-            case OkHttp:
-                expectedClass = SocketTimeoutException.class;
-                expectedMessageRegex = "connect timed out";
-                break;
-                
-            default:
-                throw new AssertionError("Unhandled clientType " + clientType);
-        }
-        
-        assertEquals(expectedClass.getName(), error.className);
-        assertTrue(error.message.matches(expectedMessageRegex), 
-            "Actual message " + error.message + " did not match regex " + expectedMessageRegex);
+        assertEquals(ed.connectTimeoutClass.getName(), error.className);
+        assertTrue(error.message.matches(ed.connectTimeoutMessageRegex), 
+            "Actual message " + error.message + " did not match regex " + ed.connectTimeoutMessageRegex);
     }
 
     /**
@@ -119,9 +111,11 @@ public class AgentIT {
     @EnumSource(HttpClientLauncher.ClientType.class)
     public void readTimeout(ClientType clientType, MisbehavingServerControl server) throws IOException {
         
+        ErrorDescriptor ed =  requireNonNull(errorDescriptors.get(clientType), "Unhandled clientType " + clientType);
         RecordedThrowable error = assertTimeout(ofSeconds(5),  () -> runTest("http://localhost:" + server.getLocalPort(), clientType));
+        
         assertEquals(SocketTimeoutException.class.getName(), error.className);
-        assertEquals( clientType != ClientType.OkHttp ? "Read timed out" : "timeout", error.message);
+        assertEquals(ed.readTimeoutMessage, error.message);
     }
 
     private RecordedThrowable runTest(String urlSpec, ClientType clientType) throws IOException, InterruptedException {
@@ -219,6 +213,22 @@ public class AgentIT {
 
         return new RecordedThrowable(className, message);
     }
+
+    /**
+     * Data class for defining specific error messages related to individual {@link ClientType client types}. 
+     */
+    static class ErrorDescriptor {
+        private Class<? extends IOException> connectTimeoutClass;
+        private String connectTimeoutMessageRegex;
+        private String readTimeoutMessage;
+
+        public ErrorDescriptor(Class<? extends IOException> connectTimeoutClass, String connectTimeoutMessageRegex,
+                String readTimeoutMessage) {
+            this.connectTimeoutClass = connectTimeoutClass;
+            this.connectTimeoutMessageRegex = connectTimeoutMessageRegex;
+            this.readTimeoutMessage = readTimeoutMessage;
+        }
+    }
     
     /**
      * Basic information about a {@link Throwable} that was recorded in a file
@@ -231,7 +241,5 @@ public class AgentIT {
             this.className = className;
             this.message = message;
         }
-        
-        
     }
 }


[sling-whiteboard] 06/08: Only print headers in case of success

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git

commit 7ad74c41d6d4c2bdb834f059715ffbf32f060ba4
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Wed Jun 12 18:05:01 2019 +0200

    Only print headers in case of success
---
 .../apache/sling/uca/impl/HttpClientLauncher.java  | 32 ++++++----------------
 1 file changed, 9 insertions(+), 23 deletions(-)

diff --git a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/HttpClientLauncher.java b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/HttpClientLauncher.java
index b4b6117..df1de9e 100644
--- a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/HttpClientLauncher.java
+++ b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/HttpClientLauncher.java
@@ -20,8 +20,8 @@ import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
 import java.net.URL;
-import java.net.URLConnection;
 import java.util.Date;
 import java.util.EnumSet;
 import java.util.stream.Collectors;
@@ -33,7 +33,6 @@ import org.apache.commons.httpclient.HttpMethod;
 import org.apache.commons.httpclient.methods.GetMethod;
 import org.apache.commons.httpclient.params.HttpClientParams;
 import org.apache.commons.httpclient.params.HttpMethodParams;
-import org.apache.http.HttpEntity;
 import org.apache.http.client.methods.CloseableHttpResponse;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.impl.client.CloseableHttpClient;
@@ -107,15 +106,18 @@ public class HttpClientLauncher {
     }
 
     private static void runUsingJavaNet(String targetUrl) throws IOException  {
-        URLConnection con = new URL(targetUrl).openConnection();
+        HttpURLConnection con = (HttpURLConnection) new URL(targetUrl).openConnection();
         System.out.println("Connection type is " + con);
         
         try (InputStream in = con.getInputStream();
                 InputStreamReader isr = new InputStreamReader(in);
                 BufferedReader br = new BufferedReader(isr)) {
-            String line;
-            while ( (line = br.readLine()) != null )
-                System.out.println("[WEB] " + line);
+            
+            System.out.println("[WEB] "  + con.getResponseCode() + " " + con.getResponseMessage());
+
+            con.getHeaderFields().forEach( (k, v) -> {
+                System.out.println("[WEB] " + k + " : " + v);
+            });
         }
     }
 
@@ -136,19 +138,6 @@ public class HttpClientLauncher {
         
         for ( Header header : get.getResponseHeaders() )
             System.out.print(new Date() + " [WEB] " + header.toExternalForm());
-        
-        
-        try (InputStream in = get.getResponseBodyAsStream()) {
-            if (in != null) {
-                try (InputStreamReader isr = new InputStreamReader(in); 
-                        BufferedReader br = new BufferedReader(isr)) {
-                    String line;
-                    while ((line = br.readLine()) != null)
-                        System.out.println(new Date() + " [WEB] " + line);
-
-                }
-            }
-        }
     }
     
     private static void runUsingHttpClient4(String targetUrl) throws IOException {
@@ -160,11 +149,8 @@ public class HttpClientLauncher {
                 for ( org.apache.http.Header header : response.getAllHeaders() )
                     System.out.println("[WEB] " + header);
                 
-                HttpEntity entity = response.getEntity();
-                // TODO - print response body
-                EntityUtils.consume(entity);
+                EntityUtils.consume(response.getEntity());
             }
-            
         }
     }
 


[sling-whiteboard] 08/08: Reduced duplication in the transformer implementations

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git

commit a75f55a71891b03d5a2d6bd3b47e011973b0a598
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Thu Jun 13 10:51:41 2019 +0200

    Reduced duplication in the transformer implementations
---
 .../uca/impl/HttpClient4TimeoutTransformer.java    | 45 ++-------------------
 .../sling/uca/impl/OkHttpTimeoutTransformer.java   | 46 ++--------------------
 ...dateFieldsInConstructorTimeoutTransformer.java} | 28 +++++++------
 3 files changed, 22 insertions(+), 97 deletions(-)

diff --git a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java
index d389518..5b5b317 100644
--- a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java
+++ b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/HttpClient4TimeoutTransformer.java
@@ -16,14 +16,6 @@
  */
 package org.apache.sling.uca.impl;
 
-import java.lang.instrument.ClassFileTransformer;
-import java.lang.instrument.IllegalClassFormatException;
-import java.security.ProtectionDomain;
-
-import javassist.ClassPool;
-import javassist.CtClass;
-import javassist.CtConstructor;
-import javassist.CtField;
 import javassist.bytecode.Descriptor;
 
 /**
@@ -32,45 +24,14 @@ import javassist.bytecode.Descriptor;
  * <p>It inserts two calls to <tt>org.apache.http.client.config.RequestConfig$Builder</tt> that set default
  * values for <tt>connectTimeout</tt> and <tt>socketTimeout</tt>.</p>
  */
-public class HttpClient4TimeoutTransformer implements ClassFileTransformer {
+public class HttpClient4TimeoutTransformer extends UpdateFieldsInConstructorTimeoutTransformer {
 
     // org.apache.http.client.config.RequestConfig.Builder
     
     private static final String REQUEST_CONFIG_BUILDER_CLASS_NAME = Descriptor.toJvmName("org.apache.http.client.config.RequestConfig$Builder");
     
-    private final long connectTimeoutMillis;
-    private final long readTimeoutMillis;
-    
     public HttpClient4TimeoutTransformer(long connectTimeoutMillis, long readTimeoutMillis) {
-        this.connectTimeoutMillis = connectTimeoutMillis;
-        this.readTimeoutMillis = readTimeoutMillis;
+        super(REQUEST_CONFIG_BUILDER_CLASS_NAME, "connectTimeout", "socketTimeout",
+            connectTimeoutMillis, readTimeoutMillis);
     }
-
-    @Override
-    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
-            ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
-        try {
-            if ( REQUEST_CONFIG_BUILDER_CLASS_NAME.equals(className) ) {
-                Log.get().log("%s asked to transform %s", getClass().getSimpleName(), className);
-                
-                ClassPool defaultPool = ClassPool.getDefault();
-                CtClass cc = defaultPool.get(Descriptor.toJavaName(className));
-                
-                CtConstructor noArgCtor = cc.getConstructor(Descriptor.ofConstructor(new CtClass[0]));
-                CtField connectTimeout = cc.getDeclaredField("connectTimeout");
-                CtField socketTimeout = cc.getDeclaredField("socketTimeout");
-                noArgCtor.insertAfter("this." + connectTimeout.getName() + " = " + connectTimeoutMillis + ";");
-                noArgCtor.insertAfter("this." + socketTimeout.getName() + " = " + readTimeoutMillis + ";");
-                
-                classfileBuffer = cc.toBytecode();
-                cc.detach();
-                Log.get().log("Transformation complete.");
-            }
-            return classfileBuffer;
-        } catch (Exception e) {
-            Log.get().fatal("Transformation failed", e);
-            return null;
-        }
-    }
-
 }
diff --git a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
index 22a660e..bcfae7c 100644
--- a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
+++ b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
@@ -16,14 +16,6 @@
  */
 package org.apache.sling.uca.impl;
 
-import java.lang.instrument.ClassFileTransformer;
-import java.lang.instrument.IllegalClassFormatException;
-import java.security.ProtectionDomain;
-
-import javassist.ClassPool;
-import javassist.CtClass;
-import javassist.CtConstructor;
-import javassist.CtField;
 import javassist.bytecode.Descriptor;
 
 /**
@@ -32,43 +24,13 @@ import javassist.bytecode.Descriptor;
  * <p>It inserts two calls to <tt>okhttp3.OkHttpClient$Builder</tt> that set default
  * values for <tt>connectTimeout</tt> and <tt>readTimeout</tt>.</p>
  */
-public class OkHttpTimeoutTransformer implements ClassFileTransformer {
+public class OkHttpTimeoutTransformer extends UpdateFieldsInConstructorTimeoutTransformer {
 
     private static final String REQUEST_CONFIG_BUILDER_CLASS_NAME = Descriptor.toJvmName("okhttp3.OkHttpClient$Builder");
     
-    private final long connectTimeoutMillis;
-    private final long readTimeoutMillis;
-    
     public OkHttpTimeoutTransformer(long connectTimeoutMillis, long readTimeoutMillis) {
-        this.connectTimeoutMillis = connectTimeoutMillis;
-        this.readTimeoutMillis = readTimeoutMillis;
+        
+        super(REQUEST_CONFIG_BUILDER_CLASS_NAME, "connectTimeout", "readTimeout", 
+            connectTimeoutMillis, readTimeoutMillis);
     }
-
-    @Override
-    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
-            ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
-        try {
-            if ( REQUEST_CONFIG_BUILDER_CLASS_NAME.equals(className) ) {
-                Log.get().log("%s asked to transform %s", getClass().getSimpleName(), className);
-                
-                ClassPool defaultPool = ClassPool.getDefault();
-                CtClass cc = defaultPool.get(Descriptor.toJavaName(className));
-                
-                CtConstructor noArgCtor = cc.getConstructor(Descriptor.ofConstructor(new CtClass[0]));
-                CtField connectTimeout = cc.getDeclaredField("connectTimeout");
-                CtField readTimeout = cc.getDeclaredField("readTimeout");
-                noArgCtor.insertAfter("this." + connectTimeout.getName() + " = " + connectTimeoutMillis + ";");
-                noArgCtor.insertAfter("this." + readTimeout.getName() + " = " + readTimeoutMillis + ";");
-                
-                classfileBuffer = cc.toBytecode();
-                cc.detach();
-                Log.get().log("Transformation complete.");
-            }
-            return classfileBuffer;
-        } catch (Exception e) {
-            Log.get().fatal("Transformation failed", e);
-            return null;
-        }
-    }
-
 }
diff --git a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/UpdateFieldsInConstructorTimeoutTransformer.java
similarity index 73%
copy from url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
copy to url-connection-agent/src/main/java/org/apache/sling/uca/impl/UpdateFieldsInConstructorTimeoutTransformer.java
index 22a660e..274bcd4 100644
--- a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
+++ b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/UpdateFieldsInConstructorTimeoutTransformer.java
@@ -27,19 +27,22 @@ import javassist.CtField;
 import javassist.bytecode.Descriptor;
 
 /**
- * Sets timeouts for HTTP calls done using <em>OkHttp 3.x</em>
- * 
- * <p>It inserts two calls to <tt>okhttp3.OkHttpClient$Builder</tt> that set default
- * values for <tt>connectTimeout</tt> and <tt>readTimeout</tt>.</p>
+ * Support class for transformers that update the timeout fields in the default constructor
  */
-public class OkHttpTimeoutTransformer implements ClassFileTransformer {
+public abstract class UpdateFieldsInConstructorTimeoutTransformer implements ClassFileTransformer {
 
-    private static final String REQUEST_CONFIG_BUILDER_CLASS_NAME = Descriptor.toJvmName("okhttp3.OkHttpClient$Builder");
-    
+    private final String className;
+    private final String connectTimeoutFieldName;
+    private final String readTimeoutFieldName;
     private final long connectTimeoutMillis;
     private final long readTimeoutMillis;
-    
-    public OkHttpTimeoutTransformer(long connectTimeoutMillis, long readTimeoutMillis) {
+
+    public UpdateFieldsInConstructorTimeoutTransformer(String className, String connectTimeoutFieldName,
+            String readTimeoutFieldName, long connectTimeoutMillis, long readTimeoutMillis) {
+
+        this.className = className;
+        this.connectTimeoutFieldName = connectTimeoutFieldName;
+        this.readTimeoutFieldName = readTimeoutFieldName;
         this.connectTimeoutMillis = connectTimeoutMillis;
         this.readTimeoutMillis = readTimeoutMillis;
     }
@@ -48,15 +51,15 @@ public class OkHttpTimeoutTransformer implements ClassFileTransformer {
     public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
             ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
         try {
-            if ( REQUEST_CONFIG_BUILDER_CLASS_NAME.equals(className) ) {
+            if ( this.className.equals(className) ) {
                 Log.get().log("%s asked to transform %s", getClass().getSimpleName(), className);
                 
                 ClassPool defaultPool = ClassPool.getDefault();
                 CtClass cc = defaultPool.get(Descriptor.toJavaName(className));
                 
                 CtConstructor noArgCtor = cc.getConstructor(Descriptor.ofConstructor(new CtClass[0]));
-                CtField connectTimeout = cc.getDeclaredField("connectTimeout");
-                CtField readTimeout = cc.getDeclaredField("readTimeout");
+                CtField connectTimeout = cc.getDeclaredField(connectTimeoutFieldName);
+                CtField readTimeout = cc.getDeclaredField(readTimeoutFieldName);
                 noArgCtor.insertAfter("this." + connectTimeout.getName() + " = " + connectTimeoutMillis + ";");
                 noArgCtor.insertAfter("this." + readTimeout.getName() + " = " + readTimeoutMillis + ";");
                 
@@ -70,5 +73,4 @@ public class OkHttpTimeoutTransformer implements ClassFileTransformer {
             return null;
         }
     }
-
 }


[sling-whiteboard] 07/08: Correct usage examples in README

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git

commit 253651565658bf022bea8affdf2a4596dbe90e16
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Wed Jun 12 18:12:29 2019 +0200

    Correct usage examples in README
---
 url-connection-agent/README.md | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/url-connection-agent/README.md b/url-connection-agent/README.md
index 916c0ca..1efcc94 100644
--- a/url-connection-agent/README.md
+++ b/url-connection-agent/README.md
@@ -16,7 +16,7 @@ It currently supports setting timeouts for HTTP connections done using:
 
 Build the project with `mvn clean package` and then run a simple connection test with 
 
-    java -javaagent:target/url-connection-agent-0.0.1-SNAPSHOT-jar-with-dependencies.jar=<connect-timeout>,<read-timeout> -cp target/test-classes:target/it-dependencies/* org.apache.sling.uca.impl.Main <url> <client-type>
+    java -javaagent:target/url-connection-agent-0.0.1-SNAPSHOT-jar-with-dependencies.jar=<connect-timeout>,<read-timeout> -cp target/test-classes:target/it-dependencies/* org.apache.sling.uca.impl.HttpClientLauncher <url> <client-type>
     
  The parameters are as follows:
  
@@ -29,14 +29,14 @@ Build the project with `mvn clean package` and then run a simple connection test
  For a test that always fails, set one of the timeouts to 1. Both executions listed below will typically fail:
  
  ```
-java -javaagent:target/url-connection-agent-0.0.1-SNAPSHOT-jar-with-dependencies.jar=1,1000 -cp target/test-classes:target/it-dependencies/* org.apache.sling.uca.impl.Main https://sling.apache.org JavaNet
-java -javaagent:target/url-connection-agent-0.0.1-SNAPSHOT-jar-with-dependencies.jar=1000,1 -cp target/test-classes:target/it-dependencies/* org.apache.sling.uca.impl.Main https://sling.apache.org JavaNet
+java -javaagent:target/url-connection-agent-0.0.1-SNAPSHOT-jar-with-dependencies.jar=1,1000 -cp target/test-classes:target/it-dependencies/* org.apache.sling.uca.impl.HttpClientLauncher https://sling.apache.org JavaNet
+java -javaagent:target/url-connection-agent-0.0.1-SNAPSHOT-jar-with-dependencies.jar=1000,1 -cp target/test-classes:target/it-dependencies/* org.apache.sling.uca.impl.HttpClientLauncher https://sling.apache.org JavaNet
  ```
  
 In contrast, the execution below should succeed:
 
 ```
-java -javaagent:target/url-connection-agent-0.0.1-SNAPSHOT-jar-with-dependencies.jar=1000,1000 -cp target/test-classes:target/it-dependencies/* org.apache.sling.uca.impl.Main https://sling.apache.org JavaNet
+java -javaagent:target/url-connection-agent-0.0.1-SNAPSHOT-jar-with-dependencies.jar=1000,1000 -cp target/test-classes:target/it-dependencies/* org.apache.sling.uca.impl.HttpClientLauncher https://sling.apache.org JavaNet
 ```
 
 To use this in your own project you should 


[sling-whiteboard] 01/08: Added support for okhttp

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git

commit 19a195ba11eef27598be9dc407f24fa3db67cb1e
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Wed Jun 12 16:51:20 2019 +0200

    Added support for okhttp
---
 url-connection-agent/pom.xml                       |  6 ++
 .../main/java/org/apache/sling/uca/impl/Agent.java |  3 +-
 .../sling/uca/impl/OkHttpTimeoutTransformer.java   | 75 ++++++++++++++++++++++
 .../java/org/apache/sling/uca/impl/AgentIT.java    | 11 +++-
 .../apache/sling/uca/impl/HttpClientLauncher.java  | 21 +++++-
 5 files changed, 112 insertions(+), 4 deletions(-)

diff --git a/url-connection-agent/pom.xml b/url-connection-agent/pom.xml
index c148a64..d37503b 100644
--- a/url-connection-agent/pom.xml
+++ b/url-connection-agent/pom.xml
@@ -133,5 +133,11 @@
             <version>4.5.4</version>
             <scope>test</scope>
         </dependency>
+        <dependency>
+          <groupId>com.squareup.okhttp3</groupId>
+          <artifactId>okhttp</artifactId>
+          <version>3.14.2</version>
+          <scope>test</scope>
+        </dependency>
     </dependencies>
 </project>
\ No newline at end of file
diff --git a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/Agent.java b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/Agent.java
index e523155..3842268 100644
--- a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/Agent.java
+++ b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/Agent.java
@@ -42,7 +42,8 @@ public class Agent {
         ClassFileTransformer[] transformers = new ClassFileTransformer[] {
             new JavaNetTimeoutTransformer(connectTimeout, readTimeout),
             new HttpClient3TimeoutTransformer(connectTimeout, readTimeout),
-            new HttpClient4TimeoutTransformer(connectTimeout, readTimeout)
+            new HttpClient4TimeoutTransformer(connectTimeout, readTimeout),
+            new OkHttpTimeoutTransformer(connectTimeout, readTimeout)
         };
         
         for ( ClassFileTransformer transformer : transformers )
diff --git a/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
new file mode 100644
index 0000000..a93e223
--- /dev/null
+++ b/url-connection-agent/src/main/java/org/apache/sling/uca/impl/OkHttpTimeoutTransformer.java
@@ -0,0 +1,75 @@
+/*
+ * 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.apache.sling.uca.impl;
+
+import java.lang.instrument.ClassFileTransformer;
+import java.lang.instrument.IllegalClassFormatException;
+import java.security.ProtectionDomain;
+
+import javassist.ClassPool;
+import javassist.CtClass;
+import javassist.CtConstructor;
+import javassist.CtField;
+import javassist.bytecode.Descriptor;
+
+/**
+ * Sets timeouts for HTTP calls done using <em>OkHttp 3.x</em>
+ * 
+ * <p>It inserts two calls to <tt>okhttp3.OkHttpClient$Builder</tt> that set default
+ * values for <tt>connectTimeout</tt> and <tt>readTimeout</tt>.</p>
+ */
+public class OkHttpTimeoutTransformer implements ClassFileTransformer {
+
+    private static final String REQUEST_CONFIG_BUILDER_CLASS_NAME = Descriptor.toJvmName("okhttp3.OkHttpClient$Builder");
+    
+    private final long connectTimeoutMillis;
+    private final long readTimeoutMillis;
+    
+    public OkHttpTimeoutTransformer(long connectTimeoutMillis, long readTimeoutMillis) {
+        this.connectTimeoutMillis = connectTimeoutMillis;
+        this.readTimeoutMillis = readTimeoutMillis;
+    }
+
+    @Override
+    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
+            ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
+        try {
+            if ( REQUEST_CONFIG_BUILDER_CLASS_NAME.equals(className) ) {
+                Log.get().log("%s asked to transform %s", getClass().getSimpleName(), className);
+                
+                ClassPool defaultPool = ClassPool.getDefault();
+                CtClass cc = defaultPool.get(Descriptor.toJavaName(className));
+                
+                // TODO - access the default constructor explicitly in case it changes
+                CtConstructor noArgCtor =  cc.getConstructors()[0];
+                CtField connectTimeout = cc.getDeclaredField("connectTimeout");
+                CtField readTimeout = cc.getDeclaredField("readTimeout");
+                noArgCtor.insertAfter("this." + connectTimeout.getName() + " = " + connectTimeoutMillis + ";");
+                noArgCtor.insertAfter("this." + readTimeout.getName() + " = " + readTimeoutMillis + ";");
+                
+                classfileBuffer = cc.toBytecode();
+                cc.detach();
+                Log.get().log("Transformation complete.");
+            }
+            return classfileBuffer;
+        } catch (Exception e) {
+            Log.get().fatal("Transformation failed", e);
+            return null;
+        }
+    }
+
+}
diff --git a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
index e8b6ac8..8ea2b52 100644
--- a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
+++ b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
@@ -93,6 +93,11 @@ public class AgentIT {
                 expectedClass = org.apache.http.conn.ConnectTimeoutException.class;
                 expectedMessageRegex = "Connect to repo1.maven.org:81 \\[.*\\] failed: connect timed out";
                 break;
+            case OkHttp:
+                expectedClass = SocketTimeoutException.class;
+                expectedMessageRegex = "connect timed out";
+                break;
+                
             default:
                 throw new AssertionError("Unhandled clientType " + clientType);
         }
@@ -113,7 +118,7 @@ public class AgentIT {
         
         RecordedThrowable error = assertTimeout(ofSeconds(5),  () -> runTest("http://localhost:" + server.getLocalPort(), clientType));
         assertEquals(SocketTimeoutException.class.getName(), error.className);
-        assertEquals("Read timed out", error.message);
+        assertEquals( clientType != ClientType.OkHttp ? "Read timed out" : "timeout", error.message);
     }
 
     private RecordedThrowable runTest(String urlSpec, ClientType clientType) throws IOException, InterruptedException {
@@ -190,7 +195,9 @@ public class AgentIT {
                     || p.getFileName().toString().equals("slf4j-api.jar")
                     || p.getFileName().toString().equals("jcl-over-slf4j.jar")
                     || p.getFileName().toString().contentEquals("httpclient.jar")
-                    || p.getFileName().toString().contentEquals("httpcore.jar") )
+                    || p.getFileName().toString().contentEquals("httpcore.jar")
+                    || p.getFileName().toString().contentEquals("okhttp.jar")
+                    || p.getFileName().toString().contentEquals("okio.jar") )
             .forEach( p -> elements.add(p.toString()));
         
         return String.join(File.pathSeparator, elements);
diff --git a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/HttpClientLauncher.java b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/HttpClientLauncher.java
index 09ef81f..b4b6117 100644
--- a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/HttpClientLauncher.java
+++ b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/HttpClientLauncher.java
@@ -40,6 +40,10 @@ import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.HttpClients;
 import org.apache.http.util.EntityUtils;
 
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
 /**
  * CLI interface to run HTTP clients
  */
@@ -48,7 +52,8 @@ public class HttpClientLauncher {
     public enum ClientType {
         JavaNet(HttpClientLauncher::runUsingJavaNet), 
         HC3(HttpClientLauncher::runUsingHttpClient3),
-        HC4(HttpClientLauncher::runUsingHttpClient4);
+        HC4(HttpClientLauncher::runUsingHttpClient4),
+        OkHttp(HttpClientLauncher::runUsingOkHttp);
         
         private final HttpConsumer consumer;
 
@@ -163,4 +168,18 @@ public class HttpClientLauncher {
         }
     }
 
+    private static void runUsingOkHttp(String targetUrl) throws IOException {
+        OkHttpClient client = new OkHttpClient();
+        
+        Request request = new Request.Builder()
+            .url(targetUrl)
+            .build();
+
+        try (Response response = client.newCall(request).execute()) {
+            System.out.println("[WEB] " + response.code() + " " + response.message());
+            response.headers().toMultimap().forEach( (n, v) -> {
+                System.out.println("[WEB] " + n + ": " + v);
+            });
+        }
+    }
 }


[sling-whiteboard] 03/08: Simplify classpath building for ITs

Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git

commit a32efe6fa85b6f522fe4081382cf5b86703f8318
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Wed Jun 12 16:55:51 2019 +0200

    Simplify classpath building for ITs
---
 .../java/org/apache/sling/uca/impl/AgentIT.java    | 25 ++++++++++++++--------
 1 file changed, 16 insertions(+), 9 deletions(-)

diff --git a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
index 7a6c0bc..ec420e5 100644
--- a/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
+++ b/url-connection-agent/src/test/java/org/apache/sling/uca/impl/AgentIT.java
@@ -30,7 +30,10 @@ import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
 import org.apache.commons.httpclient.ConnectTimeoutException;
@@ -188,16 +191,20 @@ public class AgentIT {
         List<String> elements = new ArrayList<>();
         elements.add(Paths.get("target", "test-classes").toString());
         
+        Set<String> dependencies = new HashSet<>(Arrays.asList(new String[] {
+            "commons-httpclient.jar",
+            "commons-codec.jar",
+            "slf4j-simple.jar",
+            "slf4j-api.jar",
+            "jcl-over-slf4j.jar",
+            "httpclient.jar",
+            "httpcore.jar",
+            "okhttp.jar",
+            "okio.jar"
+        }));
+        
         Files.list(Paths.get("target", "it-dependencies"))
-            .filter( p -> p.getFileName().toString().equals("commons-httpclient.jar") 
-                    || p.getFileName().toString().equals("commons-codec.jar")
-                    || p.getFileName().toString().equals("slf4j-simple.jar")
-                    || p.getFileName().toString().equals("slf4j-api.jar")
-                    || p.getFileName().toString().equals("jcl-over-slf4j.jar")
-                    || p.getFileName().toString().contentEquals("httpclient.jar")
-                    || p.getFileName().toString().contentEquals("httpcore.jar")
-                    || p.getFileName().toString().contentEquals("okhttp.jar")
-                    || p.getFileName().toString().contentEquals("okio.jar") )
+            .filter( p -> dependencies.contains(p.getFileName().toString()) )
             .forEach( p -> elements.add(p.toString()));
         
         return String.join(File.pathSeparator, elements);