How to send messages from server to client? - mysql

I am going to implement something similar to Facebook notification and this website (StackOverflow's notification which is notifying us if anyone write a comment/answer etc for our question). Please note users are going to use my application as a website not mobile application.
I came across following answer which fetch the results, but I need to push the results not fetch.
Based on suggestions I have created a simple method in my entity class and added the #PostPersist to it but it has not worked so based on this answer I added the persistence.xml file to define the listeners but after session.save(user) the aftersave method does not get triggered.
User.java
#Entity
public class User{
.....
#PostPersist
public void aftersave(){
System.err.println("*****this is post persist method****");
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<property name="hibernate.ejb.event.pre-insert" value="my.hibernate.events.listeners.Listener" />
<property name="hibernate.ejb.event.pre-update" value="my.hibernate.events.listeners.Listener" />
<property name="hibernate.ejb.event.pre-delete" value="my.hibernate.events.listeners.Listener" />
<property name="hibernate.ejb.event.post-insert" value="my.hibernate.events.listeners.Listener" />
<property name="hibernate.ejb.event.post-update" value="my.hibernate.events.listeners.Listener" />
<property name="hibernate.ejb.event.post-delete" value="my.hibernate.events.listeners.Listener" />
pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.1.Final</version>
<type>jar</type>
</dependency>

Sounds like a task for WebSockets. It is part of Java EE 7 so the Glassfish should be one of the first AS that will support it.
For intercepting the DB access you can use #PostUpdate and #PostPersist. Here is related question.
There are many ways to do the so called Server Push for notifying the connected clients:
polling (the link you've provided in the question ("Are we there yet? Are we there yet? ..."))
long polling (smarter way of polling - long-lived HTTP technique using keepalive messages)
WebSockets (JSR 356)
piggy-backing
SPDY(wiki)
Server-Sent Events (related answer, wiki)
EDIT: In the Java world, there are couple of frameworks where server push (reverse ajax) is implemented out-of-the box. If you are familiar with GWT, I would suggest Errai. Other alternative is the Atmospere. The downside of the Atmospere is the fact that it requires standalone running process next to your regular application server with your web app. I was playing with it a year ago so this may have been changed since then.
In general, it is hard to provide you with a concrete piece of code, because it depends on the framework you will choose. I am familiar with Errai so here is an example in it:
Server Side:
#ApplicationScoped
public class TickerService {
#Inject
private Event<Tick> tickEvent;
private void sendTick() {
tickEvent.fire(new Tick());
}
}
Client Side:
#EntryPoint
public class TickerClient {
public void tickHappened(#Observes Tick tick) {
// update the UI with the new data
}
}
Other benefits of using the Errai is having the CDI on the server and on the client out-of-the-box, another thing that is nice is using the web-sockets under the covers if it is supported and falling back to other solutions otherwise.
Whatever you choose, it should fit to your existing infrastructure and to your client side UI framework.

mqtt can be used for server pushing and message broadcasting.
There are more detail information in http://mqtt.org/.
======================================
Updated: Jul 11, 2013
Mqtt is a publish/subscribe, extremely simple and lightweight messaging protocol. If server is a publisher and client browser subscribe the topic which server publish to, then server can push message to client directly.
Some useful resource:
Mosquitto is an open sourced mqtt server. Easy to install and configure.
mqtt-client is a proven powerful java mqtt client.

Use Node JS and socket.io
This technology chooses the best transportation method based on the browser that the client is using.
For latest browsers it uses Web Sockets and for others it degrades gracefully to Flash Socket or Long Pooling. See more here
What you need to do is set up a server using these technologies. The server would run at a particular port. All clients would listen to that port and server would be able to push data to the client through that port.

Comet also known as Reverse Ajax, is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it.
Comet (AKA long lived http, server push) allows the server to start answering the browser's request for information very slowly, and to continue answering on a schedule dictated by the server. For more information about Comet, see the following:
Alex Russell's original post coining the term
The Wikipedia article on Comet
Comet Daily, a blog with regular posts on the subject
DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.
With Reverse Ajax, DWR allows Java code running on a server to use client side APIs to publish updates to arbitrary groups of browsers. This allows interaction 2 ways - browser calling server and server calling browser. DWR supports Comet, Polling and Piggyback (sending data in with normal requests) as ways to publish to browsers.
DWR provides integration with Spring, Struts, Guice, Hibernate and others.
You can read more from here.
Other Comet and Reverse AJAX frameworks:
Grizzly Comet API
Atmosphere
AJAX push with ICEfaces
Asynchronous Servlet using Servlet 3.0

but after session.save(user) the aftersave method does not get triggered.
#PostPersist is a JPA callback.
session.save() is a non-JPA, hibernate proprietary method. JPA uses entityManager.persist().
you're using incompatible features

Check for update from server on every 30 Seconds or as per requirement.
window.setInterval(function(){
/// call your function here
//Make AJAX call
//Update Respective HTML Contact i,e, DIV
}, 30000);

Related

Apache camel with spring DSL and Junit Coverage

I am completely new to apache camel.
I got some basic understanding about it.
Now I am going through some videos and documents to get some ideas for implementing junit test cases for apache camel spring DSL based spring boot application but it's not clear to me since there are many ways to implement or in very high level.
I am confused.. which one to follow and what is actually happening in those junits
Does anyone have example or link or videos which explains junit coverage for apache camel spring DSL based spring boot application?
I am particularly looking for junits.
also If you know someone good tutorials about apache camel let me know.
JUnit and Camel doesn't work the same as JUnit and "normal" code and as far as I am aware there's only fairly rudimentary ways to get coverage of a camel route from JUnit. Camel routes are a processing model that is essentially an in memory model of the various steps that need to run, so you can't use code coverage tools to track what parts get executed.
Consider this route (in a subclass of RouteBuilder ):
public void configure() throws Exception {
from("jms:queue:zzz_in_document_q")
.routeId("from_jms_to_processor_to_jms")
.transacted()
.log(LoggingLevel.INFO, "step 1/3: ${body}")
.bean(DocBean.class)
.log(LoggingLevel.INFO, "step 2/a3 - now I've got this: ${body}")
.process(new DocProcessor())
.log(LoggingLevel.INFO, "step 3/3 - and finally I've got this: ${body}")
.to("jms:queue:zzz_out_document_q");
}
and an associated test case, in a class that extends CamelBaseTestSupport:
#Test
public void testJmsAndDbNoInsert() throws Exception {
long docCountBefore = count("select * from document");
template.sendBody("jms:queue:zzz_in_document_q", new Long(100));
Exchange exchange = consumer.receive("jms:queue:zzz_out_document_q", 5000);
assertNotNull(exchange);
Document d = exchange.getIn().getBody(Document.class);
assertNotNull(d);
long docCountAfter = count("select * from document");
assertEquals(docCountAfter, docCountBefore);
}
When the unit test runs the app context will run the configure method, so I've got 100% coverage of my route before I even put a message on the queue! Except I don't, because all it's done is created the execution model in the camel route system and the various components and processors are now all going to run in the right order.
Beans and Processors will get included in the coverage reports, but if you have complex logic in the routes it's not going to give you coverage on this.
There is this capability, delivered around 2017 - https://issues.apache.org/jira/browse/CAMEL-8657 - but I haven't used it and am not sure how it will go working with whatever coverage tooling you use.

.NET Core Configuration - System.Net connectionManagement/maxconnections?

I am migrating a console app (REST client app) from .NET framework to .NET Core.
In my current (framework) version, I use the app.config file to set the System.Net configuration:
<system.net>
<connectionManagement>
<add address="*" maxconnection="65535"/>
</connectionManagement>
</system.net>
In .NET Core, I have to use a JSON file for configuration. There is no documentation for implementing these settings using the new configuration schema. Does anyone know how this might look inside the new JSON config, or the correct way to implement this in Core? Do I need to build a designated "System.Net.json" config file (separate from an AppSettings.json) specifically to do this?
Thanks.
I assume you're trying to avoid the limit of 2 connections per endpoint, which is default on .NET Framework. Such limit does not exist on .NET Core. So you don't need the above setting at all.
Note that to achieve better perf, we recommend to use HttpClient/HttpClientHandler over HttpWebRequest/ServicePoint on .NET Core. HttpWebRequest/ServicePoint APIs are compat-only.
If you want to limit HttpClient connections, then use HttpClientHandler.MaxConnectionsPerServer
Assuming you are using Kestrel as your web server (and not doing it through IIS implementation), you should be able to set this in your UseKestrel in your BuildWebHost.
It would go something like this:
.UseKestrel(options =>
{
options.Limits.MaxConcurrentConnections = 100;
})
You can also add this in your HttpClientHandler, It's called MaxConnectionsPerServer. It can be seen here.
Some addition to Karel Zikmund answer. (As i don’t have permissions to comment).
According to this doc connections are limited since .net core 2.0:
https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.defaultconnectionlimit?view=netcore-3.1
What is missed in doc is if ServicePointManager used for .net core HttpClient implementation. According to this info it is used in .net core, but for HttpWebRequest, not HttpClient: https://github.com/dotnet/runtime/issues/26048

Quartz.net Setup Throwing Error: "onfiguration parser encountered <job>"

I have a Asp.net C# MVC 3 application implementing the Sharp Architecture. I have been trying to get Quartz.net to setup and work nicely with Castle Windsor for a few days without any luck. Based on what I know, I have setup everything correctly, but continue to have issues.
In my Global.cs file, creating my Container and trying to register quartz jobs:
var container = new WindsorContainer(new XmlInterpreter("quartz_jobs.xml"));
container.AddFacility("quartznet", new QuartzFacility());
In my quartz_jobs.xml file I have the following contents:
<?xml version="1.0" encoding="utf-8" ?>
<quartz xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="1.0"
overwrite-existing-jobs="true">
<job>
<job-detail>
<name>DeleteLoansWithoutClientsJob</name>
<job-type>EasyOptions.Web.Mvc.Code.Jobs.DeleteLoansWithoutClientsJob, EasyOptions.Web.Mvc</job-type>
<durable>true</durable>
</job-detail>
<trigger>
<cron>
<name>DeleteLoansWithoutClientsJobTrigger</name>
<group>MyJobs</group>
<description>A description</description>
<job-name>DeleteLoansWithoutClientsJob</job-name>
<job-group>MyJobs</job-group>
<cron-expression>0 0/1 * * * ?</cron-expression>
</cron>
</trigger>
</job>
Problem is, you're pointing Windsor to the Quartz.NET config file.
There are two separate configurations: Windsor's and Quartz.NET's. Windsor is usually configured with code nowadays (i.e. fluent config), though it still supports XML configuration. However the Quartz.NET facility doesn't currently support code config, you have to use Windsor's XML config (at least for this, other components/facilities may still be configured via code). Then there's Quartz.NET, usually configured via an external quartz_jobs.xml file.
I recommend using the Quartz.NET facility sample app as reference. In particular, here's the sample Windsor config and the sample Quartz.NET config.
EDIT: if Quartz.NET says it can't find quartz_jobs.xml in a web application you need to include the web root in the configuration path: "~/quartz_jobs.xml" (instead of plain "quartz_jobs.xml")
I've written a blog post on how to integrate Quartz.NET with an IoC container. My example code uses Castle Windsor.
The blog post can be found here: http://thecodesaysitall.blogspot.com/2012/02/integrate-quartznet-with-your-favourite.html

SL4 WCF RIA Query Issue: "Completed" happening before it's really completed?

I have a strange little issue with a WCF RIA service I'm using in a SL4 application. Here is the code for a button click handler I've got:
private void btnTest_Click(object sender, RoutedEventArgs e)
{
LanguageContext context = new LanguageContext();
LoadOperation<Language> op = context.Load(context.GetLanguagesQuery());
op.Completed += (obj, args) =>
{
if (!op.HasError)
{
System.Threading.Thread.Sleep(500);
MessageBox.Show(context.Languages.FirstOrDefault().DisplayName);
}
};
}
Note that there's a Sleep call in the handler. Without that sleep call, I get an exception (A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)). If this code is in the "Completed" handler, I figured it was actually, well, completed by the time it got there. Why does it die without the Sleep()? BTW, the Sleep() isn't an option for production, it was just a problem-sovling tool :)
So, If I add "pooling=false" to my connection string, everything works. However, I don't really like that answer. Connection pooling is a good thing. Is there a way to leave it on and have things still work?
I can also reproduce this issue.
For example, I have a unit test that if run twice in succession will fail the second time.
This unit test performs a few things:
1. Drops and recreates the database using a custom Entity Framework 4.1 DbContext Initiailzer
2. Launches a silverlight application
3. Click a button in the silverlight application
At this point the silverlight application makes a call to a wcf ria service to query the database that was just created.
However, every time the unit test is run a second time, I get the same error.
But the error goes away immediately if I click the button again for example.
Setting "Pooling=False" in my connection string did not resolve the issue in my case.
However, I was able to resolve the issue by restarting the web server which hosts the silverlight application and ria service after the database is created.
In my case, I just decided to use Cassini Dev Web Server v4 and run the tests on that web server instead of iis.
Windows 7 Ultimate x64
Visual Studio 2010 SP1
Entity Framework 4.1
WCF RIA Services SP1 for Silverlight 4
Silverlight 4
MSTest
Edit:
Entity Framework 4.1 Update 1 contains a bug fix to remove the need to specify ‘Persist Security Info=True’ in the connection string when using SQL authentication.
http://www.microsoft.com/download/en/details.aspx?id=26825
I am not (yet) sure if the bug is related and might resolve this issue as well.

Websocket and Java Swing front end

Is it doable to make Websocket interfaced with Java Swing front end? If so how?
Try mine:
http://github.com/TooTallNate/Java-WebSocket
Contains a Client and Server implementation. In the example folder there's a simple JFrame subclass called ChatClient. Look at it's source for a Swing reference.
Essentially you just need to subclass net.tootallnate.websocket.WebSocketClient and implement the onOpen, onClose, and onMessage methods. The class has an interface very similarly to the WebSockets API for HTML5.
Kaazing WebSocket Gateway ships with support for JavaScript, Flex, Silverlight, but also native Java clients (stand alone as well as applets). For more information, check out
http://tech.kaazing.com/documentation/index.html