<|start_filename|>extensions/rest-automation-lib/src/test/resources/public/sample.js<|end_filename|>
var x = 10;
console.log(x);
console.log("hello world");

<|start_filename|>connectors/core/cloud-connector/src/main/java/org/platformlambda/cloud/ServiceLifeCycle.java<|end_filename|>
package org.platformlambda.cloud;

import org.platformlambda.core.models.EventEnvelope;
import org.platformlambda.core.models.LambdaFunction;
import org.platformlambda.core.system.Platform;
import org.platformlambda.core.system.PostOffice;
import org.platformlambda.core.system.PubSub;
import org.platformlambda.core.util.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

public class ServiceLifeCycle {
    private static final Logger log = LoggerFactory.getLogger(ServiceLifeCycle.class);

    public static final String TYPE = "type";
    public static final String INIT = "init";
    public static final String TOKEN = "token";
    public static final long INITIALIZE = -100;
    private static final String SEQUENCE = "seq";
    private static final long FIRST_POLL = 1500;
    private static final long INTERVAL = 3000;
    private final String topic;
    private final String token;
    private final int partition;
    private static LambdaFunction resetHandler;

    /**
     * When offset is set to the special value INITIALIZE, initial load
     * will send an initialization token to the EventConsumer to make sure
     * the consumer is ready to read new events.
     *
     * @param topic that the consumer uses
     * @param partition for the topic
     * @param token of random value
     */
    public ServiceLifeCycle(String topic, int partition, String token) {
        this.topic = topic;
        this.partition = partition;
        this.token = token;
    }

    public void start() {
        final Platform platform = Platform.getInstance();
        final PostOffice po = PostOffice.getInstance();
        final Utility util = Utility.getInstance();
        final PubSub ps = PubSub.getInstance();
        final String INIT_HANDLER = INIT + "." + (partition < 0? topic : topic + "." + partition);
        final List<String> task = new ArrayList<>();
        LambdaFunction f = (headers, body, instance) -> {
            if (INIT.equals(body)) {
                int n = util.str2int(headers.get(SEQUENCE));
                try {
                    Map<String, String> event = new HashMap<>();
                    event.put(TYPE, INIT);
                    event.put(TOKEN, token);
                    event.put(SEQUENCE, String.valueOf(n));
                    log.info("Contacting {}, partition {}, sequence {}", topic, partition, n);
                    ps.publish(topic, partition, event, INIT);
                    task.clear();
                    String handle = po.sendLater(new EventEnvelope().setTo(INIT_HANDLER).setBody(INIT)
                                    .setHeader(SEQUENCE, n+1), new Date(System.currentTimeMillis() + INTERVAL));
                    task.add(handle);
                } catch (IOException e) {
                    log.error("Unable to send initToken to consumer - {}", e.getMessage());
                }
            } else {
                if (!task.isEmpty()) {
                    po.cancelFutureEvent(task.get(0));
                }
                platform.release(INIT_HANDLER);
                log.info("{}, partition {} ready", topic, partition);
            }
            return true;
        };
        try {
            platform.registerPrivate(INIT_HANDLER, f, 1);
            po.sendLater(new EventEnvelope().setTo(INIT_HANDLER).setBody(INIT).setHeader(SEQUENCE, 1),
                    new Date(System.currentTimeMillis() + FIRST_POLL));
        } catch (IOException e) {
            log.error("Unable to register {} - {}", INIT_HANDLER, e.getMessage());
        }
    }

    public static void setResetHandler(LambdaFunction resetHandler) {
        ServiceLifeCycle.resetHandler = resetHandler;
    }

    public static void releaseConnecton(String reason) {
        if (resetHandler != null) {
            try {
                resetHandler.handleEvent(new HashMap<>(), reason, 1);
            } catch (Exception e) {
                log.error("Unable to release connection - {}", e.getMessage());
            }
        }
    }

}


<|start_filename|>system/platform-core/src/test/java/org/platformlambda/core/util/EventEnvelopeRawBodyTest.java<|end_filename|>
package org.platformlambda.core.util;

import org.junit.Assert;
import org.junit.Test;
import org.platformlambda.core.models.EventEnvelope;
import org.platformlambda.core.util.models.PoJo;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class EventEnvelopeRawBodyTest {

    @Test
    public void booleanTest() throws IOException {
        boolean HELLO = true;
        EventEnvelope source = new EventEnvelope();
        source.setBody(HELLO);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        Assert.assertEquals(true, target.getRawBody());
        Assert.assertEquals(true, target.getBody());
    }

    @Test
    public void integerTest() throws IOException {
        int HELLO = 100;
        EventEnvelope source = new EventEnvelope();
        source.setBody(HELLO);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        Assert.assertEquals(100, target.getRawBody());
        Assert.assertEquals(100, target.getBody());
    }

    @Test
    public void longTest() throws IOException {
        long HELLO = 100L;
        EventEnvelope source = new EventEnvelope();
        source.setBody(HELLO);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        // long will be compressed to integer by MsgPack
        Assert.assertEquals(100, target.getRawBody());
        Assert.assertEquals(100, target.getBody());
    }

    @Test
    public void floatTest() throws IOException {
        float HELLO = 1.23f;
        EventEnvelope source = new EventEnvelope();
        source.setBody(HELLO);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        Assert.assertEquals(1.23f, target.getRawBody());
        Assert.assertEquals(1.23f, target.getBody());
    }

    @Test
    public void doubleTest() throws IOException {
        double HELLO = 1.23d;
        EventEnvelope source = new EventEnvelope();
        source.setBody(HELLO);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        Assert.assertEquals(1.23d, target.getRawBody());
        Assert.assertEquals(1.23d, target.getBody());
    }

    @Test
    public void bigDecimalTest() throws IOException {
        String VALUE = "1.23";
        BigDecimal HELLO = new BigDecimal(VALUE);
        EventEnvelope source = new EventEnvelope();
        source.setBody(HELLO);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        // big decimal is converted to string if it is not encoded in a PoJo
        Assert.assertEquals(VALUE, target.getRawBody());
        Assert.assertEquals(VALUE, target.getBody());
    }

    @Test
    public void dateTest() throws IOException {
        Utility util = Utility.getInstance();
        Date HELLO = new Date();
        EventEnvelope source = new EventEnvelope();
        source.setBody(HELLO);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        Assert.assertEquals(util.date2str(HELLO), target.getRawBody());
        Assert.assertEquals(util.date2str(HELLO), target.getBody());
    }

    @SuppressWarnings("unchecked")
    @Test
    public void pojoTest() throws IOException {
        String HELLO = "hello";
        PoJo pojo = new PoJo();
        pojo.setName(HELLO);
        EventEnvelope source = new EventEnvelope();
        source.setBody(pojo);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        Assert.assertTrue(target.getRawBody() instanceof Map);
        Map<String, Object> map = (Map<String, Object>) target.getRawBody();
        Assert.assertEquals(HELLO, map.get("name"));
        Assert.assertTrue(target.getBody() instanceof PoJo);
        PoJo output = (PoJo) target.getBody();
        Assert.assertEquals(HELLO, output.getName());
    }

    @SuppressWarnings("unchecked")
    @Test
    public void pojoListTest() throws IOException {
        String HELLO = "hello";
        PoJo pojo = new PoJo();
        pojo.setName(HELLO);
        List<PoJo> list = Collections.singletonList(pojo);
        EventEnvelope source = new EventEnvelope();
        source.setBody(list);
        byte[] b = source.toBytes();
        EventEnvelope target = new EventEnvelope(b);
        // raw body is encoded as a map containing a list of map
        // e.g. {list=[{number=0, long_number=0, name=hello}]}
        Assert.assertTrue(target.getRawBody() instanceof Map);
        Map<String, Object> map = (Map<String, Object>) target.getRawBody();
        MultiLevelMap multi = new MultiLevelMap(map);
        Assert.assertEquals(HELLO, multi.getElement("list[0].name"));
        Assert.assertTrue(target.getBody() instanceof List);
        List<PoJo> output = (List<PoJo>) target.getBody();
        Assert.assertEquals(1, output.size());
        Assert.assertEquals(HELLO, output.get(0).getName());
    }

}


<|start_filename|>system/platform-core/src/test/java/org/platformlambda/core/util/UserNotificationTest.java<|end_filename|>
package org.platformlambda.core.util;

import org.junit.Assert;
import org.junit.Test;
import org.platformlambda.core.exception.AppException;
import org.platformlambda.core.models.LambdaFunction;
import org.platformlambda.core.system.Platform;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class UserNotificationTest {

    private static final String NOTIFICATION_MANAGER = "notification.manager";

    @Test
    public void webUserNotificationTest() throws IOException, AppException, TimeoutException {
        Platform platform = Platform.getInstance();
        String ME = platform.getOrigin();
        String TYPE = "type";
        String LIST = "list";
        String TOPIC = "topic";
        String PUBLISH = "publish";
        String TEST_TOPIC = "test.topic";
        LambdaFunction mock = (headers, body, instance) -> {
            String type = headers.get(TYPE);
            if (LIST.equals(type)) {
                if (headers.containsKey(TOPIC)) {
                    Map<String, List<String>> result = new HashMap<>();
                    result.put(ME, Collections.singletonList("ws.12345.1"));
                    return result;
                }
                return Collections.singletonList(TEST_TOPIC);
            }
            if (PUBLISH.equals(type)) {
                return true;
            }
            return false;
        };
        platform.registerPrivate(NOTIFICATION_MANAGER, mock, 1);
        UserNotification notifier = UserNotification.getInstance();
        List<String> topics = notifier.listTopics();
        Assert.assertTrue(topics.contains(TEST_TOPIC));
        Map<String, List<String>> connections = notifier.getTopic(TEST_TOPIC);
        Assert.assertTrue(connections.containsKey(ME));
        notifier.publish(TEST_TOPIC, "hello world");
    }

}


<|start_filename|>system/platform-core/src/main/java/org/platformlambda/core/services/Multicaster.java<|end_filename|>
package org.platformlambda.core.services;

import org.platformlambda.core.annotations.EventInterceptor;
import org.platformlambda.core.models.EventEnvelope;
import org.platformlambda.core.models.LambdaFunction;
import org.platformlambda.core.system.PostOffice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

@EventInterceptor
public class Multicaster implements LambdaFunction {
    private static final Logger log = LoggerFactory.getLogger(Multicaster.class);

    private final String source;
    private final List<String> targets;

    public Multicaster(String source, List<String> targets) {
        this.source = source;
        this.targets = targets;
        log.info("Multicast routing - {} -> {}", source, targets);
    }

    @Override
    public Object handleEvent(Map<String, String> headers, Object body, int instance) {
        PostOffice po = PostOffice.getInstance();
        EventEnvelope event = (EventEnvelope) body;
        for (String service: targets) {
            if (po.exists(service)) {
                try {
                    po.send(event.copy().setTo(service));
                } catch (Exception e) {
                    log.warn("Unable to relay {} -> {} - {}", source, service, e.getMessage());
                }
            } else {
                log.warn("Unable to relay {} -> {} - target not reachable", source, service);
            }
        }
        return null;
    }
}


<|start_filename|>system/platform-core/src/test/java/org/platformlambda/core/util/models/PoJoVariance.java<|end_filename|>
package org.platformlambda.core.util.models;

import java.util.Date;

public class PoJoVariance {

    private int number;
    private String name;
    private String address;
    private String fullName;
    private Date date;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
}


<|start_filename|>system/platform-core/src/test/java/org/platformlambda/core/util/ExceptionTransportTest.java<|end_filename|>
package org.platformlambda.core.util;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.platformlambda.core.exception.AppException;
import org.platformlambda.core.models.EventEnvelope;
import org.platformlambda.core.models.LambdaFunction;
import org.platformlambda.core.models.TypedLambdaFunction;
import org.platformlambda.core.system.Platform;
import org.platformlambda.core.system.PostOffice;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExceptionTransportTest {

    private static final String ROUTE = "exception.test";
    private static final String CALLBACK = "callback.function";
    private static final String DEMO = "demo";
    private static final BlockingQueue<EventEnvelope> bench = new ArrayBlockingQueue<>(1);

    @BeforeClass
    public static void setup() throws IOException {
        Platform platform = Platform.getInstance();
        LambdaFunction f = (headers, body, instance) -> {
            throw new IllegalArgumentException("demo");
        };
        platform.registerPrivate(ROUTE, f, 1);
    }

    @Test
    public void transportTest() throws IOException, TimeoutException, InterruptedException {
        PostOffice po = PostOffice.getInstance();
        try {
            po.request(ROUTE, 5000, "demo");
            throw new IOException("Event exception transport failed");
        } catch (AppException e) {
            Throwable cause = e.getCause();
            Assert.assertTrue(cause instanceof IllegalArgumentException);
            Assert.assertEquals(DEMO, cause.getMessage());
        }
    }

    @Test
    public void callbackExceptionTest() throws IOException, InterruptedException {
        Platform platform = Platform.getInstance();
        platform.registerPrivate(CALLBACK, new MyCallBack(), 1);
        EventEnvelope request = new EventEnvelope();
        request.setTo(ROUTE);
        request.setReplyTo(CALLBACK);
        request.setBody("ok");
        PostOffice po = PostOffice.getInstance();
        po.send(request);
        EventEnvelope result = bench.poll(10, TimeUnit.SECONDS);
        Assert.assertNotNull(result);
        Assert.assertNotNull(result.getException());
        Assert.assertTrue(result.getException() instanceof IllegalArgumentException);
        Assert.assertEquals(DEMO, result.getException().getMessage());
    }

    private static class MyCallBack implements TypedLambdaFunction<EventEnvelope, Object> {

        @Override
        public Object handleEvent(Map<String, String> headers, EventEnvelope body, int instance) {
            bench.offer(body);
            return true;
        }
    }
}


<|start_filename|>system/platform-core/src/test/java/org/platformlambda/core/util/MulticastTest.java<|end_filename|>
package org.platformlambda.core.util;

import org.junit.Assert;
import org.junit.Test;
import org.platformlambda.core.models.LambdaFunction;
import org.platformlambda.core.system.Platform;
import org.platformlambda.core.system.PostOffice;

import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class MulticastTest {

    @Test
    public void routingTest() throws IOException, InterruptedException {
        final String[] targets = {"v1.hello.service.1", "v1.hello.service.2"};
        final PostOffice po = PostOffice.getInstance();
        final String TEXT = "ok";
        final AtomicInteger counter = new AtomicInteger(0);
        final BlockingQueue<Boolean> completion = new ArrayBlockingQueue<>(1);
        final ConcurrentMap<String, String> result = new ConcurrentHashMap<>();
        LambdaFunction f = (headers, body, instance) -> {
            result.put(po.getRoute(), (String) body);
            if (counter.incrementAndGet() == 2) {
                completion.offer(true);
            }
            return true;
        };
        Platform platform = Platform.getInstance();
        for (String t: targets) {
            platform.registerPrivate(t, f, 1);
        }
        po.send("v1.hello.world", TEXT);
        completion.poll(5, TimeUnit.SECONDS);
        Assert.assertEquals(2, result.size());
        for (String t: targets) {
            Assert.assertEquals(TEXT, result.get(t));
        }
    }

}


<|start_filename|>system/platform-core/src/test/java/org/platformlambda/core/util/models/ObjectWithGenericTypeVariance.java<|end_filename|>
package org.platformlambda.core.util.models;

public class ObjectWithGenericTypeVariance <T> {

    private T content;
    private int id;

    public T getContent() {
        return content;
    }

    public void setContent(T content) {
        this.content = content;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

<|start_filename|>system/platform-core/src/main/java/org/platformlambda/core/models/InboxBase.java<|end_filename|>
package org.platformlambda.core.models;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public abstract class InboxBase {

    protected String id;

    protected static final ConcurrentMap<String, InboxBase> inboxes = new ConcurrentHashMap<>();

    public static InboxBase getHolder(String inboxId) {
        return inboxes.get(inboxId);
    }

    public String getId() {
        return id;
    }

}
