I'm trying to understand how to work with Skype using java (JSkype lib)
i use example (official site):
package testproj;
import net.lamot.java.jskype.general.AbstractMessenger;
import net.lamot.java.jskype.general.MessageListenerInterface;
import net.lamot.java.jskype.windows.Messenger;
import java.lang.Thread;
import java.lang.Exception;
import java.util.Date;
public class JSkype implements MessageListenerInterface {
private AbstractMessenger msgr = null;
public JSkype() {
msgr = new Messenger();
msgr.addListener(this);
msgr.initialize();
try {
Thread.sleep(5000);
msgr.sendMessage("MESSAGE echo123 test message");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new JSkype();
}
public void onMessageReceived(String str) {
System.out.println("RESULT: "+str);
}
}
after run, in console i have many information, but for me more intresting information, that I receive after send message:
RESULT: MESSAGE 21129 STATUS SENDING
RESULT: MESSAGE 21129 STATUS SENDING
RESULT: CHAT #my.name/$echo123;9797238991f90d78 ACTIVITY_TIMESTAMP 1294574640
and now I'm trying to understand, how to determine the success of sending a message?
yep, we need parsind result string.. but what is a number 21129? 9797238991f90d78? how i can know this number before start parsing?
Related
I have two java classes communicating using a vert.x EventBus.
I have a Productor.java class:
package TP1;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;
public class Productor extends AbstractVerticle
{
public void start() throws Exception
{
System.out.println("> Launching Productor...");
EventBus ebReady = vertx.eventBus();
//Send ready message
ebReady.send("canal-ready", "ready", messageReady -> {
//If Consumer received the ready message
if(messageReady.succeeded())
{
//Parse json response
JsonObject jsonObject = new JsonObject(messageReady.result().body().toString());
//Get answer value
int answerValue = Calcul.factorial(jsonObject.getInteger("param"));
String answer = Integer.toString(answerValue);
messageReady.reply(answer);//ERROR HERE
}
else
System.out.println("> No response!");
});
}
}
and a Consumer.java class:
package TP1;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;
public class Consumer extends AbstractVerticle
{
public void start() throws Exception
{
System.out.println("> Launching Consumer...");
String jsonString = "{\"class\":\"Calcul\",\"method\":\"factoriel\",\"param\":5}";
JsonObject jsonObj = new JsonObject(jsonString);
EventBus ebReady = vertx.eventBus();
//Wait for ready message
ebReady.consumer("canal-ready", messageReady -> {
//Parse the ready message
String readyString = messageReady.body().toString();
//Make sure it's the ready message
if(readyString.equals("ready"))
{
//Send json back (messageReady.succeeded())
messageReady.reply(jsonObj, messageReadyReply -> {
System.out.println(messageReadyReply);
});
}
});
}
}
I can't build the Productor class but have no problem with the Consumer one.
What's wrong with the messageReady.reply(answer); part in the Productor.java class?
You were missing a call to result() (see here) before getting the message and executing methods on it. However, you're using methods that have been deprecated in the 3.8 version (example) and are missing from 4.0, so I would advise that you use the other signature instead.
I try to launch this app using RMI client-server.
Firstly, I ran it and had the error "Connection refused to host: localhost".
After that I went go system32/drivers/etc/hosts and fix it, added line:
127.0.0.1 localhost
It wasn't led me to problem solution.
Then I looked up same questions in stackoverflow about how to fix this problem, then solved it with (ran in cmd):
start rmiregistry
So, rmiregistry ran and i had got a new error - NotBoundException (but I could fix "Connection refusal" problem).
servicebrowser.java:
package servicebrowser;
import java.awt.*;
import javax.swing.*;
import java.rmi.*;
import java.awt.event.*;
public class ServiceBrowser {
JPanel mainPanel;
JComboBox serviceList;
ServiceServer server;
public void buildGUI() {
Object[] services = getServicesList();
}
Object[] getServicesList() {
Object obj = null;
Object[] services = null;
try {
obj = Naming.lookup("rmi://127.0.0.1/ServiceServer");
}
catch (Exception ex) { ex.printStackTrace(); }
server = (ServiceServer) obj;
try {
services = server.getServiceList();
}
catch (Exception ex) { ex.printStackTrace(); }
return services;
}
class MyListListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
Object selection = serviceList.getSelectedItem();
loadService(selection);
}
}
public static void main(String[] args) {
new ServiceBrowser().buildGUI();
}
}
class ServiceServerImpl:
import java.rmi.*;
import java.util.*;
import java.rmi.server.*;
public class ServiceServerImpl extends UnicastRemoteObject
implements ServiceServer {
HashMap serviceList;
public ServiceServerImpl() throws RemoteException {
setUpServices();
}
private void setUpServices() {
serviceList = new HashMap();
}
public Object[] getServiceList() {
System.out.println("in remote");
return serviceList.keySet().toArray();
}
public Service getService(Object serviceKey) throws RemoteException {
Service theService = (Service) serviceList.get(serviceKey);
return theService;
}
public static void main (String[] args) {
try {
Naming.rebind("ServiceServer", new ServiceServerImpl());
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Remote service is running");
}
}
What is wrong with it? I turned off firewall too, certaintly.
Thanks a lot!
I solved my problem right this way.
Firstly, I edited classes servicebrowser, ServiceServerImpl.
class servicebrowser:
Before:
try {
obj = Naming.lookup("rmi://127.0.0.1/ServiceServer");
}
Now (plus I added import java.rmi.registry.LocateRegistry, import java.rmi.registry.Registry in top part of code):
try {
Registry registry = LocateRegistry.getRegistry("127.0.0.1", 10001);
obj = registry.lookup("ServiceServer");
}
class ServiceServerImpl:
Before:
try {
Naming.rebind("ServiceServer", new ServiceServerImpl());
}
Now (like a previous class I added import classes in top part of code):
try {
Registry registry = LocateRegistry.createRegistry(10001);
registry.bind("ServiceServer", new ServiceServerImpl());
}
Secondly, I try to ran project (F6) in Netbeans, where servicebrowser marked as main class. It was refusal connection again. After that I only ran class ServiceServerImpl (Shift + F6) then ran entire projecе. So, it works.
P.S. I didn't use cmd and try to
"start rmiregistry"
because the app works without it.
I am using Akka websockets to push data to some client.
This is what I have done so far:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.Http;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.model.ws.Message;
import akka.http.javadsl.model.ws.WebSocket;
import akka.japi.Function;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
public class Server {
public static HttpResponse handleRequest(HttpRequest request) {
System.out.println("Handling request to " + request.getUri());
if (request.getUri().path().equals("/greeter")) {
final Flow<Message, Message, NotUsed> greeterFlow = greeterHello();
return WebSocket.handleWebSocketRequestWith(request, greeterFlow);
} else {
return HttpResponse.create().withStatus(404);
}
}
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create();
try {
final Materializer materializer = ActorMaterializer.create(system);
final Function<HttpRequest, HttpResponse> handler = request -> handleRequest(request);
CompletionStage<ServerBinding> serverBindingFuture = Http.get(system).bindAndHandleSync(handler,
ConnectHttp.toHost("localhost", 8080), materializer);
// will throw if binding fails
serverBindingFuture.toCompletableFuture().get(1, TimeUnit.SECONDS);
System.out.println("Press ENTER to stop.");
new BufferedReader(new InputStreamReader(System.in)).readLine();
} finally {
system.terminate();
}
}
public static Flow<Message, Message, NotUsed> greeterHello() {
return Flow.fromSinkAndSource(Sink.ignore(),
Source.single(new akka.http.scaladsl.model.ws.TextMessage.Strict("Hello!")));
}
}
At the client side, I am successfully receiving a 'Hello!' message.
However, now I want to send data dynamically (preferably from an Actor), something like this:
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
public class PushActor extends UntypedActor {
#Override
public void onReceive(Object message) {
if (message instanceof String) {
String statusChangeMessage = (String) message;
// How to push this message to a socket ??
} else {
System.out.println(String.format("'%s':\nReceived unknown message '%s'!", selfActorPath, message));
}
}
}
I am unable to find any example regarding this online.
The following is the software stack being used:
Java 1.8
akka-http 10.0.10
One - not necessarily very elegant - way of doing this is to use Source.actorRef and send the materialized actor somewhere (maybe a router actor?) depending on your requirements.
public static Flow<Message, Message, NotUsed> greeterHello() {
return Flow.fromSinkAndSourceMat(Sink.ignore(),
Source.actorRef(100, OverflowStrategy.fail()),
Keep.right()).mapMaterializedValue( /* send your actorRef to a router? */);
}
Whoever receives the actorRefs of the connected clients must be responsible for routing messages to them.
I´m very new to Akka. I have created a simple Hello World App using it.
The App is very simple, it sends a message to my simple Actor. What I want is to send a message back to the first sender of the message. I can´t get the return message. How can someone do that? Do the client have to implement a onReceive method? I have tried to comment in the code.
import akka.actor.UntypedActor;
public class HelloActor extends UntypedActor {
#Override
public void onReceive(Object o) throws Exception {
if(o instanceof String){
String message = (String)o;
System.out.println(message);
// how to get this response ?
getSender().tell("World",getSelf());
}
}
}
The Client
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
public class Client{
public static void main(String[] args){
ActorSystem actorSystem = ActorSystem.create("HelloWorldSystem");
ActorRef listener = actorSystem.actorOf(new Props(HelloActor.class), "listener");
// sending is OK but how to get the response?
listener.tell("Hello");
}
}
The correct answer is to use a Future:
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.dispatch.*;
import akka.dispatch.Future;
import akka.pattern.Patterns;
import akka.util.Duration;
import akka.util.Timeout;
public class Client{
public static void main(String[] args){
ActorSystem actorSystem = ActorSystem.create("HelloWorldSystem");
ActorRef listener = actorSystem.actorOf(new Props(HelloActor.class), "listener");
Timeout timeout = new Timeout(Duration.create(5, "seconds"));
Future<Object> future = Patterns.ask(listener, "Hello", timeout);
try{
String result = (String) Await.result(future, timeout.duration());
System.out.println(result);
}catch (Exception e){
e.printStackTrace();
}
}
}
I'm trying to use my phone as a realtime MJPEG video source. So far, capturing frames and converting them into JPEGs is no big deal. My real issue is sending the multipart response properly. There's tons of documentation about sending multipart responses out there, but the issue with them is that they all expect that all of the images are available at the time the HTTP request comes in (such as would be used for a multi-image upload). In order to stream in realtime, of course, I need to be able to begin to send the multipart response while continually adding jpegs in the body. I'm by no means a HTTP buff, so it's not desirable for me be required to roll my own HTTP response and write directly to a socket. Is there a library out there that supports this kind of behavior? I've scoured the internet for solutions, but I really don't see anything useful out there.
Any ideas? Worst case scenario, I'd be willing to look at human-readable documentation of how to write a multipart response by hand, but I'd really just rather use a library if that's possible.
Thanks in advance.
edit: got it working using the orielly servlet library as per sigmavirus' suggestion. Note that the MJPEG stream is more or less implicitly inferred from the fact that I'm sending a multipart/x-mixed-replace that only has image/jpeg's in it. Check out the comment in my code for a tutorial that shows what jetty libraries you'll need to get this running. Of course, you'll additionally need cos.jar, the Orielly servlet library. The code follows:
package edu.stevens.arpac.webclient;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.conn.util.InetAddressUtils;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.Request;
import com.oreilly.servlet.MultipartResponse;
import com.oreilly.servlet.ServletUtils;
import android.os.Environment;
import android.util.Log;
// holla at http://puregeekjoy.blogspot.com/2011/06/running-embedded-jetty-in-android-app.html
public class JettyServer extends Thread
{
private static final String TAG = "JettyServer";
private Server webServer;
private Boolean isStarted = false;
public JettyServer()
{
super();
Log.i(TAG, "Initializing server to port 8080");
webServer = new Server(8080);
Handler handler = new AbstractHandler() {
public void handle(String target, Request request, HttpServletRequest servletRequest,
HttpServletResponse servletResponse) throws IOException, ServletException {
ServletOutputStream out = servletResponse.getOutputStream();
MultipartResponse multi = new MultipartResponse(servletResponse);
Boolean go = true;
while( go )
{
try
{
multi.startResponse("image/jpeg");
ServletUtils.returnFile(Environment.getExternalStorageDirectory().getPath() + "/ARPac/twi.jpg", out);
multi.endResponse();
}
catch(IOException ex)
{
go = false;
Log.i(TAG, "IO Failed with exception " + ex.getMessage());
}
}
request.setHandled(true);
}
};
webServer.setHandler(handler);
try {
webServer.start();
Log.d(TAG, "started Web server # " + getIPAddress());
isStarted = true;
}
catch (Exception e) {
Log.d(TAG, "unexpected exception starting Web server: " + e);
}
}
/**
* Get IP address from first non-localhost interface
* #return address or empty string
*/
private String getIPAddress()
{
try
{
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces)
{
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs)
{
if (!addr.isLoopbackAddress())
{
String sAddr = addr.getHostAddress().toUpperCase();
if (InetAddressUtils.isIPv4Address(sAddr))
{
//Log.d(TAG, "IP address is: " + sAddr);
return sAddr;
}
}
}
}
}
catch (Exception ex)
{
Log.e(TAG, "could not get IP address: " + ex.getMessage());
} // for now eat exceptions
Log.e(TAG, "Could not find a non-loopback IPv4 address!");
return "";
}
public void teardown()
{
if( isStarted )
{
try {
webServer.stop();
isStarted = false;
} catch (Exception e) {
Log.e(TAG, "Couldn't stop server. Probably was called when server already stopped.");
}
}
}
public void run()
{
}
}
Have you seen this? http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartResponse.html It looks like the example sends each part individually and waits a specified time limit before sending the next or receiving an interrupt.