[JAVA] Critque needed

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

[JAVA] Critque needed

Post by VladSun »

EventListener.java

Code: Select all

import java.applet.Applet;
import java.net.Socket;
import java.net.URL;
import java.io.*;
import java.awt.*;
 
import java.net.MalformedURLException;
 
public class EventListener extends Applet implements Runnable
{
    protected int       port = 0;
    protected Socket    sock = null;
 
    protected String    eventHandlerObject = null;
 
    protected BufferedReader        socketReader = null;
    protected OutputStreamWriter    socketWriter = null;
 
    protected TextArea  textArea = null;
    protected boolean   debugMode = false;
    protected boolean   autoConnect = false;
 
 
    @Override
    public void init()
    {
        this.debugMode = (this.getParameter("debugMode") != null);
        this.autoConnect = (this.getParameter("autoConnect") != null);
 
        if (this.debugMode)
        {
            this.setLayout(null);
            this.textArea = new TextArea();
            this.textArea.setBounds(new Rectangle(0, 0, 800, 450));
            this.add(this.textArea);
        }
 
        if (Integer.parseInt(this.getParameter("port")) != 0)
        {
            this.port = Integer.parseInt(this.getParameter("port"));
        }
        else
        {
            this.log("Port is undefined or not integer");
            return;
        }
 
        if (this.getParameter("handler") == null)
        {
            this.log("Handler is undefined");
            return;
        }
 
        this.eventHandlerObject = this.getParameter("handler");
 
        if (this.autoConnect)
        {
            this.connect();
        }
    }
 
    public void setHandler(String handler)
    {
        if (handler != null && handler.length() != 0)
            this.eventHandlerObject = handler;
    }
 
    public boolean disconnect()
    {
        if (this.sock.isClosed())
            return true;
        
        try
        {
            this.sock.close();
        }
        catch (IOException e)
        {
            this.log(e);
            this.handle("onDisconnectFailure", e.toString());
            return false;
        }
        this.handle("onDisconnectSuccess");
        return true;
    }
 
    public boolean connect()
    {
        if (this.sock != null && this.sock.isConnected())
        {
            try
            {
                this.sock.close();
            }
            catch (IOException e)
            {
                this.log(e);
                return false;
            }
        }
 
        try
        {
            sock = new Socket(this.getCodeBase().getHost(), this.port);
        }
        catch (IOException e)
        {
            this.log(this.getCodeBase().getHost() + ":" + this.port);
            this.log(e);
            this.handle("onConnectFailure", e.toString());
            return false;
        }
 
        try
        {
            this.socketWriter = new OutputStreamWriter(sock.getOutputStream());
            this.socketReader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        }
        catch (IOException e)
        {
            this.log(e);
            this.handle("onConnectFailure", e.toString());
            return false;
        }
 
        this.handle("onConnectSuccess");
        
        Thread sockerReaderThread = new Thread(this);
        sockerReaderThread.start();
 
        return true;
    }
 
    public boolean write(String message)
    {
        if (this.sock == null || !this.sock.isConnected())
        {
            this.handle("onConnectionFailure");
            return false;
        }
 
        try
        {
            socketWriter.write(message);
            socketWriter.flush();
        }
        catch (IOException e)
        {
            this.log(e);
            this.handle("onWriteFailure", e.toString());
            return false;
        }
        this.handle("onWriteSuccess");
        return true;
    }
 
    @Override
    public void run()
    {
        String line;
        
        try
        {
            while (true)
            {
                if (this.sock == null || !this.sock.isConnected())
                {
                    this.handle("onConnectionFailure");
                    return;
                }
 
                if ( (line = this.socketReader.readLine()) != null)
                {
                    this.log(line);
                    this.handle("onReadSuccess", line);
                }
            }
        }
        catch (IOException e)
        {
            this.log(e);
            this.handle("onReadFailure", e.toString());
        }
    }
 
    @Override
    public void stop()
    {
        if (this.sock.isClosed())
            return;
 
        try
        {
            this.sock.close();
        }
        catch (IOException e)
        {
            this.log(e);
        }
    }
    
    public void handle(String handler, String data)
    {
        if (handler == null)
            return;
        
        try
        {
            this.getAppletContext().showDocument(new URL("javascript:"+ this.eventHandlerObject + "['" + handler + "']" + "(\"" + data +"\")"));
        }
        catch (MalformedURLException e)
        {
            this.log(e);
        }
    }
 
    public void handle(String handler)
    {
        if (handler == null)
            return;
 
        try
        {
            this.getAppletContext().showDocument(new URL("javascript:" + this.eventHandlerObject + "['" + handler + "']()"));
        }
        catch (MalformedURLException e)
        {
            this.log(e);
        }
    }
 
    public void log(String message)
    {
        if (this.debugMode && this.textArea != null)
        {
            textArea.append(message + "\n");
        }
    }
 
    public void log(Exception ex)
    {
        this.log(ex.toString());
    }
}
baseHandler.js

Code: Select all

Ext.namespace("Ext.EventListener"); 

Ext.EventListener.BaseHandler = function(config)
{    
	Ext.apply(this, config);    
	Ext.EventListener.BaseHandler.superclass.constructor.call(this);    
	
	this.addEvents
	(
		'connectSuccess',        
		'readSuccess',        
		'writeSuccess',        
		'disconnectSuccess',         
		'connectFailure',        
		'readFailure',        
		'writeFailure',        
		'disconnectFailure',         
		'readResponse',         
		'receivedResponse',        
		'receivedEvent'    
		);     
	this.eventListener = window.document[config['listenerName']];
} 

Ext.extend(Ext.EventListener.BaseHandler, Ext.util.Observable,
{
	eventListener       : null,     
	
	request             : function (msg)    
	{
		this.eventListener.write(msg);
	},     
	
	connect             : function ()    
	{
		this.eventListener.connect();
	},     
	
	onConnectSuccess    : function ()    
	{
		this.fireEvent("connectSuccess", this);
	},    
	
	onReadSuccess       : function (data)    
	{
		this.fireEvent("readSuccess", data, this);
	},    
	
	onWriteSuccess      : function ()    
	{
		this.fireEvent("writeSuccess", this);
	},    
	
	onDisconnectSuccess : function ()    
	{
		this.fireEvent("disconnectSuccess", this);
	},     
	
	onConnectFailure    : function (msg)    
	{
		this.fireEvent("connectFailure", msg, this);
	},    
	
	onReadFailure       : function (msg)    
	{
		this.fireEvent("readFailure", msg, this);
	},    
	
	onWriteFailure      : function (msg)    
	{
		this.fireEvent("writeFailure", msg, this);
	},    
	
	onDisconnectFailure : function (msg)    
	{
		this.fireEvent("disconnectFailure", msg, this);
	}
});
index.php

Code: Select all

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>    
		<title></title>    
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
		<script type="text/javascript" src="/scripts/ext/ext-base.js"></script>    
		<script type="text/javascript" src="/scripts/ext/ext-debug.js"></script>    
		<script type="text/javascript" src="/scripts/baseHandler.js"></script>    
		<script>
			
        var handler = null;         
		Ext.onReady(function ()        
		{            
			handler = new Ext.EventListener.BaseHandler(            
			{                
				listenerName    : 'asterisk'            
			});             
			
			handler.connect();             
			handler.on(            
			{                
				connectSuccess  :                
				{                    
					scope   : handler,                    
					fn      : function ()                    
					{                        
						alert("Connected");                    
					}                
				},                 
				
				readSuccess :                
				{                    
					scope   : handler,                    
					fn      : function (text)                    
					{                        
						alert(text);                    
					}                
				}            
			})        
		});     
		
		</script>
	</head>
	<body>    
		<applet code="EventListener.class" archive="EventListener.jar" width="0" height="0" name="asterisk">        
			<param name="port" value="5038">        
			<param name="handler" value="handler">    
		</applet>
	</body>
</html>
EventListener.jar.zip
Self-signed JAR archive (please, remove the .zip extension, [The extension jar is not allowed.])
(6.76 KiB) Downloaded 309 times
It's a Java "stream proxy" for AJAX.
It opens a TCP stream to a specified port on the web server and listens for incoming data. Writing data is also possible.

So ... I'm not very good at Java so any advices and criticism are welcome :)
Last edited by VladSun on Wed Oct 12, 2011 10:19 am, edited 1 time in total.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: [JAVA] Critque needed

Post by VladSun »

No critique ?!? :) WOW, I feel so god-like :)
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: [JAVA] Critque needed

Post by Weirdan »

VladSun wrote:No critique ?!? :) WOW, I feel so god-like :)
It's more likely the case of Joe the Uncatchable. Seriously, we're more of a PHP forum here :)
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: [JAVA] Critque needed

Post by VladSun »

Yes, of course. I thought the Java code part was simple enough (maybe because it's my first attempt to write something in Java for the last 5+ years), so there would be people here experienced enough to give some criticism. Also, it's a mixture of client-side Java/JavaScript and server side (optionally) PHP code, so it can't be either pure Java related topic, either pure JS related or pure PHP.
I've seen here a lot of server-pull AJAX topics, so I thought a "client-server-streaming" AJAX solution would be helpful to show. One can imagine that the Java applet together with the JS event handler and interface, is nothing but a JS library for TCP streaming.

I used it for capturing events (and writing commands to) from the Asterisk call manager service in a PHP intranet application, so I think it could be useful for the PHP community here.
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply