MessageBus使得你可以在支持MessageBus的程序中增加新的通信机制;与此类似,Message使得你任何时候可以在程序中增加新的Message类型。
HttpMessageBus
看下面一个具体的MessageBus实现,它通过HTTP来POST消息:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.NET.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* HttpMessageBus是一个MessageBus实现,
* 它采用HTTP POST来发送消息。
* @author Tony Sintes JavaWorld Q&A
*/
public class HttpMessageBus implements MessageBus {
private String _url;
private final static String _KEY_VALUE_DELIM = "=";
private final static String _NEW_KEY_VALUE = "&";
private final static String _ENCODING = "application/x-www-form-urlencoded";
private final static String _TYPE = "Content-Type";
private final static int _KEY = 0;
private final static int _VALUE = 1;
public HttpMessageBus( String url )
{
_url = url;
}
public String sendMessage( String[][] values ) throws BusException
{
String post = _formulatePOST( values );
try
{
return _sendPOST( post );
}
catch( MalformedURLException exception )
{
throw new HttpBusException( exception.getMessage() );
}
catch( IOException exception )
{
throw new HttpBusException( exception.getMessage() );
}
}
private String _formulatePOST( String [][] values ) {
if( ( values == null ) || ( values.length == 0 ) )
{
return "";
}
StringBuffer sb = new StringBuffer();
String new_pair = "";
for( int i = 0; i < values.length; i ++ )
{
sb.append( new_pair );
sb.append( URLEncoder.encode( values[i][_KEY] ) );
sb.append( _KEY_VALUE_DELIM );
sb.append( URLEncoder.encode( values[i][_VALUE] ) );
new_pair = _NEW_KEY_VALUE;
}
String post = sb.toString();
return post;
}
private String _sendPOST( String post ) throws MalformedURLException, IOException
{
URLConnection conn = _setUpConnection();
_write( post, conn );
return _read( conn );
}
private URLConnection _setUpConnection() throws MalformedURLException, IOException
{
URL url = new URL( _url );
URLConnection conn = url.openConnection();
conn.setDoInput ( true );
conn.setDoOutput ( true );
conn.setUseCaches ( false );
conn.setRequestProperty( _TYPE, _ENCODING );
return conn;
}
private void _write( String post, URLConnection conn ) throws IOException
{
DataOutputStream output = new DataOutputStream ( conn.getOutputStream() );
output.writeBytes( post );
output.flush ();
output.close ();