[camel] branch graalvm updated: Clean the sample route a bit

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[camel] branch graalvm updated: Clean the sample route a bit

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

gnodet pushed a commit to branch graalvm
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/graalvm by this push:
     new 66ac737  Clean the sample route a bit
66ac737 is described below

commit 66ac737e88e866e1447a5ac5ddbe36d67b436541
Author: Guillaume Nodet <[hidden email]>
AuthorDate: Thu Aug 2 17:24:06 2018 +0200

    Clean the sample route a bit
---
 platforms/graalvm/example/pom.xml                  |  3 +-
 .../example/src/graalvm/reflectionconfig.json      |  4 -
 .../graalvm/example/SimpleCamelRouteBuilder.java   | 95 +++++++---------------
 .../org/apache/camel/graalvm/CamelRuntime.java     | 77 ++++++++++--------
 .../main/java/org/apache/camel/graalvm/Main.java   | 19 -----
 .../java/org/apache/camel/graalvm/Reflection.java  |  8 ++
 .../apache/camel/graalvm/support/CamelFeature.java | 19 ++++-
 7 files changed, 97 insertions(+), 128 deletions(-)

diff --git a/platforms/graalvm/example/pom.xml b/platforms/graalvm/example/pom.xml
index fb76a88..f3bbcde 100644
--- a/platforms/graalvm/example/pom.xml
+++ b/platforms/graalvm/example/pom.xml
@@ -82,11 +82,10 @@
                                 <argument>-cp</argument>
                                 <classpath/>
                                 <argument>-DCamelSimpleLRUCacheFactory=true</argument>
-                                <argument>-H:ReflectionConfigurationFiles=../src/graalvm/reflectionconfig.json</argument>
                                 <argument>-H:IncludeResources=META-INF/.*</argument>
                                 <argument>-H:Features=org.apache.camel.graalvm.support.CamelFeature</argument>
                                 <argument>-H:+JNI</argument>
-                                <argument>org.apache.camel.graalvm.Main</argument>
+                                <argument>org.apache.camel.graalvm.example.SimpleCamelRouteBuilder</argument>
                             </arguments>
                         </configuration>
                     </execution>
diff --git a/platforms/graalvm/example/src/graalvm/reflectionconfig.json b/platforms/graalvm/example/src/graalvm/reflectionconfig.json
deleted file mode 100644
index 5ceedf9..0000000
--- a/platforms/graalvm/example/src/graalvm/reflectionconfig.json
+++ /dev/null
@@ -1,4 +0,0 @@
-[
-  { "name" : "org.apache.camel.graalvm.example.SimpleCamelRouteBuilder", "allPublicConstructors" : true },
-  { "name" : "org.apache.camel.graalvm.example.SimpleCamelRouteBuilder$MyOrderService", "allPublicMethods" : true }
-]
\ No newline at end of file
diff --git a/platforms/graalvm/example/src/main/java/org/apache/camel/graalvm/example/SimpleCamelRouteBuilder.java b/platforms/graalvm/example/src/main/java/org/apache/camel/graalvm/example/SimpleCamelRouteBuilder.java
index ce889b1..1acb184 100644
--- a/platforms/graalvm/example/src/main/java/org/apache/camel/graalvm/example/SimpleCamelRouteBuilder.java
+++ b/platforms/graalvm/example/src/main/java/org/apache/camel/graalvm/example/SimpleCamelRouteBuilder.java
@@ -4,72 +4,39 @@ import java.util.ArrayList;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import java.util.function.Supplier;
 
-import org.apache.camel.AsyncCallback;
-import org.apache.camel.AsyncProcessor;
 import org.apache.camel.Exchange;
-import org.apache.camel.Expression;
-import org.apache.camel.Processor;
-import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.component.bean.BeanProcessor;
+import org.apache.camel.graalvm.CamelRuntime;
+import org.apache.camel.graalvm.Reflection;
 import org.apache.camel.impl.DefaultExchange;
-import org.apache.camel.processor.aggregate.AggregationStrategy;
 
-public class SimpleCamelRouteBuilder extends RouteBuilder {
+public class SimpleCamelRouteBuilder extends CamelRuntime {
+
+    public static void main(String[] args) throws Exception {
+        new SimpleCamelRouteBuilder().run(args);
+    }
 
     @Override
     public void configure() {
-        Executors.newCachedThreadPool(new ThreadFactory() {
-            @Override
-            public Thread newThread(Runnable r) {
-                Thread th = new Thread(r);
-                th.setDaemon(true);
-                return th;
-            }
-        });
-
-        from("file:./target/orders")
-            .setHeader(MyOrderService.class.getName(), newOrderService())
-            .split(body().tokenize("@"), new AggregationStrategy() {
-                @Override
-                public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
-                    return SimpleCamelRouteBuilder.this.aggregate(oldExchange, newExchange);
-                }
-            })
+
+        bind("orderService", new MyOrderService());
+
+        from("file:./target/orders?idempotent=true")
+            .setHeader("orderState", MyOrderState::new)
+            .split(body().tokenize("@"), SimpleCamelRouteBuilder.this::aggregate)
             // each splitted message is then send to this bean where we can process it
-            .process(stateless(MyOrderService.class.getName(), "handleOrder"))
+            .bean("orderService", "handleOrder(${header.orderState}, ${body})")
             // this is important to end the splitter route as we do not want to do more routing
             // on each splitted message
             .end()
             // after we have splitted and handled each message we want to send a single combined
             // response back to the original caller, so we let this bean build it for us
             // this bean will receive the result of the aggregate strategy: MyOrderStrategy
-            .process(stateless(MyOrderService.class.getName(), "buildCombinedResponse"))
+            .bean("orderService", "buildCombinedResponse(${header.orderState}, ${body})")
             // log out
             .to("log:out");
     }
 
-    public Expression extractMessage() {
-        return new Expression() {
-            @Override
-            public <T> T evaluate(Exchange exchange, Class<T> type) {
-                return type.cast(exchange.getIn().getBody(String.class));
-            }
-        };
-    }
-
-    public Supplier<Object> newOrderService() {
-        return new Supplier<Object>() {
-            @Override
-            public Object get() {
-                return new MyOrderService();
-            }
-        };
-    }
-
     public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
         // put order together in old exchange by adding the order from new exchange
         List<String> orders;
@@ -92,27 +59,21 @@ public class SimpleCamelRouteBuilder extends RouteBuilder {
         return oldExchange;
     }
 
-    private Processor stateless(String header, String method) {
-        return new AsyncProcessor() {
-            @Override
-            public boolean process(Exchange exchange, AsyncCallback callback) {
-                return getBeanProcess(exchange).process(exchange, callback);
-            }
-            @Override
-            public void process(Exchange exchange) throws Exception {
-                getBeanProcess(exchange).process(exchange);
-            }
-            protected BeanProcessor getBeanProcess(Exchange exchange) {
-                BeanProcessor bp = new BeanProcessor(
-                        exchange.getIn().getHeader(header),
-                        exchange.getContext());
-                bp.setMethod(method);
-                return bp;
-            }
-        };
+    public class MyOrderService {
+
+        @Reflection
+        public String handleOrder(MyOrderState state, String line) {
+            return state.handleOrder(line);
+        }
+
+        @Reflection
+        public Map<String, Object> buildCombinedResponse(MyOrderState state, List<String> lines) {
+            return state.buildCombinedResponse(lines);
+        }
+
     }
 
-    public class MyOrderService {
+    public class MyOrderState {
 
         private int counter;
 
diff --git a/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/CamelRuntime.java b/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/CamelRuntime.java
index 10684f1..66abc7c 100644
--- a/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/CamelRuntime.java
+++ b/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/CamelRuntime.java
@@ -17,53 +17,64 @@
 
 package org.apache.camel.graalvm;
 
-import java.io.File;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Set;
+import java.util.Collections;
+import java.util.Map;
 
 import org.apache.camel.CamelContext;
-import org.apache.camel.Exchange;
-import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
 import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.component.file.FileComponent;
-import org.apache.camel.component.file.FileConsumer;
-import org.apache.camel.component.file.FileEndpoint;
-import org.apache.camel.component.file.FileOperations;
-import org.apache.camel.component.file.strategy.GenericFileProcessStrategySupport;
-import org.apache.camel.impl.DefaultEndpoint;
 import org.apache.camel.impl.SimpleRegistry;
-import org.apache.camel.util.IntrospectionSupport;
+import org.apache.camel.main.MainSupport;
 
 public abstract class CamelRuntime extends RouteBuilder {
 
+    private Main main = new Main();
     private SimpleRegistry registry = new SimpleRegistry();
     private CamelContext context = new FastCamelContext(registry);
 
-    public void start() throws Exception {
-        context.addRoutes(this);
-
-//        FileEndpoint e = (FileEndpoint) new FileComponent(context).createEndpoint("file:target/orders");
-//        FileConsumer c = new FileConsumer(e, ex -> {
-//        }, new FileOperations(e), new GenericFileProcessStrategySupport<File>() {
-//        });
-//
-//        Set<Method> methods = IntrospectionSupport.findSetterMethods(c.getClass(), "initialDelay", true);
-//        System.err.println("Setter founds: " + methods.size());
-//        for (Method method : methods) {
-//            System.err.println(method.toGenericString());
-//        }
-//        System.err.println("Methods: " + Arrays.toString(c.getClass().getMethods()));
-//        System.err.println("Methods: " + Arrays.toString(c.getClass().getSuperclass().getMethods()));
-//
-//
-//        IntrospectionSupport.setProperty(context, c, "initialDelay", "1000");
-
-        context.start();
+    public CamelRuntime() {
+        setContext(context);
     }
 
     public void bind(String name, Object object) {
         registry.put(name, object);
     }
 
+    public void run(String[] args) throws Exception {
+        main.setRouteBuilders(Collections.singletonList(this));
+        main.run(args);
+    }
+
+    public SimpleRegistry getRegistry() {
+        return registry;
+    }
+
+    class Main extends MainSupport {
+        public Main() {
+            options.removeIf(o -> "-r".equals(o.getAbbreviation()));
+        }
+
+        @Override
+        protected void doStop() throws Exception {
+            super.doStop();
+            context.stop();
+        }
+
+        @Override
+        protected void doStart() throws Exception {
+            super.doStart();
+            postProcessContext();
+            context.start();
+        }
+
+        @Override
+        protected ProducerTemplate findOrCreateCamelTemplate() {
+            return context.createProducerTemplate();
+        }
+
+        @Override
+        protected Map<String, CamelContext> getCamelContextMap() {
+            return Collections.singletonMap("camel-1", context);
+        }
+    }
 }
diff --git a/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/Main.java b/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/Main.java
deleted file mode 100644
index 5d14fc1..0000000
--- a/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/Main.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.apache.camel.graalvm;
-
-import org.apache.camel.CamelContext;
-
-public class Main extends org.apache.camel.main.Main {
-
-    @Override
-    protected CamelContext createContext() {
-        return new FastCamelContext(registry);
-    }
-
-    public static void main(String[] args) throws Exception {
-        Main main = new Main();
-        instance = main;
-        main.run(args);
-        System.exit(main.getExitCode());
-    }
-
-}
diff --git a/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/Reflection.java b/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/Reflection.java
new file mode 100644
index 0000000..0bdaf6c
--- /dev/null
+++ b/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/Reflection.java
@@ -0,0 +1,8 @@
+package org.apache.camel.graalvm;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Reflection {
+}
diff --git a/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/support/CamelFeature.java b/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/support/CamelFeature.java
index d56f1b3..b995d1c 100644
--- a/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/support/CamelFeature.java
+++ b/platforms/graalvm/support/src/main/java/org/apache/camel/graalvm/support/CamelFeature.java
@@ -3,10 +3,12 @@ package org.apache.camel.graalvm.support;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Method;
 
-import org.apache.camel.CamelContext;
 import org.apache.camel.Component;
 import org.apache.camel.Consumer;
+import org.apache.camel.Endpoint;
 import org.apache.camel.Producer;
+import org.apache.camel.graalvm.CamelRuntime;
+import org.apache.camel.graalvm.Reflection;
 import org.apache.camel.spi.DataFormat;
 import org.apache.camel.spi.Language;
 import org.apache.xbean.finder.ClassFinder;
@@ -28,18 +30,29 @@ public class CamelFeature implements Feature {
         }
     }
 
+    private void allowMethod(Method method) {
+        RuntimeReflection.register(method);
+    }
+
     public void beforeAnalysis(BeforeAnalysisAccess access) {
         try {
-            ClassFinder finder = new ClassFinder(CamelContext.class.getClassLoader());
+            ClassFinder finder = new ClassFinder(CamelRuntime.class.getClassLoader());
+
+            finder.findAnnotatedClasses(Reflection.class).forEach(this::allowInstantiate);
+            finder.findAnnotatedMethods(Reflection.class).forEach(this::allowMethod);
+
             finder.findImplementations(Component.class).forEach(this::allowInstantiate);
             finder.findImplementations(Language.class).forEach(this::allowInstantiate);
             finder.findImplementations(DataFormat.class).forEach(this::allowInstantiate);
+            finder.findImplementations(Endpoint.class).forEach(this::allowMethods);
             finder.findImplementations(Consumer.class).forEach(this::allowMethods);
             finder.findImplementations(Producer.class).forEach(this::allowMethods);
+
             allowInstantiate(org.apache.camel.component.file.strategy.GenericFileProcessStrategyFactory.class);
             allowMethods(org.apache.camel.component.file.strategy.GenericFileProcessStrategyFactory.class);
+
         } catch (Throwable t) {
-            throw new RuntimeException("Unable to analyse classes", t);
+            t.printStackTrace();
         }
     }