Search in sources :

Example 1 with CallOptions

use of services.moleculer.context.CallOptions in project moleculer-java by moleculer-java.

the class CommonUtils method parseParams.

// --- PARSE CALL / BROADCAST PARAMS ---
public static final ParseResult parseParams(Object[] params) {
    Tree data = null;
    CallOptions.Options opts = null;
    Groups groups = null;
    if (params != null) {
        if (params.length == 1) {
            if (params[0] instanceof Tree) {
                data = (Tree) params[0];
            } else {
                data = new CheckedTree(params[0]);
            }
        } else {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            String prev = null;
            Object value;
            for (int i = 0; i < params.length; i++) {
                value = params[i];
                if (prev == null) {
                    if (!(value instanceof String)) {
                        if (value instanceof CallOptions.Options) {
                            opts = (CallOptions.Options) value;
                            continue;
                        }
                        if (value instanceof Groups) {
                            groups = (Groups) value;
                            continue;
                        }
                        i++;
                        throw new IllegalArgumentException("Parameter #" + i + " (\"" + value + "\") must be String, Context, Groups, or CallOptions!");
                    }
                    prev = (String) value;
                    continue;
                }
                map.put(prev, value);
                prev = null;
            }
            data = new Tree(map);
        }
    }
    return new ParseResult(data, opts, groups);
}
Also used : CallOptions(services.moleculer.context.CallOptions) CallOptions(services.moleculer.context.CallOptions) LinkedHashMap(java.util.LinkedHashMap) Groups(services.moleculer.eventbus.Groups) Tree(io.datatree.Tree)

Example 2 with CallOptions

use of services.moleculer.context.CallOptions in project moleculer-java by moleculer-java.

the class DefaultServiceRegistry method receiveRequest.

// --- RECEIVE REQUEST FROM REMOTE SERVICE ---
@Override
public void receiveRequest(Tree message) {
    // Verify protocol version
    if (checkVersion) {
        String ver = message.get("ver", "unknown");
        if (!ServiceBroker.PROTOCOL_VERSION.equals(ver)) {
            logger.warn("Invalid protocol version (" + ver + ")!");
            return;
        }
    }
    // Get action property
    String action = message.get("action", (String) null);
    if (action == null || action.isEmpty()) {
        logger.warn("Missing \"action\" property!");
        return;
    }
    // Get strategy (action endpoint array) by action name
    Strategy<ActionEndpoint> strategy;
    readLock.lock();
    try {
        strategy = strategies.get(action);
    } finally {
        readLock.unlock();
    }
    if (strategy == null) {
        logger.warn("Invalid action name (" + action + ")!");
        return;
    }
    // Get local action endpoint (with cache handling)
    ActionEndpoint endpoint = strategy.getEndpoint(nodeID);
    if (endpoint == null) {
        logger.warn("Not a local action (" + action + ")!");
        return;
    }
    // Get request's unique ID
    String id = message.get("id", (String) null);
    if (id == null || id.isEmpty()) {
        logger.warn("Missing \"id\" property!");
        return;
    }
    // Get sender's nodeID
    String sender = message.get("sender", (String) null);
    if (sender == null || sender.isEmpty()) {
        logger.warn("Missing \"sender\" property!");
        return;
    }
    // Create CallOptions
    int timeout = message.get("timeout", 0);
    Tree params = message.get("params");
    // TODO Process other properties:
    // Tree meta = message.get("meta");
    // int level = message.get("level", 1);
    // boolean metrics = message.get("metrics", false);
    // String parentID = message.get("parentID", (String) null);
    // String requestID = message.get("requestID", (String) null);
    CallOptions.Options opts = CallOptions.nodeID(nodeID).timeout(timeout);
    Context ctx = contextFactory.create(action, params, opts, null);
    // Invoke action
    try {
        new Promise(endpoint.handler(ctx)).then(data -> {
            // Send response
            FastBuildTree msg = new FastBuildTree(5);
            msg.putUnsafe("sender", nodeID);
            msg.putUnsafe("id", id);
            msg.putUnsafe("ver", ServiceBroker.PROTOCOL_VERSION);
            msg.putUnsafe("success", true);
            msg.putUnsafe("data", data);
            transporter.publish(Transporter.PACKET_RESPONSE, sender, msg);
        }).catchError(error -> {
            // Send error
            transporter.publish(Transporter.PACKET_RESPONSE, sender, throwableToTree(id, sender, error));
        });
    } catch (Throwable error) {
        // Send error
        transporter.publish(Transporter.PACKET_RESPONSE, sender, throwableToTree(id, sender, error));
    }
}
Also used : Context(services.moleculer.context.Context) CallOptions(services.moleculer.context.CallOptions) Arrays(java.util.Arrays) ScheduledFuture(java.util.concurrent.ScheduledFuture) Enumeration(java.util.Enumeration) FastBuildTree(services.moleculer.util.FastBuildTree) CommonUtils.convertAnnotations(services.moleculer.util.CommonUtils.convertAnnotations) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServiceBroker(services.moleculer.ServiceBroker) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ContextFactory(services.moleculer.context.ContextFactory) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) ServiceBrokerConfig(services.moleculer.config.ServiceBrokerConfig) CommonUtils.getHostName(services.moleculer.util.CommonUtils.getHostName) LinkedHashSet(java.util.LinkedHashSet) PrintWriter(java.io.PrintWriter) Eventbus(services.moleculer.eventbus.Eventbus) Iterator(java.util.Iterator) StringWriter(java.io.StringWriter) Collection(java.util.Collection) NetworkInterface(java.net.NetworkInterface) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) UIDGenerator(services.moleculer.uid.UIDGenerator) Field(java.lang.reflect.Field) RemoteException(java.rmi.RemoteException) Promise(services.moleculer.Promise) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Lock(java.util.concurrent.locks.Lock) Strategy(services.moleculer.strategy.Strategy) Tree(io.datatree.Tree) Transporter(services.moleculer.transporter.Transporter) Annotation(java.lang.annotation.Annotation) Context(services.moleculer.context.Context) StrategyFactory(services.moleculer.strategy.StrategyFactory) CommonUtils.nameOf(services.moleculer.util.CommonUtils.nameOf) Collections(java.util.Collections) Promise(services.moleculer.Promise) FastBuildTree(services.moleculer.util.FastBuildTree) FastBuildTree(services.moleculer.util.FastBuildTree) Tree(io.datatree.Tree) CallOptions(services.moleculer.context.CallOptions)

Aggregations

Tree (io.datatree.Tree)2 LinkedHashMap (java.util.LinkedHashMap)2 CallOptions (services.moleculer.context.CallOptions)2 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 Annotation (java.lang.annotation.Annotation)1 Field (java.lang.reflect.Field)1 InetAddress (java.net.InetAddress)1 NetworkInterface (java.net.NetworkInterface)1 RemoteException (java.rmi.RemoteException)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Enumeration (java.util.Enumeration)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 LinkedHashSet (java.util.LinkedHashSet)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1