Jawampa and Wampy.js clients

52 views
Skip to first unread message

Juan BG

unread,
Jul 31, 2018, 5:08:20 PM7/31/18
to WAMP
Hi everyone here, I'm working at WAMP project with Java (Router and Client) and JavaScript (Client) I'm using, jawampa & wampy.js. I have a some problems to get it, The following is my app description: 
  • I need a router 
  • I need create a client in the same space that my router
  • I need create a JS client
  • Register a procedure from my js client to be called to my java client.
  • Register a procedure from my java client to be called to my js client.
  • Call the java procedure through a click in html button
  • Call the js procedure through a command line action. 

But I can't make to my client call the Js procedure using the same client. I'll show my code. 

JAVA CODE (JAWAMPA)

/**
* This class will works like a router with an client embed.
*/

public class Router {

    final static Logger LOGGER = Logger.getLogger(Router.class);
    private WampRouter router;
    private SimpleWampWebsocketListener server;

    /**
     * The reason to be of this method is start the procedure and executes run
     * method which creates a Router an a client (the client can be extract from
     * here an put in an individual project).
     *
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Hello World!");

        new Router().start();

    }

    /**
     * This method start the router with all configuration for this. The router is
     * acting like a little wamp server to support the client connection through a
     * realm.
     */
    private void start() {
        // Get configurations.
        WampConfigurator wampConfigurator = loadRouterPropierties();

        // instance to create news routers.
        WampRouterBuilder routerBuilder = new WampRouterBuilder();
        // instance router

        // complete url compose by properties file.
        URI serverUrl = URI.create("ws://" + wampConfigurator.path + ":" + wampConfigurator.port + "/ws1");

        WampClient client1;

        try {
            routerBuilder.addRealm(wampConfigurator.realm);
            router = routerBuilder.build();

            server = new SimpleWampWebsocketListener(router, serverUrl, null);
            server.start();

            LOGGER.info("Server is running");
            System.out.println("Server is up");

            client1 = createEmbedClient();

            client1.statusChanged().subscribe(new Action1<WampClient.State>() {

                @Override
                public void call(State t1) {
                    System.out.println("Session status changed to " + t1);
                    if (t1 instanceof WampClient.ConnectedState) {

                        client1.registerProcedure("echo.first").subscribe(new Action1<Request>() {
                                    @Override
                                    public void call(Request request) {
                
                                            request.reply("hello from here");
                                        
                                    }
                                }, new Action1<Throwable>() {
                                    @Override
                                    public void call(Throwable e) {
                                        System.out.println("failed to register procedure: " + e);
                                    }
                                }, new Action0() {
                                    @Override
                                    public void call() {
                                        System.out.println("procedure subscription ended");
                                    }
                                });                     
                        
                    }
                }
            });

        } catch (ApplicationError applicationError) {
            applicationError.printStackTrace();
            LOGGER.error(applicationError.getMessage());

            return;
        }
        client1.open();
        
        waitForCar(client1);
        
    }



    private void waitForCar(WampClient client1) {
        Scanner scanner = new Scanner(System.in);
            System.out.println(scanner.next().equals("Card"));
            if(scanner.next().equals("Card")) {
// CALL a remote procedure
                client1.call("sqrt.value", Long.class, 3, 3)
.subscribe(new Action1<Long>() {
@Override
public void call(Long result) {
System.out.println("mul2() called with result: " + result);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable e) {
   System.out.println(e.getMessage());
boolean isProcMissingError = false;
if (e instanceof ApplicationError) {
if (((ApplicationError) e).uri().equals("wamp.error.no_such_procedure"))
isProcMissingError = true;
}
if (!isProcMissingError) {
System.out.println("call of mul2() failed: " + e);
}
}
});
            
        }
        
    }

    /**
     * This method create a new client embed, is connected this router.
     *
     * @return Client.
     */
    private WampClient createEmbedClient() {

        IWampConnectorProvider connectorProvider = new NettyWampClientConnectorProvider();
        WampClientBuilder builder = new WampClientBuilder();
        try {
            builder.withConnectorProvider(connectorProvider).withUri("ws://localhost:8088/ws1").withRealm("realm1")
                    .withInfiniteReconnects().withReconnectInterval(3, TimeUnit.SECONDS);

            return builder.build();

        } catch (ApplicationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

    }

    /**
     * load configuration from classpath/resources/application.properties.
     *
     * @return An instance from a inner private class which encapsulate the
     * configuration properties.
     */
    private WampConfigurator loadRouterPropierties() {
        Properties prop = new Properties();
        InputStream input = null;
        WampConfigurator wampConfigurator = null;

        try {

            ClassLoader classloader = Thread.currentThread().getContextClassLoader();

            input = classloader.getResourceAsStream("application.properties");

            // load a properties file
            prop.load(input);

            // get the property value and create a configurator class.
            wampConfigurator = new WampConfigurator(prop.getProperty("wamp.url"), prop.getProperty("wamp.port"),
                    prop.getProperty("wamp.realm"));
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage());
                }
            }
        }

        return wampConfigurator;
    }

    /**
     * This class is created to encapsulate all the properties on
     * application.properties.
     * **************************************WARNING*********************************************
     * **** IS IMPORTANT UPDATE THIS CLASS SIMULTANEOUSLY WITH
     * application.properties FILE. *****
     */
    private class WampConfigurator {
        String realm;
        String path;
        String port;

        public WampConfigurator(String path, String port, String realm) {
            this.realm = realm;
            this.path = path;
            this.port = port;
        }
    }
}



JAVASCRIPT (WAMPY.JS)


<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Wampy.js</title>
<script src="js/browser/wampy.min.js"></script>
</head>

<body>
<h1>This is a example of wampy.js</h1>

<script>
const ws = new Wampy('ws://127.0.0.1:8088/ws1', {
realm: 'realm1'
});


//REGISTER A CALL

const sqrt_f = function (data) {
return {
argsList: data.argsList[0] * data.argsList[0]
}
};


ws.register('sqrt.value', {
rpc: sqrt_f,
onSuccess: function (data) {
console.log('RPC successfully registered');
},
onError: function (err) {
console.log('RPC registration failed!', err.error);
}
});



function makeCall() {
ws.call('echo.first', null,
function (result) {
console.log('Server time is ' + result.argsList[0]);
});


}
</script>

<button onclick="makeCall()">Normal Button</button>
</body>

</html>

I want to know how to use the client that I create, configure and initiate in start() java method in waitForCar() java method which is calling the sqrt.value procedure in my js. 


Following the jawampa documentation that says:



WampClient client = builder.build();
client.statusChanged().subscribe(...);
client.open();

// ...
// use the client here *************** Here is the waitForCar(client) Method. 
// ...

// Wait synchronously for the client to close
// On environments like UI thread asynchronous waiting should be preferred
client.close().toBlocking().last();

Anyone can help me? 
Greetings from Mexico amigos!. 

Reply all
Reply to author
Forward
0 new messages