jawampa--Wamp support to Java libraries

Source: Internet
Author: User

Jawampa

is a library that supports the Web application message Delivery protocol [WAMP] to Java.

Provides WAMPV2 client functionality and server-side functionality, and supports all currently defined WAMPV2 roles (caller, callee, publisher, subscriber, Agent, reseller).

Pluggable transport layer is available. The connectors and servers using different network mechanisms and low-level libraries can be built and inserted into Jawampa.

The Rxjava observables display client user interface enables a powerful combination of different asynchronous operations and provides a simple solution for delegating data processing between different threads.

Declare the dependencies of the following underlying libraries:

<dependency>

<groupId>ws.wamp.jawampa</groupId>

<artifactId>jawampa-core</artifactId>

<version>0.4.2</version>

</dependency>

However, since the Jawampa Core library does not provide a transport layer, users should typically use the JAWAMPA Transport provider library (for example, Jawampa-netty-see subdirectories) as proxies. This will automatically also add a dependency on the Jawampa-core.

WAMP client API (wampclient)

Wampclients must be created through the Wampclientbuilder object. 3 Required parameters must be set through the builder:

A connector provider that describes the framework that will be used to establish a connection to the Wamp router.

URI describing the Wamp router address

Domains that the client should join on the router

In addition, there are optional parameters, such as allowing automatic reconnection between the client and the router, or allowing the configuration of the client to behave in the event of a communication error.

Example:

Final wampclient client; Try {    new  wampclientbuilder ();    Builder.withconnectorprovider (Connectorprovider)           . Withuri ("Ws://localhost:8080/wamprouter")           . Withrealm ("Examplerealm")           . Withinfinitereconnects ()           . Withreconnectinterval (5, timeunit.seconds);       =catch  (Wamperror e) {     System.out.println (e);     return ;}
View Code

The Wampclient object provides Rxjava Observable statuschanged () that notifies the user of the current state of the session between the client and the router, which can be disconnectedstate, Connectingstate or Connectedstate. Applications can monitor this observable to detect when additional steps should be taken (for example, subscribing to a topic or registering a function after a connection).

StatusChanged () returns behaviorobservable, so it immediately sends a notification to the subscriber about the current state, not just in the case of a state change.

StatusChanged () returns a behaviorobservable, so it immediately sends a notification to the subscriber and the user of the current shape change.

Example:

client.statuschanged ()      . Observeon (Applicationscheduler)      , {        if  instanceof  wampclient.connectedstate) {        elseifinstanceof  Wampclient.disconnectedstate) {             elseifinstanceof  wampclient.connectingstate) {                }});
View Code

In order to initiate a connection between the client and the router, the client open () member function must be called. This causes the first connection attempt and the state to change from Disconnectedstate to Connectingstate.

You must use the close () member function to close when the client is no longer needed. This closes the connection to the remote router and stops all reconnection attempts. The wampclient cannot be reopened after it has been closed. If necessary, create a new instance of Wampclient.

The shutdown process is also asynchronous. Therefore, calling close () does not guarantee that the client shuts down immediately. However, the close () call returns a observable that can be used to wait for the client to be successfully closed.

Example of a typical session life cycle:

Wampclient client = builder.build (); client.statuschanged (). Subscribe (...); Client.open (); //  ... // Use the client here //  ... // Wait synchronously for the client to close // On the environments like UI thread asynchronous waiting should is preferredclient.close (). Toblocking (). Last ();
View Code

Execute procedure Call

Remote procedure calls can be performed through the various call member functions of wampclient.

All overloaded versions of the call require the name of the calling procedure (and it must be a valid Wamp Uri) as the first parameter. All versions of Call () return a observable that is used to asynchronously pass the result of a function invocation to the caller. It is an active observable, which means that the call will independently determine whether someone subscribes to it. However, the results will be cached in observable, which means that later subscribers will be able to retrieve the results.

If the procedure call succeeds, the result is used to invoke the Subscriber OnNext method, and then the oncompleted call is executed. If the remote procedure call fails, the Subscriber OnError () method is called and the error appears as a parameter.

Different overloads of call () allow parameters to be supplied to the procedure in different ways, and return values are retrieved in different ways:

The most explicit signature of the call is the observable <Reply> called (String procedure,arraynode arguments,objectnode argumentskw) which allows the transfer of positional and keyword parameters to the wamp process, and returns a structure that also contains the fields that call the result's location and keyword parameters. Parameters and return values use the Arraynode and Objectnode data types from the Jackson JSON library to describe any other type of array or object.

If you call a simplified variable, only the positional parameter can be observed <Reply> called (String procedure,object ... args) can be used to allow positional parameters to be passed as varargs arrays. It will also automatically use the Jacksons object Mapping feature to convert all of the Java pojo keyword parameters in its jsonnode form and create a parameter array from it. This means that any type of Java object can be used directly as a function parameter, as long as they can be serialized and deserialized correctly. For more complex data structures, you may want to use annotations to indicate the serializer.

The last variant of

Call () provides some further convenience and has the following signature:<t> <T> invoke (String procedure,class <T> Returnvalueclass, Object ... args). You can use it when the procedure does not provide or provide only one location return value. You can then specify the type of the expected return value in the second argument, and the call will automatically attempt to map the first result parameter of a procedure call to the desired type. This will also be done through the Jackson object mapping. With this simplification, you can invoke the remote procedure and listen for the return value in the following ways (using JAVA8):

observable<string> result = Client.call ("Myservice.concat", String.  Class, "Hello nr", 123); // Subscribe for the result // OnNext'll be called in case of success with a String value // OnError'll be called in case of errors with a throwable Result.observeon (applicationscheduler)       - System.out.println (TXT),                 System.err.println (err));
View Code

Providing remote procedures to other customers

With Wamp, all clients connected to the router are able to provide procedures that can be used by any other client.

Jawampa exposes this functionality through the Registerprocedure () member function. Registerprocedure will return a observable that will be used to receive incoming function calls. Each incoming request to the registration process name is pushed to the subscribers OnNext method in the form of the request class. Applications can retrieve and process requests on any thread through Observeon, and can use the Request class member function to send responses to requests. This procedure will only be registered at the router after the subscription is invoked, and if the subscription is unsubscribed, it will be unregistered at the router.

If an error occurs during the process registration of the router, the Subscribers onerror method is called to notify about the error. If the session is disconnected (or disconnected), the subscription will simply be completed using oncompleted.

An example of a procedure that provides a callback for the first integer parameter:

//provide a procedureObservable proc = client.registerprocedure ("Echo.first"). Subscribe (Request- {        if(request.arguments () = =NULL|| Request.arguments (). Size ()! = 1 | | !request.arguments (). Get (0). Canconverttolong ()) {Try{request.replyerror (NewApplicationerror (Applicationerror.invalid_parameter)); } Catch(Applicationerror e) {}}Else {            LongA = Request.arguments (). Get (0). Aslong ();        Request.reply (a); }}, E-System.err.println (e));//Unregister The procedureProc.unsubscribe ();
View Code

Publish Events

The Publish () function of wampclient can be used to publish events to all other connected Wamp clients by publishing an event with a subject (which must be a valid Wamp Uri) to the router.

Like call (), the Publish () function provides various overloads that allow event arguments to be passed in different formats.

The Publish () function returns a observable <Long>. Just like the observable returned from call (), this is also an active observable that does not require a subscription to perform the publication. Subscribers subscribed to observable will receive a onnext () call that is passed Publicationid or onerror () when the publication fails. This can be for example when there is no connection to the router.

Examples of publishing events:

Client.publish ("Example.event", "Hello", "from Nr",)      . Subscribe (/        **/  },        /**/});
View Code

Subscribe to Events

To subscribe to events published from other clients on the router, you can use the Wampclient makesubscription () function. Makesubscription requires a topic of interest to the client and returns a observable that can be used to execute the subscription. The topic subscription on the router will only occur on subscribe () called Observable. After that, for each received event, the Subscriber OnNext () function is called to pass the event in the form of a pubsubdata structure that contains the positional and keyword arguments. If the subscription is not executed on the router because of error onerror () it will be called to pass the error. If the connection is closed or get is closed, the subscription will be completed using oncompleted ().

Tip: For most applications, it is meaningful to perform a subscription after connecting to the router in the statuschanged () handler.

Overloading of the Makesubscription function, which can be used only if the client is interested only in the first positional parameter of the event. It allows you to specify the class type of the event data and automatically attempts to convert the received event to this data type through the Jacksons Object mapping feature. If the client does not have a parameter void.class can use a observable <void>, which notifies the user when no event is received for the parameter. If the received event data cannot be converted to the desired format, the subscription will be canceled and an error will be passed through the onerror () function.

Examples of subscription events:

// Subscribe to an event observable<string> eventsubscription =client.makesubscription ("Example.event", String.   Class)      /*** / },                 /* */ }); // unsubscribefrom the event eventsubscription.unsubscribe ();
View Code

Wamp Server API (Wamprouter)

JAWAMPA provides a wamp router that can be bundled into an application to avoid installing, configuring, and running an external router. By instantiating the provider API in the application and the Wamprouter wampclient, you can emulate the classic server architecture, where the server listens for connections and provides APIs.

The Wamprouter class implements the entire routing and domain logic described in the WAMPV2 basic configuration file. It can only be created through the Wamprouterbuilder class, which allows the router to be configured before it is instantiated. In the current version of Jawampa, the realm that the router must expose must be configured through it.

Example of configuring and instantiating a router:

New Wamprouterbuilder (); Wamprouter router; Try {    Routerbuilder.addrealm ("REALM1");    Routerbuilder.addrealm ("realm2");     =catch  (Applicationerror e) {    e.printstacktrace ();     return ;}
View Code

The router will run directly after the build. But it won't listen to any connections, so so far it won't do anything. If you let the router work, the server must be set to accept connections, register them on Wamprouter, and then push messages to it.

Wamprouter provides an implementation of a iwampconnectionacceptor interface that can be used to register a new connection with the client. It can be queried by Wamprouter.connectionacceptor () getter.

Registering a new connection on the router is a process that requires two stages:

First, the connection provider must call Connectionacceptor.createnewconnectionlistener () and query the Iwampconnectionlistener instance from the router. This will be the interface for new connections to push messages after they are fully established and registered. The returned interface has not yet occupied any non-garbage collection resources in the router. Therefore, if the connection provider determines that the connection cannot be established correctly, it is not harmful to ignore the return value.

In the second step, the new connection must be registered on the router by calling Connectionacceptor.acceptnewconnection (Connection,connectionlistener); This provides the iwampconnection type of send interface to the router.

Once the two steps are complete, the new connection can send messages only to the listener. Sending a message earlier can result in undefined behavior.

Provide iwampconnection Wamprouter will use the interface to send messages over the connection. The following connection routers must be guaranteed:

The router must be able to invoke the method on the interface as long as it does not call Close (... ) on it. If the connection is closed or in an error state, the implementation of the interface should answer SendMessage (...) by denying the provided promise. Call The router will always call Close (...) on the interface. ), even if the connection is closed by the remote side. The connection must be guaranteed that the method will not be called on the retrieved Iwampconnectionlistener interface after it closes the call by satisfying the provided future acknowledgment. The router will accept the close (... Called to confirm that all resources owned by the connection have been released as flags. A sample implementation of the server that pushes messages to the Netty framework-based router can be found in the Jawampa-netty subproject.

Turn off the router

To turn off the router, you must call the close () member function:

Router.close.toBlocking (). Last ();

This will gracefully shut down all WAMP sessions established between the router and the client, and will close the underlying transport channel. If a new connection is made to the router after close (), it will reject these connections by shutting them down.

Just like the close () call on Wampclient closes a wamprouter is also an unsynchronized process, and when the router shuts down completely, the call returns a observable signal.

To allow the router to listen on the port, accept incoming connections, you must start one or more servers that use the router as their final request handler.

Jawampa is very active in the working state. Therefore, the following restrictions apply:

The transfer of binary values required in the WAMP specification is not supported correctly. Jawampa will use Jackson to convert data from binary to JSON, which uses Base64 encoding, but does not pre-provision data with leading 0 bytes.

Jawampa only supports certain selected parts of the WAMPV2 Basic profile and Advanced configuration files. Many advanced configuration file features are not implemented.

The Jawampa only supports websocket connections between WAMP clients and routers.

The roles of the client and the router are transferred correctly, but all other operations are not considered. For example. The remote peer is not verified to actually provide the required functionality. Assume that all peers implement all the roles that apply to them.

jawampa--Wamp support to Java libraries

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.