I'm trying to get a node.js app to interact with a .NET SDK fingerprint reader called U.are.U. The SDK provides .dll (win32 and x64), Java and .NET libraries. I decided to use .NET for the simple of use, having all the interfaces ready to use and all.
So, the current problem I'm facing is how to call those .NET functions and still preserve the asynchronous nature of node.js. The application flow (on the .NET example) is pretty straight forward, 3 calls on the library, and the fingerprint is done.
private IEnumerable<Fmd> CaptureAndExtractFmd()
{
while (!reset)
{
DataResult<Fmd> resultConversion;
try
{
if (count >= 8)
{
SendMessage("Enrollment was unsuccessful. Please try again.");
count = 0;
break;
}
Fid fid = null;
if (!_sender.CaptureFinger(ref fid))
break;
if (fid == null)
continue;
count++;
resultConversion = FeatureExtraction.CreateFmdFromFid(fid, Constants.Formats.Fmd.ANSI);
SendMessage("A finger was captured. \r\nCount: " + (count));
if (resultConversion.ResultCode != Constants.ResultCode.DP_SUCCESS)
break;
}
catch (Exception)
{
break;
}
yield return resultConversion.Data;
}
}
How can I change it so it can be usable in node.js, instead of a .NET gui program?
It also need to be noted that the node.js isn't always going to call a function on the .NET program to receive a function. The identification part of the program happens asynchronously and is set off when someone places a finger on the fingerprint reader, that means that the node.js part have no idea when that is going to happen. So I cannot rely on asking data on the .NET part all the time, it must call callbacks on the node.js without having been asked. So basically, it's a bidirectional communication, not only on request, since requesting using a webserver would be much easier.
I've found a node.js library that can close the gap between .NET and node.js called edge.js would this be of any help?
Basically, edge.js can make it work, along with node-webkit (which I'll be shipping my app), I can call the node APIs directly in the page, so I can update the DOM depending on the result from the library. I need to be able to register an async task that CAN notify from inside the CLR to the node.js counterpart either by emitting an event or calling a callback!
According to the edge.js author it can be done easily https://github.com/tjanczuk/edge/issues/54#issuecomment-17967082 I just don't have enough .NET skills to do so (from a full fledged module) with all the callbacks.
Using this SDK's .NET library is not the appropriate solution for this problem.
Node.js itself is a C++ app, and trying to use a .NET library properly is just asking for a world of hurt, especially when the SDK also provides a native C/C++ library!
Of course, you can't just use the C++ library directly; you'll have to write a C++ wrapper. In the node world, these are known as addons. Writing an addon isn't exactly simple, but even someone with little C++ experience should be able to follow the examples in the documentation and get something working.
Getting a native addon built in Windows can also be a little tricky; here's some tips to help you get started.
Since the SDK you're using is behind a paywall, I can't provide any specific examples. However, I imagine your C++ wrapper object will expose a few methods, and you'll also write a JS wrapper around that to expose a clean API. For example:
var uareu = require('./uareu.node') // the native C++ addon dll
, events = require('events')
, util = require('util');
function FingerprintReader() {
events.EventEmitter.call(this); // initialize the EventEmitter
// do stuff with the native module
// whenever a finger is placed on the reader:
this.emit('finger', { id: idFromSdk });
}
util.inherits(FingerprintReader, events.EventEmitter); // we want this module
// to be an EventEmitter
module.exports = FingerprintReader; // export for require()ing in your app
Now your app can just:
var FingerprintReader = require('fingerprint')
, fp = new FingerprintReader();
fp.on('finger', function(d) {
// do something with `d.id`
});
This example obviously glosses over a lot, but should give you a good idea of what needs to happen on the JS end of things. As far as detecting when a finger is placed on the reader, again, I can't really say how you'll do that without access to the SDK. I'd bet that you'll end up polling somewhere. This should be done on a separate thread in your addon.
Bonus: going the native route means you'll probably also be compatible with the SDK's Linux version, so your app will also work on Linux!
After a long time since this question was posted, I can use edge.js easily to communicate IN and OUT my .NET UI (even control node.js within node-webkit from .NET UI), using node event emitter:
// demo basic code in node.js
var
edge = require('edge'),
Bridge = edge.func('../path/to/compiled.dll'),
callback,
ev = new require('events').EventEmitter();
ev.on('acquire', function(fingerdata){
console.log(fingerdata);
});
ev.on('error', function(){
});
callback = function(event, report){
// report the result of the event emitter back to .NET
// you can even pass the "report" to the event handler, so you can return anything you want back to .NET, not just a boolean
report(null, ev.emit(event.name, event.data));
//ev.emit(event.name, {data: event.data, report: report});
};
var bridge = Bridge(callback, true);
// calling bridge(null, true); "releases" my device, should be called on process.on('exit')
And now you can call in/out from .NET using events, instead of calling native code (that might not be thread safe)
namespace Bridge
{
public class Startup
{
public async Task<object> Invoke(Func<object, Task<object>>callback)
{
Bridge.Base.setCallback(callback);
MainForm mainForm = new Bridge.MainForm();
Task.Run(async () =>
{
Application.Run(mainForm);
});
return (Func<object, Task<object>>)(async (i) => { Bridge.Base.release(); return null; });
}
}
}
// inside Bridge.Base
static public void setCallback(Func<object, Task<object>> cb)
{
if (callback == null)
{
callback = cb;
}
}
static public async void Emit(string name, object data)
{
return await Task.Run(async () =>
{
return await callback(new {
name = name,
data = data
});
});
}
static public Func<object, Task<object>> callback = null;
can now call Emit('error', "My error") from anywhere my derived classes from Base, asynchronously. Just notice that I recently started dwelving in C#, and my code presented here might not be the best fit.
Interesting problem. Would it be possible to just drop the function that you care about into an ASHX file (custom HTTP handler) and then post to that from your node application? Depending on what you want to return you might have to do some serializing/deserializing, but this seems like it might be the easiest way to fire a piece of C# code from a Node app....
Microsoft has a pretty good set of tutorials on custom HTTP handlers that can be found here.
The basic ASHX skeleton is below:
<%# WebHandler Language="C#" Class="NodeHandler" %>
using System;
using System.Web;
public class NodeHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//Handle fingerprint stuff!!!
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}
You would replace the contents of ProcessRequest with a modified version of your existing function.
I would create either self hosted WCF service ( ie windows service that has wcf endpoint) or use frameworks like OpenRasta or ServiceStack to replace WCF
In all three cases I would end up having json web service that return result of last call to CaptureAndExtractFmd
Then I would consume that service in node.js
If you need any further information with the way you decided to go, just create another question.
Sample code with WCF, C# part
[ServiceContract]
public interface IFingerprintContrat {
[OperationContract]
Fmd[] GetLastFeature();
}
public class FingerprintService {
Fmd[] GetLastFeature() {
return CaptureAndExtractFmd().ToArray()
}
}
using (ServiceHost host = new ServiceHost(typeof(FingerprintService), baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close the ServiceHost.
host.Close();
}
Node.js part
var request = require("request");
request.get("baseaddress/GetLastFeature", function (err, res, body) {
if (!err) {
var resultsObj = JSON.parse(body);
console.log(resultsObj);
}
});
Related
I've recently run into a use case where the "Async" suffix recommended by the .NET Task-based Asynchronous Pattern (TAP) conflicts with what's already in existence.
I'm dealing with System.Management.Automation.Runspaces.Runspace during the course of attempting PowerShell remoting to execute cmdlets as part of my app.
Ignoring the questions that arise around whether it's best practice to knock-up a remoting session each time you want to run a cmdlet (for an enterprise scale application this might be a lot) or to create a connection and attempt to maintain it during the app's lifetime (with reconnection logic)...
My application is based on TAP which proliferates from the WebApi2 controller all the way down to the backend, what I'm trying to do is asynchronously open a Runspace connection - but noticed that there's already an OpenAsync method which isn't awaitable and returns void - which is like some weird mash-up between async void (for event handlers), void (non-async) and the Async suffix.
I'm using Stephen Cleary's Nito.AsyncEx nuget package to provide me with a AsyncAutoResetEvent which I can asynchronously await before attempting connection/reconnection).
The question is: should I care about the fact that my code really isn't going to be properly "async" in using either Open or OpenAsync on the Runspace?
If I should care - what's the best practice in this situation? It doesn't look like Microsoft have released updated DLLs which provide awaitable Open methods for the Runspace. Strangely despite MS giving information on how to use these libraries, they've added the caveat on the nuget site:
Versions 6.1.7601.* are unofficial packages for .Net 4.0 and are not
supported by Microsoft.
There also seems to be this DLL-esque package on nuget from Microsoft, aagggghh!
Currently my plan is something akin to this:
public async Task<Result> StartAsync()
{
if (!IsConnected)
{
try
{
await _asyncRunspaceLock.WaitAsync();
if (!IsConnected)
{
var protocol = IsHttpsEnabled ? "https" : "http";
var serverUrl = $"{protocol}://{Fqdn}/OcsPowershell";
var uri = new Uri(serverUrl);
var connectionInfo = new WSManConnectionInfo(uri, ShelUri, PSCredential.Empty)
{
SkipRevocationCheck = true,
};
var runspace = runspaceFactory.CreateRunspace(connectionInfo);
runspace.OpenAsync();
}
}
catch (Exception ex)
{
// TODO: Handle logging the 3rd party exception at the lowest level.
return Result.Fail(ex.Message);
}
finally
{
_asyncRunspaceLock.Set();
}
}
return Result.Ok();
}
It's a work in progress, I guess the same issue crops up around the RunspaceFactory's CreateRunspace static method which isn't async (at least it isn't named with the Async suffix).
Any helpful advice or experience would be greatly appreciated.
Thanks
peteski
From the documentation:
If you're adding a TAP method to a class that already contains that method name with the Async suffix, use the suffix TaskAsync instead. For example, if the class already has a GetAsync method, use the name GetTaskAsync.
For a project I have programmed a wcf service library. It can be hosted in IIS and in a self-hosted service.
For all external systems that are connected, I have provided Mock implementations which give some generic data, so such the service (library) keeps running and doing work. It is a classic automaton / finite-state machine.
While bootstrapping, all data sources are connected. In testing mode, the mock implementations are connected. So when I run tests, the service library is "started" from a self-hosted service, not IIS and the the state machine keeps running and processing data packages.
Is there any way to get some kind of "test coverage" from such a run.
I would really appreciate if I could tell which code paths are hit by the example data I provide from the mock objects. And then provide more testdata to get a higher coverage.
If I could do this without having to provide "lots of extra" testing code, it would be great. I think a lot of cases are already covered from the data provided from the mock objects. But right now I have no starting point for that.
Here are some code examples to give a more clear picture of what is meant. Code is strongly simplified of course.
In a very simple console application to start the service (self hosted version)
static void Main(string[] args)
{
using (var host = new ServiceHost(typeof(MyServiceLib.Service.MyServiceLib)))
{
host.Open();
Console.ReadLine();
host.Close();
}
}
In the service library, a constructor is called from that code
public MyServiceLib()
{
Task.Factory.StartNew(this.Scaffold);
}
Which does nothing more than starting the state machine
private void Scaffold()
{
// lots of code deleted for simplicity reasons
var dataSource = new MockDataSource();
// inject the mocked datasource
this.dataManager = new DataManager(dataSource);
// this runs in its own thread. There are parts that are started on a timer event.
this.dataManager.Start();
}
public class DataManager : IDataManager
{
public void Start()
{
while (this.IsRunning)
{
var data = this.dataSource.getNext();
if (data != null)
{
// do some work with the data retrieved
// lots of code paths will be hit from that
this.Process(data);
}
else
{
Thread.Sleep(1000);
}
}
}
public void Process(IData data)
{
switch (data.PackageType)
{
case EnumPackageType.Single:
{
ProcessSingle(data);
break;
}
case EnumPackageType.Multiple:
{
ProcessMultiple(data);
break;
}
// here are lots of cases
default:
{
Logger.Error("unknown package type");
break;
}
}
}
}
What I have tried so far:
OpenCover
with a special test dll that would create the Host as shown above, but the host cannot be created properly, so the testing does not start really. I get a "Host is in fault state" error message. I followed this mini-tutorial. Despite that I get a coverage report with a calculated coverage of about 20%. But the service is just starting, it is not doing any work so far.
Visual Studio Performance Tools
The steps are essentially described in this article. I get a myproject.coverage file, but I cannot view it, because I only have a VS Professional, the coverage seems to be only of use in Test Premium or Ultimate editions.
Besides having tried those two, I will accept any answer showing how to get it up and running with any of those (openCover preferred).
Will accept an answer that shows how to test this setup and get a code coverage while leveraging tools to generate most of the code (as pex would, but after trial I see it does not generate very good code).
It would help to see the operations of the service.
I never tried running such "console kind" application under a coverage tool.
I would suggest writing a test with let's say NUnit (or any other unit testing framework; it's not a unit test, obviously, but the technique fits quite well).
In the test, you open the service host, create a client of the service, let the client execute some operations on your service, and close the service host.
Run this test under a coverage tool, and you should be done.
I've done that with NUnit and NCover about 7 years ago, using their current versions at that time (NCover was free software, if I remember it right).
Looks like with OpenCover you are actually getting the coverage, but the service is entering Faulted state, so to you need to catch the faults from your ServiceHost and adress that.
Basically you need some kind of error log, and the first thing i would try is looking in the system event logs (Win+R, eventvwr.msc, Enter).
You can also try to listen to the Faulted events on your ServiceHost:
host.Faulted += new EventHandler(host_faulted);
Here is the link to another SO answer addressing this issue:
How to find out the reason of ServiceHost Faulted event
I would suggest testing your business logic and not the bootstrap code. I mean testing DataManager class and not the hosting and the initializing code. You can write a unit test, using one of the unit testing frameworks, for example NUnit. Then you can run your tests either in Visual Studio with Resharper Ultimate or in your Continuous Integration with Code Coverage tool, like OpenCover or dotCover to get your code coverage.
[TestFixture]
public class DataManagerTests
{
[Test]
public void Process_Single_Processed()
{
// Arrange
IData data = new SingleData();
DataManager dataManager = new DataManager();
// Act
dataManager.Process(data);
// Assert
// check data processed correctly
}
}
in order to allow your Unit-Test-Framework to determin the coverage you have to host the service within the "runner" of the framework (aka. the process that is executing the tests).
The coverage is calculated by and withing the "runner" what means that you can not get coverage if the service is hosted anywhere else.
Below I'll add an example how to do this.
Greetings
Juy Juka
namespace ConsoleApplication4
{
using System.ServiceModel; // Don't forgett to add System.ServiceModel as Reference to the Project.
public class Program
{
static void Main(string[] args)
{
string arg = ((args != null && args.Length > decimal.Zero ? args[(int)decimal.Zero] : null) ?? string.Empty).ToLower(); // This is only reading the input for the example application, see also end of Main method.
string randomUrl = "net.tcp://localhost:60" + new System.Random().Next(1, 100) + "/rnd" + new System.Random().Next(); // random URL to allow multiple instances parallel (for example in Unit-Tests). // Better way?
if (arg.StartsWith("t"))
{
// this part could be written as a UnitTest and should be
string result = null;
using (ServiceHost host = new ServiceHost(typeof(MyService)))
{
host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(), randomUrl);
host.Open();
IMyService instance = ChannelFactory<IMyService>.CreateChannel(new NetTcpBinding(), new EndpointAddress(randomUrl), null);
result = instance.GetIdentity();
host.Close();
}
// Assert.Equals(result,"Juy Juka");
}
else if (arg.StartsWith("s"))
{
// This part runs the service and provides it to the outside. Just to show that it is a real and working host. (and not only working in a Unit-Test)
using (ServiceHost host = new ServiceHost(typeof(MyService)))
{
host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(), randomUrl);
host.Open();
System.Console.Out.WriteLine("Service hosted under following URL. Terminate with ENTER.");
System.Console.Out.WriteLine(randomUrl);
System.Console.In.ReadLine();
host.Close();
}
}
else if (arg.StartsWith("c"))
{
// This part consumes a service that is run/hosted outoside of the application. Just to show that it is a real and working host. (and not only working in a Unit-Test)
System.Console.Out.WriteLine("Please enter URL of the Service. Execute GetIdentity with ENTER. Terminate with ENTER.");
IMyService instance = ChannelFactory<IMyService>.CreateChannel(new NetTcpBinding(), new EndpointAddress(System.Console.In.ReadLine()), null);
System.Console.Out.WriteLine(instance.GetIdentity());
System.Console.In.ReadLine();
}
else
{
// This is only to explain the example application here.
System.Console.Out.WriteLine("I don't understand? Please use one of the following (Terminate this instance with ENTER):");
System.Console.Out.WriteLine("t: To host and call the service at once, like in a UnitTest.");
System.Console.Out.WriteLine("s: To host the servic, waiting for clients.");
System.Console.Out.WriteLine("c: To contact a hosted service and display it's GetIdenttity result.");
System.Console.In.ReadLine();
}
}
}
// Declaration and Implementation of the Service
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetIdentity();
}
public class MyService : IMyService
{
public string GetIdentity()
{
return "Juy Juka";
}
}
}
I am a normal C# developer but occasionally I develop application in Java. I'm wondering if there is any Java equivalent of C# async/await?
In simple words what is the java equivalent of:
async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
var urlContents = await client.GetStringAsync("http://msdn.microsoft.com");
return urlContents.Length;
}
No, there isn't any equivalent of async/await in Java - or even in C# before v5.
It's a fairly complex language feature to build a state machine behind the scenes.
There's relatively little language support for asynchrony/concurrency in Java, but the java.util.concurrent package contains a lot of useful classes around this. (Not quite equivalent to the Task Parallel Library, but the closest approximation to it.)
The await uses a continuation to execute additional code when the asynchronous operation completes (client.GetStringAsync(...)).
So, as the most close approximation I would use a CompletableFuture<T> (the Java 8 equivalent to .net Task<TResult>) based solution to process the Http request asynchronously.
UPDATED on 25-05-2016 to AsyncHttpClient v.2 released on Abril 13th of 2016:
So the Java 8 equivalent to the OP example of AccessTheWebAsync() is the following:
CompletableFuture<Integer> AccessTheWebAsync()
{
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
return asyncHttpClient
.prepareGet("http://msdn.microsoft.com")
.execute()
.toCompletableFuture()
.thenApply(Response::getResponseBody)
.thenApply(String::length);
}
This usage was taken from the answer to How do I get a CompletableFuture from an Async Http Client request?
and which is according to the new API provided in version 2 of AsyncHttpClient released on Abril 13th of 2016, that has already intrinsic support for CompletableFuture<T>.
Original answer using version 1 of AsyncHttpClient:
To that end we have two possible approaches:
the first one uses non-blocking IO and I call it AccessTheWebAsyncNio. Yet, because the AsyncCompletionHandler is an abstract class (instead of a functional interface) we cannot pass a lambda as argument. So it incurs in inevitable verbosity due to the syntax of anonymous classes. However, this solution is the most close to the execution flow of the given C# example.
the second one is slightly less verbose however it will submit a new Task that ultimately will block a thread on f.get() until the response is complete.
First approach, more verbose but non-blocking:
static CompletableFuture<Integer> AccessTheWebAsyncNio(){
final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
final CompletableFuture<Integer> promise = new CompletableFuture<>();
asyncHttpClient
.prepareGet("https://msdn.microsoft.com")
.execute(new AsyncCompletionHandler<Response>(){
#Override
public Response onCompleted(Response resp) throws Exception {
promise.complete(resp.getResponseBody().length());
return resp;
}
});
return promise;
}
Second approach less verbose but blocking a thread:
static CompletableFuture<Integer> AccessTheWebAsync(){
try(AsyncHttpClient asyncHttpClient = new AsyncHttpClient()){
Future<Response> f = asyncHttpClient
.prepareGet("https://msdn.microsoft.com")
.execute();
return CompletableFuture.supplyAsync(
() -> return f.join().getResponseBody().length());
}
}
async and await are syntactic sugars. The essence of async and await is state machine. The compiler will transform your async/await code into a state machine.
At the same time, in order for async/await to be really practicable in real projects, we need to have lots of Async I/O library functions already in place. For C#, most original synchronized I/O functions has an alternative Async version. The reason we need these Async functions is because in most cases, your own async/await code will boil down to some library Async method.
The Async version library functions in C# is kind of like the AsynchronousChannel concept in Java. For example, we have AsynchronousFileChannel.read which can either return a Future or execute a callback after the read operation is done. But it’s not exactly the same. All C# Async functions return Tasks (similar to Future but more powerful than Future).
So let’s say Java do support async/await, and we write some code like this:
public static async Future<Byte> readFirstByteAsync(String filePath) {
Path path = Paths.get(filePath);
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path);
ByteBuffer buffer = ByteBuffer.allocate(100_000);
await channel.read(buffer, 0, buffer, this);
return buffer.get(0);
}
Then I would imagine the compiler will transform the original async/await code into something like this:
public static Future<Byte> readFirstByteAsync(String filePath) {
CompletableFuture<Byte> result = new CompletableFuture<Byte>();
AsyncHandler ah = new AsyncHandler(result, filePath);
ah.completed(null, null);
return result;
}
And here is the implementation for AsyncHandler:
class AsyncHandler implements CompletionHandler<Integer, ByteBuffer>
{
CompletableFuture<Byte> future;
int state;
String filePath;
public AsyncHandler(CompletableFuture<Byte> future, String filePath)
{
this.future = future;
this.state = 0;
this.filePath = filePath;
}
#Override
public void completed(Integer arg0, ByteBuffer arg1) {
try {
if (state == 0) {
state = 1;
Path path = Paths.get(filePath);
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path);
ByteBuffer buffer = ByteBuffer.allocate(100_000);
channel.read(buffer, 0, buffer, this);
return;
} else {
Byte ret = arg1.get(0);
future.complete(ret);
}
} catch (Exception e) {
future.completeExceptionally(e);
}
}
#Override
public void failed(Throwable arg0, ByteBuffer arg1) {
future.completeExceptionally(arg0);
}
}
There is no equivalent of C# async/await in Java at the language level. A concept known as Fibers aka cooperative threads aka lightweight threads could be an interesting alternative. You can find Java libraries providing support for fibers.
Java libraries implementing Fibers
JetLang
Kilim
Quasar
You can read this article (from Quasar) for a nice introduction to fibers. It covers what threads are, how fibers can be implemented on the JVM and has some Quasar specific code.
As it was mentioned, there is no direct equivalent, but very close approximation could be created with Java bytecode modifications (for both async/await-like instructions and underlying continuations implementation).
I'm working right now on a project that implements async/await on top of JavaFlow continuation library, please check https://github.com/vsilaev/java-async-await
No Maven mojo is created yet, but you may run examples with supplied Java agent. Here is how async/await code looks like:
public class AsyncAwaitNioFileChannelDemo {
public static void main(final String[] argv) throws Exception {
...
final AsyncAwaitNioFileChannelDemo demo = new AsyncAwaitNioFileChannelDemo();
final CompletionStage<String> result = demo.processFile("./.project");
System.out.println("Returned to caller " + LocalTime.now());
...
}
public #async CompletionStage<String> processFile(final String fileName) throws IOException {
final Path path = Paths.get(new File(fileName).toURI());
try (
final AsyncFileChannel file = new AsyncFileChannel(
path, Collections.singleton(StandardOpenOption.READ), null
);
final FileLock lock = await(file.lockAll(true))
) {
System.out.println("In process, shared lock: " + lock);
final ByteBuffer buffer = ByteBuffer.allocateDirect((int)file.size());
await( file.read(buffer, 0L) );
System.out.println("In process, bytes read: " + buffer);
buffer.rewind();
final String result = processBytes(buffer);
return asyncResult(result);
} catch (final IOException ex) {
ex.printStackTrace(System.out);
throw ex;
}
}
#async is the annotation that flags a method as asynchronously executable, await() is a function that waits on CompletableFuture using continuations and a call to "return asyncResult(someValue)" is what finalizes associated CompletableFuture/Continuation
As with C#, control flow is preserved and exception handling may be done in regular manner (try/catch like in sequentially executed code)
Java itself has no equivalent features, but third-party libraries exist which offer similar functionality, e.g.Kilim.
Java doesn't have direct equivalent of C# language feature called async/await, however there's a different approach to the problem that async/await tries to solve. It's called project Loom, which will provide virtual threads for high-throughput concurrency. It will be available in some future version of OpenJDK.
This approach also solves "colored function problem" that async/await has.
Similar feature can be also found in Golang (goroutines).
First, understand what async/await is. It is a way for a single-threaded GUI application or an efficient server to run multiple "fibers" or "co-routines" or "lightweight threads" on a single thread.
If you are ok with using ordinary threads, then the Java equivalent is ExecutorService.submit and Future.get. This will block until the task completes, and return the result. Meanwhile, other threads can do work.
If you want the benefit of something like fibers, you need support in the container (I mean in the GUI event loop or in the server HTTP request handler), or by writing your own.
For example, Servlet 3.0 offers asynchronous processing. JavaFX offers javafx.concurrent.Task. These don't have the elegance of language features, though. They work through ordinary callbacks.
There isn't anything native to java that lets you do this like async/await keywords, but what you can do if you really want to is use a CountDownLatch. You could then imitate async/await by passing this around (at least in Java7). This is a common practice in Android unit testing where we have to make an async call (usually a runnable posted by a handler), and then await for the result (count down).
Using this however inside your application as opposed to your test is NOT what I am recommending. That would be extremely shoddy as CountDownLatch depends on you effectively counting down the right number of times and in the right places.
I make and released Java async/await library.
https://github.com/stofu1234/kamaitachi
This library don't need compiler extension, and realize stackless IO processing in Java.
async Task<int> AccessTheWebAsync(){
HttpClient client= new HttpClient();
var urlContents= await client.GetStringAsync("http://msdn.microsoft.com");
return urlContents.Length;
}
↓
//LikeWebApplicationTester.java
BlockingQueue<Integer> AccessTheWebAsync() {
HttpClient client = new HttpClient();
return awaiter.await(
() -> client.GetStringAsync("http://msdn.microsoft.com"),
urlContents -> {
return urlContents.length();
});
}
public void doget(){
BlockingQueue<Integer> lengthQueue=AccessTheWebAsync();
awaiter.awaitVoid(()->lengthQueue.take(),
length->{
System.out.println("Length:"+length);
}
);
}
There is an "equivalent" of await developed by EA: https://github.com/electronicarts/ea-async. Refer to the Java example code:
import static com.ea.async.Async.await;
import static java.util.concurrent.CompletableFuture.completedFuture;
public class Store
{
public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost)
{
if(!await(bank.decrement(cost))) {
return completedFuture(false);
}
await(inventory.giveItem(itemTypeId));
return completedFuture(true);
}
}
Java has unfortunately no equivalent of async/await. The closest you can get is probably with ListenableFuture from Guava and listener chaining, but it would be still very cumbersome to write for cases involving multiple asynchronous calls, as the nesting level would very quickly grow.
If you're ok with using a different language on top of JVM, fortunately there is async/await in Scala which is a direct C# async/await equivalent with an almost identical syntax and semantics:
https://github.com/scala/async/
Note that although this functionality needed a pretty advanced compiler support in C#, in Scala it could be added as a library thanks to a very powerful macro system in Scala and therefore can be added even to older versions of Scala like 2.10. Additionally Scala is class-compatible with Java, so you can write the async code in Scala and then call it from Java.
There is also another similar project called Akka Dataflow http://doc.akka.io/docs/akka/2.3-M1/scala/dataflow.html which uses different wording but conceptually is very similar, however implemented using delimited continuations, not macros (so it works with even older Scala versions like 2.9).
If you're just after clean code which simulates the same effect as async/await in java and don't mind blocking the thread it is called on until it is finished, such as in a test, you could use something like this code:
interface Async {
void run(Runnable handler);
}
static void await(Async async) throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
async.run(new Runnable() {
#Override
public void run() {
countDownLatch.countDown();
}
});
countDownLatch.await(YOUR_TIMEOUT_VALUE_IN_SECONDS, TimeUnit.SECONDS);
}
await(new Async() {
#Override
public void run(final Runnable handler) {
yourAsyncMethod(new CompletionHandler() {
#Override
public void completion() {
handler.run();
}
});
}
});
I have developed a library JAsync to do this.
It is just released today.
It makes the developer's asynchronous programming experience as close as possible to the usual synchronous programming, including code style and debugging.
Here is the example.
#RestController
#RequestMapping("/employees")
public class MyRestController {
#Inject
private EmployeeRepository employeeRepository;
#Inject
private SalaryRepository salaryRepository;
// The standard JAsync async method must be annotated with the Async annotation, and return a Promise object.
#Async()
private Promise<Double> _getEmployeeTotalSalaryByDepartment(String department) {
double money = 0.0;
// A Mono object can be transformed to the Promise object. So we get a Mono object first.
Mono<List<Employee>> empsMono = employeeRepository.findEmployeeByDepartment(department);
// Transformed the Mono object to the Promise object.
Promise<List<Employee>> empsPromise = JAsync.from(empsMono);
// Use await just like es and c# to get the value of the Promise without blocking the current thread.
for (Employee employee : empsPromise.await()) {
// The method findSalaryByEmployee also return a Mono object. We transform it to the Promise just like above. And then await to get the result.
Salary salary = JAsync.from(salaryRepository.findSalaryByEmployee(employee.id)).await();
money += salary.total;
}
// The async method must return a Promise object, so we use just method to wrap the result to a Promise.
return JAsync.just(money);
}
// This is a normal webflux method.
#GetMapping("/{department}/salary")
public Mono<Double> getEmployeeTotalSalaryByDepartment(#PathVariable String department) {
// Use unwrap method to transform the Promise object back to the Mono object.
return _getEmployeeTotalSalaryByDepartment(department).unwrap(Mono.class);
}
}
And in debug mode, you can see all the variable just like the synchronous code.
The other great thing about this project is that it's one of the few projects of its kind that's still active right now. It's just been released, so it has a lot of potential
Most of the examples I've found for SignalR are assuming ASP.NET (MVC or not). I'm using NancyFX. I'm having just one problem, so I'm hoping there's something I'm overlooking or some thing I need to do in Nancy to compensate for not being ASP.NET.
My one goal is to be able to notify the client browsers when a server event happens. I don't plan on replacing my Nancy routes with hub methods. But I would like the ability to call into the browser from my routes (actions).
I have very simple Hub that I created following the example in the SignalR Wiki. I'm not even sure I need it, since I don't plan on calling client to server.
public interface IUserNotifier
{
void Start();
void Notify(object #event);
}
I used an interface in hopes that I would be able to inject the same hub later on to use in my nancy routes... I'm not sure that is in the cards.
[HubName("userNotifier")]
public class UserNotifier : Hub, IUserNotifier
{
public void Start()
{
Notify(new {Status = "Started"});
}
public void Notify(object #event)
{
Clients.notification(#event);
}
}
When I have the following code in my html file, I can see that it executes the Start() method, and then the Notify() method, delivering content to my client.
var communicator = $.connection.userNotifier;
$.extend(communicator, {
Notification: function(event) {
alert("notification received from server!");
console.log(event);
}
});
$.connection.hub.start()
.done(function() {
communicator.start();
});
Like I said, "starting" the hub works and sends a notification to the client. Very cool. But, then, my primary goal hasn't been accomplished yet. I need to initiate these notifications from other places in my code where they might not be directly associated with a "request".
I tried injecting my IUserNotifier in my nancy modules for use in the routes, but when the Notify() is fired, I get:
That's because the Clients property on the Hub base class is null (hasn't been initialized). So, I switched gears. I tried to follow multiple examples, including the example from the wiki page about hubs in the section called "Broadcasting over a Hub from outside of a Hub":
public class NotifierModule : NancyModule
{
public NotifierModule(){
Get["/notify/{message}"] = p => {
var context = GlobalHost.ConnectionManager.GetHubContext<UserNotifier>();
context.Clients.notification(new { Message = p.message });
};
}
}
My Nancy route executes without throwing errors. Except my browser never receives the message. If I set a breakpoint in the route, I can see that Clients is initialized. Maybe the collection of clients is initialized but empty. Who knows? Maybe you do. :)
Again, my main goal is to be able to send events/notifications to the browser from anywhere in my code, any time. Is that too much to ask? What should I be doing here?
I'm sure you must have found the answer already. However, I figured I could try and help out in case anyone else runs into a similar problem. In order for your server on the .NET side to send messages to clients, it would also need to have a connection made to the hub.
var connection = new HubConnection("http://localhost/");
connection.Start();
connection.Notify("Hello");
Check out an official example at:
https://github.com/SignalR/SignalR/blob/master/samples/Microsoft.AspNet.SignalR.Client.Samples/Program.cs
This is example code in java.
Shared interfaces:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Compute extends Remote {
public Object executeTask(Task t) throws RemoteException;
}
Task (this will be passed as parameter):
import java.io.Serializable;
public interface Task extends Serializable {
public Object execute();
}
Server:
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ComputeEngine extends UnicastRemoteObject implements Compute {
public ComputeEngine() throws RemoteException {
super();
}
public Object executeTask(Task t) {
return t.execute();
}
public static void main(String[] args) {
setRmiCodebase();
System.setSecurityManager(new RMISecurityManager());
try {
Compute engine = new ComputeEngine();
Naming.rebind("//localhost:1099/Compute", engine);
System.out.println("ComputeEngine started.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void setRmiCodebase() {
String codebase = System.getProperty("java.rmi.server.codebase");
if (codebase != null)
return;
// set codebase based on location of this clsas (is it in jar or filesistem?)
}
}
Client:
import java.math.BigDecimal;
/**
* Calculates Pi to arbitrary number of digits:
*/
public class Pi implements Task {
public Pi(int digits) {
this.digits = digits;
}
public Object execute() {
return computePi(digits);
}
public static BigDecimal computePi(int digits) {
// compute Pi
}
}
Client main:
import java.math.BigDecimal;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
public class ComputePi {
public static void main(String[] args) {
setRmiCodebase();
System.setSecurityManager(new RMISecurityManager());
try {
Compute comp = (Compute)Naming.lookup("//localhost:1099/Compute");
Pi task = new Pi(100);
BigDecimal pi = (BigDecimal)comp.executeTask(task);
System.out.println(pi);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void setRmiCodebase() {
String codebase = System.getProperty("java.rmi.server.codebase");
if (codebase != null)
return;
// set codebase based on location of this clsas (is it in jar or filesistem?)
}
}
As you can see, code (not just data) from client is transfered to server and executed there and result of computation is returned. Server does not know that class Pi exists, it only knows about Task interface.
I need something like this to work in .net environment (C# if it is important). WCF would be nice, but I am looking for the most straightforward solution, so WCF is not compulsory. I am not sure even what keyword to use to google documetation or solution for this.
Any help will be appreciated.
Afaik .NET doesn't support this out of the box - you can do remoting but that won't (as is) let you run code from the client on the server. I think you would have to implement something that transfers the dll containing the code you want to execute to the server, and then probably load that dll in a separate AppDomain (because you can't unload dll's unless you load them into a separate AppDomain), and then have a way to specify the class to run.
.NET does not natively support "sending code" to be executed on another computer. Typically the necessary code would be compiled to assemblies and pre-installed on the server before it is called by the client. This is true of both remoting and WCF. You could have a two-way remoting situation where the server calls back to a method on the client via WCF, but I suspect this is not what you want. The only way I'm aware of to really run dynamic code on the server is to generate dynamic code, send it to the server as a string, and then have the server compile it to an in-memory assembly on the fly and then execute it. If you are interested in doing so, take a look at my answer to a similar question:
Autovivified properties?
However, it's not exactly something I would suggest in most cases. I would suggest you rethink your design, first, to see if there is any way to do what you need in a typical ".NET way".
What You want is .NET Remoting.
Here's link to article showing how to migrate from RMI to .NET Remoting.
But according to this MSDN article this is a legacy technology and You should use WCF.
Edit:
You can't "just like that" get .NET Remoting functionality with WCF.
Here you can read discussion about porting from .NET Remoting to WCF.
But if you don't know WCF at all You shoud start here. And You probably won't get your results fast :).
This MSDN page has more or less this exact use case you described. You just need to modify the ServiceContract
http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx
You would probably only need to modify this part:
[ServiceContract(Namespace = "http://UE.Samples")]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
}
// Service class which implements the service contract.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
return n1 + n2;
}
Instead of scalar values put your executeTask method with parameter of your own class there.
I don't believe .NET has a built-in solution for transferring executable code from client to server. Assuming the security constraints allow it, you might consider sending interpretable code such as Python or JavaScript which could be executed server-side via IronPython or IronJS respectively. If C# is a requirement (and you still have access to the source code), sending the source and compiling server-side (via Roslyn or the Mono's evaluator).