trying to make a tutorial on recommendation engine example with qbit- running into some problems.
trying to make a book out of QBit wiki.
getting familiar with gitbook
-----------------------------------------------------------
the latest version of qbit wasn't ruuning examples because it was missing qbit.ipr file which i fixed by gradle idea.
now the files for qbit-worker-callback example and many more have a "j" logo on them instead of a "c" logo. trying to find out what is that. it is not available under "file types by Intellij IDEA" also you can not run them.
npm is a package manager for JavaScript, and is the default for Node.js. As of Node.js version 0.6.3, npm is bundled and installed automatically with the environment. npm runs through the command line and manages dependencies for an application. It also allows users to install Node.js applications that are available on the npm registry. npm is written entirely in JavaScripthttps://www.youtube.com/watch?v=pa4dc480Apo
Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux, FreeBSD, and IBM i.
Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application's throughput and scalability. These technologies are commonly used for real-time web applications.
Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.
Saturday, February 28, 2015
Friday, February 27, 2015
2-27-15
Reread
QBit Microservice Java Lib Working With CallBacks and Java 8 Lambda expressions
If the processor finds that the memory location is in the cache, a cache hit has occurred. However, if the processor does not find the memory location in the cache, a cache miss has occurred.
In Java Applications it is very common to use in Memory Cache for better performance.
A cache is an area of local memory that holds a copy of frequently accessed data that is otherwise expensive to get or compute.
Items will expire based on a time to live period.
Cache will keep most recently used items if you will try to add more items then max specified.
For the expiration of items we can timestamp the last access and in a separate thread remove the items when the time to live limit is reached. This is nice for reducing memory pressure for applications that have long idle time in between accessing the cached objects.
QBit Microservice Java Lib Working With CallBacks and Java 8 Lambda expressions
start tutorial on the simple call back example quick and detailed
a few notes about cache and random stuff...
----------------------------------------------------
In Java Applications it is very common to use in Memory Cache for better performance.
A cache is an area of local memory that holds a copy of frequently accessed data that is otherwise expensive to get or compute.
Items will expire based on a time to live period.
Cache will keep most recently used items if you will try to add more items then max specified.
For the expiration of items we can timestamp the last access and in a separate thread remove the items when the time to live limit is reached. This is nice for reducing memory pressure for applications that have long idle time in between accessing the cached objects.
Thursday, February 26, 2015
2-26-15
starting to read/understand
QBit Microservices using Service Workers and sharded service workers
starting to read/understand
Using QBit Java microservice lib with Spring Boot
starting to read/understand
QBit Microservice Java Lib Working With CallBacks and Java 8 Lambda expressions
----------------------------------------------------------
Pooling is a resource management term that refers to the grouping together of resources (assets, equipment, personnel, effort, etc.) for the purposes of maximizing advantage and/or minimizing risk to the users. The term is used in many disciplines.
Consumer method represents a function that accepts a single argument of an arbitrary type and produce no result.
Dynamic dispatch is often used in object-oriented languages when different classes contain different implementations of the same method due to common inheritance. For example, suppose you have classes A, B, and C, where B and C both inherit the method foo()from A. Now suppose x is a variable of class A. At run time, x may actually have a value of type B or C and in general you can't know what it is at compile time.
With static dispatch, a method call x.foo() will always refer to the implementation of foo() for class A because static binding only looks at the declared type of the object. With dynamic dispatch the language will determine the type of the value of x at run-time and call the version of foo()that is associated with whatever type the value has, whether A, B, or C.
-----------
You can use Spring Boot and QBit together. You could configure QBit to work with/in Spring MVC, or you can just use QBit as the servlet that handles requests.
Remember this about QBit. It runs standalone with Jetty or Vertx. It can run in any Servlet container.
To really grasp QBit, one must grasp the concepts of a CallBack and queues. A CallBack is a way to get an async response in QBit from a microservice. You call a service method and it calls you back. This also covers when to handle @QueueCallback for notification of queue empty, queue hit limit, and queue started a new batch
RecommendationService is our CPU intensive service. will be the recommendation engine. It our hypothetical example RecommendationService is very CPU intensive. It has to iterate through products and user data and pick a match. It is a classic N+1. In our example, we do all of this real time based on the latest user activity, to the last second. What page did that just view? What product did they just bookmark? What product did they buy? What product did their friends buy? What product are people in their same demographic buying now. This is real time analytics. This does not mean that there is not machine learning or Hadoop batch jobs churning data some where. But the churned data is mixed with the data science, pre-chewed caches and counters, and up to the second user activity to make a decision based on data in memory and historic data (blended).RecommendationService is the tip of the ice-burg, but it is brute force, exhaustive and fast.
UserDataService is our heavy IO service. As much as we would like to, we do know which RecommendationService node a user might land on we can't if we are truly elastic. Are they using an XBox on the west coast, an iPhone in Hawaii, when/how will they hit our recommendation engine who knows. UserDataService manages editing, backup, and syncing user data. UserDataService keeps most users in-memory and also manages replicating and storing user data.
QBit Microservices using Service Workers and sharded service workers
starting to read/understand
Using QBit Java microservice lib with Spring Boot
starting to read/understand
QBit Microservice Java Lib Working With CallBacks and Java 8 Lambda expressions
----------------------------------------------------------
Pooling is a resource management term that refers to the grouping together of resources (assets, equipment, personnel, effort, etc.) for the purposes of maximizing advantage and/or minimizing risk to the users. The term is used in many disciplines.
Consumer method represents a function that accepts a single argument of an arbitrary type and produce no result.
Dynamic dispatch is often used in object-oriented languages when different classes contain different implementations of the same method due to common inheritance. For example, suppose you have classes A, B, and C, where B and C both inherit the method foo()from A. Now suppose x is a variable of class A. At run time, x may actually have a value of type B or C and in general you can't know what it is at compile time.
With static dispatch, a method call x.foo() will always refer to the implementation of foo() for class A because static binding only looks at the declared type of the object. With dynamic dispatch the language will determine the type of the value of x at run-time and call the version of foo()that is associated with whatever type the value has, whether A, B, or C.
-----------
You can use Spring Boot and QBit together. You could configure QBit to work with/in Spring MVC, or you can just use QBit as the servlet that handles requests.
Remember this about QBit. It runs standalone with Jetty or Vertx. It can run in any Servlet container.
To really grasp QBit, one must grasp the concepts of a CallBack and queues. A CallBack is a way to get an async response in QBit from a microservice. You call a service method and it calls you back. This also covers when to handle @QueueCallback for notification of queue empty, queue hit limit, and queue started a new batch
UserDataService is our heavy IO service. As much as we would like to, we do know which RecommendationService node a user might land on we can't if we are truly elastic. Are they using an XBox on the west coast, an iPhone in Hawaii, when/how will they hit our recommendation engine who knows. UserDataService manages editing, backup, and syncing user data. UserDataService keeps most users in-memory and also manages replicating and storing user data.
Wednesday, February 25, 2015
2-25-15
reading some more on servlets...
starting to read/understand
QBit Microservices using Service Workers and sharded service workers
starting to read/understand
Using QBit Java microservice lib with Spring Boot
starting to read/understand
QBit Microservice Java Lib Working With CallBacks and Java 8 Lambda expressions
---------------------------------------------------------
servlets continued
- the most common CGI: SERVER_NAME=, SERVER_PORT, REQUEST_METHOD, SCRIPT_NAME, PATH_INFO, QUERY_STRING, CONTENT_TYPE, CONTENT_LENGTH.
-the main server is configured to recognize that if the requested URI starts with for example /servlet after the computer name and port; then connects to a specific port number. then passes the request body to that port number.the CGI variable are always available o any program that wants to retrieve them.
-a servlet container is a software program which after start up runs constantly in the background and listens on a specific port number.
-the servlet container acts like a java server to the main web server. it processes the request and outputs the results back to the main web server. the main web server can then decide what to do with the output. if it is html the server can just pass it the client's browser.
- when it detects an incoming data stream on the port. the servlet container retrieves the request information and stores it in a standard java object of type HttpServletRequest.
-an HTTP servlet gets the request object then does what ever with it and sends java's response back to the main web server.
-the main web server attaches additional response header and sends the response back to the client's browser
life cycle of a java servlet
-when the servlet container starts up it creates an instance of the the servlet class
-the container or java server calls that instance's init() method which is always allowed to complete before the service() doGet() or doPost() method can ever be called.
from now on whenever a browser requests a servlet, the server calls that instance's service() method. if multiple requests are received , the sever calls the same service() method in a separate thread unless the java server is maintaining instance pools.
-for GET and POST requests on HttpServlets, the service() method automatically calls doGet(), or doPost() method which you define in the servlet's code.
-if the server ever needs to be shut down or if too many servlets are loaded in memory and some of them are not being used, it calls the servlet instances's destroy() method. any data in memory that needs to be saved can then be written to disk in in the destroy() method.
- the server then forgets that the servlet instance ever existed. the instance is ultimately garbage collected to free up memory.
-when the server restarts or the net servlet is called the lifecycle starts all over again
how to process a request to a servlet
-the java server or container automatically:
process the string query from get methods and the the request body from post methods.
decodes the url encoded strings and the request body
stores the resulting name - value pairs in a request object
calls the servlet's doGet() or doPost() method depending on the incoming request method
-java's HTTP request object has a number of methods to access various parts of the incoming request. here are some the methods used often:
req.getServerName()
request.getServerPort()
someReq.getMethod()
requ.getServletPath()
req.getPathInfo()
req.getPathTranslated()
eq.getQueryString()
req.getContentType()
req.getContentLength()
-gets all request query string and request body name/value
Enumeration keys = req.getParameterNames();
while (keys.hasMoreElements() ) {
String key = (String)keys.nextElement(); //To retrieve a single value String value =
req.getParameter(key); // If the same key has multiple values (check boxes) String[] valueArray =
req.getParameterValues();
}
Note: If the parameter data was sent in the request body, for example in a POST request, then don't use getInputStream() or getReader(). Instead use the getParameter...() methods.
-gets a session object with a particular request (true means create one if non exictent. don't call getWrite() before this call
//Also makes a new session if none exists
HttpSession session = req.getSession(true);
-Gets the part of this request's URL from the protocol name up to the query string
String urlUptoQuestionMark = request.getRequestURI();
it can be done also by
StringBuffer buff = HttpUtils.getRequestURL(req);
the returned URL string contains a protocol server name port number and server path but it does not include query string parameters
-A servlet (or a full servlet web application) maintains same information across all the clients in a "ServletContext" object (unlike "HttpSession" objects which are specific to one client).
-The Java server administrator sets the servlet context of a web application (group of servlets)in the Java server by defining:
path prefix for the web application
class names
initialization parameters for servlets
request-URI-to-specific-servlet mappings
session parameters
mime types for static files
-Get a servlet web application's context path as configured in the java server (e.g. /myApp):
String cool = request.getContextPath();
-To work with a Servlet Context as a Java object, just call getServletContext() within a servlet. It is always available.
ServletContext sct = getServletContext();
-Get another "URL" object on the same server. The path to get must begin with a "/" and is interpreted as relative to the current context root.
URL gotten = getServletContext().getResource("/whatever/else")
-Convert Internet path to computer file path
String file = getServletContext().getRealPath("path string");
-Get Servlet Container make and model:
String serverInfo = getServletContext().getServerInfo();
-Get the names of the runtime initialization parameters for this servlet, if any. The Java server administrator may have specified these parameters as name=value pairs when configuring this servlet in the server. These are the counterparts of command line options passed to a command line application.
Enumeration enum
= getServletContext().getInitParameterNames();
String initString = getServletContext().getInitParameter("parameter name");
Tuesday, February 24, 2015
2-24-15
Todo List app working with qbit and TodoService (controller) and TodoObject check the code here [todo list app]
[Quick start] Building a todo list app with qbit
[detailed tutorial] Building a todo list app with qbit
reading about servlets....
-----------------------------------------------------------
Todo List app
Todo list app is working now with qbit and todoservice check out the code here [todo list app].
The todo list app is simple you can add your todo items via a text box and hitting enter. once they are added you can check the box for the item to draw a line through the todo item, and you can delete an item by double clicking it here is a picture of the app:

[detailed tutorial] Building a todo list app with qbit
This is done you can check it out here on this link https://github.com/advantageous/qbit/wiki/%5BDetailed-Tutorial%5D-Building-a-single-page;-Todo-List-Application-with-QBit
[Quick start] Building a todo list app with qbit
[detailed tutorial] Building a todo list app with qbit
reading about servlets....
-----------------------------------------------------------
Todo List app
Todo list app is working now with qbit and todoservice check out the code here [todo list app].
The todo list app is simple you can add your todo items via a text box and hitting enter. once they are added you can check the box for the item to draw a line through the todo item, and you can delete an item by double clicking it here is a picture of the app:

Once get the code for it build it and run it on your machine you can access the app on your localhost:
http://localhost:9999/ui/index.html
The app is coded in html, css and javascript. TodoService is the controller for this example it will generate the id element for the items listed. this id will be used to add, delete, and draw a line trough them.
[Quick Start] Building a Todo List application with qbit.
This is done you can check it out here on this link https://github.com/advantageous/qbit/wiki/%5BQuick-Start%5D-Building-a-single-page;-Todo-List-Application-with-QBit
This is done you can check it out here on this link https://github.com/advantageous/qbit/wiki/%5BDetailed-Tutorial%5D-Building-a-single-page;-Todo-List-Application-with-QBit
Reading about servlets
how a browse talks to a web server?
-type a url in the browser or click on a link
-browser sends a get or a post request to the server
how a browse talks to a web server?
-type a url in the browser or click on a link
-browser sends a get or a post request to the server
- if its a get request the browser appends the values from various form fields to the end of the requested URL, this info is called a query string.
-the query strong is URL encoded; a ? separates the requested URL from the query string
-the main web server interprets anthing after the ? symbol as a query string
-multipe name and values are seperated by a & symbol.
-spaces are replaced by + signs
-if we have a post request the browser still encodes the form fields in values but this time it won't append it to the end of the requested URL as in the get request, it may set a special content length header field whose value is the number of bytes that follow in the request body.
-after sending all the header fields, the browser then sends all the encoded texts as the body of the request.
-after the web server readds all the headers of the request, it will read the body, possibly knowing how many bytes to read from the content length header
-a GET request sent by the browser will look like something of this nature:
GET /cgi-bin/runApp/p1?name=your+name&....... HTTP/1.0
Accept:*/*
Connection: keep-Alive
Host: www.w3.org
User-Agent: Generic
-blank line at the end of the header to tell the serve that headers are finished. there is no body for the get request since the query string is attache to the end of the URL.
-a post request sent by the browser will something like this:
POST /cgi-bin/runApp/p1 HTTP/1.0
Accept:*/*
Connection: keep-Alive
Host: www.w3.org
User-Agent: Generic
name=your+name&......
-name= is the request body like a form submision for example, content length is not required in requests.
-a server response sent to the browser will like this:
HTTP/1.1 200 OK
Date: 1 jan 2015 10:30:33 GMT
Server: Apache/1.3
Last-Modified: Mon, 2 Dec 2014 10:30:33 GMT
Etag: "
Accept-Ranges:bytes
Content-Length: 10343
Connection: Keep-Alive
Keep-Alive: timeout=15
Content-Type: text/html; charset=iso-8895-1
<HTML><HEAD><TITLE>...</TITLE></HEAD>
<BODY>. . .</BODY>
</HTML>
-Normally you will have to only set the Content-Type in your application, the web server will put in the other headers.
-the browser access the web server at the default port which is port number 80 for http requests 21 for FTP requests you can also specify the port number.
-any computer called by any website can have up to 64000 port numbers; up to 1024 port numbers are usually reserved for wel known protocols.
-The receiving computer checks which port number the request came in on and passes it to the corresponding process . after start up th main web server process runs constantly in the background and listens on for example port number 80 for incoming requests.
-when the incoming request is detected the main web server will start a separate thread or process to serve that request, connects the incoming stream to it, and goes back to listening for more requests. so there could be a huge number of server threads or processes running at the same time processing different requests on busy sites. each thread or process is essentially the same as the main web server and is referred to as the main web server.
-the main web server sets several standard environment variables related to a request. these variables have been standardized by the CGI (common Gateway Interface)
Monday, February 23, 2015
2-23-15
Todo list app works with QBit get the code from here todo-list app qbit
working on [Quick Start] Building a Todo List application with QBit
working on[detailed tutorial] Building a Todo List application with QBit
Reading about servlets and jsp...
planning on Reading and trying to understand
Working with Callbacks and java 8 Lambda expressions
------------------------------------------------------
todo list app
I got the todo list app to work with qbit without the need for the todo service and todo object, trying to figure out a way to include them in the process. check out the code here
JSP
java server pages: it is a mixture of java and html java between <% %>
jsp is a web page the client is is a web browser.
the browser issues a http request by the internet to a jsp page residing in some web server.
some proccessing takes place on the server after that an http response is sent back via the iternat to the browser.
the processing that takes place on the web server is as follows:
browser sends an http request to a web server.
the web server recognizes that the request is for a jsp page because it sees that the request has a jsp extension on the file name.
once the server recognizes the request it sends it to the jsp container.
the jsp container then loads the jsp and it will convert it into a servlet (jsp is an extension of a servlet).
in the conversion the html is converted into out.write and the jsp elements are converted to java code.
now the jsp container compiles the servlet into an executable class and forwards it to the servlet engine
the servlet engine laods the servlet class and executes it, during the execution the servlet produces an output in html format which the servlet engine passes to the web server inside an http response.
the web server then sendds the http response to the browser in terms of static html content.
the web browser then handles the dynamically generated html page inside the http response exactly as if it were a static page
JSP
java server pages: it is a mixture of java and html java between <% %>
jsp is a web page the client is is a web browser.
the browser issues a http request by the internet to a jsp page residing in some web server.
some proccessing takes place on the server after that an http response is sent back via the iternat to the browser.
the processing that takes place on the web server is as follows:
browser sends an http request to a web server.
the web server recognizes that the request is for a jsp page because it sees that the request has a jsp extension on the file name.
once the server recognizes the request it sends it to the jsp container.
the jsp container then loads the jsp and it will convert it into a servlet (jsp is an extension of a servlet).
in the conversion the html is converted into out.write and the jsp elements are converted to java code.
now the jsp container compiles the servlet into an executable class and forwards it to the servlet engine
the servlet engine laods the servlet class and executes it, during the execution the servlet produces an output in html format which the servlet engine passes to the web server inside an http response.
the web server then sendds the http response to the browser in terms of static html content.
the web browser then handles the dynamically generated html page inside the http response exactly as if it were a static page
Sunday, February 22, 2015
2-22-15
JAVA 1.8:
-Interfaces
-learning lambda
Will revisit this.......
Working some more on the todo list app...
------------------------------------------------------------
Interface
-with java 1.8 you can have a static method with a body on the interface
-you can have a default method with a body on the interface
like in this example:
when you run this you get the following:
What is Lambda?
-Lambda is a function
-Function is a process that takes parameters and returns a value
-In the past functions can only be implemented by using methods, java changed that.
-Lambda lets you treat functions like data; they can be stored or passed around
-Lambda enables you to pass a function as a parameter to a different function directly; this was not possible before java 8.
Here is a simple example:
we have a main
and an interface with a abstract method returnInt
the output for this would be:
instead of making a separate class and a method to return x * x we just used Lambda -> make an instance of the interface iret then x -> x * x as seen in the example above you get a return value of x = x * x as shown.
Another example: Creating a thread.
Runnable is just an interface and Thread is a class, similar to the last example.
Another example; if you want to round a double to an integer using the Function interface and its apply abstract method do the following:
This will round the Double PI into an integer.
Another example do some math with the same interface do the following:
-Interfaces
-learning lambda
Will revisit this.......
Working some more on the todo list app...
------------------------------------------------------------
Interface
-with java 1.8 you can have a static method with a body on the interface
-you can have a default method with a body on the interface
like in this example:
package com.company; /** * Created by fadi on 2/22/15. */public interface IReturn { public default int returnInt(int x) { return x; } public static boolean isIReturn(Object obj) { return obj instanceof IReturn; } }
package com.company; public class Main implements IReturn { public static void main(String[] args) { System.out.println("Hello World this is java 1.8"); Main main = new Main(); System.out.println(IReturn.isIReturn(new Object())); System.out.println(IReturn.isIReturn(main));System.out.println(main.returnInt(119)); } // public int returnInt(int x){//// return x = 10;// }}
when you run this you get the following:
Hello World this is java 1.8
false
true
119
-Lambda is a function
-Function is a process that takes parameters and returns a value
-In the past functions can only be implemented by using methods, java changed that.
-Lambda lets you treat functions like data; they can be stored or passed around
-Lambda enables you to pass a function as a parameter to a different function directly; this was not possible before java 8.
Here is a simple example:
we have a main
package com.company; public class Main implements IReturn { public static void main(String[] args) { System.out.println("Hello World this is java 1.8"); //Main main = new Main(); IReturn iret = (int x) -> { return x * x; }; //System.out.println(IReturn.isIReturn(new Object())); System.out.println(iret.returnInt(10)); new Thread(thread).start(); } public int returnInt(int x){ return x + 2; } }
and an interface with a abstract method returnInt
public interface IReturn { public abstract int returnInt(int x); public static boolean isIReturn(Object obj) { return obj instanceof IReturn; } }
the output for this would be:
Hello World this is java 1.8
100
instead of making a separate class and a method to return x * x we just used Lambda -> make an instance of the interface iret then x -> x * x as seen in the example above you get a return value of x = x * x as shown.
Another example: Creating a thread.
Runnable thread = () -> { System.out.println("This is a thread"); };
System.out.println(iret.returnInt(10));
new Thread(thread).start();
Runnable is just an interface and Thread is a class, similar to the last example.
Another example; if you want to round a double to an integer using the Function interface and its apply abstract method do the following:
unction<Double, Integer> func = (Double d) -> { return (int) Math.round(d); };
System.out.println(func.apply(Math.PI));
This will round the Double PI into an integer.
Another example do some math with the same interface do the following:
Function<Double, Double> func = (Double x) -> { return ((x * x) + (x / 100) + 1500); };
System.out.println(func.apply(100d));This will do the following returns x = (100 * 100) + (100 /100) +1500 = 11501.0So Lambda will make your programing life much easier if you understand it well it will save you from writing alot of code. i will revisit this.....Here is the full example listing:import java.util.function.Function; public class Main implements IReturn { public static void main(String[] args) { System.out.println("Hello World this is java 1.8"); //Main main = new Main(); IReturn iret = (int x) -> { return x * x; }; Runnable thread = () -> { System.out.println("This is a thread"); }; //Function<Double, Integer> func = (Double d) -> { return (int) Math.round(d); }; Function<Double, Double> func = (Double x) -> { return ((x * x) + (x / 100) + 1500); }; //System.out.println(IReturn.isIReturn(new Object())); System.out.println(iret.returnInt(10)); new Thread(thread).start(); //System.out.println(func.apply(Math.PI)); System.out.println(func.apply(100d)); } public int returnInt(int x){ return x + 2; }}package com.company; /** * Created by fadi on 2/22/15. */ public interface IReturn { public abstract int returnInt(int x); public static boolean isIReturn(Object obj) { return obj instanceof IReturn; }
Saturday, February 21, 2015
2-21-2015
Readings:
Using QBit microservice lib's REST support with URI params. on Rick's blog
and understanding part of
qbit - The Microservice Lib for Java - JSON, REST, WebSocket, Speed! on on Rick's blog.
reading/understanding about some of the annotations used like
@RequestMapping
@pathVariable
Working on the Todolist app. (the code broke again the method getReceiver can not be found prob a renaming issue)
-----------------------------------------------------------
Using QBit microservice lib's Rest and some of the intro
- if we have a program such as a todo list called (TodoService) and we want to start it up and host it on a server just do the following with QBit:
public static void main(String... args) { ServiceServer server = new ServiceServerBuilder().build(); server.initServices(new TodoService()); server.start(); }
-You can always invoke QBit services via a WebSocket proxy. The advantage of a WebSocket proxy is it allows you execute 1M RPC+ a second (1 million remote calls every second).
to use a microservice remotely via websocket with qbit is very simple do the following:
/* Start QBit client for WebSocket calls. */ final Client client = clientBuilder() .setPort(7000).setRequestBatchSize(1).build(); /* Create a proxy to the service. */ final AdderServiceClientInterface adderService = client.createProxy(AdderServiceClientInterface.class, "adder-service"); client.start(); /* Call the service */ adderService.add(System.out::println, 1, 2);
The above code uses a WebSocket proxy interface to call an AdderService:
@RequestMapping("/adder-service") public class AdderService { @RequestMapping("/add/{0}/{1}") public int add(@PathVariable int a, @PathVariable int b) { return a + b; } }
with the following interface:
interface AdderServiceClientInterface { void add(Callback<Integer> callback, int a, int b); }
The output for this is:
3
-You could also just use REST, and actually use the URI params that we setup. REST is nice but it is going to be slower than WebSocket support.
To use the adder service remotely using REST HTTP do the following:
HttpClient httpClient = httpClientBuilder() .setHost("localhost") .setPort(7000).build(); httpClient.start(); String results = httpClient .get("/services/adder-service/add/2/2").body(); System.out.println(results);
the output for this would be:
4
you can also access the service from curl.
$ curl http://localhost:7000/services/adder-service/add/2/2
Working with Websocket and HTTPclient etc...
Websocket server and client:
-------------------------------------------------------------
Annotation
@RequestMapping: mehtod to be invoked when a client enters a url that matches the path of the @RequestMappin for example:
when a user enters the following URL:
the method add would be invoked.
if the user enter the wrong path he will get a 404 status error page, resources not available.
when curly brackets are used such in the example above the user can substitute it with any value he wishes:
the user then can request the following page:
or any page with different numbers at the end.
this is where the @PathVarible comes in handy.
@PathVariables: to retrieve the values entered by the user we just use @PathVariable like here:
Now when a user enters the URL, we can retrieve the last 2 values and add them; like when he enters:
a = 2 and b =2, then the add method is called and returns 4.
Todolist app
the hello code broke again due to a renaming issue fixed it by changing getReceiver to getResponse.
Websocket server and client:
-create an HTTP server
/* Create an HTTP server. */
HttpServer httpServer = httpServerBuilder()
.setPort(8080).build();
-setup websocket server support
/* Setup WebSocket Server support. */
httpServer.setWebSocketOnOpenConsumer(webSocket -> {
webSocket.setTextMessageConsumer(message -> {
webSocket.sendText("ECHO " + message);
});
});
-Start the server
/* Start the server. */
httpServer.start();
-Setup the websocket client
/** CLIENT. */
/* Setup an httpClient. */
HttpClient httpClient = httpClientBuilder()
.setHost("localhost").setPort(8080).build();
httpClient.start();
-client websocket
/* Setup the client websocket. */
WebSocket webSocket = httpClient
.createWebSocket("/websocket/rocket");
/* Setup the text consumer. */
webSocket.setTextMessageConsumer(message -> {
System.out.println(message);
});
webSocket.openAndWait();
/* Send some messages. */
webSocket.sendText("Hi mom");
webSocket.sendText("Hello World!");
-Output
ECHO Hi mom
ECHO Hello World!
-------------------------------------------------------------
Annotation
@RequestMapping: mehtod to be invoked when a client enters a url that matches the path of the @RequestMappin for example:
@RequestMapping("/adder-service") public class AdderService { @RequestMapping("/add/{0}/{1}") public int add(@PathVariable int a, @PathVariable int b) { return a + b; } }
when a user enters the following URL:
$ curl http://localhost:7000/services/adder-service/add/2/2
the method add would be invoked.
if the user enter the wrong path he will get a 404 status error page, resources not available.
when curly brackets are used such in the example above the user can substitute it with any value he wishes:
@RequestMapping("/add/{0}/{1}")
the user then can request the following page:
$ curl http://localhost:7000/services/adder-service/add/3/7
or any page with different numbers at the end.
this is where the @PathVarible comes in handy.
@PathVariables: to retrieve the values entered by the user we just use @PathVariable like here:
@RequestMapping("/add/{0}/{1}") public int add(@PathVariable int a, @PathVariable int b) { return a + b; }
Now when a user enters the URL, we can retrieve the last 2 values and add them; like when he enters:
$ curl http://localhost:7000/services/adder-service/add/2/2
a = 2 and b =2, then the add method is called and returns 4.
Todolist app
the hello code broke again due to a renaming issue fixed it by changing getReceiver to getResponse.
Subscribe to:
Posts (Atom)