Blockchain Websocket in Java - java

I am creating a program in java for websocket for blockchain.
My this example is working well :
`
import java.io.;
import com.neovisionaries.ws.client.;
public class Test
{
private static final String SERVER = "wss://ws.blockchain.info/inv";
public static void main(String[] args) throws Exception
{
WebSocket ws = connect();
ws.sendText("{\"op\":\"unconfirmed_sub\"}");
}
private static WebSocket connect() throws IOException, WebSocketException
{
return new WebSocketFactory().setConnectionTimeout(500000000).createSocket(SERVER)
.addListener(new WebSocketAdapter() {
public void onTextMessage(WebSocket websocket, String message) {
System.out.println(message);
}
})
.connect();
}
} `
but not this one :
`
import java.io.*;
import com.neovisionaries.ws.client.*;
public class Test
{
private static final String SERVER = "wss://ws.blockchain.info/inv";
public static void main(String[] args) throws Exception
{
WebSocket ws = connect();
ws.sendText("{\"op\":\"addr_sub\", \"addr\":\"65SQr6sh9SeS39PRbw8PHGp9wpv39\"}");
}
private static WebSocket connect() throws IOException, WebSocketException
{
return new WebSocketFactory().setConnectionTimeout(500000000).createSocket(SERVER)
.addListener(new WebSocketAdapter() {
public void onTextMessage(WebSocket websocket, String message) {
System.out.println(message);
}
})
.connect();
}
}`
Same way in jquery it is working, but not in java

Related

how to make multi-clients server chat app with java rmi

i made chat room using java rmi but the problem is that the message appears only to one client(the last to connect) for example 3 clients connect to the server(client1,client2,client3)
if client3 sends a message it appears only in server's console . and if server sends a message it appears only to client3's console.
i want to make the message to be shown to all the users connected to the server.
here is my code( i used eclipse for this project):
serveur.java
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import java.rmi.registry.*;
public class serveur {
public static void main (String[] argv) {
try {
Scanner s = new Scanner(System.in);
System.out.println("Entrez votre nom et appuyez sur Entree:");
String name=s.nextLine().trim();
chat server = new chat(name);
Registry registre = LocateRegistry.createRegistry(1099);
Naming.rebind( "CHAT",server);
System.out.println(" Le CHAT est pret:");
while(true){
String msg = s.nextLine().trim();
if (server.getClient() != null){
chatint Client = server.getClient();
msg = server.getName()+" : "+msg;
Client.send(msg);
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
client.java
public class client {
public static void main(String args[]) {
try {
Scanner s = new Scanner(in);
out.println("Entrez votre nom et appuyez sur Entrez:");
String name = s.nextLine().trim();
chatint client = new chat(name);
chatint server = (chatint)Naming.lookup("CHAT");
String msg = "["+client.getName()+"] s'est connecte";
server.send(msg);
out.println("[System] Le CHAT est pret:");
server.setClient(client);
while(true){
msg = s.nextLine().trim();
msg = client.getName()+" : "+msg;
server.send(msg);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
chatint.java
import java.rmi.*;
public interface chatint extends Remote{
public String getName() throws RemoteException;
public void send(String s) throws RemoteException;
public void setClient( chatint c) throws RemoteException;
public chatint getClient() throws RemoteException;
}
chat.java
package projetSid;
import java.rmi.*;
import java.rmi.server.*;
public class chat extends UnicastRemoteObject implements chatint {
public String name;
public chatint client = null;
public chat(String n) throws RemoteException {
this.name = n;
}
public String getName() throws RemoteException {
return this.name;
}
public void setClient(chatint c){
client = c;
}
public chatint getClient(){
return client;
}
public void send(String s) throws RemoteException{
System.out.println(s);
}
}

How to write simple smack 4.2.3 app that connects to server and answer to user

I have simple smack 3.2.1 application. It connect to xmpp server
and waiting for another user conversation initiation. When user ask question
via chat, application send response (answer). And it is working fine. Here is code:
JabberApplication.java:
package jabberapplication;
import org.jivesoftware.smack.XMPPException;
public class JabberApplication {
public static void main(String[] args) throws XMPPException, InterruptedException {
String username = "USERNAME";
String password = "PASSWORD";
String server = "SERVER";
int port=5222;
XmppManager xmppManager = new XmppManager(server, port);
xmppManager.init();
xmppManager.performLogin(username, password);
xmppManager.setStatus(true, "Hello everyone");
boolean isRunning = true;
while (isRunning) {
Thread.sleep(50);
}
xmppManager.destroy();
}
}
XmppManager.java:
package jabberapplication;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
public class XmppManager {
private final String server;
private final int port;
private XMPPConnection connection;
private ChatManager chatManager;
private MessageListener messageListener;
private ConversationController conversationController;
public XmppManager(String server, int port) {
this.server = server;
this.port = port;
}
public void init() throws XMPPException {
System.out.println(String.format("Initializing connection to server %1$s port %2$d", server, port));
ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration(server, port);
connection = new XMPPConnection(connectionConfiguration);
connection.connect();
System.out.println("Connected: " + connection.isConnected());
chatManager = connection.getChatManager();
chatManager.addChatListener(new MyChatManagerListener());
messageListener = new MyMessageListener();
conversationController = new ConversationController();
}
public void performLogin(String username, String password) throws XMPPException {
if (connection != null && connection.isConnected()) {
connection.login(username, password);
}
}
public void setStatus(boolean available, String status) {
Presence.Type type = available ? Type.available : Type.unavailable;
Presence presence = new Presence(type);
presence.setStatus(status);
connection.sendPacket(presence);
}
public void destroy() {
if (connection != null && connection.isConnected()) {
connection.disconnect();
}
}
public void sendMessage(String message, String buddyJID) throws XMPPException {
System.out.println(String.format("Sending mesage '%1$s' to user %2$s", message, buddyJID));
Chat chat = chatManager.createChat(buddyJID, messageListener);
chat.sendMessage(message);
}
class MyMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message message) {
String from = message.getFrom();
String body = message.getBody();
if (!body.equals("null")) {
System.out.println(String.format("Received message '%1$s' from %2$s", body, from));
try {
chat.sendMessage(conversationController.getAnswer(body));
} catch (XMPPException ex) {
System.out.println(ex.getMessage());
}
}
}
}
class MyChatManagerListener implements ChatManagerListener {
#Override
public void chatCreated(Chat chat, boolean bln) {
int indexAt = chat.getParticipant().indexOf("#");
String username = chat.getParticipant().substring(0, indexAt);
chat.addMessageListener(messageListener);
try {
chat.sendMessage("Hello " + username + " !");
} catch (XMPPException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Well, the question is: How to write similar app using smack library version 4.2.3. It looks like that in 4.2.3 there are no MessageListener and ChatManagerListener classes. Any suggestions ?
Best Regards.
For Smack 4.2.3, ChatManagerListener interface is under org.jivesoftware.smack.chat class (note : chat not Chat).
So, you need to change import to org.jivesoftware.smack.chat.ChatManagerListener.
Also, MessageListener is now change to ChatMessageListener also under org.jivesoftware.smack.chat class.
So, you need to change import to org.jivesoftware.smack.chat.ChatMessageListener.
And rename the implements to as below :
class MyMessageListener implements ChatMessageListener

java RMI Chat - remote server doesn't execute code

My chat works fine on the localhost but when I try to do it on the remote server, it doesn't go on.
RemoteClass >
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ChatInterface extends Remote {
public String getName() throws RemoteException;
public void sendMsg(String message) throws RemoteException;
public void setInterface (ChatInterface x) throws RemoteException; }
ClientImpl >
import Interface.ChatInterface;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ChatClient extends UnicastRemoteObject implements ChatInterface{
private String name;
private ChatInterface server;
public ChatClient(String name) throws RemoteException{
this.name = name;
}
#Override
public String getName() throws RemoteException {
return this.name;
}
#Override
public void sendMsg(String message) throws RemoteException {
System.out.println(message);
}
#Override
public void setInterface(ChatInterface server) throws RemoteException {
this.server = server;
} }
ClientMain >
import Interface.ChatInterface;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
public class Client{
public static void main(String[] args){
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
Registry registry = LocateRegistry.getRegistry("hostname", port);
ChatInterface chatClient = new ChatClient("User01");
ChatInterface chatServer = (ChatInterface) registry.lookup("ChatServer");
System.out.println("[System] Chat is ready");
chatServer.setInterface(chatClient);
String message = "["+chatClient.getName()+"] got connected";
chatServer.sendMsg(message);
Scanner s = new Scanner(System.in);
while (true) {
message = s.nextLine().trim();
message = "["+ chatClient.getName()+"]" + message;
chatServer.sendMsg(message);
}
} catch (Exception e) {
System.out.println("[System] Server failed: " + e);
System.exit(1);
}
} }
ServerImpl >
import Interface.ChatInterface;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
public class ChatServer extends UnicastRemoteObject implements ChatInterface{
private String name;
private ArrayList<ChatInterface> clients;
public ChatServer(String name)throws RemoteException{
this.name = name;
this.clients = new ArrayList<>();
}
#Override
public String getName() throws RemoteException {
return this.name;
}
#Override
public void sendMsg(String message) throws RemoteException {
broadcast(message);
}
#Override
public synchronized void setInterface(ChatInterface client) throws RemoteException {
clients.add(client);
}
public ArrayList<ChatInterface> getClients(){
return clients;
}
private void broadcast(String message) throws RemoteException {
for (ChatInterface client : clients) {
client.sendMsg(message);
}
} }
ServerMain >
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(9876);
Registry registry = LocateRegistry.getRegistry(port);
ChatServer chatServer = new ChatServer("Server");
registry.bind("ChatServer", chatServer);
System.out.println("Server ready :)");
} catch (Exception e) {
System.out.println("[System] Server failed: " + e.toString());
System.exit(1);
}
}
}
The server doesn't do anything at this line
chatServer.setInterface(chatClient);
But doesn't provoke any error. It continues to run for both client & server.
If you have any advice, thank you

Getting Null Pointer Exception for function isElementPresent in Selenium ...

I am getting null pointer exception when I call headerVerification method from main function of TestDriver class, though the element is present.
Start Server Class:
package WebTesting;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class StartServer {
private String host;
private String nameOfBrowser;
private int port;
private String url;
public StartServer(String host, int port, String nameOfBrowser, String url){
this.host=host;
this.port=port;
this.nameOfBrowser=nameOfBrowser;
this.url=url;
}
public static Selenium browser;
public void startServer(){
browser = new DefaultSelenium(host, port, nameOfBrowser, url);
browser.start();
browser.open("/");
System.out.println("Browser Started !!!");
}
}
Header Verification Class
package WebTesting;
import com.thoughtworks.selenium.Selenium;
public class HeaderVerification {
private String elementPath;
private String linkPath;
private String testLink;
public HeaderVerification(String elementPath, String linkPath, String testLink){
this.elementPath=elementPath;
this.linkPath=linkPath;
this.testLink=testLink;
}
public static Selenium browser;
public void headerVerification() throws InterruptedException{
System.out.println(elementPath);
if(browser.isElementPresent(elementPath)){
Thread.sleep(5000);
System.out.println("Header is Present");
browser.click(linkPath);
Thread.sleep(5000);
if(browser.getLocation().equals(testLink)){
System.out.println("Correct Location!!!");
}
else
System.out.println("Incorrect Location!!!");
browser.close();
System.out.println("Browser Closed!!!");
}
}
}
TestDriver Class
package WebTesting;
public class TestDriver {
/**
* #param args
*/
static StartServer ss = new StartServer("localhost", 4444, "*firefox", "http://docs.seleniumhq.org/");
static HeaderVerification hv = new HeaderVerification ("//div[#id='header']", "//a[#title='Overview of Selenium']", "http://docs.seleniumhq.org/about/");
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ss.startServer();
hv.headerVerification();
}
}
The brower static variable is null in the HeaderVerification class. You should add
HeaderVerification.browser = browser;
in StarstServer.startServer() method.

Apache MINA reading from IoSession

I am new to Apache MINA kindly guide me how to read from IoSession. I have stored a POJO in it.
public static EchoUDPServerDiscoveryObjectResponseProperties echoProperties
session.write(echoProperties);
Custom Client:
package client;
import java.net.InetSocketAddress;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.logging.Level;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.udp.client.MemMonClient;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
/**
*
* #author az
*/
public class CustomClient extends IoHandlerAdapter{
private IoSession session;
private IoConnector connector;
private ConnectFuture connFuture;
public CustomClient() throws InterruptedException{
connector = new NioDatagramConnector();
connector.setHandler(this);
connFuture = connector.connect(new InetSocketAddress("192.168.3.22",6502));
connFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture future) {
if (future.isConnected()) {
session = future.getSession();
try {
try {
sendData();
// connFuture.await();
} catch (CharacterCodingException ex) {
java.util.logging.Logger.getLogger(MemMonClient.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
private void sendData() throws InterruptedException, CharacterCodingException {
IoBuffer buffer = IoBuffer.allocate(8);
buffer.setAutoExpand(true);
buffer.putString("any", Charset.forName("UTF-8").newEncoder());
buffer.flip();
session.write(buffer);
}
#Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}
#Override
public void messageReceived(IoSession session, Object message)
throws Exception {
connFuture.getSession().getConfig().setUseReadOperation(true);
ReadFuture r = connFuture.getSession().read();
connFuture.await();
connFuture.getSession().getConfig().setUseReadOperation(true);
Object obj = r.getMessage();
System.out.println("r.getMessage(); "+obj);
IoBuffer buffer = IoBuffer.allocate(2048);
buffer.setAutoExpand(true);
Object objReceived = buffer.getObject();
System.out.println(objReceived.toString());
System.out.println("reveived Session recv...");
}
#Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("Message sent...");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("Session closed...");
}
#Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("Session created...");
}
#Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("Session idle...");
}
#Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("Session opened...");
}
public static void main (String are[]){
try{
new CustomClient();
}catch(Exception ex){ex.printStackTrace();}
}
}
POJO Java
package pojo;
import java.io.Serializable;
/**
*
* #author az
*/
public class kojo implements Serializable{
private String name = "null";
private String address = "null";
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
}
Custom Server Java
package server;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
/**
*
* #author az
*/
public class CustomServer {
public CustomServer(){
try {
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
acceptor.setHandler(new ServerHandler(this));
//DefaultIoFilterChainBuilder filter = acceptor.getFilterChain();
DatagramSessionConfig dcfg = acceptor.getSessionConfig();
dcfg.setReuseAddress(true);
acceptor.bind(new InetSocketAddress(6501));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void receiveUpdate(){
}
public static void main(String are[]){
new CustomServer();
}
}
Server Handler
package server;
import java.nio.charset.Charset;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
*
* #author az
*/
public class ServerHandler extends IoHandlerAdapter {
private CustomServer server;
public ServerHandler(CustomServer server) {
this.server = server;
}
#Override
public void messageReceived(IoSession session, Object message)
throws Exception {
if (message instanceof IoBuffer) {
//decode POJO and send to client
IoBuffer buffer = (IoBuffer) message;
System.out.println(buffer.getString(Charset.forName("UTF-8").newDecoder()));
buffer.setAutoExpand(true);
buffer.putObject(new pojo.POJO());
buffer.flip();
session.write(buffer);
System.out.print("Object Attached and Sent");
}
}
#Override
public void messageSent(IoSession session, Object message) {
System.out.println("Message sent");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("Session closed...");
}
#Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("Session created...");
}
#Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("Session idle...");
}
#Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("Session Opened...");
}
}

Categories