PHP to Java Connection - java

I am working on a project where I send supposedly press a button on a webpage and it then executes a command in java. What I'm looking for is something like this. Say if I pressed a button and then it sends a command to the minecraft server to reload plugins. How would I go achieving this? Thanks

When you have to comunicate between different applications you will problably need a bridge. In your case I'd suggest to use Minecraft's RCON service (must be enabled in the confingiration) or a plugin that do something similar, like Websend.
Websend code is actually available on Github if you would like to know how the plugin work.

Connection between PHP and Java through sockets
Step 1:
Create a java server
I have created a nice API for these situations. you can use them if you would like:
ChatServer
all you need to do is create a new instance of this class
package com.weebly.foxgenesis.src;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.*;
public final class ChatServer implements Runnable
{
private final int CLIENTMAXIMUM;
private ChatServerThread clients[];
private ServerSocket server = null;
private Thread thread = null;
private int clientCount = 0;
private final ServerReciever output;
private List<ConnectHandler> connectHandlers = new ArrayList<ConnectHandler>();
private List<QuitHandler> quitHandlers = new ArrayList<QuitHandler>();
/**
* creates a new ChatServer for connection between clients
* #param a ServerReciever implementing class
*/
public ChatServer(ServerReciever a)
{
CLIENTMAXIMUM = a.getMaximunClients();
output = a;
clients = new ChatServerThread[CLIENTMAXIMUM];
try
{
server = new ServerSocket();
server.bind(new InetSocketAddress(output.getHost(), output.getPort()));
log(server);
start();
}
catch(IOException ioe)
{
error("Can not bind to port " + a.getPort() + ": " + ioe.getMessage());
}
}
/**
* Force the Server to handle a msg
*/
public void add(String text)
{
output.handle(text);
}
/**
* Force the Server to handle an error
*/
public void error(String text)
{
output.handleError(text);
}
/**
* Log to the server
*/
public void log(Object text)
{
output.handleLog(text);
}
/**
* send a message to a specific client
* #param ID ID of client
* #param msg
*/
public void send(int ID, String msg)
{
clients[findClient(ID)].send(msg);
add(msg);
}
/**
* Called by runnable
*/
public void run()
{
while (thread != null)
{
try
{
if(clientCount != CLIENTMAXIMUM){
log("Waiting for a client ...");
addThread(server.accept());
}
}
catch(IOException ioe)
{
error("Server accept error: " + ioe);
stop();
}
}
}
private void start()
{
if (thread == null)
{
thread = new Thread(this);
thread.start();
}
}
/**
* Stops the server
*/
#SuppressWarnings("deprecation")
public void stop()
{
if (thread != null)
{
thread.stop();
thread = null;
}
}
private int findClient(int ID)
{
for (int i = 0; i < clientCount; i++)
if (clients[i].getID() == ID)
return i;
return -1;
}
/**
* sends a message to a
* #param ID
* #param input
*/
public synchronized void handle(int ID, String input)
{
StringTokenizer t = new StringTokenizer(input);
String[] arg = new String[t.countTokens()];
for(int i=0; t.hasMoreElements(); i++)
arg[i] = t.nextToken(",");
if(arg[0] == "new")
switch(input)
{
case".bye":
{
clients[findClient(ID)].send(".bye");
remove(ID);
break;
}
default:
{
for (int i = 0; i < clientCount; i++)
clients[i].send(input);
break;
}
}
}
/**
* sends a message to all clients
* #param input message to send
*/
public void sendAll(String input)
{
for (int i = 0; i < clientCount; i++)
clients[i].send(input);
}
/**
* remove a selected ID
* #param ID ID of client
*/
#SuppressWarnings("deprecation")
public synchronized void remove(int ID)
{
int pos = findClient(ID);
if (pos >= 0)
{
ChatServerThread toTerminate = clients[pos];
log("Removing client thread " + ID + " at " + pos);
if (pos < clientCount-1)
for (int i = pos+1; i < clientCount; i++)
clients[i-1] = clients[i];
clientCount--;
QuitEvent e = new QuitEvent(toTerminate.getID());
e.setGameBreaking(true);
for(QuitHandler a: quitHandlers)
a.quit(e);
try
{
toTerminate.close(); }
catch(IOException ioe)
{
error("Error closing thread: " + ioe);
}
toTerminate.stop();
}
}
private void addThread(Socket socket)
{
if (clientCount < clients.length)
{
log("Client accepted: " + socket);
clients[clientCount] = new ChatServerThread(this, socket);
try
{
clients[clientCount].open();
clients[clientCount].start();
ClientConnectEvent e = new ClientConnectEvent(clients[clientCount],clients[clientCount].getID());
clientCount++;
for(ConnectHandler a: connectHandlers)
a.connect(e);
}
catch(IOException ioe)
{
error("Error opening thread: " + ioe);
}
}
else
error("Client refused: maximum " + clients.length + " reached.");
}
public String toString()
{
return "ChatServer{;host=" + output.getHost() + ";port=" + output.getPort() + ";clients=" + clientCount + ";}";
}
public int getAmountOfClients()
{
return clientCount;
}
public void addConnectHandler(ConnectHandler handler)
{
connectHandlers.add(handler);
}
public void removeConnectHandler(ConnectHandler handler)
{
connectHandlers.remove(handler);
}
public int getMaxClients()
{
return CLIENTMAXIMUM;
}
public void addQuitHandler(QuitHandler quitHandler)
{
quitHandlers.add(quitHandler);
}
public void removeQuitHandler(QuitHandler quithandler)
{
quitHandlers.remove(quithandler);
}
}
ChatServerThread
Used by the ChatServer as client connections
package com.weebly.foxgenesis.src;
import java.net.*;
import java.io.*;
public final class ChatServerThread extends Thread
{
private ChatServer server = null;
private Socket socket = null;
private int ID = -1;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
public ChatServerThread(ChatServer server, Socket socket)
{
super();
this.server = server;
this.socket = socket;
this.ID = socket.getPort();
}
#SuppressWarnings("deprecation")
public void send(String msg)
{
try
{
streamOut.writeUTF(msg);
streamOut.flush();
}
catch(IOException ioe)
{
server.error(ID + " ERROR sending: " + ioe.getMessage());
server.remove(ID);
stop();
}
}
public int getID()
{
return ID;
}
#SuppressWarnings("deprecation")
#Override
public void run()
{
server.log("Server Thread " + ID + " running.");
while (true)
{
try
{
server.handle(ID, streamIn.readUTF());
}
catch(IOException ioe)
{
server.error(ID + " ERROR reading: " + ioe.getMessage());
server.remove(ID);
stop();
}
}
}
public void open() throws IOException
{
streamIn = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(new
BufferedOutputStream(socket.getOutputStream()));
}
public void close() throws IOException
{
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
}
ClientConnectEvent
package com.weebly.foxgenesis.src;
public class ClientConnectEvent extends ConnectionEvent
{
private final ChatServerThread client;
public ClientConnectEvent(ChatServerThread client, int clientID)
{
super(clientID);
this.client = client;
}
public ChatServerThread getClient()
{
return client;
}
#Override
public boolean isConnectionBreaking(){return false;}
}
ConnectHandler
package com.weebly.foxgenesis.src;
public interface ConnectHandler
{
public void connect(ClientConnectEvent e);
}
ClientQuitEvent
package com.weebly.foxgenesis.src;
public class ClientQuitEvent extends ConnectionEvent
{
public ClientQuitEvent(int clientID)
{
super(clientID);
}
#Override
public boolean isConnectionBreaking()
{
return true;
}
}
QuitHandler
package com.weebly.foxgenesis.src;
public interface QuitHandler
{
public void quit(ClientQuitEvent e);
}
ServerReciever
package com.weebly.foxgenesis.src;
public interface ServerReciever
{
public void handle(String msg);
public void handleError(String msg);
public int getPort();
public int getMaximunClients();
public void handleLog(Object text);
public String getHost();
}
ConnectionEvent
package com.weebly.foxgenesis.src;
public abstract class ConnectionEvent
{
public abstract boolean isConnectionBreaking();
private int clientID;
public ConnectionEvent(int clientID)
{
this.clientID = clientID;
}
public int getClientID()
{
return clientID;
}
}
Step 2:
Connect Server to Bukkit
i have provided an example on how to connect the server to bukkit by making a new plugin.
public class MyPlugin extends JavaPlugin
{
#Override
public void onEnable()
{
ChatServer server = new ChatServer(new ServerReciever()
{
#Override
public void handle(String msg){handleMsg(msg);}
#Override
public void handleError(String msg){handleErr(msg);}
#Override
public int getPort(){return 25567}
#Override
public int getMaximunClients(){return 100;}
#Override
public void handleLog(Object text){log(text);}
#Override
public String getHost(){return "localhost";}
}
}
public void handleLog(Object text)
{
System.out.println(text);
}
public void handelErr(String msg)
{
System.err.println(msg);
}
public void handleMsg(String msg)
{
if(msg.equalsIgnoreCase("reload"))
Bukkit.reloadOrSomething(); //i don't know the void off the top of my head
}
}
Step 3:
Port Forward
if you don't know what that is go ahead and google it. there are some great tutorials online. you want to port forward the port that you set in the code.
Step 4:
Send a message to the Server
i do not know PHP but all you need to do is send a UTF-8 Encoded message to the server's ip on the port that you hard coded above.
Step 5:
ENJOY!

Related

Could not render red5 recorded media stream

I have problem of playing back the recorded media file from red5 published stream, following is my code. I could see a file called out.flv is created, but this out.flv can not be played back.
public class Red5ClientTest {
private static Timer timer;
private static RTMPClient client;
private static String sourceStreamName;
private static int videoTs;
private static int audioTs;
private static FLVWriter writer;
private static int bytesRead =0;
public static void main(String[] args) throws IOException {
String sourceHost = "localhost";
int sourcePort = 1935;
String sourceApp = "oflaDemo";
sourceStreamName = "myStream";
timer = new Timer();
client = new RTMPClient();
String path = "c:\\temp\\out.flv";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
writer = new FLVWriter(file,true);
client.setStreamEventDispatcher(new StreamEventDispatcher());
client.setStreamEventHandler(new INetStreamEventHandler() {
public void onStreamEvent(Notify notify) {
System.out.printf("onStreamEvent: %s\n", notify);
ObjectMap<?, ?> map = (ObjectMap<?, ?>) notify.getCall().getArguments()[0];
String code = (String) map.get("code");
System.out.printf("<:%s\n", code);
if (StatusCodes.NS_PLAY_STREAMNOTFOUND.equals(code)) {
System.out.println("Requested stream was not found");
client.disconnect();
}
else if (StatusCodes.NS_PLAY_UNPUBLISHNOTIFY.equals(code)
|| StatusCodes.NS_PLAY_COMPLETE.equals(code)) {
System.out.println("Source has stopped publishing or play is complete");
client.disconnect();
}
}
});
client.setConnectionClosedHandler(new Runnable() {
public void run() {
if (writer != null) {
writer.close();
}
System.out.println("Source connection has been closed, proxy will be stopped");
System.exit(0);
}
});
client.setExceptionHandler(new ClientExceptionHandler() {
#Override
public void handleException(Throwable throwable) {
throwable.printStackTrace();
System.exit(1);
}
});
// connect the consumer
Map<String, Object> defParams = client.makeDefaultConnectionParams(sourceHost, sourcePort,
sourceApp);
// add pageurl and swfurl
defParams.put("pageUrl", "");
defParams.put("swfUrl", "app:/Red5-StreamRelay.swf");
// indicate for the handshake to generate swf verification data
client.setSwfVerification(true);
// connect the client
client.connect(sourceHost, sourcePort, defParams, new IPendingServiceCallback() {
public void resultReceived(IPendingServiceCall call) {
System.out.println("connectCallback");
ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
String code = (String) map.get("code");
if ("NetConnection.Connect.Rejected".equals(code)) {
System.out.printf("Rejected: %s\n", map.get("description"));
client.disconnect();
//proxy.stop();
}
else if ("NetConnection.Connect.Success".equals(code)) {
// 1. Wait for onBWDone
timer.schedule(new BandwidthStatusTask(), 2000L);
Object result = call.getResult();
System.out.println("Red5ClientTest.main()");
}
else {
System.out.printf("Unhandled response code: %s\n", code);
}
}
});
// keep sleeping main thread while the proxy runs
// kill the timer
//timer.cancel();
System.out.println("Stream relay exit");
}
/**
* Handles result from subscribe call.
*/
private static final class SubscribeStreamCallBack implements IPendingServiceCallback {
public void resultReceived(IPendingServiceCall call) {
System.out.println("resultReceived: " + call);
Object result = call.getResult();
System.out.println("results came {}" + result);
}
}
private static final class StreamEventDispatcher implements IEventDispatcher {
public void dispatchEvent(IEvent event) {
System.out.println("ClientStream.dispachEvent()" + event.toString());
try {
//RTMPMessage build = RTMPMessage.build((IRTMPEvent) event);
IRTMPEvent rtmpEvent = (IRTMPEvent) event;
ITag tag = new Tag();
tag.setDataType(rtmpEvent.getDataType());
if (rtmpEvent instanceof VideoData) {
videoTs += rtmpEvent.getTimestamp();
tag.setTimestamp(videoTs);
}
else if (rtmpEvent instanceof AudioData) {
audioTs += rtmpEvent.getTimestamp();
tag.setTimestamp(audioTs);
}
IoBuffer data = ((IStreamData) rtmpEvent).getData().asReadOnlyBuffer();
tag.setBodySize(data.limit());
tag.setBody(data);
try {
writer.writeTag(tag);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("writting....");
}
catch (Exception e) {//IOException
e.printStackTrace();
}
}
}
private static final class BandwidthStatusTask extends TimerTask {
#Override
public void run() {
// check for onBWDone
System.out.println("Bandwidth check done: " + client.isBandwidthCheckDone());
// cancel this task
this.cancel();
// create a task to wait for subscribed
timer.schedule(new PlayStatusTask(), 1000L);
// 2. send FCSubscribe
client.subscribe(new SubscribeStreamCallBack(), new Object[] { sourceStreamName });
}
}
private static final class PlayStatusTask extends TimerTask {
#Override
public void run() {
// checking subscribed
System.out.println("Subscribed: " + client.isSubscribed());
// cancel this task
this.cancel();
// 3. create stream
client.createStream(new CreateStreamCallback());
}
}
/**
* Creates a "stream" via playback, this is the source stream.
*/
private static final class CreateStreamCallback implements IPendingServiceCallback {
public void resultReceived(IPendingServiceCall call) {
System.out.println("resultReceived: " + call);
int streamId = ((Number) call.getResult()).intValue();
System.out.println("stream id: " + streamId);
// send our buffer size request
if (sourceStreamName.endsWith(".flv") || sourceStreamName.endsWith(".f4v")
|| sourceStreamName.endsWith(".mp4")) {
client.play(streamId, sourceStreamName, 0, -1);
}
else {
client.play(streamId, sourceStreamName, -1, 0);
}
}
}
}
what could I be doing possibly wrong here?
Finally got it
public class TeqniRTMPClient {
private static final Logger logger = LoggerFactory.getLogger(MyRtmpClient.class);
public static void main(String args[]) throws IOException {
TeqniRTMPClient client = new TeqniRTMPClient("localhost", 1935, "oflaDemo", "myStream");
client.recordStream();
}
private RTMPClient client;
private ITagWriter writer;
private String sourceHost;
private int sourcePort;
private String sourceApp;
private String sourceStreamName;
private int lastTimestamp;
private int startTimestamp = -1;
public TeqniRTMPClient(String sourceHost, int sourcePort, String sourceApp,
String sourceStreamName) {
super();
this.sourceHost = sourceHost;
this.sourcePort = sourcePort;
this.sourceApp = sourceApp;
this.sourceStreamName = sourceStreamName;
}
public void recordStream() throws IOException {
client = new RTMPClient();
String path = "c:\\temp\\out.flv";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FLVService flvService = new FLVService();
flvService.setGenerateMetadata(true);
try {
IStreamableFile flv = flvService.getStreamableFile(file);
writer = flv.getWriter();
}
catch (Exception e) {
throw new RuntimeException(e);
}
client.setStreamEventDispatcher(new StreamEventDispatcher());
client.setStreamEventHandler(new INetStreamEventHandler() {
public void onStreamEvent(Notify notify) {
System.out.printf("onStreamEvent: %s\n", notify);
ObjectMap<?, ?> map = (ObjectMap<?, ?>) notify.getCall().getArguments()[0];
String code = (String) map.get("code");
System.out.printf("<:%s\n", code);
if (StatusCodes.NS_PLAY_STREAMNOTFOUND.equals(code)) {
System.out.println("Requested stream was not found");
client.disconnect();
}
else if (StatusCodes.NS_PLAY_UNPUBLISHNOTIFY.equals(code)
|| StatusCodes.NS_PLAY_COMPLETE.equals(code)) {
System.out.println("Source has stopped publishing or play is complete");
client.disconnect();
}
}
});
client.setExceptionHandler(new ClientExceptionHandler() {
#Override
public void handleException(Throwable throwable) {
throwable.printStackTrace();
System.exit(1);
}
});
client.setConnectionClosedHandler(new Runnable() {
public void run() {
if (writer != null) {
writer.close();
}
System.out.println("Source connection has been closed, proxy will be stopped");
System.exit(0);
}
});
// connect the consumer
Map<String, Object> defParams = client.makeDefaultConnectionParams(sourceHost, sourcePort,
sourceApp);
// add pageurl and swfurl
defParams.put("pageUrl", "");
defParams.put("swfUrl", "app:/Red5-StreamRelay.swf");
// indicate for the handshake to generate swf verification data
client.setSwfVerification(true);
// connect the client
client.connect(sourceHost, sourcePort, defParams, new IPendingServiceCallback() {
public void resultReceived(IPendingServiceCall call) {
System.out.println("connectCallback");
ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
String code = (String) map.get("code");
if ("NetConnection.Connect.Rejected".equals(code)) {
System.out.printf("Rejected: %s\n", map.get("description"));
client.disconnect();
}
else if ("NetConnection.Connect.Success".equals(code)) {
// 1. Wait for onBWDone
client.createStream(new CreateStreamCallback());
Object result = call.getResult();
System.out.println("Red5ClientTest.main()");
}
else {
System.out.printf("Unhandled response code: %s\n", code);
}
}
});
}
class CreateStreamCallback implements IPendingServiceCallback {
public void resultReceived(IPendingServiceCall call) {
System.out.println("resultReceived: " + call);
int streamId = ((Number) call.getResult()).intValue();
System.out.println("stream id: " + streamId);
// send our buffer size request
if (sourceStreamName.endsWith(".flv") || sourceStreamName.endsWith(".f4v")
|| sourceStreamName.endsWith(".mp4")) {
client.play(streamId, sourceStreamName, 0, -1);
}
else {
client.play(streamId, sourceStreamName, -1, 0);
}
}
}
class StreamEventDispatcher implements IEventDispatcher {
private int videoTs;
private int audioTs;
public void dispatchEvent(IEvent event) {
System.out.println("ClientStream.dispachEvent()" + event.toString());
try {
IRTMPEvent rtmpEvent = (IRTMPEvent) event;
logger.debug("rtmp event: " + rtmpEvent.getHeader() + ", "
+ rtmpEvent.getClass().getSimpleName());
if (!(rtmpEvent instanceof IStreamData)) {
logger.debug("skipping non stream data");
return;
}
if (rtmpEvent.getHeader().getSize() == 0) {
logger.debug("skipping event where size == 0");
return;
}
byte dataType = rtmpEvent.getDataType();
ITag tag = new Tag();
tag.setDataType(dataType);
if (rtmpEvent instanceof VideoData) {
VideoData video = (VideoData) rtmpEvent;
FrameType frameType = video.getFrameType();
videoTs += rtmpEvent.getTimestamp();
tag.setTimestamp(videoTs);
}
else if (rtmpEvent instanceof AudioData) {
audioTs += rtmpEvent.getTimestamp();
tag.setTimestamp(audioTs);
}
IoBuffer data = ((IStreamData) rtmpEvent).getData().asReadOnlyBuffer();
tag.setBodySize(data.limit());
tag.setBody(data);
try {
writer.writeTag(tag);
}
catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("writting....");
}
catch (Exception e) {//IOException
e.printStackTrace();
}
}
}
}

Java - TCP client/server using ObjectOutputStream and threading

I am trying to develop some kind of chat application (learning purposes) but when I send my objects from the client to the server only the first one seems to get received. No error is shown or nothing so I don't really know whats wrong.
Server code:
import chattychat.domain.Message;
import chattychat.domain.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* #author
*/
public class Server {
private final int PORT;
private ServerSocket server;
public Server(){
this.PORT = 6565;
}
public Server(int port){
this.PORT = port;
}
public void listenSocket(){
try{
this.server = new ServerSocket(this.PORT);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;
try{
//server.accept returns a client connection
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
}
}
}
class ClientWorker implements Runnable {
private Socket client;
private ObjectInputStream in;
//Constructor
ClientWorker(Socket client) {
this.client = client;
}
public void run(){
try{
this.in = new ObjectInputStream(this.client.getInputStream());
Object obj = this.in.readObject();
System.out.println("called");
if(obj instanceof Message){
Message msg = (Message)obj;
System.out.println(msg);
}else if(obj instanceof User){
User user = (User)obj;
System.out.println(user);
}
System.out.println();
}catch (IOException e) {
System.out.println("Read failed");
//System.exit(-1);
} catch (ClassNotFoundException ex) {
System.out.println("Object not found");
//System.exit(-1);
}
}
}
#Override
protected void finalize(){
try{
this.server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
public static void main(String[] args){
Server s = new Server();
//s.communicate();
s.listenSocket();
}
}
Client code:
import chattychat.domain.Message;
import chattychat.domain.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
/**
*
* #author laurensputseys
*/
public class Client {
private final int PORT = 6565;
private String SERVER = "localhost";
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
private boolean isConnected;
public Client(){
this.isConnected = false;
}
public Client(String server){
this.SERVER = server;
}
public String getServer(){
return this.SERVER;
}
public int getPort(){
return this.PORT;
}
public void communicate(Message msg){
while(!isConnected){
try{
this.socket = new Socket(this.getServer(), this.getPort());
isConnected = true;
this.out = new ObjectOutputStream(this.socket.getOutputStream());
this.out.writeObject(msg);
this.out.flush();
this.out.close();
}catch(SocketException se){
se.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
public void register(User usr){
while(!isConnected){
try{
this.socket = new Socket(this.getServer(), this.getPort());
isConnected = true;
this.out = new ObjectOutputStream(this.socket.getOutputStream());
this.out.writeObject(usr);
this.out.flush();
this.out.close();
}catch(SocketException se){
se.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
public boolean isConnected(){
return isConnected;
}
public static void main(String[] args){
Client c = new Client();
User u1 = new User("firstname 1", "lastname1", "testuser");
User u2 = new User("firstname 2", "lastname2", "Testuser");
Message m1 = new Message(u1, u2, "Hello from P1 to P2");
Message m2 = new Message(u2, u1, "Hello from P2 to P1");
System.out.println("Send 1");
c.communicate(m1);
System.out.println("Send 2");
c.communicate(m2);
System.out.println("Send 3");
c.register(u1);
}
}
message class:
import java.io.Serializable;
import java.util.Objects;
/**
*
* #author
*/
public class Message implements Serializable{
private static final long serialVersionUID = 7526472295622776147L;
private User from;
private User to;
private String message;
public Message(User from, User to, String message){
this.setFrom(from);
this.setTo(to);
this.setMessage(message);
}
private void setFrom(User from){
this.from = from;
}
private void setTo(User to){
this.to = to;
}
private void setMessage(String message){
this.message = message;
}
public String getMessage(){
return this.message;
}
#Override
public boolean equals(Object o){
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
Message tmpMsg = (Message)o;
return this.to.equals(tmpMsg.to) && this.from.equals(tmpMsg.from) && this.getMessage().equals(tmpMsg.getMessage());
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + Objects.hashCode(this.from);
hash = 59 * hash + Objects.hashCode(this.to);
hash = 59 * hash + Objects.hashCode(this.message);
return hash;
}
#Override
public String toString(){
return "From: " + this.from + " to: " + this.to + " message: " +this.getMessage();
}
}
User class:
import java.io.Serializable;
import java.util.Objects;
/**
*
* #author
*/
public class User implements Serializable{
private static final long serialVersionUID = 7526456787322776147L;
private String firstname;
private String lastname;
private String password;
public User(String firstname, String lastname, String password){
setFirstname(firstname);
setLastname(lastname);
setPassword(password);
}
private void setFirstname(String firstname){
this.firstname = firstname; //TODO
}
private void setLastname(String lastname){
this.lastname = lastname; //TODO
}
private void setPassword(String password){
this.password = password; //TODO
}
#Override
public boolean equals(Object o){
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
User tmpUser = (User)o;
return this.firstname.equals(tmpUser.firstname) && this.lastname.equals(tmpUser.lastname);
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + this.firstname.length();
hash = 59 * hash + this.lastname.length();
hash = 59 * hash + this.password.length();
return hash;
}
#Override
public String toString(){
return this.firstname + " " + this.lastname;
}
}
Thanks in advance!
Without reading your code very thoroughly. Your clients communicate methods sets connected to true on the first call. So the while loop will not be entered on the second call to communicate. You should separate connecting to server and sending messages. Also, your client worker thread in server seems to return after one object read. The run method should return when connection is broken, not when one message is read.

JSch upload with progress monitor

I try to implement a SFTP upload with a progress bar.
Unfortunately the progress bar is not updated...
Here is a part of my code:
public class MainView extends JFrame implements SftpProgressMonitor {
private static final Logger LOG = Logger.getLogger(MainView.class);
private String _source;
private JProgressBar _progressBar;
private JButton _button;
public MainView() {
initComponents();
}
void initComponents() {
_button = new JButton("Send");
_button.addActionListener(new ActionListener() {
// If clicked, send event to controller...
});
_progressBar = new JProgressBar();
// Do init stuff here
// ...
}
#Override
public boolean count(long byteTransfered) {
int transfered = _progressBar.getValue();
transfered += byteTransfered;
_progressBar.setValue(transfered);
return true;
}
#Override
public void end() {
LOG.info("Transfer of "+_source+" finished!");
}
#Override
public void init(int op, String src, String dest, long max) {
_progressBar.setValue(0);
_progressBar.setMinimum(0);
_progressBar.setMaximum((int) max);
_source = src;
}
}
public class Controller {
private final MainView _view;
private final SftpClient _ftp;
private final Server _server;
public Controller() {
_server = new Server("192.168.0.1");
_view = new MainView();
_ftp = new SftpClient(_server);
_view.setVisible(true);
}
public void send() {
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
public void run() {
File testFile = new File("/PathToFile/file.txt");
String remoteDir = "/MyRemoteDir/";
_ftp.put(testFile, remoteDir, testFile.getName(), _view);
}
});
}
public static void main(String[] args) {
Controller controller = new Controller();
}
}
public class SftpClient {
private static final Logger LOG = Logger.getLogger(SftpClient.class);
/** Connection port number */
public static final int PORT = 22;
/** SECURED protocol name */
public static final String PROTOCOL = "sftp";
/** Connection time out in milliseconds */
public static final int TIME_OUT = 3000;
private Server _server;
/** This class serves as a central configuration point, and as a factory for Session objects configured with these settings */
private JSch _client;
/** A session represents a connection to a SSH server */
private Session _session;
/** Channel connected to a SECURED server (as a subsystem of the SSH server) */
private ChannelSftp _channelSftp;
/**
* Value returned by the last executed command.
*/
private int _exitValue;
public SftpClient(Server server) {
_client = new JSch();
_server = server;
}
protected void connect() throws AuthenticationException, Exception {
try {
if (_client == null) {
_client = new JSch();
}
if (_session == null) {
_session = _client.getSession(_server.getLogin(), _server.getAddress(), PORT);
_session.setConfig("StrictHostKeyChecking", "no");
_session.setPassword(_server.getPassword());
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting to "+_server.getAddress()+" with login "+_server.getLogin()+"...");
}
}
if (!_session.isConnected()) {
_session.connect(TIME_OUT);
}
if(_channelSftp == null || _channelSftp.isConnected() == false) {
Channel c = _session.openChannel(PROTOCOL);
c.connect();
// disconnect previous channel if it has not been killed properly
if (_channelSftp != null && _channelSftp.isConnected()) {
_channelSftp.disconnect();
}
_channelSftp = (ChannelSftp) c;
}
if (LOG.isInfoEnabled()) {
LOG.info("Connected to "+_server.getAddress()+" with login "+_server.getLogin());
}
} catch(JSchException e) {
if ("Auth fail".equals(e.getMessage())) {
throw new AuthenticationException(e);
} else {
throw new Exception(e);
}
}
}
protected void connect(String path) throws AuthenticationException, Exception {
connect();
if (_channelSftp != null && _channelSftp.isConnected()) {
_channelSftp.cd(path);
}
}
#Override
public void disconnect() {
if (_channelSftp != null && _channelSftp.isConnected()) {
_channelSftp.disconnect();
_channelSftp.exit();
}
if (_session != null && _session.isConnected()) {
_session.disconnect();
if (LOG.isInfoEnabled()) {
LOG.info("SECURED FTP disconnected");
}
}
}
#Override
public void put(File localFile, String destPath, SftpProgressMonitor monitor) throws Exception {
put(localFile, destPath, localFile.getName(), monitor);
}
#Override
public void put(File localFile, String destPath, String remoteFileName, SftpProgressMonitor monitor) throws Exception {
if (LOG.isInfoEnabled()) {
LOG.info("Send file "+localFile+" to "+_server+" in "+destPath);
}
if (localFile == null) {
_exitValue = -1;
LOG.error("The given local file is null. Aborting tranfer.");
return;
}
if (!localFile.exists()) {
_exitValue = -1;
LOG.error("'"+localFile+"' doesn't exist. Aborting tranfer.");
return;
}
if(!localFile.canRead()) {
_exitValue = -1;
LOG.error("Cannot read '"+localFile+"'. Aborting tranfer.");
return;
}
final InputStream input = new BufferedInputStream(new FileInputStream(localFile));
if (input == null || input.available() <= 0) {
_exitValue = -1;
LOG.error("Cannot read file "+localFile);
return;
}
try {
connect(destPath);
_channelSftp.put(input, remoteFileName, monitor);
_exitValue = _channelSftp.getExitStatus();
} catch(SftpException e){
throw new IOException(e);
} finally {
if (_channelSftp != null && _channelSftp.isConnected()) {
_channelSftp.disconnect();
_channelSftp.exit();
}
IOUtils.closeQuietly(input);
}
}
}
The count() method is never called. And the source and destination strings of the init contain both -. Am I doing it wrong?
I've changed my code and it works now. I don't use put(InputStream src, String dst, int mode) anymore but put(String src, String dst, SftpProgressMonitor monitor).
I've also implemented a DefaultBoundedRangeModel class. It modifies directly the JProgressBar and it is more interesting for me because I have several files to transfer.
public class ProgressModel extends DefaultBoundedRangeModel implements SftpProgressMonitor {
/** Logger */
private static Logger LOG = Logger.getLogger(ProgressModel.class);
private String _fileBeingTransfered;
/**
* Constructs the model.
*/
public ProgressModel() {
_fileBeingTransfered = "";
}
#Override
public boolean count(long count) {
int value = (int) (getValue() + count);
setValue(value);
fireStateChanged();
if(value < getMaximum()) {
return true;
} else {
return false;
}
}
#Override
public void end() {
LOG.info(_fileBeingTransfered+" transfert finished.");
if(getValue() == getMaximum()) {
LOG.info("All transfers are finished!");
}
}
#Override
public void init(int op, String src, String dest, long max) {
LOG.info("Transfering "+src+" to "+dest+" | size: "+max);
_fileBeingTransfered = src;
}
}
I don't know what caused my problem. Maybe it was the put method.
In order to get updates you have to send reference to monitor to FTP client. And you do this:
_ftp.put(testFile, remoteDir, testFile.getName(), _view);
However what _view is? It is a private final field of class Controller that is never initialized. Therefore it is null. You implemented your callback method count() into class MainView but do not send reference to it to the FTP client. I do not know where do you create instance of Controller but you should pass reference to instance of MainView to it.

MQTT Client in Java - Starting my Listener in a Thread

I am using org.fusesource.mqtt (mqtt-client-1.0-20120208.162159-18-uber) and wrote a listener in Java based on the non-blocking example.
I use my listener class in the following way:
Listener mqList = new Listener("tcp://localhost:1883", "mytopic/#", "c:/test.log", true);
new Thread(mqList).start( );
This work perfectly.
If I create two instances/threads then conflicts seem to arise and I get connect/disconnect messages flowing over me.
Here is the usage that fails:
Listener mqList = new Listener("tcp://localhost:1883", "mytopic/#", "c:/test.log", true);
new Thread(mqList).start( );
Listener mqList1 = new Listener("tcp://localhost:1883", "mytopic1/#", "c:/test1.log", true);
new Thread(mqList1).start( );
My Listener class is quite simple and I am puzzled why this does not work in multiple threads. Any ideas/hints?
Here is my class definition:
import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.UTF8Buffer;
import org.fusesource.mqtt.client.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.logging.*;
import java.io.*;
import java.net.URISyntaxException;
public class Listener implements Runnable{
private static final long DEFAULT_SLEEP_BEFORE_RE_ATTEMPT_IN_SECONDS = 5000;
private static final long DEFAULT_MAX_RE_ATTEMPT_DURATION_IN_SECONDS = 3600 * 3;
private long listenerSleepBeforeReAttemptInSeconds;
private long listenerMaxReAttemptDurationInSeconds;
private MQTT mqtt;
private ArrayList<Topic> topics;
private boolean listenerDebug;
private String listenerHostURI;
private String listenerTopic;
private String listenerLogFile;
private long listenerLastSuccessfulSubscription;
private Logger fLogger;
private String NEW_LINE = System.getProperty("line.separator");
public Listener(String listenerHostURI, String listenerTopic, String logFile, boolean debug) {
this(listenerHostURI, listenerTopic, logFile, DEFAULT_SLEEP_BEFORE_RE_ATTEMPT_IN_SECONDS, DEFAULT_MAX_RE_ATTEMPT_DURATION_IN_SECONDS, debug);
}
public Listener(String listenerHostURI, String listenerTopic, String logFile, long listenerSleepBeforeReAttemptInSeconds, long listenerMaxReAttemptDurationInSeconds, boolean debug) {
init(listenerHostURI, listenerTopic, logFile, listenerSleepBeforeReAttemptInSeconds, listenerMaxReAttemptDurationInSeconds, debug);
}
private void init(String listenerHostURI, String listenerTopic, String logFile, long listenerSleepBeforeReAttemptInSeconds, long listenerMaxReAttemptDurationInSeconds, boolean debug) {
this.listenerHostURI = listenerHostURI;
this.listenerTopic = listenerTopic;
this.listenerLogFile = logFile;
this.listenerSleepBeforeReAttemptInSeconds = listenerSleepBeforeReAttemptInSeconds;
this.listenerMaxReAttemptDurationInSeconds = listenerMaxReAttemptDurationInSeconds;
this.listenerDebug = debug;
initMQTT();
}
private void initMQTT() {
mqtt = new MQTT();
listenerLastSuccessfulSubscription = System.currentTimeMillis();
try {
fLogger = Logger.getLogger("eTactica.mqtt.listener");
FileHandler handler = new FileHandler(listenerLogFile);
fLogger.addHandler(handler);
} catch (IOException e) {
System.out.println("Logger - Failed");
}
try {
mqtt.setHost(listenerHostURI);
} catch (URISyntaxException e) {
stderr("setHost failed: " + e);
stderr(e);
}
QoS qos = QoS.AT_MOST_ONCE;
topics = new ArrayList<Topic>();
topics.add(new Topic(listenerTopic, qos));
}
private void stdout(String x) {
if (listenerDebug) {
fLogger.log(Level.INFO, x + NEW_LINE);
}
}
private void stderr(String x) {
if (listenerDebug) {
fLogger.log(Level.SEVERE, x + NEW_LINE);
}
}
private void stderr(Throwable e) {
if (listenerDebug) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
fLogger.log(Level.SEVERE, sw.toString() + NEW_LINE);
}
}
private void subscriptionSuccessful() {
listenerLastSuccessfulSubscription = System.currentTimeMillis();
}
private boolean tryToListen() {
return ((System.currentTimeMillis() - listenerLastSuccessfulSubscription) < listenerMaxReAttemptDurationInSeconds * 1000);
}
private void sleepBeforeReAttempt() throws InterruptedException {
stdout(String.format(("Listener stopped, re-attempt in %s seconds."), listenerSleepBeforeReAttemptInSeconds));
Thread.sleep(listenerSleepBeforeReAttemptInSeconds);
}
private void listenerReAttemptsOver() {
stdout(String.format(("Listener stopped since reattempts have failed for %s seconds."), listenerMaxReAttemptDurationInSeconds));
}
private void listen() {
final CallbackConnection connection = mqtt.callbackConnection();
final CountDownLatch done = new CountDownLatch(1);
/* Runtime.getRuntime().addShutdownHook(new Thread(){
#Override
public void run() {
setName("MQTT client shutdown");
stderr("Disconnecting the client.");
connection.getDispatchQueue().execute(new Runnable() {
public void run() {
connection.disconnect(new Callback<Void>() {
public void onSuccess(Void value) {
stdout("Disconnecting onSuccess.");
done.countDown();
}
public void onFailure(Throwable value) {
stderr("Disconnecting onFailure: " + value);
stderr(value);
done.countDown();
}
});
}
});
}
});
*/
connection.listener(new org.fusesource.mqtt.client.Listener() {
public void onConnected() {
stdout("Listener onConnected");
}
public void onDisconnected() {
stdout("Listener onDisconnected");
}
public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) {
stdout(topic + " --> " + body.toString());
ack.run();
}
public void onFailure(Throwable value) {
stdout("Listener onFailure: " + value);
stderr(value);
done.countDown();
}
});
connection.resume();
connection.connect(new Callback<Void>() {
public void onFailure(Throwable value) {
stderr("Connect onFailure...: " + value);
stderr(value);
done.countDown();
}
public void onSuccess(Void value) {
final Topic[] ta = topics.toArray(new Topic[topics.size()]);
connection.subscribe(ta, new Callback<byte[]>() {
public void onSuccess(byte[] value) {
for (int i = 0; i < value.length; i++) {
stdout("Subscribed to Topic: " + ta[i].name() + " with QoS: " + QoS.values()[value[i]]);
}
subscriptionSuccessful();
}
public void onFailure(Throwable value) {
stderr("Subscribe failed: " + value);
stderr(value);
done.countDown();
}
});
}
});
try {
done.await();
} catch (Exception e) {
stderr(e);
}
}
#Override
public void run() {
while (tryToListen()) {
initMQTT();
listen();
try {
sleepBeforeReAttempt();
} catch (InterruptedException e) {
stderr("Sleep failed:" + e);
stderr(e);
}
}
listenerReAttemptsOver();
}
}
A TCP port can have only one listener. That number in "tcp://localhost:1883" has to be unique for each listener. Someplace, presumably (I'm not familiar with this specific API) you're probably starting a client with a port number too; the numbers must match between the client and server.

Java Telnet Library

I am really not clear on explaining this requirement but what I need basically is a JSP page that connects to a Unix server and gets the word count of a file and displays on the JSP page. I have looked on various questions here but nothing helped. A sample code would be of much help. Thanks
Kavin, I guess you must have found some other solution or moved on by now. However, I just came across a requirement that led me to this page.
I looked through the somewhat smuckish responses on this page and many others but could not find a simple to use Telnet client at all.
I spent a little bit of time and wrote a simple client on top of Commons Net's solution. Please forgive the System.out and System.err in the code, I got it to barely work.
public static void main(String[] args) throws Exception {
SimpleTelnetClient client = new SimpleTelnetClient("localhost", 2323);
client.connect();
String result = client.waitFor("login:");
System.out.println("Got " + result);
client.send("username");
result = client.waitFor("Password:");
System.out.println("Got " + result);
client.send("password");
client.waitFor("#");
client.send("ls -al");
result = client.waitFor("#");
System.out.println("Got " + result);
client.send("exit");
}
Not sure if it will help you anymore, but perhaps it could be a starting point for others.
import java.io.InputStream;
import java.io.PrintStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
public class SimpleTelnetClient {
static class Responder extends Thread {
private StringBuilder builder = new StringBuilder();
private final SimpleTelnetClient checker;
private CountDownLatch latch;
private String waitFor = null;
private boolean isKeepRunning = true;
Responder(SimpleTelnetClient checker) {
this.checker = checker;
}
boolean foundWaitFor(String waitFor) {
return builder.toString().contains(waitFor);
}
public synchronized String getAndClearBuffer() {
String result = builder.toString();
builder = new StringBuilder();
return result;
}
#Override
public void run() {
while (isKeepRunning) {
String s;
try {
s = checker.messageQueue.take();
} catch (InterruptedException e) {
break;
}
synchronized (Responder.class) {
builder.append(s);
}
if (waitFor != null && latch != null && foundWaitFor(waitFor)) {
latch.countDown();
}
}
}
public String waitFor(String waitFor) {
synchronized (Responder.class) {
if (foundWaitFor(waitFor)) {
return getAndClearBuffer();
}
}
this.waitFor = waitFor;
latch = new CountDownLatch(1);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
String result = null;
synchronized (Responder.class) {
result = builder.toString();
builder = new StringBuilder();
}
return result;
}
}
static class TelnetReader extends Thread {
private final SimpleTelnetClient checker;
private final TelnetClient tc;
TelnetReader(SimpleTelnetClient checker, TelnetClient tc) {
this.checker = checker;
this.tc = tc;
}
#Override
public void run() {
InputStream instr = tc.getInputStream();
try {
byte[] buff = new byte[1024];
int ret_read = 0;
do {
ret_read = instr.read(buff);
if (ret_read > 0) {
checker.sendForResponse(new String(buff, 0, ret_read));
}
} while (ret_read >= 0);
} catch (Exception e) {
System.err.println("Exception while reading socket:" + e.getMessage());
}
try {
tc.disconnect();
checker.stop();
System.out.println("Disconnected.");
} catch (Exception e) {
System.err.println("Exception while closing telnet:" + e.getMessage());
}
}
}
private String host;
private BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>();
private int port;
private TelnetReader reader;
private Responder responder;
private TelnetClient tc;
public SimpleTelnetClient(String host, int port) {
this.host = host;
this.port = port;
}
protected void stop() {
responder.isKeepRunning = false;
responder.interrupt();
}
public void send(String command) {
PrintStream ps = new PrintStream(tc.getOutputStream());
ps.println(command);
ps.flush();
}
public void sendForResponse(String s) {
messageQueue.add(s);
}
public void connect() throws Exception {
tc = new TelnetClient();
TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
try {
tc.addOptionHandler(ttopt);
tc.addOptionHandler(echoopt);
tc.addOptionHandler(gaopt);
} catch (InvalidTelnetOptionException e) {
System.err.println("Error registering option handlers: " + e.getMessage());
}
tc.connect(host, port);
reader = new TelnetReader(this, tc);
reader.start();
responder = new Responder(this);
responder.start();
}
public String waitFor(String s) {
return responder.waitFor(s);
}
}
Why wouldn't you just use an open source telnet client. There is bound to be several to choose from. Google lists many.

Categories

Resources