Search in sources :

Example 31 with Tree

use of io.datatree.Tree in project moleculer-java by moleculer-java.

the class TcpTransporterTest method createOfflineDescriptor.

protected NodeDescriptor createOfflineDescriptor(boolean local, String nodeID) {
    Tree info = new Tree();
    info.put("seq", 0);
    info.put("port", 1);
    info.put("hostname", nodeID);
    NodeDescriptor nd = new NodeDescriptor(nodeID, true, local, info);
    nd.offlineSince = 1;
    return nd;
}
Also used : NodeDescriptor(services.moleculer.transporter.tcp.NodeDescriptor) Tree(io.datatree.Tree)

Example 32 with Tree

use of io.datatree.Tree in project moleculer-java by moleculer-java.

the class CommonUtils method getNodeInfos.

// --- GET ALL NODE INFO STRUCTURES OF ALL NODES ---
public static final Tree getNodeInfos(ServiceBroker broker, Transporter transporter) {
    Tree infos = new Tree();
    if (transporter == null) {
        infos.putObject(broker.getNodeID(), broker.getConfig().getServiceRegistry().getDescriptor());
    } else {
        Set<String> nodeIDset = transporter.getAllNodeIDs();
        String[] nodeIDarray = new String[nodeIDset.size()];
        nodeIDset.toArray(nodeIDarray);
        Arrays.sort(nodeIDarray, String.CASE_INSENSITIVE_ORDER);
        for (String nodeID : nodeIDarray) {
            Tree info = transporter.getDescriptor(nodeID);
            if (info == null) {
                continue;
            }
            infos.putObject(nodeID, info);
        }
    }
    return infos;
}
Also used : Tree(io.datatree.Tree)

Example 33 with Tree

use of io.datatree.Tree in project moleculer-java by moleculer-java.

the class CommonUtils method convertAnnotations.

// --- ANNOTATION TO JSON CONVERTER ---
public static final void convertAnnotations(Tree config, Annotation[] annotations) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    for (Annotation annotation : annotations) {
        // Create entry for annotation
        String annotationName = annotation.toString();
        int i = annotationName.lastIndexOf('.');
        if (i > -1) {
            annotationName = annotationName.substring(i + 1);
        }
        i = annotationName.indexOf('(');
        if (i > -1) {
            annotationName = annotationName.substring(0, i);
        }
        if (annotationName.length() > 1) {
            annotationName = Character.toLowerCase(annotationName.charAt(0)) + annotationName.substring(1);
        } else {
            annotationName = annotationName.toLowerCase();
        }
        if ("name".equals(annotationName) || "override".equals(annotationName)) {
            continue;
        }
        Tree annotationMap = config.putMap(annotationName);
        // Add annotation values
        Class<? extends Annotation> type = annotation.annotationType();
        Method[] members = type.getDeclaredMethods();
        for (Method member : members) {
            member.setAccessible(true);
            String propName = member.getName();
            Object propValue = member.invoke(annotation);
            annotationMap.putObject(propName, propValue);
            Tree newChild = annotationMap.get(propName);
            if (newChild.size() < 1) {
                newChild.remove();
            }
        }
        int size = annotationMap.size();
        if (size == 0) {
            annotationMap.remove();
        } else if (size == 1) {
            Tree value = annotationMap.getFirstChild();
            if (value != null && "value".equals(value.getName())) {
                annotationMap.setObject(value.asObject());
            }
        }
    }
}
Also used : Tree(io.datatree.Tree) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation)

Example 34 with Tree

use of io.datatree.Tree in project moleculer-java by moleculer-java.

the class Sample method main.

public static void main(String[] args) throws Exception {
    System.out.println("START");
    try {
        ServiceBrokerConfig cfg = new ServiceBrokerConfig();
        // RedisTransporter t = new RedisTransporter();
        // t.setDebug(false);
        // cfg.setTransporter(t);
        ServiceBroker broker = new ServiceBroker(cfg);
        MathService math = new MathService();
        broker.createService(math);
        broker.start();
        broker.use(new Middleware() {

            @Override
            public Action install(Action action, Tree config) {
                if (config.get("name", "?").equals("v1.math.test")) {
                    return new Action() {

                        @Override
                        public Object handler(Context ctx) throws Exception {
                            Object original = action.handler(ctx);
                            Object replaced = System.currentTimeMillis();
                            broker.getLogger().info("Middleware invoked! Replacing " + original + " to " + replaced);
                            return replaced;
                        }
                    };
                }
                return null;
            }
        });
        broker.waitForServices("v1.math").then(ok -> {
            for (int i = 0; i < 2; i++) {
                broker.call("v1.math.add", "a", 3, "b", 5).then(in -> {
                    broker.getLogger(Sample.class).info("Result: " + in);
                }).catchError(err -> {
                    broker.getLogger(Sample.class).error("Error: " + err);
                });
            }
            System.out.println("FIRST CALL ->3");
            broker.call("service2.test", new Tree(), CallOptions.retryCount(3)).catchError(cause -> {
                cause.printStackTrace();
            });
        });
        ((DefaultContextFactory) broker.getConfig().getContextFactory()).setMaxCallLevel(3);
        Thread.sleep(1000);
        broker.createService(new Service2Service());
        Thread.sleep(1000);
        broker.createService(new Service3Service());
        Thread.sleep(60000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("STOP");
}
Also used : Context(services.moleculer.context.Context) DefaultContextFactory(services.moleculer.context.DefaultContextFactory) CallOptions(services.moleculer.context.CallOptions) Listener(services.moleculer.eventbus.Listener) Cache(services.moleculer.cacher.Cache) Action(services.moleculer.service.Action) Middleware(services.moleculer.service.Middleware) Version(services.moleculer.service.Version) Name(services.moleculer.service.Name) Subscribe(services.moleculer.eventbus.Subscribe) Dependencies(services.moleculer.service.Dependencies) Service(services.moleculer.service.Service) Tree(io.datatree.Tree) Context(services.moleculer.context.Context) ServiceBrokerConfig(services.moleculer.config.ServiceBrokerConfig) Action(services.moleculer.service.Action) ServiceBrokerConfig(services.moleculer.config.ServiceBrokerConfig) Middleware(services.moleculer.service.Middleware) DefaultContextFactory(services.moleculer.context.DefaultContextFactory) Tree(io.datatree.Tree)

Example 35 with Tree

use of io.datatree.Tree in project moleculer-java by moleculer-java.

the class CircuitBreakerTest method setUp.

// --- SET UP ---
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
protected void setUp() throws Exception {
    sr = new DefaultServiceRegistry();
    tr = new TestTransporter();
    cb = new DefaultCircuitBreaker();
    cb.setMaxErrors(3);
    cb.setEnabled(true);
    ExecutorService ex = new ExecutorService() {

        @Override
        public void execute(Runnable command) {
            command.run();
        }

        @Override
        public <T> Future<T> submit(Runnable task, T result) {
            task.run();
            return CompletableFuture.completedFuture(result);
        }

        @Override
        public Future<?> submit(Runnable task) {
            task.run();
            return CompletableFuture.completedFuture(null);
        }

        @Override
        public <T> Future<T> submit(Callable<T> task) {
            try {
                return CompletableFuture.completedFuture(task.call());
            } catch (Exception e) {
                CompletableFuture future = CompletableFuture.completedFuture(null);
                future.completeExceptionally(e);
                return future;
            }
        }

        @Override
        public List<Runnable> shutdownNow() {
            return Collections.emptyList();
        }

        @Override
        public void shutdown() {
        }

        @Override
        public boolean isTerminated() {
            return false;
        }

        @Override
        public boolean isShutdown() {
            return false;
        }

        @Override
        public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            return null;
        }

        @Override
        public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
            return null;
        }

        @Override
        public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
            return null;
        }

        @Override
        public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
            return null;
        }

        @Override
        public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
            return false;
        }
    };
    br = ServiceBroker.builder().monitor(new ConstantMonitor()).registry(sr).transporter(tr).nodeID("local").breaker(cb).executor(ex).build();
    br.start();
    for (int i = 0; i < 10; i++) {
        Tree config = new Tree();
        config.put("nodeID", "node" + i);
        Tree actions = config.putMap("actions");
        LinkedHashMap<String, Object> action = new LinkedHashMap<>();
        action.put("name", "test.test");
        ((Map) actions.asObject()).put("test.test", action);
        sr.addActions(config);
    }
}
Also used : ConstantMonitor(services.moleculer.monitor.ConstantMonitor) Callable(java.util.concurrent.Callable) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) LinkedHashMap(java.util.LinkedHashMap) DefaultServiceRegistry(services.moleculer.service.DefaultServiceRegistry) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) Collection(java.util.Collection) TimeUnit(java.util.concurrent.TimeUnit) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) Tree(io.datatree.Tree) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

Tree (io.datatree.Tree)60 FastBuildTree (services.moleculer.util.FastBuildTree)26 Test (org.junit.Test)12 NodeDescriptor (services.moleculer.transporter.tcp.NodeDescriptor)12 CheckedTree (services.moleculer.util.CheckedTree)9 TimeoutException (java.util.concurrent.TimeoutException)6 Promise (services.moleculer.Promise)6 CommonUtils.readTree (services.moleculer.util.CommonUtils.readTree)6 RemoteException (java.rmi.RemoteException)4 LinkedHashMap (java.util.LinkedHashMap)4 CallOptions (services.moleculer.context.CallOptions)4 Context (services.moleculer.context.Context)4 Annotation (java.lang.annotation.Annotation)3 HashSet (java.util.HashSet)3 LinkedHashSet (java.util.LinkedHashSet)3 Map (java.util.Map)3 NoSuchElementException (java.util.NoSuchElementException)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 ServiceBrokerConfig (services.moleculer.config.ServiceBrokerConfig)3 Action (services.moleculer.service.Action)3