redstone-xmlrpc-1.1/0000755000175000017500000000000011514116146013455 5ustar chuckchuckredstone-xmlrpc-1.1/build.xml0000644000175000017500000001015110660134732015276 0ustar chuckchuck redstone-xmlrpc-1.1/source/0000755000175000017500000000000011514116146014755 5ustar chuckchuckredstone-xmlrpc-1.1/source/ajax.js0000644000175000017500000001323410435036553016245 0ustar chuckchuck/** * Creates a connection object that may be used to post messages * to a server. */ function Connection() { var self = this; /** * Returns an XmlHttpRequest object for the current browser. */ this.getXmlHttpRequest = function() { var result = null; try { result = new XMLHttpRequest(); } catch ( e ) { try { result = new ActiveXObject( 'Msxml2.XMLHTTP' ) } catch( e ) { var success = false; var MSXML_XMLHTTP_PROGIDS = new Array( 'Microsoft.XMLHTTP', 'MSXML2.XMLHTTP', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0' ); for ( var i = 0; i < MSXML_XMLHTTP_PROGIDS.length && !success; i++ ) { try { result = new ActiveXObject( MSXML_XMLHTTP_PROGIDS[ i ] ); success = true; } catch ( e ) { result = null; } } } } self.xmlHttpRequest = result; return result; } /** * Posts a message to a server. */ this.post = function( url, content, contentType ) { if ( typeof self.xmlHttpRequest.abort == 'function' && self.xmlHttpRequest.readyState != 0 ) { self.xmlHttpRequest.abort(); } self.xmlHttpRequest.open( 'POST', url, false ); if ( typeof self.xmlHttpRequest.setRequestHeader == 'function' ) { self.xmlHttpRequest.setRequestHeader( 'Content-Type', contentType ); } self.xmlHttpRequest.send( content ); return self.xmlHttpRequest.responseText; } if ( !this.getXmlHttpRequest() ) { throw new Error( "Could not load XMLHttpRequest object" ); } } /** * Client object constructor. */ function AjaxService( url, handlerName ) { this.url = url; this.handlerName = handlerName; this.connection = new Connection(); } /** * Posts an XML-RPC message to the supplied method using the * given arguments. */ AjaxService.prototype.invoke = function( method, arguments ) { return this.connection.post( this.url, this.getMessage( method, arguments ), 'text/xml' ); } /** * Generates an XML-RPC message based on the supplied method name * and argument array. */ AjaxService.prototype.getMessage = function( method, arguments ) { if ( arguments == null ) { arguments = new Array(); } var message = '' + this.handlerName + '.' + method + ''; if ( arguments.length > 0 ) { message += ''; for ( var i = 0; i < arguments.length; i++ ) { var argument = arguments[ i ]; message += '' + argument.serialize() + ''; } message += ''; } message += ''; return message; } /** * Serialization functions for the String datatype. */ String.prototype.serialize = function() { return '' + this + ''; } /** * Serialization functions for the Number datatype. */ Number.prototype.serialize = function() { if ( this % 1 != 0 ) // Very crude way of determining type. May be mismatch at server. { return '' + this + ''; } else { return '' + this + ''; } } /** * Serialization function for the Boolean datatype. */ Boolean.prototype.serialize = function() { return '' + this + ''; } /** * Serialization function for the Array datatype. It reuses the * other serialization functions to serialize the members of the array. */ Array.prototype.serialize = function() { var result = ''; for ( var i = 0; i < this.length; i++ ) { result += '' + this[ i ].serialize() + ''; } result += ''; return result; } /** * Serialization function for Date datatype. */ Date.prototype.serialize = function() { return '' + this.getFullYear() + ( this.getMonth() < 10 ? '0' : '' ) + this.getMonth() + ( this.getDay() < 10 ? '0' : '' ) + this.getDay() + 'T' + ( this.getHours() < 10 ? '0' : '' ) + this.getHours() + ':' + ( this.getMinutes() < 10 ? '0' : '' ) + this.getMinutes() + ':' + ( this.getMinutes() < 10 ? '0' : '' ) + this.getSeconds() + ''; // Phew :-) } /** * Serialization functions for the complex datatypes. It reuses the * other serialization functions to serialize the members of the object. */ Object.prototype.serialize = function() { var result = ''; for ( var member in this ) { if ( typeof( this[ member ] ) != 'function' ) { result += ''; result += '' + member + ''; result += '' + this[ member ].serialize() + ''; result += ''; } } result += ''; return result; }redstone-xmlrpc-1.1/source/redstone/0000755000175000017500000000000011514116146016600 5ustar chuckchuckredstone-xmlrpc-1.1/source/redstone/xmlrpc/0000755000175000017500000000000011514116146020105 5ustar chuckchuckredstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcMessages.java0000644000175000017500000000344010435021152023637 0ustar chuckchuck/* Copyright © 2006 by Redstone Handelsbolag All Rights Reserved. The copyright to the source code herein is the property of Redstone Handelsbolag. The source code may be used and/or copied only with written permission from Redstone or in accordance with the terms and conditions stipulated in the agreement/contract under which the source code has been supplied. */ package redstone.xmlrpc; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * Contains various messages generated by the library. The original messages are * stored in XmlRpcMessages.properties, which may be overridden by creating * additional locale specific bundles. This is achieved by placing a copy of * XmlRpcMessages.properties with the locale specific suffix (like * XmlRpcMessages_de.properties for German). The bundle will automatically be selected * depending on the default locale of the JVM. * * @author Greger Olsson */ public class XmlRpcMessages { /** * Returns a message from the resource bundle corresponding to the given key. * * @param key The message key. * @return The message corresponding to the message key. * @throws MissingResourceException If the message is not found. */ public static String getString( String key ) { try { return RESOURCE_BUNDLE.getString( key ); } catch ( MissingResourceException e ) { return '!' + key + '!'; } } /** */ private static final String BUNDLE_NAME = "redstone.xmlrpc.XmlRpcMessages"; /** */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle( BUNDLE_NAME ); } redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcProxy.java0000644000175000017500000001576610653503613023240 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * An XmlRpcProxy lets you use the services of an XML-RPC server through * Java interfaces. It uses the Dynamic Proxy API introduced in JDK 1.3 to * dynamically convert calls through Java interfaces to XML-RPC messages. This * may be an improvement over the XmlRpcClient since using a server through Java * interfaces allows compilation-time type checking, IDE code completion, and * prevents typos and other errors. * * @author Greger Olsson */ public class XmlRpcProxy implements InvocationHandler { /** * Creates a new dynamic proxy object that implements all the * supplied interfaces. This object may be type cast to any of * the interface supplied in the call. Method calls through the * interfaces will be translated to XML-RPC calls to the server * in the supplied url. * * @param url The XML-RPC server that will receive calls through * the interfaces. * * @param interfaces The list of interfaces the proxy should * implement. * * @return An object implementing the supplied interfaces with * XML-RPC support. */ public static Object createProxy( URL url, Class[] interfaces, boolean streamMessages ) { return createProxy( url, null, interfaces, streamMessages ); } /** * Creates a new dynamic proxy object that implements all * supplied interfaces. This object may be type cast to any of * the interface supplied in the call. Method calls through the * interfaces will be translated to XML-RPC calls to the server * in the supplied url. * * @param url The XML-RPC server that will receive calls through * the interfaces * * @param interfaces The list of interfaces the proxy should * implement * * @param objectName The name under which the handler is * reachable * * @return An object implementing the supplied interfaces with * XML-RPC support */ public static Object createProxy( URL url, String objectName, Class[] interfaces, boolean streamMessages ) { return Proxy.newProxyInstance( interfaces[ 0 ].getClassLoader(), interfaces, new XmlRpcProxy( url, objectName, streamMessages ) ); } /** * Sets the HTTP request properties that the proxy will use for the next invocation, * and any invocations that follow until setRequestProperties() is invoked again. Null * is accepted and means that no special HTTP request properties will be used in any * future XML-RPC invocations using this XmlRpcProxy instance. * * @param requestProperties The HTTP request properties to use for future invocations * made using this XmlRpcProxy instance. These will replace * any previous properties set using this method or the * setRequestProperty() method. */ public void setRequestProperties( Map requestProperties ) { client.setRequestProperties( requestProperties ); } /** * Sets a single HTTP request property to be used in future invocations. * @see setRequestProperties() * * @param name Name of the property to set * @param value The value of the property */ public void setRequestProperty( String name, String value ) { client.setRequestProperty( name, value ); } /** * Handles method calls invoked on the proxy object. This is not used by the * application but has to be public so that the dynamic proxy has access to it. * It just hands the call over to the performCall method. * * @see The Dynamic Proxy API in JDK 1.3 * * @return Any of the values returned by an XmlRpcClient. */ public Object invoke( Object proxy, Method method, Object[] args ) throws XmlRpcException, XmlRpcFault { String handlerName; if ( objectName == null ) { // The recommended way to use XmlRpcProxy is to tie the proxy to a specific // handler name. If not we must extract the name, given the name of the interface // we're calling through, which may contain '.' and '$'. String declaringClass = method.getDeclaringClass().getName(); if ( declaringClass.indexOf( '$' ) != -1 ) { handlerName = declaringClass.substring( declaringClass.lastIndexOf( '$' ) + 1 ); } else if ( declaringClass.indexOf( '.' ) != -1 ) { handlerName = declaringClass.substring( declaringClass.lastIndexOf( '.' ) + 1 ); } else { handlerName = declaringClass; } } else { handlerName = objectName; } // Let the basic XmlRpcClient perform the call. This may result in an XmlRpcException // which will be propagated out from this method. return client.invoke( handlerName + "." + method.getName(), args ); } /** * Creates a new XmlRpcProxy which is a dynamic proxy invocation handler with * an encapsulated XmlRpcClient. Not for pubilc usage -- use createProxy() */ protected XmlRpcProxy( URL url, String objectName, boolean streamMessages ) { client = new XmlRpcClient( url, streamMessages ); this.objectName = objectName; } /** The encapsulated XmlRpcClient receiving the converted dynamic calls */ protected XmlRpcClient client; /** The name of the handler that will handle the converted dynamic calls */ protected String objectName; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcInvocation.java0000644000175000017500000001300210435021152024174 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.Writer; import java.util.List; /** * Contains information about a particular invocation intercepted * by an invocation processor. Invocation objects are only used * on the server side, and only when calling on invocation processors. * * @author Greger Olsson */ public class XmlRpcInvocation { /** * @param invocationId The unique identity of the invocation. * @param handlerName The name of the handler that was invoked. * @param methodName The name of the method within the handler that was invoked. * @param handler The invocation handler that was invoked. * @param arguments Arguments used in the invocation. * @param writer The java.io.Writer that the response will be written over. */ public XmlRpcInvocation( int invocationId, String handlerName, String methodName, XmlRpcInvocationHandler handler, List arguments, Writer writer ) { this.invocationId = invocationId; this.handlerName = handlerName; this.methodName = methodName; this.handler = handler; this.arguments = arguments; this.writer = writer; } /** * A sequence number for tracing invocations between preProcess() and * postProcess() calls. This is unique within each session. That is, * the sequence is restarted when the application restarts. * * @return The sequence number of the call. */ public int getInvocationId() { return invocationId; } /** * Returns the name of the invocation handler targeted by the invocation. * * @return The name of the invocation handler targeted by the invocation. */ public String getHandlerName() { return handlerName; } /** * Returns the name of the method in the invocation handler targeted by the invocation. * Using naming conventions for method names various types of filters and processors * may be created. * * @return The name of the method in the invocation handler targeted by the invocation. */ public String getMethodName() { return methodName; } /** * Sets a new method name to be invoked instead of the * original method name. This can be handy when using a * naming convention where the public XML-RPC interface * uses names with prefixes, for instance, which are stripped * away before reaching the invocation handler, and so forth. * * @param methodName The name of the method to user. */ public void setMethodName( String methodName ) { this.methodName = methodName; } /** * Returns a list of arguments supplied in the invocation. This list may be modified * by the processor. Arguments may be analyzed, modified, added or removed before a * call is dispatched to the handler method. * * @return A list of arguments supplied in the invocation. */ public List getArguments() { return arguments; } /** * Returns the handler that will be or has been invoked. This information * may be used in conjunction with the handler name and method name to * achieve some filtering scheme or some other type of processing procedure. * * @return Returns the handler that will be or has been invoked. */ public XmlRpcInvocationHandler getHandler() { return handler; } /** * Returns the writer that the response of the invocation will be written * to. The interceptor may write custom content to the writer as a custom * header to the original response or as a complete replacement to the * response. * * @see XmlRpcInvocationInterceptor#after(XmlRpcInvocation, Object) * * @return The writer that the response will be written to. */ public Writer getWriter() { return writer; } /** The unique identity of the invocation. */ private int invocationId; /** The name of the handler that was invoked. */ private String handlerName; /** The name of the method within the handler that was invoked. */ private String methodName; /** The invocation handler that was invoked. */ private XmlRpcInvocationHandler handler; /** Arguments used in the invocation. */ private List arguments; /** The java.io.Writer that the response will be written over. */ private Writer writer; } redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcDispatcher.java0000644000175000017500000002513210473701237024173 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.xml.sax.SAXException; /** * Objects of the XmlRpcDispather class perform the parsing of inbound XML-RPC * messages received by an XmlRpcServer and are responsible for invoking handlers and * dealing with their return values and exceptions. * * @author Greger Olsson */ public class XmlRpcDispatcher extends XmlRpcParser { /** * Creates a dispatcher and associates it with an XmlRpcServer and the IP address * of the calling client. * * @param server */ public XmlRpcDispatcher( XmlRpcServer server, String callerIp ) { this.server = server; this.callerIp = callerIp; } /** * Returns the IP adress of the client being dispatched. * * @return The IP adress of the client being dispatched. */ public String getCallerIp() { return callerIp; } /** * Inbound XML-RPC messages to a server are delegated to this method. It * performs the parsing of the message, through the inherited parse() method, * and locates and invokes the appropriate invocation handlers. * * @throw Exception When the inbound XML message cannot be parsed due to no * available SAX driver, or when an invalid message was received. * All other exceptions are caught and encoded within the * XML-RPC writer. */ public void dispatch( InputStream xmlInput, Writer xmlOutput ) throws XmlRpcException { // Parse the inbound XML-RPC message. May throw an exception. parse( xmlInput ); // Response is written directly to the Writer supplied by the XmlRpcServer. this.writer = xmlOutput; // Exceptions will from hereon be encoded in the XML-RPC response. int separator = methodName.lastIndexOf( "." ); if ( separator > -1 ) { final String handlerName = methodName.substring( 0, separator ); methodName = methodName.substring( separator + 1 ); XmlRpcInvocationHandler handler = server.getInvocationHandler( handlerName ); if ( handler != null ) { final int callId = ++callSequence; XmlRpcInvocation invocation = null; if( server.getInvocationInterceptors().size() > 0 ) { invocation = new XmlRpcInvocation( callId, handlerName, methodName, handler, arguments, writer ); } try { // Invoke the method, which may throw any kind of exception. If any of the // preProcess calls thinks the invocation should be cancelled, we do so. if ( !preProcess( invocation ) ) { writeError( XmlRpcMessages.getString( "XmlRpcDispatcher.InvocationCancelled" ) ); } else { Object returnValue = handler.invoke( methodName, arguments ); returnValue = postProcess( invocation, returnValue ); // If the return value wasn't intercepted by any of the interceptors, // write the response using the current serlialization mechanism. if ( returnValue != null ) { writeValue( returnValue ); } } } catch ( Throwable t ) { processException( invocation, t ); writeError( t.getClass().getName() + ": " + t.getMessage() ); } } else { writeError( XmlRpcMessages.getString( "XmlRpcDispatcher.HandlerNotFound" ) ); } } else { writeError( XmlRpcMessages.getString( "XmlRpcDispatcher.InvalidMethodNameFormat" ) ); } } /** * Override the endElement() method of the XmlRpcParser class, and catch * the method name element. The method name element is unique for XML-RPC * calls, and belongs here in the server. */ public void endElement( String uri, String name, String qualifiedName ) throws SAXException { if ( name.equals( "methodName" ) ) { methodName = this.consumeCharData(); } else { super.endElement( uri, name, qualifiedName ); } } /** * Implementation of abstract method introduced in XmlRpcParser. It will * be called whenever a value is parsed during a parse() call. In this * case, the parsed values represent arguments to be sent to the invocation * handler of the call. */ protected void handleParsedValue( Object value ) { arguments.add( value ); } /** * Invokes all processor objects registered with the XmlRpcServer this dispatcher is * working for. * * @todo Determine a way for a preProcess call to indicate the reason for cancelling * the invocation. * * @return true if the invocation should continue, or false if the invocation should * be cancelled for some reason. */ private boolean preProcess( XmlRpcInvocation invocation ) { XmlRpcInvocationInterceptor p; for ( int i = 0; i < server.getInvocationInterceptors().size(); ++i ) { p = ( XmlRpcInvocationInterceptor ) server.getInvocationInterceptors().get( i ); if ( !p.before( invocation ) ) { return false; } } return true; } /** * Invokes all interceptor objects registered with the XmlRpcServer this dispatcher is * working for. */ private Object postProcess( XmlRpcInvocation invocation, Object returnValue ) { XmlRpcInvocationInterceptor p; for ( int i = 0; i < server.getInvocationInterceptors().size(); ++i ) { p = ( XmlRpcInvocationInterceptor ) server.getInvocationInterceptors().get( i ); returnValue = p.after( invocation, returnValue ); // If the interceptor intercepts the return value completely and takes // responsibility for writing a response directly to the client, break // the interceptor chain and return immediately. if ( returnValue == null ) { return null; } } return returnValue; } /** * Invokes all processor objects registered with the XmlRpcServer this dispatcher is * working for. */ private void processException( XmlRpcInvocation invocation, Throwable exception ) { XmlRpcInvocationInterceptor p; for ( int i = 0; i < server.getInvocationInterceptors().size(); ++i ) { p = ( XmlRpcInvocationInterceptor ) server.getInvocationInterceptors().get( i ); p.onException( invocation, exception ); } } /** * Writes a return value to the XML-RPC writer. * * @param value The value to be encoded into the writer. * @throws IOException */ private void writeValue( Object value ) throws IOException { server.getSerializer().writeEnvelopeHeader( value, writer ); if ( value != null ) { server.getSerializer().serialize( value , writer ); } server.getSerializer().writeEnvelopeFooter( value, writer ); } /** * Creates an XML-RPC fault struct and puts it into the writer buffer. * * @param message The fault string. */ private void writeError( String message ) { try { logger.log( Level.WARNING, message ); this.server.getSerializer().writeError( message, writer ); } catch ( IOException ignore ) { // If an exception occurs at this point there is no way to recover. // We are already trying to send a fault to the client. We swallow // the exception and trace it to the console. logger.log( Level.SEVERE, XmlRpcMessages.getString( "XmlRpcDispatcher.ErrorSendingFault" ), ignore ); } } /** The XmlRpcServer this dispatcher is working for */ private XmlRpcServer server; /** The IP address of the caller */ private String callerIp; /** The name of the method the client wishes to call */ private String methodName; /** The arguments for the method */ private List arguments = new ArrayList( 6 ); /** Holds the XML-RPC repsonse as it is built up */ private Writer writer; /** The current call sequence for traceability */ private static int callSequence; /** Logger used to log problems an exceptions. */ private static Logger logger = Logger.getLogger( XmlRpcDispatcher.class.getName() ); }redstone-xmlrpc-1.1/source/redstone/xmlrpc/interceptors/0000755000175000017500000000000011514116146022626 5ustar chuckchuckredstone-xmlrpc-1.1/source/redstone/xmlrpc/interceptors/DebugInvocationInterceptor.java0000644000175000017500000000624710473701237031005 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.interceptors; import redstone.xmlrpc.XmlRpcInvocation; import redstone.xmlrpc.XmlRpcInvocationInterceptor; /** * Simple invocation processor that traces the calls made through an XmlRpcServer. * This is used for debugging purposes only. This may be replaced with a more * competent logging processor that perhaps is only logging exceptions that occur. * * @author Greger Olsson */ public class DebugInvocationInterceptor implements XmlRpcInvocationInterceptor { /** * Prints info on the invocation, the method, and its arguments. * * @param invocation The invocation. */ public boolean before( XmlRpcInvocation invocation ) { StringBuffer message = new StringBuffer( 192 ); message.append( invocation.getInvocationId() ) .append( ": " ) .append( invocation.getHandlerName() ) .append( '.' ) .append( invocation.getMethodName() ) .append( invocation.getArguments().toString() ); System.out.println( message.toString() ); return true; } /** * Prints trace info on the invocation return value. * * @param invocation The invocation. * @param returnValue The value returned from the method. */ public Object after( XmlRpcInvocation invocation, Object returnValue ) { StringBuffer message = new StringBuffer( 192 ); message.append( invocation.getInvocationId() ) .append( ": " ) .append( returnValue ); System.out.println( message.toString() ); return returnValue; } /** * Prints trace info on the invocation exception. * * @param invocation The invocation. * @param invocation The exception thrown by the method. */ public void onException( XmlRpcInvocation invocation, Throwable exception ) { StringBuffer message = new StringBuffer( 192 ); message.append( invocation.getInvocationId() ) .append( ": " ) .append( exception.getMessage() ); if ( exception.getCause() != null ) { message.append( exception.getCause().getMessage() ); } System.out.println( message.toString() ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcSerializer.java0000644000175000017500000002527110660134732024220 0ustar chuckchuck/* Copyright (c) 2007 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.IOException; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import redstone.xmlrpc.util.Base64; /** * The XmlRpcSerializer class converts Java objects to their XML-RPC counterparts * according to the XML-RPC specification. It inherently supports basic object * types like String, Integer, Double, Float, Boolean, Date, and byte arrays. For other * types of objects, custom serializers need to be registered. The Redstone XML-RPC * library comes with a set of useful serializers for collections and other types * of objects. @see the redstone.xmlrpc.serializers . * * TODO Change synchronization of global dateFormatter to prevent bottleneck. * * @author Greger Olsson */ public class XmlRpcSerializer { /** * Constructor adding all core custom serializers. */ public XmlRpcSerializer() { this( true ); } /** * Constructor that may add all the custom serializers in the library * (which is almost always what you want). * * @param addCustomSerializers Indicates if the core custom serializers should be added. */ public XmlRpcSerializer( boolean addCustomSerializers ) { if ( addCustomSerializers ) { customSerializers.add( new redstone.xmlrpc.serializers.LongPrimitiveSerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.LongWrapperSerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.MapSerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.ListSerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.CollectionSerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.ObjectArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.IntArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.FloatArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.LongArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.DoubleArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.BooleanArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.IntrospectingSerializer() ); } } /** * * * @param writer * @throws IOException */ public void writeEnvelopeHeader( Object value, Writer writer ) throws IOException { writer.write( "" ); } /** * * * @param value * @param writer * @throws IOException */ public void writeEnvelopeFooter( Object value, Writer writer ) throws IOException { if ( value != null ) { writer.write( "" ); } else { writer.write( "void" + "" ); } } /** * * * @param message * @param writer * @throws IOException */ public void writeError( String message, Writer writer ) throws IOException { writer.write( "" ); writer.write( "" ); writer.write( "faultCode-1" ); writer.write( "faultString" ); writer.write( message ); writer.write( "" ); } /** * Converts the supplied Java object to its XML-RPC counterpart according to * the XML-RPC specification. */ public void serialize( Object value, Writer writer ) throws XmlRpcException, IOException { writer.write( "" ); if ( value instanceof String || value instanceof Character ) { writer.write( "" ); String string = value.toString(); int length = string.length(); for ( int i = 0; i < length; ++i ) { char c = string.charAt( i ); switch( c ) { case '<' : writer.write( "<" ); break; case '&' : writer.write( "&" ); break; default : writer.write (c); } } writer.write( "" ); } else if ( value instanceof Integer || value instanceof Short || value instanceof Byte ) { writer.write( "" ); writer.write( value.toString() ); writer.write( "" ); } else if ( value instanceof Double || value instanceof Float ) { writer.write( "" ); writer.write( value.toString() ); writer.write( "" ); } else if ( value instanceof Boolean ) { writer.write( "" ); writer.write( ( ( Boolean ) value ).booleanValue() == true ? "1" : "0" ); writer.write( "" ); } else if ( value instanceof java.util.Calendar ) { writer.write( "" ); synchronized( dateFormatter ) { writer.write( dateFormatter.format( ( ( Calendar ) value ).getTime() ) ); } writer.write( "" ); } else if ( value instanceof java.util.Date ) { writer.write( "" ); synchronized( dateFormatter ) { writer.write( dateFormatter.format( ( Date ) value ) ); } writer.write( "" ); } else if ( value instanceof byte[] ) { writer.write( "" ); writer.write( Base64.encode( ( byte[] ) value ) ); writer.write( "" ); } else { // Value was not of basic type, see if there's a custom serializer // registered for it. for ( int i = 0; i < customSerializers.size(); ++i ) { XmlRpcCustomSerializer serializer = ( XmlRpcCustomSerializer ) customSerializers.get( i ); if ( serializer.getSupportedClass().isInstance( value ) ) { serializer.serialize( value, writer, this ); writer.write( "" ); return; } } throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcSerializer.UnsupportedType" ) + value.getClass() ); } writer.write( "" ); } /** * Registers a custom serializer. The serializer is placed the list of serializers * before more general serializers from the same inheritance tree. That is, adding * a serializer supporting serialization of java.util.Vector will be placed before * a serializer for java.util.Collection. In other words, when serializing an * object of type Vector, the java.util.Vector serializer will override a * more general java.util.Collection serializer. * * @value customSerializer The serializer to extend the original serializer with. */ public void addCustomSerializer( XmlRpcCustomSerializer customSerializer ) { Class supportedClass = customSerializer.getSupportedClass(); for ( int i = 0; i < customSerializers.size(); ++i ) { XmlRpcCustomSerializer customSerializerEntry = ( XmlRpcCustomSerializer ) customSerializers.get( i ); // Does the supplied serializer support a subclass or sub-interface of // the serializer at the current element. If so, the supplied serializer // should end up in front of the current entry. if ( customSerializerEntry.getSupportedClass().isAssignableFrom( supportedClass ) ) { customSerializers.add( i, customSerializer ); return; } } // The serializer does not support classes that inherit from previously // registered serializer classes. It may be put at the end of the list. customSerializers.add( customSerializer ); } /** * Unregisters a previously registered custom serializer. * * @value customSerializer The serializer to unregister. */ public void removeCustomSerializer( XmlRpcCustomSerializer customSerializer ) { customSerializers.remove( customSerializer ); } /** The list of currently registered custom serializers */ protected List/**/ customSerializers = new ArrayList(); /** Date formatter shared by all XmlRpcValues */ private static final SimpleDateFormat dateFormatter = new SimpleDateFormat( "yyyyMMdd'T'HH:mm:ss" ); } redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcCallback.java0000644000175000017500000000423010435021152023562 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; /** * Callback interface to implement when using asynchronous invocations with * XmlRpcClient. The XmlRpcClient will call either onResult(), onFault(), or * onException() based on the outcome of the invocation. * * @author Greger Olsson */ public interface XmlRpcCallback { /** * Called by the XmlRpcClient when a response was received from the server. * * @param result The object containing the result value. */ public void onResult( Object result ); /** * Called by the XmlRpcClient when a fault response was received from the server. * * @param faultCode The error code reported by the XML-RPC service. * * @param faultMessage The error message reported by the XML-RPC service. */ public void onFault( int faultCode, String faultMessage ); /** * Called by the XmlRpcClient when an exception was raised during the call. This * only includes exceptions occurring locally. Remote exceptions are transported as * XML-RPC faults and are reported through the onFault() callback. * * @param exception The local exception which can be the result of network problems, * or problems with the XML payload and serialization. */ public void onException( XmlRpcException exception ); }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcParser.java0000644000175000017500000002662610564311726023353 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.InputStream; import java.util.Stack; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** * An XmlRpcParser converts inbound XML-RPC messages to their Java counterparts through * the use of a SAX compliant parser. This is an abstract class that is only concerned * with the XML-RPC values contained in a message. Deriving classes supply a * handleParsedValue() method that is called whenever an XML-RPC value has been parsed. * *

If a class needs to be notified of additional parts of an XML-RPC message, the * startElement() or endElement() methods are overridden and extended with checks for * the appropriate element. This is the case with XmlRpcClient that wants to know if * a fault element is present. Also, the XmlRpcServer wants to know the name of the * method for which values are supplied.

* *

Internally, the implementation uses pre-calculated hash values of the element names * to allow for switch() constructs when comparing elements supplied by the SAX parser.

* * @author Greger Olsson */ public abstract class XmlRpcParser extends DefaultHandler { /** The hash value of value elements */ public final static int VALUE = 111972721; /** The hash value of string elements */ public final static int STRING = -891985903; /** The hash value of i4 elements */ public final static int I4 = 3307; /** The hash value of i8, Apache elements */ public final static int I8 = 3311; /** The hash value of int elements */ public final static int INT = 104431; /** The hash value of boolean elements */ public final static int BOOLEAN = 64711720; /** The hash value of double elements */ public final static int DOUBLE = -1325958191; /** The hash value of double elements */ public final static int DATE = -586971087; /** The hash value of double elements */ public final static int BASE64 = -1396204209; /** The hash value of struct elements */ public final static int STRUCT = -891974699; /** The hash value of array elements */ public final static int ARRAY = 93090393; /** The hash value of member elements */ public final static int MEMBER = -1077769574; /** The hash value of name elements */ public final static int NAME = 3373707; /** * Abstract method implemented by specialized message parsers like XmlRpcServer * and XmlRpcClient. The method is called for every parsed top-level value. * That is, it is called once for arrays and structs, and not once for every * element. * * @param obj The parsed value object. Can be String, Integer, Double, Boolean, * Date, Vector, byte[], or Map objects. */ protected abstract void handleParsedValue( Object obj ); /** * Parses the XML-RPC message contained in the supplied input stream. It does so * by using the current SAX driver, and will call handleParsedValue() for every * top-level value contained in the message. This method can be overridden to * supply additional processing, like identifying method names and such. This * implementation is only concerned with the values of the message. * * @param is The input stream containing the XML-RPC message * * @throw Exception If anything went wrong during the whole parsing phase */ public void parse( InputStream is ) throws XmlRpcException { XMLReader reader = null; synchronized ( readers ) { if ( readers.empty() ) { try { reader = XMLReaderFactory.createXMLReader(); } catch ( SAXException e ) { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcParser.ReaderInstantiationError" ), e ); } } else { reader = ( XMLReader ) readers.pop(); } } reader.setContentHandler( this ); try { try { reader.parse( new InputSource( is ) ); } catch ( Exception e ) { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcParser.ParsingError" ), e ); } } finally { readers.push( reader ); } } /** * Called by SAX driver when a new element has been found in the message. * *

This implementation uses a switch construct on the hash value of the element * name. This increases readability, in my opinion, and perhaps performance * as well (only one loop -- in hashCode() -- instead of in every equals() call).

* * @param See SAX documentation */ public void startElement( String uri, String name, String qualifiedName, Attributes attributes ) throws SAXException { int element = hashCode( name ); switch( element ) { case VALUE: if ( currentValue != null ) { values.push( currentValue ); } currentValue = new XmlRpcValue(); shallProcessCharData = true; break; case STRING: case I4: case I8: case INT: case BOOLEAN: case DOUBLE: case DATE: case BASE64: case ARRAY: case STRUCT: currentValue.setType( element ); case NAME: shallProcessCharData = true; } } /** * Called by SAX driver when a new end-element has been found in the message.

* * This implementation determines if our current state is that we have a current * value that needs to be processed, and if that value has some character data * in the buffer required to finalize the value. The handleParsedValue() method * is only called if a top-level value element has ended. If not, the value * is added to the enclosing value, which may be an array or a struct.

* * Note that struct values are processed when the member element ends and not * when the value element ends. This is because we need to use the included * member name. * * @param See SAX documentation */ public void endElement( String uri, String name, String qualifiedName ) throws SAXException { if ( currentValue != null && shallProcessCharData ) { currentValue.processCharacterData( consumeCharData() ); } else { charData.setLength( 0 ); } switch( hashCode( name ) ) { case VALUE: int depth = values.size(); if ( depth == 0 ) { handleParsedValue( currentValue.value ); currentValue = null; } else if ( values.elementAt( depth - 1 ).hashCode() != STRUCT ) { XmlRpcValue v = currentValue; currentValue = ( XmlRpcValue ) values.pop(); currentValue.addChildValue( v ); } break; case MEMBER: XmlRpcValue v = currentValue; currentValue = ( XmlRpcValue ) values.pop(); currentValue.addChildValue( v ); break; } } /** * Called by the SAX driver when character data is available. * *

This implementation appends the data to an internal string buffer. * The method is called for every element, wether characters are included * int the element or not. This leads to the buffer being prepended with whitespace * until actual character data is aquired. This is removed using the trim() * method when the character data is consumed.

* * @param See SAX documentation */ public void characters( char[] data, int start, int length ) { charData.append( data, start, length ); } /** * Consumes the data in the internal string buffer. Whitespace is trimmed and the * buffer is emptied. * * @return The string representing the trimmed string value of the buffer. */ protected String consumeCharData() { String data = charData.toString().trim(); charData.setLength( 0 ); shallProcessCharData = false; return data; } /** * Internal hashcode algorithm. This algorithm is used instead * of the build-in hashCode() method of java.lang.String to ensure * that that the same hash value is calculated in all JVMs. The code * in this class switches execution based on has values rather than * using the String.equals() call for each element. Hash values for * the XML-RPC elements have been pre-calculated and are represented * by the hash constants at the top of this file. * * @param string The string to calculate a hash for. */ private int hashCode( String string ) { int hash = 0; int length = string.length(); for ( int i = 0; i < length; ++i ) { hash = 31 * hash + string.charAt( i ); } return hash; } /** Our stack of values. May contain several levels depending on message complexity */ private Stack values = new Stack(); /** The current value (the currently enclosing element) */ private XmlRpcValue currentValue; /** Determines if we shall process the character data fed by the SAX driver */ private boolean shallProcessCharData; /** The accumulated character data from the SAX driver. Is emptied when consumed */ private StringBuffer charData = new StringBuffer( 128 ); /** A cache of parsers so that we don't have to recreate them at every call. TODO Determine if necessary. */ private static Stack/**/ readers = new Stack(); }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcServer.java0000644000175000017500000001510710473701237023354 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.InputStream; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import redstone.xmlrpc.handlers.ReflectiveInvocationHandler; /** * An XmlRpcServer is responsible for hosting a set of invocation handlers and a set of * invocation interceptors. It is invoked by calling the execute() method, supplying a * stream containing the XML-RPC message to be handled. The messages will be parsed and * dispatched to the corresponding invocation handler, if any. * *

The XmlRpcServer may also be started as a service accepting connections on a given port. * This way, a servlet environment is not required to be able to expose XML-RPC services. * The server acts as a minimal HTTP server accepting text/xml posts containing XML-RPC * messages, only.

* *

For further information on setting up an XML-RPC server, see the documentation.

* * @author Greger Olsson */ public class XmlRpcServer { /** * Default constructor using default serializer supporting the basic types as well * the custom serializers. */ public XmlRpcServer() { this.serializer = new XmlRpcSerializer(); } /** * Accepts a serializer to be used during serialization. * * @param serializer The serializer to use for response messages. */ public XmlRpcServer( XmlRpcSerializer serializer ) { this.serializer = serializer; } /** * Dispatches the call contained in the supplied input stream. The stream should contain * a proper XML message conforming to the XML-RPC specification. * * @param xmlInput The stream containing the XML-RPC message. * * @param xmlOutput The stream to put the response in. * * @throws XmlRpcException if the input stream contains unparseable XML or if some error * occurs in the SAX driver. */ public void execute( InputStream xmlInput, Writer output ) throws XmlRpcException { XmlRpcDispatcher dispatcher = new XmlRpcDispatcher( this, "(unknown)" ); dispatcher.dispatch( xmlInput, output ); } /** * Binds an invocation handler object to the given name. * * @param name The name to bind the handler to. * * @param handler The invocation handler object. */ public void addInvocationHandler( String name, Object handler ) { handlers.put( name, new ReflectiveInvocationHandler( handler ) ); } /** * Binds an invocation handler object to the given name. * * @param name The name to bind the handler to. * * @param handler The invocation handler object. */ public void addInvocationHandler( String name, XmlRpcInvocationHandler handler ) { handlers.put( name, handler ); } /** * Returns the invocation handler with the given name. * * @param name The name of the invocation handler to return. * @return The invocation handler with the given name. */ public XmlRpcInvocationHandler getInvocationHandler( String name ) { return ( XmlRpcInvocationHandler ) handlers.get( name ); } /** * Unbinds a previously bound invocation handler. * * @param name The name of the handler to unbind. */ public void removeInvocationHandler( String name ) { handlers.remove( name ); } /** * Invocation interceptors are invoked on every call, regardless of which handler or * method the call is intended for. Interceptors are useful for supplying entry points * for logging and other utilities like transaction handling. For instance, a fictive * TransactionalInvocationInterceptor may examine the name of the method called upon, and * if it starts with "tx_" it may attach an additional transaction object in the * argument vector. * * @param interceptor An invocation interceptor that will be invoked on every call * sent to this server. */ public void addInvocationInterceptor( XmlRpcInvocationInterceptor interceptor ) { interceptors.add( interceptor ); } /** * Returns the incovation interceptors installed in this server. * * @return The incovation interceptors installed in this server. */ public List getInvocationInterceptors() { return interceptors; } /** * Removes a previously registered invocation interceptor. The interceptor will no * longer be invoked on inbound calls. * * @param interceptor The invocation interceptor to remove */ public void removeInvocationInterceptor( XmlRpcInvocationInterceptor interceptor ) { interceptors.remove( interceptor ); } /** * Returns the serializer this server is using to encode responses. * * @return The serializer this server is using. */ public XmlRpcSerializer getSerializer() { return serializer; } /** * Sets the serializer this server is to use when encoding responses. * * @return The serializer this server shall use. */ public void setSerializer( XmlRpcSerializer serializer ) { this.serializer = serializer; } /** */ private Map/**/ handlers = new HashMap(); /** */ private List/**/ interceptors = new ArrayList(); /** */ private XmlRpcSerializer serializer; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcArray.java0000644000175000017500000001557010473701237023170 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; /** *

An Array represents an XML-RPC array in its Java form. Essentially, * it's just a java.util.ArrayList with utility methods for extracting * members of any of the data types supported by the XML-RPC library. * The class does not introduce any new field members which makes it * no more expensive than a regular ArrayList.

* *

To extract nested values from the list, use the new simplified * accessors which perform the casting for you:

* *

 *  boolean boolean = myList.getStruct( 0 ).getBoolean( "someBoolean" );
* * * @author Greger Olsson */ public class XmlRpcArray extends ArrayList { /** * Returns the String at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a String. */ public String getString( int index ) { return ( String ) get( index ); } /** * Returns the boolean at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a Boolean. */ public boolean getBoolean( int index ) { return ( ( Boolean ) get( index ) ).booleanValue(); } /** * Returns the Boolean wrapper at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a Boolean. */ public Boolean getBooleanWrapper( int index ) { return ( Boolean ) get( index ); } /** * Returns the integer at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not an Integer. */ public int getInteger( int index ) { return ( ( Integer ) get( index ) ).intValue(); } /** * Returns the Integer wrapper at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a Integer. */ public Integer getIntegerWrapper( int index ) { return ( Integer ) get( index ); } /** * Returns the Double at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a Double. */ public double getDouble( int index ) { return ( ( Double ) get( index ) ).doubleValue(); } /** * Returns the Double wrapper at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a Double. */ public Double getDoubleWrapper( int index ) { return ( Double ) get( index ); } /** * Returns the Array at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not an Array. */ public XmlRpcArray getArray( int index ) { return ( XmlRpcArray ) get( index ); } /** * Returns the Struct at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a Struct. */ public XmlRpcStruct getStruct( int index ) { return ( XmlRpcStruct ) get( index ); } /** * Returns the Date at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a Date. */ public Date getDate( int index ) { return ( Date ) get( index ); } /** * Returns the byte[] at the given index in the array. * * @param index The index into the array to extract the value from. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a byte[]. */ public byte[] getBinary( int index ) { return ( byte[] ) get( index ); } /** * Returns the byte[] with at the given index in the Array, as an * input stream (currently, a java.io.ByteArrayInputStream). * * @param key The key of the value to extract. * * @throws ArrayOutOfBoundsException if index > size() - 1. * @throws ClassCastException if the value at the given index is not a byte[]. */ public InputStream getBinaryAsStream( int index ) { return new ByteArrayInputStream( ( byte[] ) get( index ) ); } /** Serial version UID. */ private static final long serialVersionUID = 3256446889107863860L; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcServlet.java0000644000175000017500000002042410660572474023537 0ustar chuckchuck/* Copyright (c) 2007 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.StringTokenizer; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that publishes an XmlRpcServer in a web server. * * @author Greger Olsson */ public class XmlRpcServlet extends HttpServlet { /** * Initializes the servlet by instantiating the XmlRpcServer that will * hold all invocation handlers and processors. The servlet configuration * is read to see if the XML-RPC responses generated should be streamed * immediately to the resonse (non-compliant) or if they should be buffered * before being sent (compliant, since then the Content-Length header may * be set, as stipulated by the XML-RPC specification).

* * Further, the configuration is read to see if any services are mentioned * declaratively that are to be instantiated and published. An alternative * to this is to create a new servlet class extending from XmlRpcServlet * that publishes services programmatically. */ public void init( ServletConfig config ) throws ServletException { String services = config.getInitParameter( "services" ); String contentType = config.getInitParameter( "contentType" ); String streamMessages = config.getInitParameter( "streamMessages" ); if ( streamMessages != null && streamMessages.equals( "1" ) ) { this.streamMessages = true; } if ( contentType != null && contentType.startsWith( "text/javascript+json" ) ) { this.contentType = "text/javascript+json"; server = new XmlRpcServer( new XmlRpcJsonSerializer() ); } else { this.contentType = "text/xml"; server = new XmlRpcServer(); } this.contentType += "; charset=" + XmlRpcMessages.getString( "XmlRpcServlet.Encoding" ); if ( services != null ) { addInvocationHandlers( services ); } } /** * Returns the XmlRpcServer that is backing the servlet. * * @return The XmlRpcServer backing the servlet. */ public XmlRpcServer getXmlRpcServer() { return server; } /** * Indicates whether or not messages are streamed or if they are built in memory * to be able to calculate the HTTP Content-Length. * * @return True if messages are streamed directly over the socket as it is built. */ public boolean getStreamMessages() { return streamMessages; } /** * Returns the content type of the messages returned from the servlet which is * text/xml for XML-RPC messages and text/javascript+json for JSON messages. * * @return The content type of the messages returned from this servlet. */ public String getContentType() { return contentType; } /** * Handles reception of XML-RPC messages. * * @param req * @param res * @throws ServletException * @throws IOException */ public void doPost( HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setCharacterEncoding( XmlRpcMessages.getString( "XmlRpcServlet.Encoding" ) ); res.setContentType( contentType ); if ( streamMessages ) { server.execute( req.getInputStream(), res.getWriter() ); res.getWriter().flush(); } else { Writer responseWriter = new StringWriter( 2048 ); server.execute( req.getInputStream(), responseWriter ); String response = responseWriter.toString(); // TODO EXPENSIVE!! res.setContentLength( response.length() ); responseWriter = res.getWriter(); responseWriter.write( response ); responseWriter.flush(); } } /** * Adds invocation handlers based on the service classes mentioned in the supplied * services string. * * @param services List of services specified as fully qualified class names separated * by whitespace (tabs, spaces, newlines). Each class name is also prefixed * by the name of the service to use for the class: *

     *    
     *        services
     *        
     *            SimpleDatabase:java.util.HashMap
     *            RandomNumberGenerator:java.util.Random
     *        
     *    
     *                  
* * @throws ServletException If the services argument is invalid or contains names of * classes that cannot be loaded and instantiated. */ private void addInvocationHandlers( String services ) throws ServletException { StringTokenizer tokenizer = new StringTokenizer( services ); while ( tokenizer.hasMoreTokens() ) { String service = tokenizer.nextToken(); int separatorIndex = service.indexOf( ':' ); if ( separatorIndex > -1 ) { String serviceName = service.substring( 0, separatorIndex ); String className = service.substring( separatorIndex + 1 ); try { Class serviceClass = Class.forName( className ); Object invocationHandler = serviceClass.newInstance(); server.addInvocationHandler( serviceName, invocationHandler ); } catch ( ClassNotFoundException e ) { throw new ServletException( XmlRpcMessages.getString( "XmlRpcServlet.ServiceClassNotFound" ) + className, e ); } catch ( InstantiationException e ) { throw new ServletException( XmlRpcMessages.getString( "XmlRpcServlet.ServiceClassNotInstantiable" ) + className, e ); } catch ( IllegalAccessException e ) { throw new ServletException( XmlRpcMessages.getString( "XmlRpcServlet.ServiceClassNotAccessible" ) + className, e ); } } else { throw new ServletException( XmlRpcMessages.getString( "XmlRpcServlet.InvalidServicesFormat" ) + services ); } } } /** The XmlRpcServer containing the handlers and processors. */ private XmlRpcServer server; /** Indicates whether or not response messages should be streamed. */ private boolean streamMessages; /** */ private String contentType; /** Serial Version UID. */ private static final long serialVersionUID = 3544388119488050993L; } redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcJsonSerializer.java0000644000175000017500000001443110473701237025050 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.IOException; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * The XmlRpcJsonSerializer class converts Java objects to their JSON counterparts. * It inherently supports basic object types like String, Integer, Double, Float, Boolean, * Date, and byte arrays. For other types of objects, custom serializers need to be * registered. The Redstone XML-RPC library comes with a set of useful serializers for * collections and other types of objects. @see the redstone.xmlrpc.serializers.json . * * Although this is not what you would expect to find in an XML-RPC library, implementing * a JSON serializer required very little effort and gives great value for JavaScript * clients that wants to use XML-RPC services in their AJAX implementations. It is easy * to create XML-RPC compatible messages in JavaScript but less easy to parse the response * which is not required using this format, just use eval( responseText ) to get a * JavaScript object. * * TODO Change synchronization of global dateFormatter to prevent bottleneck. * * @author Greger Olsson */ public class XmlRpcJsonSerializer extends XmlRpcSerializer { /** * Constructor adding all core custom serializers. */ public XmlRpcJsonSerializer() { this( true ); } /** * Constructor that may add all the custom serializers in the library * (which is almost always what you want). * * @param addCustomSerializers Indicates if the core custom serializers should be added. */ public XmlRpcJsonSerializer( boolean addCustomSerializers ) { super( false ); if ( addCustomSerializers ) { customSerializers.add( new redstone.xmlrpc.serializers.json.MapSerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.json.ListSerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.json.CollectionSerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.json.ObjectArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.json.IntArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.json.FloatArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.json.DoubleArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.json.BooleanArraySerializer() ); customSerializers.add( new redstone.xmlrpc.serializers.json.IntrospectingSerializer() ); } } /** * Overrides the default serializing mechanism to use JSON format instead. */ public void writeEnvelopeHeader( Object value, Writer writer ) throws IOException { writer.write( '(' ); } /** * Overrides the default serializing mechanism to use JSON format instead. */ public void writeEnvelopeFooter( Object value, Writer writer ) throws IOException { writer.write( ')' ); } /** * Overrides the default serializing mechanism to use JSON format instead. */ public void writeError( String message, Writer writer ) throws IOException { writer.write( '\'' ); writer.write( message ); writer.write( '\'' ); } /** * Overrides the default serializing mechanism to use JSON format instead. */ public void serialize( Object value, Writer writer ) throws XmlRpcException, IOException { if ( value instanceof String || value instanceof Character ) { writer.write( '\'' ); writer.write( value.toString() ); writer.write( '\'' ); } else if ( value instanceof Number || value instanceof Boolean ) { writer.write( value.toString() ); } else if ( value instanceof java.util.Calendar ) { writer.write( "new Date('" ); synchronized( dateFormatter ) { writer.write( dateFormatter.format( ( ( Calendar ) value ).getTime() ) ); } writer.write( "')" ); } else if ( value instanceof java.util.Date ) { writer.write( "new Date('" ); synchronized( dateFormatter ) { writer.write( dateFormatter.format( ( Date ) value ) ); } writer.write( "')" ); } else { // Value was not of basic type, see if there's a custom serializer // registered for it. for ( int i = 0; i < customSerializers.size(); ++i ) { XmlRpcCustomSerializer serializer = ( XmlRpcCustomSerializer ) customSerializers.get( i ); if ( serializer.getSupportedClass().isInstance( value ) ) { serializer.serialize( value, writer, this ); return; } } throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcSerializer.UnsupportedType" ) + value.getClass() ); } } /** Shared date formatter shared. */ private static final SimpleDateFormat dateFormatter = new SimpleDateFormat( "yyyy-dd-mm HH:mm:ss" ); } redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcMessages.properties0000644000175000017500000000276210662317236025135 0ustar chuckchuckXmlRpcClient.NetworkError=A network error occurred. XmlRpcClient.ParseError=The response could not be parsed. XmlRpcClient.Encoding=UTF-8 XmlRpcServlet.Encoding=UTF-8 XmlRpcServlet.ServiceClassNotFound=The service class cannot not found: XmlRpcServlet.ServiceClassNotInstantiable=The service class cannot be instantiated: XmlRpcServlet.ServiceClassNotAccessible=The service class is not accessible: XmlRpcServlet.InvalidServicesFormat=The services parameter format is invalid: XmlRpcSerializer.UnsupportedType=Could not serialize response. Unsupported type: XmlRpcValue.IllegalDate=Illegal date encountered: XmlRpcValue.UnexpectedNestedValue=Nested value encountered for a non-composite value XmlRpcParser.ReaderInstantiationError=Could not instantiate XMLReader parser XmlRpcParser.ParsingError=A problem occured during parsing XmlRpcDispatcher.HandlerNotFound=The specified handler cannot be found XmlRpcDispatcher.InvalidMethodNameFormat=Invalid method name format XmlRpcDispatcher.InvocationCancelled=The invocation was cancelled by a processor object XmlRpcDispatcher.ErrorSendingFault=Could not send fault back to client due to communication problems Base64.InvalidDataLength=Error decoding BASE64 element: Miscalculated data length ReflectiveInvocationHandler.MethodNotPublished=The method has not been published or does not exist ReflectiveInvocationHandler.MethodDontExist=The method cannot be found. Signature: IntrospectingSerializer.SerializationError=Could not serialize property: redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcFault.java0000644000175000017500000000413510435021152023145 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; /** * Exception thrown by the XML-RPC library in case of a fault response. The * exception is thrown only if the call was successfully made but the response * contained a fault message. If a call could not be made due to a local * problem (if an argument could not be serialized or if there was a network * problem) an XmlRpcException is thrown instead. * * @author Greger Olsson */ public class XmlRpcFault extends Exception { /** * Creates a new exception with the supplied message and error code. * The message and error code values are those returned from the remote * XML-RPC service. * * @param message The exception message. */ public XmlRpcFault( int errorCode, String message ) { super( message ); this.errorCode = errorCode; } /** * Returns the error code reported by the remote XML-RPC service. * * @return the error code reported by the XML-RPC service. */ public int getErrorCode() { return errorCode; } /** The exception error code. See XML-RPC specification. */ public final int errorCode; /** Serial version UID. */ private static final long serialVersionUID = 3257566200450856503L; } redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcInvocationInterceptor.java0000644000175000017500000000754510435021152026432 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; /** * Invocation processors are called by XmlRpcServers before and after a call is * dispathed to its invocation handler. Processors are called for all inbound messages * regardless of destination. They serve as appropriate entry points where logging * and other type of processing may be inserted. For instance, a transaction * processor may examine the name of the method being called, and if it starts * with "tx_" it may add an additional transaction argument to the list of arguments * received by the method. After the call is dispatched, the transaction may be * commited or rolled back, in case of an error. * * @author Greger Olsson */ public interface XmlRpcInvocationInterceptor { /** * Called by an XmlRpcServer before the method with the supplied name is called. * The arguments list may be altered if necessary. The method must have matching * parameters, however. * *

If, for some reason, the processor wishes to cancel the invocation altogether, it * returns false from this method. This may be the case for filtering processors where * certain IP-addresses are restricted from particular methods, or if the arguments * contain some encrypted password and username that does not authorize.

* * @param invocation The invocation intercepted by the processor. * * @return true if the invocation should proceed, or false if not. */ boolean before( XmlRpcInvocation invocation ); /** * Called by an XmlRpcServer after the supplied method has been called. The * processor may alter the return value, if it wants, before the response is * created. This may be useful if the information therein should be encrypted * or compressed, for instance. * *

If the interceptor returns null it means that the call was intercepted * completely and that the interceptor itself is responsible of generating * a response to the caller through the java.io.Writer in the XmlRpcInvocation. * This makes it possible to write interceptors that override the whole * serialization mechanism to return customized content for invocations.

* * @param invocation The invocation intercepted by the processor. * * @param returnValue The object returned by the method. If the method * returned a primitive, it is wrapped in its object counterpart. * * @return The (possibly modified) returnValue argument, or null if the interceptor * has intercepted the call completely and no value is to be returned. */ Object after( XmlRpcInvocation incovation, Object returnValue ); /** * Called by an XmlRpcServer when the supplied method throws an exception. * * @param invocation The invocation intercepted by the processor. * * @param exception The exception thrown by the method. */ void onException( XmlRpcInvocation incovation, Throwable exception ); }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/0000755000175000017500000000000011514116146022441 5ustar chuckchuckredstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/LongPrimitiveSerializer.java0000644000175000017500000000564010564311726030140 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes primitiv longs. Note that unless setUseApacheExtension( true ) * has been invoked, the longs are demoted to integers before being serialized * into regular XML-RPC <i4>'s, possibly losing significant bits in the * conversion. * * @author Greger Olsson */ public class LongPrimitiveSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return long.class; } /** * Sets whether or not to use the <i8> Apache extensions when * serializing longs. * * @param useApacheExtension Flag for specifying the Apache extension to be used. */ public void setUseApacheExtension( boolean useApacheExtension ) { this.useApacheExtension = useApacheExtension; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { Long longValue = ( Long ) value; if ( !useApacheExtension ) { writer.write( "" ); writer.write( Integer.toString( longValue.intValue() ) ); writer.write( "" ); } else { writer.write( "" ); writer.write( Long.toString( longValue.longValue() ) ); writer.write( "" ); } } /** Flag indicating whether or not the Apache <i8> extension should be used. */ private boolean useApacheExtension; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/IntArraySerializer.java0000644000175000017500000000410210435021152027055 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of primitive integers. * * @author Greger Olsson */ public class IntArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return int[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); int[] array = ( int[] ) value; for ( int i = 0; i < array.length; ++i ) { writer.write( "" ); writer.write( Integer.toString( array[ i ] ) ); writer.write( "" ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/ListSerializer.java0000644000175000017500000000434610435021152026251 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import java.util.List; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * A custom serializer that support serialization of objects implementing * the java.util.List interface. For ArrayLists, for instance, this may * be more effective than the CollectionSerializer since this serializer * uses random access rather that instantiating an iterator. * * @author Greger Olsson */ public class ListSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return List.class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); List list = ( List ) value; for ( int i = 0; i < list.size(); ++i ) { builtInSerializer.serialize( list.get( i ), writer ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/DoubleArraySerializer.java0000644000175000017500000000412510435021152027542 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of primitive doubles. * * @author Greger Olsson */ public class DoubleArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return double[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); double[] array = ( double[] ) value; for ( int i = 0; i < array.length; ++i ) { writer.write( "" ); writer.write( Double.toString( array[ i ] ) ); writer.write( "" ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/LongWrapperSerializer.java0000644000175000017500000000561710564311726027614 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes a Long wrapper. Note that unless setUseApacheExtension( true ) * has been invoked, the longs are demoted to integers before being serialized * into regular XML-RPC <i4>'s, possibly losing significant bits in the * conversion. * * @author Greger Olsson */ public class LongWrapperSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Long.class; } /** * Sets whether or not to use the <i8> Apache extensions when * serializing longs. * * @param useApacheExtension Flag for specifying the Apache extension to be used. */ public void setUseApacheExtension( boolean useApacheExtension ) { this.useApacheExtension = useApacheExtension; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { Long longValue = ( Long ) value; if ( !useApacheExtension ) { writer.write( "" ); writer.write( Integer.toString( longValue.intValue() ) ); writer.write( "" ); } else { writer.write( "" ); writer.write( Long.toString( longValue.longValue() ) ); writer.write( "" ); } } /** Flag indicating whether or not the Apache <i8> extension should be used. */ private boolean useApacheExtension; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/BooleanArraySerializer.java0000644000175000017500000000412210435021152027704 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of booleans. * * @author Greger Olsson */ public class BooleanArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return boolean[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); boolean[] array = ( boolean[] ) value; for ( int i = 0; i < array.length; ++i ) { writer.write( "" ); writer.write( array[ i ] == true ? "1" : "0" ); writer.write( "" ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/IntrospectingSerializer.java0000644000175000017500000000616710435021152030171 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcMessages; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes any Java object using Introspection to learn which properties that * the object exposes. Note: this code is poorly tested. Use at your own risk. * It does *not* support circular references; only directed graphs are supported. * * @author Greger Olsson */ public class IntrospectingSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Object.class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); try { BeanInfo beanInfo = Introspector.getBeanInfo( value.getClass(), java.lang.Object.class ); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for ( int i = 0; i < descriptors.length; ++i ) { Object propertyValue = descriptors[ i ].getReadMethod().invoke( value, ( Object[] ) null ); if ( propertyValue != null ) { writer.write( "" ); writer.write( descriptors[ i ].getDisplayName() ); writer.write( "" ); builtInSerializer.serialize( propertyValue, writer ); writer.write( "" ); } } } catch( java.lang.Exception e ) { throw new XmlRpcException( XmlRpcMessages.getString( "IntrospectingSerializer.SerializationError" ), e ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/FloatArraySerializer.java0000644000175000017500000000411710435021152027376 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of primitive floats. * * @author Greger Olsson */ public class FloatArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return float[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); float[] array = ( float[] ) value; for ( int i = 0; i < array.length; ++i ) { writer.write( "" ); writer.write( Float.toString( array[ i ] ) ); writer.write( "" ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/ObjectArraySerializer.java0000644000175000017500000000426710435021152027545 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of objects into XML-RPC arrays. For each value in the array * it recursively calls the built in XmlRpcSerializer, which potentially ends up back * in this class if a value in the array is another object array. * * @author Greger Olsson */ public class ObjectArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Object[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); Object[] array = ( Object[] ) value; for ( int i = 0; i < array.length; ++i ) { builtInSerializer.serialize( array[ i ], writer ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/CollectionSerializer.java0000644000175000017500000000425310435021152027426 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Iterator; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes java.util.Collections. See also ListSerializer which serializes * java.util.Lists which use direct access instead of iterators. * * @author Greger Olsson * @see ListSerializer */ public class CollectionSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Collection.class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); Iterator it = ( ( Collection ) value ).iterator(); while ( it.hasNext() ) { builtInSerializer.serialize( it.next(), writer ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/LongArraySerializer.java0000644000175000017500000000620410564311726027243 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of primitive longs. Note that unless * setUseApacheExtension( true ) has been invoked, the longs are demoted to * integers before being serialized into regular XML-RPC <i4>'s, possibly * losing significant bits in the conversion.

* * @author Greger Olsson */ public class LongArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return long[].class; } /** * Sets whether or not to use the <i8> Apache extensions when * serializing longs. * * @param useApacheExtension Flag for specifying the Apache extension to be used. */ public void setUseApacheExtension( boolean useApacheExtension ) { this.useApacheExtension = useApacheExtension; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); long[] array = ( long[] ) value; for ( int i = 0; i < array.length; ++i ) { if ( !useApacheExtension ) { writer.write( "" ); writer.write( Integer.toString( ( int ) array[ i ] ) ); writer.write( "" ); } else { writer.write( "" ); writer.write( Long.toString( array[ i ] ) ); writer.write( "" ); } } writer.write( "" ); } /** Flag indicating whether or not the Apache <i8> extension should be used. */ private boolean useApacheExtension; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/MapSerializer.java0000644000175000017500000000551610435021152026053 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Map; import java.util.Set; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes java.util.Maps into XML-RPC structs. For each value in the map * it recursively calls the XmlRpcSerializer, which potentially ends up back * in this class if a value in the Map is another Map. The key should be a String * or something that properly implements toString(). * * @author Greger Olsson */ public class MapSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Map.class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "" ); Map map = ( Map ) value; Set keys = map.keySet(); Iterator it = keys.iterator(); while ( it.hasNext() ) { Object key = it.next(); writer.write( "" ); writer.write( key.toString() ); writer.write( ""); // Reuse default serializing mechanism for each member. // If the member is another HashMap, this will result in // a recursive call to this method. If no serializer // supports the member type, an XmlRpcException will be thrown. builtInSerializer.serialize( map.get( key ), writer ); writer.write( "" ); } writer.write( "" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/0000755000175000017500000000000011514116146023412 5ustar chuckchuckredstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/IntArraySerializer.java0000644000175000017500000000411610435021152030033 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of primitive integers. * * @author Greger Olsson */ public class IntArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return int[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( '[' ); int[] array = ( int[] ) value; for ( int i = 0; i < array.length; ++i ) { writer.write( Integer.toString( array[ i ] ) ); if ( i < array.length - 1 ) { writer.write( ',' ); } } writer.write( ']' ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/ListSerializer.java0000644000175000017500000000452310435021152027217 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.io.IOException; import java.io.Writer; import java.util.List; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * A custom serializer that support serialization of objects implementing * the java.util.List interface. For ArrayLists, for instance, this may * be more effective than the CollectionSerializer since this serializer * uses random access rather that instantiating an iterator. * * @author Greger Olsson */ public class ListSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return List.class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( '[' ); List list = ( List ) value; for ( int i = 0; i < list.size(); ++i ) { builtInSerializer.serialize( list.get( i ), writer ); if ( i < list.size() - 1 ) { writer.write( ',' ); } } writer.write( ']' ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/DoubleArraySerializer.java0000644000175000017500000000413010435021152030507 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of primitive doubles. * * @author Greger Olsson */ public class DoubleArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return double[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( '[' ); double[] array = ( double[] ) value; for ( int i = 0; i < array.length; ++i ) { writer.write( Double.toString( array[ i ] ) ); if ( i < array.length - 1 ) { writer.write( ',' ); } } writer.write( ']' ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/BooleanArraySerializer.java0000644000175000017500000000413410435021152030660 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of booleans. * * @author Greger Olsson */ public class BooleanArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return boolean[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( '[' ); boolean[] array = ( boolean[] ) value; for ( int i = 0; i < array.length; ++i ) { writer.write( array[ i ] == true ? "true" : "false" ); if ( i != array.length - 1 ) { writer.write( ',' ); } } writer.write( ']' ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/IntrospectingSerializer.java0000644000175000017500000000627710435021152031144 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcMessages; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes any Java object using Introspection to learn which properties that * the object exposes. Note: this code is poorly tested. Use at your own risk. * It does *not* support circular references; only directed graphs are supported. * * @author Greger Olsson */ public class IntrospectingSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Object.class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( "{" ); try { BeanInfo beanInfo = Introspector.getBeanInfo( value.getClass(), java.lang.Object.class ); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for ( int i = 0; i < descriptors.length; ++i ) { Object propertyValue = descriptors[ i ].getReadMethod().invoke( value, ( Object[] ) null ); if ( propertyValue != null ) { writer.write( '"' ); writer.write( descriptors[ i ].getDisplayName() ); writer.write( "\":" ); builtInSerializer.serialize( propertyValue, writer ); if ( i < descriptors.length - 1 ) { writer.write( ',' ); } } } } catch( java.lang.Exception e ) { throw new XmlRpcException( XmlRpcMessages.getString( "IntrospectingSerializer.SerializationError" ), e ); } writer.write( "}" ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/FloatArraySerializer.java0000644000175000017500000000412410435021152030345 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of primitive floats. * * @author Greger Olsson */ public class FloatArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return float[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( '[' ); float[] array = ( float[] ) value; for ( int i = 0; i < array.length; ++i ) { writer.write( Float.toString( array[ i ] ) ); if ( i < array.length - 1 ) { writer.write( ',' ); } } writer.write( ']' ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/ObjectArraySerializer.java0000644000175000017500000000443210435021152030510 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.io.IOException; import java.io.Writer; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes arrays of objects into JSON arrays. For each value in the array * it recursively calls the built in XmlRpcSerializer, which potentially ends up back * in this class if a value in the array is another object array. * * @author Greger Olsson */ public class ObjectArraySerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Object[].class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( '[' ); Object[] array = ( Object[] ) value; for ( int i = 0; i < array.length; ++i ) { builtInSerializer.serialize( array[ i ], writer ); if ( i < array.length - 1 ) { writer.write( ',' ); } } writer.write( ']' ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/CollectionSerializer.java0000644000175000017500000000447510435021152030405 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Collection; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; import redstone.xmlrpc.serializers.ListSerializer; /** * Serializes java.util.Collections. See also ListSerializer which serializes * java.util.Lists which use direct access instead of iterators. * * @author Greger Olsson * @see ListSerializer */ public class CollectionSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Collection.class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( '[' ); Iterator it = ( ( Collection ) value ).iterator(); while ( it.hasNext() ) { builtInSerializer.serialize( it.next(), writer ); if ( it.hasNext() ) { writer.write( ',' ); } } writer.write( ']' ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/serializers/json/MapSerializer.java0000644000175000017500000000555410435021152027026 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.serializers.json; import java.io.IOException; import java.io.Writer; import java.util.Set; import java.util.Map; import java.util.Iterator; import redstone.xmlrpc.XmlRpcCustomSerializer; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcSerializer; /** * Serializes java.util.Maps into JSON objects. For each value in the map * it recursively calls the XmlRpcSerializer, which potentially ends up back * in this class if a value in the Map is another Map. The key should be a String * or something that properly implements toString(). * * @author Greger Olsson */ public class MapSerializer implements XmlRpcCustomSerializer { /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#getSupportedClass() */ public Class getSupportedClass() { return Map.class; } /* (Documentation inherited) * @see redstone.xmlrpc.XmlRpcCustomSerializer#serialize(java.lang.Object, java.io.Writer, redstone.xmlrpc.XmlRpcSerializer) */ public void serialize( Object value, Writer writer, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException { writer.write( '{' ); Map map = ( Map ) value; Set keys = map.keySet(); Iterator it = keys.iterator(); while ( it.hasNext() ) { Object key = it.next(); writer.write( '"' ); writer.write( key.toString() ); writer.write( "\":" ); // Reuse default serializing mechanism for each member. // If the member is another HashMap, this will result in // a recursive call to this method. If no serializer // supports the member type, an XmlRpcException will be thrown. builtInSerializer.serialize( map.get( key ), writer ); if ( it.hasNext() ) { writer.write( ',' ); } } writer.write( '}' ); } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcException.java0000644000175000017500000000352110435021152024026 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; /** * The exception thrown by the XML-RPC library in case of serialization or * network problems. If a call is successfully made but the remote XML-RPC service * returns a fault message, an XmlRpcFault exception will be thrown. * * @author Greger Olsson */ public class XmlRpcException extends RuntimeException { /** * Creates a new exception with the supplied message. * * @param message The exception message. */ public XmlRpcException( String message ) { super( message ); } /** * Creates a new exception with the supplied message. * The supplied cause will be attached to the exception. * * @param message The error message. * @param cause The original cause leading to the exception. */ public XmlRpcException( String message, Throwable cause ) { super( message, cause ); } /** */ private static final long serialVersionUID = 3257844394139596598L; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcValue.java0000644000175000017500000001176710564311726023173 0ustar chuckchuck/* Copyright (c) 2006 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.text.SimpleDateFormat; import java.text.ParseException; import redstone.xmlrpc.util.Base64; /** * An XmlRpcValue wraps a value object that is initialized with data supplied from the * XmlRpcParser according to a specific XML-RPC type. When parsing a message, the parser * first determines the type of the value, and sets it accordingly. It then sets the actual * value of the XmlRpcValue object. The XmlRpcValue object is responsible for handling the * raw character data from the parser, according to the type of the value. * * @author Greger Olsson */ public class XmlRpcValue { /** * Constructs an XmlRpcValue initially assumed to be a string. */ XmlRpcValue() { type = XmlRpcParser.STRING; } /** * Sets the type of the value. If the type is a composite type, a corresponding * XmlRpcArray or XmlRpcStruct will be created to hold the nested values. */ void setType( int type ) { this.type = type; if ( type == XmlRpcParser.ARRAY ) { value = new XmlRpcArray(); } else if ( type == XmlRpcParser.STRUCT ) { value = new XmlRpcStruct(); } } /** * Processes the character data supplied by the parser. Depending on the current type * of the value, the data will be treated accordingly. * * @param charData the character data from the XML-RPC message. */ void processCharacterData( String charData ) throws XmlRpcException { switch ( type ) { case XmlRpcParser.STRING: value = charData; break; case XmlRpcParser.I4: case XmlRpcParser.INT: value = new Integer( charData ); break; case XmlRpcParser.I8: value = new Long( charData ); break; case XmlRpcParser.BOOLEAN: value = new Boolean( Integer.parseInt( charData ) == 1 ); break; case XmlRpcParser.DOUBLE: value = new Double( charData ); break; case XmlRpcParser.DATE: try { // TODO Optimize. synchronized( dateFormatter ) { value = dateFormatter.parse( charData ); } } catch( ParseException e ) { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcValue.IllegalDate" ) + charData, e ); } break; case XmlRpcParser.BASE64: value = Base64.decode( charData.getBytes() ); break; case XmlRpcParser.STRUCT: memberName = charData; break; } } /** * Adds a child value to this value, if it is of composite type (array or struct). * * @param value The nested valued of this value. */ void addChildValue( XmlRpcValue childValue ) { if ( type == XmlRpcParser.ARRAY ) { ( ( XmlRpcArray ) value ).add( childValue.value ); } else if ( type == XmlRpcParser.STRUCT ) { ( ( XmlRpcStruct ) value ).put( memberName, childValue.value ); } else { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcValue.UnexpectedNestedValue" ) ); } } /** * @todo describe. */ public int hashCode() { return type; } /** The encapsulated, interpreted value */ Object value; /** The type of the value (see XmlRpcParser) */ int type; /** If this is a struct value, this holds the member name */ String memberName; /** Date formatter shared by all XmlRpcValues */ private static final SimpleDateFormat dateFormatter = new SimpleDateFormat( "yyyyMMdd'T'HH:mm:ss" ); }redstone-xmlrpc-1.1/source/redstone/xmlrpc/util/0000755000175000017500000000000011514116146021062 5ustar chuckchuckredstone-xmlrpc-1.1/source/redstone/xmlrpc/util/Base64.java0000644000175000017500000001207510653466133022765 0ustar chuckchuck package redstone.xmlrpc.util; import redstone.xmlrpc.XmlRpcMessages; /** * Provides encoding of raw bytes to base64-encoded characters, and * decoding of base64 characters to raw bytes. The original version * was written by Kevin Kelly which has been updated to support * newline characters based on from Object Refinery Limited and * contributors. * * @author Kevin Kelley (kelley@iguana.ruralnet.net) * @author Object Refinery Limited and Contributors */ public class Base64 { /** * Returns an array of base64-encoded characters to represent the * passed data array. * * @param data the array of bytes to encode * @return base64-coded character array. */ static public char[] encode( byte[] data ) { char[] out = new char[ ( ( data.length + 2 ) / 3 ) * 4 ]; // 3 bytes encode to 4 chars. Output is always an even // multiple of 4 characters. for ( int i = 0, index = 0; i < data.length; i += 3, index += 4 ) { boolean quad = false; boolean trip = false; int val = (0xFF & data[ i ] ); val <<= 8; if ( ( i + 1 ) < data.length ) { val |= ( 0xFF & data[ i + 1 ] ); trip = true; } val <<= 8; if ( ( i + 2 ) < data.length ) { val |= ( 0xFF & data[ i + 2 ] ); quad = true; } out[ index + 3 ] = alphabet[ ( quad ? ( val & 0x3F ) : 64 ) ]; val >>= 6; out[ index + 2 ] = alphabet[ ( trip ? ( val & 0x3F ) : 64 ) ]; val >>= 6; out[ index + 1 ] = alphabet[ val & 0x3F ]; val >>= 6; out[ index ] = alphabet[ val & 0x3F ]; } return out; } /** * Returns an array of bytes which were encoded in the passed * character array. * * @param data the array of base64-encoded characters which can * contain whitespace, padding, and invalid characters * which are stripped from the input. * * @return decoded data array */ static public byte[] decode( byte[] data ) { // Calculate actual length of the data, filtering away any // non-BASE64 characters. int tempLen = data.length; for ( int i = 0; i < data.length; ++i ) { if ( ( data[ i ] > 255) || codes[ data[ i ] ] < 0 ) { --tempLen; } } // Calculate required length of byte array: // -- 3 bytes for every 4 valid base64 chars // -- plus 2 bytes if there are 3 extra base64 chars, // or plus 1 byte if there are 2 extra. int len = ( tempLen / 4 ) * 3; if ( ( tempLen % 4 ) == 3 ) { len += 2; } if ( ( tempLen % 4 ) == 2 ) { len += 1; } final byte[] out = new byte[ len ]; int shift = 0; int accum = 0; int index = 0; for ( int i = 0; i < data.length; ++i ) { final int value = ( data[ i ] > 255 ) ? -1 : codes[ data[ i ] ]; // Skip over non-code if ( value >= 0 ) { accum <<= 6; // bits shift up by 6 each time thru shift += 6; // loop, with new bits being put in accum |= value; // at the bottom. // Whenever there are 8 or more shifted in, write them out from // the top, leaving any excess at the bottom for next iteration. if ( shift >= 8 ) { shift -= 8; out[index++] = ( byte ) ( ( accum >> shift ) & 0xff ); } } } if ( index != out.length ) { throw new RuntimeException( XmlRpcMessages.getString( "Base64.InvalidDataLength" ) ); } return out; } /** Code characters for values 0..63 */ static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray(); /** Lookup table for converting base64 characters to value in range 0..63 */ static private byte[] codes = new byte[256]; /** Initialize look-up table */ static { for ( int i = 0; i < 256; i++ ) { codes[ i ] = -1; } for ( int i = 'A'; i <= 'Z'; i++ ) { codes[ i ] = ( byte )( i - 'A' ); } for ( int i = 'a'; i <= 'z'; i++ ) { codes[ i ] = ( byte )( 26 + i - 'a' ); } for ( int i = '0'; i <= '9'; i++ ) { codes[ i ] = ( byte )( 52 + i - '0' ); } codes[ '+' ] = 62; codes[ '/' ] = 63; } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcCustomSerializer.java0000644000175000017500000000641010435021152025374 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.IOException; import java.io.Writer; /** * Java objects are serialized into XML-RPC values using instances of classes * implementing the XmlRpcCustomSerializer class. When processing an argument or a return * value for an XML-RPC call, the XmlRpcSerializer will look through its list of * XmlRpcCustomSerializer objects for a serializer that matches the object type of the * value. The getValueClass() returns the Class supported by that serializer. * *

A number of serializers for common types are already implemented, but you may * wish to add custom serializers for special types of Java objects.

* * @author Greger Olsson */ public interface XmlRpcCustomSerializer { /** * Returns the class of objects this serializer knows how to handle. * * @return The class of objects interpretable to this serializer. */ Class getSupportedClass(); /** * Asks the custom serializer to serialize the supplied value into the supplied * writer. The supplied value will be of the type reported in getSupportedClass() * or of a type extending therefrom. * * @param value The object to serialize. * * @param output The writer to place the serialized data. * * @param builtInSerializer The built-in serializer used by the client or the server. * * @throws XmlRpcException if the value somehow could not be serialized. Many serializers * rely on the built in serializer which also may throw this * exception. * * @throws IOException if there was an error serializing the value through the * writer. The exception is the exception thrown by the * writer, which in most cases will be a StringWriter, in which * case this exception will never occurr. XmlRpcSerializer and * custom serializers may, however, be used outside of the * XML-RPC library to encode information in XML-RPC structs, in * which case the writer potentially could be writing the * information over a socket stream for instance. */ void serialize( Object value, Writer output, XmlRpcSerializer builtInSerializer ) throws XmlRpcException, IOException; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/handlers/0000755000175000017500000000000011514116146021705 5ustar chuckchuckredstone-xmlrpc-1.1/source/redstone/xmlrpc/handlers/ValidationHandler.java0000644000175000017500000001532210473701237026147 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.handlers; import java.util.Map; import java.util.List; import java.util.Date; import java.util.HashMap; import java.util.ArrayList; import redstone.xmlrpc.handlers.ReflectiveInvocationHandler; /** * Handler for the XML-RPC validation suite. This suite is used to verify * the implementation using the verification service at http://www.xmlrpc.com. * * @author Greger Olsson */ public class ValidationHandler extends ReflectiveInvocationHandler { /** * This handler takes a single parameter, an array of structs, each of which contains at least three elements * named moe, larry and curly, all s. Your handler must add all the struct elements named curly and * return the result. */ public int arrayOfStructsTest( List structs ) { int result = 0; for ( int i = 0; i < structs.size(); ++i ) { Map struct = ( Map ) structs.get( i ); result += ( ( Integer ) struct.get( "curly" ) ).intValue(); } return result; } /** * This handler takes a single parameter, a string, that contains any number of predefined entities, namely <, * >, &, ' and ". Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, * ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes. To validate, the numbers must be correct. */ public Map countTheEntities( String str ) { int ctLeftAngleBrackets = 0; int ctRightAngleBrackets = 0; int ctAmpersands = 0; int ctApostrophes = 0; int ctQuotes = 0; for ( int i = 0; i < str.length(); ++i ) { switch ( str.charAt( i ) ) { case '<': ++ctLeftAngleBrackets; break; case '>': ++ctRightAngleBrackets; break; case '&': ++ctAmpersands; break; case '\'': ++ctApostrophes; break; case '\"': ++ctQuotes; break; } } Map/**/ result = new HashMap(); result.put( "ctLeftAngleBrackets", new Integer( ctLeftAngleBrackets ) ); result.put( "ctRightAngleBrackets", new Integer( ctRightAngleBrackets ) ); result.put( "ctAmpersands", new Integer( ctAmpersands ) ); result.put( "ctApostrophes", new Integer( ctApostrophes ) ); result.put( "ctQuotes", new Integer( ctQuotes ) ); return result; } /** * This handler takes a single parameter, a struct, containing at least three elements named moe, larry and * curly, all s. Your handler must add the three numbers and return the result. */ public int easyStructTest( Map struct ) { int result = 0; result += ( ( Integer ) struct.get( "moe" ) ).intValue(); result += ( ( Integer ) struct.get( "larry" ) ).intValue(); result += ( ( Integer ) struct.get( "curly" ) ).intValue(); return result; } /** * This handler takes a single parameter, a struct. Your handler must return the struct. */ public Map echoStructTest( Map struct ) { return struct; } /** * This handler takes six parameters, and returns an array containing all the parameters. */ public List manyTypesTest( int number, boolean bool, String string, double dbl, Date dateTime, byte[] bytes ) { List result = new ArrayList( 6 ); result.add( new Integer( number ) ); result.add( new Boolean( bool ) ); result.add( string ); result.add( new Double( dbl ) ); result.add( dateTime ); result.add( bytes ); return result; } /** * This handler takes a single parameter, which is an array containing between 100 and 200 elements. Each * of the items is a string, your handler must return a string containing the concatenated text of the first and * last elements. */ public String moderateSizeArrayCheck( List strings ) { return ( ( String ) strings.get( 0 ) ) + ( ( String ) strings.get( strings.size() - 1 ) ); } /** * This handler takes a single parameter, a struct, that models a daily calendar. At the top level, there is one * struct for each year. Each year is broken down into months, and months into days. Most of the days are * empty in the struct you receive, but the entry for April 1, 2000 contains a least three elements named * moe, larry and curly, all s. Your handler must add the three numbers and return the result. */ public int nestedStructTest( Map struct ) { int result = 0; try { struct = ( Map ) struct.get( "2000" ); struct = ( Map ) struct.get( "04" ); struct = ( Map ) struct.get( "01" ); result += ( ( Integer ) struct.get( "moe" ) ).intValue(); result += ( ( Integer ) struct.get( "larry" ) ).intValue(); result += ( ( Integer ) struct.get( "curly" ) ).intValue(); } catch ( Exception e ) { e.printStackTrace(); } return result; } /** * This handler takes one parameter, and returns a struct containing three elements, times10, times100 and * times1000, the result of multiplying the number by 10, 100 and 1000. */ public Map simpleStructReturnTest( int number ) { Map/**/ result = new HashMap(); result.put( "times10", new Integer( number * 10 ) ); result.put( "times100", new Integer( number * 100 ) ); result.put( "times1000", new Integer( number * 1000 ) ); return result; } }redstone-xmlrpc-1.1/source/redstone/xmlrpc/handlers/ReflectiveInvocationHandler.java0000644000175000017500000002343710473701237030205 0ustar chuckchuck/* Copyright (c) 2005 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc.handlers; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import redstone.xmlrpc.XmlRpcException; import redstone.xmlrpc.XmlRpcInvocationHandler; import redstone.xmlrpc.XmlRpcMessages; /** * Note that methods that are to be called over XML-RPC need to be public, or the * client will receive a fault message. * * @author Greger Olsson */ public class ReflectiveInvocationHandler implements XmlRpcInvocationHandler { /** * Constructs the handler and sets the current object as the target. That * is, use 'this' as the target to receive the invocations. */ public ReflectiveInvocationHandler() { target = this; } /** * Constructs the handler and sets the supplied object as the invocation target. * This is used when wrapping an object in a reflective handler. Wrapping is * useful if you want to publish an object that is not a ReflectiveInvocationHander. * * @param target The object to wrap up. */ public ReflectiveInvocationHandler( Object target ) { this.target = target; } /** * Constructs the handler and sets the supplied objects as the invocation target. * This is used when wrapping an object in a reflective handler. The user may also * specify a list of methods that should be available in the target. * * @param target The object to wrap up. * * @param entryPoints A list of method names that should be available for invocation. */ public ReflectiveInvocationHandler( Object target, String[] entryPoints ) { this.target = target; this.entryPoints = entryPoints; } /** * Assigns a list of method names that are used when invoking methods on this handler. * After calling this method, only methods listed in the supplied entryPoints list * will be available for invocation. Note that for a given method "testMethod", all * overloaded versions of that method will be available. That is, the invocation * mechanism does not take into account parameter lists, just names.

* * A null entry point list means all public methods are available. * * @param entryPoints A list of method names that may be invoked on this handler, or * null if all methods should be available. */ public void setEntryPoints( String[] entryPoints ) { this.entryPoints = entryPoints; } /** * Called by the XmlRpcServer when a method is to be invoked. This implementation * tries to locate the supplied method in the target object using Java Reflection. * If the invocation handler keeps a list of published methods, this is first checked * to see if the call should be carried through. * * @param methodName The name of the method to call. * * @param arguments A vector containting all arguments required by the method. */ public Object invoke( String methodName, List arguments ) throws Throwable { // Is this handler restricted? If so, is methodName published? Throws an exception if not. if ( entryPoints != null ) checkEntryPoint( methodName ); // Determine types of inbound parameters Class[] argClasses = null; Object[] argValues = null; if( arguments != null ) { argValues = arguments.toArray(); argClasses = new Class[ argValues.length ]; for ( int i = 0; i < argValues.length; ++i ) { argClasses[ i ] = argValues[ i ].getClass(); } } return execute( methodName, argClasses, argValues ); } /** * Locates the method with the given signature and invokes it. The getMethod( Object, Class[] ) * method of java.lang.Class requires the argument classes to exactly match the formal * parameters of the method. Therefor, an internal algorithm is used to locate the * method where the parameters only need to be assignment compatible with the arguments. * That is, a handler method accepting a java.lang.Object for a parameter will match * a java.lang.String argument.

* * Note: in order to reduce the complexity of the algorithm and to minimize * CPU overhead, overloaded methods in the handler class must be listed with increasing * parameter type specialization:

* *

     *    class TestHandler extends ReflectiveInvocationHandler
     *    {
     *        public void myMethod( Object param ) { ... }
     *
     *        public void myMethod( String param ) { ... }
     *    }
     *  

* * This, however, is only necessary when the number of parameters are the same and they * descend from the same super class. In other words, if the first myMethod() method * would accept a Collection instead of an Object, the methods may be listed in any * order. (Short version: the reflection algorithm will pick the first matching method, * from the end, where the arguments in the call are assignment compatible with the * parameters). * * @param methodName The name of the method * * @param argClasses An Array of Classes identifying the method signature * * @param argValues An Array of parameter objects * * @throws May throw any Exception */ protected Object execute( String methodName, Class[] argClasses, Object[] argValues ) throws Throwable { Method[] methods = target.getClass().getMethods(); outer: for ( int i = 0; i < methods.length; ++i ) { Method method = methods[ i ]; if ( method.getName().equals( methodName ) ) { Class[] parameterTypes = method.getParameterTypes(); if ( parameterTypes.length == argClasses.length ) { for ( int j = 0; j < parameterTypes.length; ++j ) { Class type = parameterTypes[ j ]; if ( type.isPrimitive() ) { if ( type.getName().equals( "D" ) && argClasses[ j ] != Double.class ) continue outer; if ( type.getName().equals( "I" ) && argClasses[ j ] != Integer.class ) continue outer; if ( type.getName().equals( "Z" ) && argClasses[ j ] != Boolean.class ) continue outer; } else { if ( !parameterTypes[ j ].isAssignableFrom( argClasses[ j ] ) ) { continue outer; } } } try { return method.invoke( target, argValues ); } catch ( InvocationTargetException it_e ) { throw it_e.getTargetException(); } } } } // Include all class names of the arguments in the error response // to make it easier to debug. The invocation handler tries to find // a method matching these classes, and one could not be found. StringBuffer error = new StringBuffer( 128 ); error.append( XmlRpcMessages.getString( "ReflectiveInvocationHandler.MethodDontExist" ) ); for ( int i = 0; i < argClasses.length; ++i ) { error.append( argClasses[ i ].getName() ); error.append( ' ' ); } throw new XmlRpcException( error.toString() ); } /** * Checks if the supplied methodName is one of the public entry points. If not, * this method throws an exception that will eventually reach the caller. * * @param methodName The name of the method to look for. * * @throws XmlRpcException if the method is not one of the published methods. */ private void checkEntryPoint( String methodName ) throws XmlRpcException { for ( int i = 0; i < entryPoints.length; ++i ) { if ( entryPoints[ i ].equals( methodName ) ) return; } throw new XmlRpcException( XmlRpcMessages.getString( "ReflectiveInvocationHandler.MethodNotPublished" ) ); } /** The object to reflect upon when locating methods. */ protected Object target; /** An optional list of "public" entry points. **/ private String[] entryPoints; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcStruct.java0000644000175000017500000001554010473701237023373 0ustar chuckchuck/* Copyright (c) 2006 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Date; import java.util.HashMap; /** *

A Struct represents an XML-RPC struct in its Java form. Essentially, * it's just a plain java.util.HashMap with utility methods for extracting * members of any of the data types supported by the XML-RPC library. * The class does not introduce any new field members which makes it * no more expensive than a regular HashMap.

* *

To extract nested values from the struct, use the new simplified * accessors which perform the casting for you:

* *
 *  Date date = myStruct.getArray( "someListOfStructs" ).getStruct( 0 ).getDate( "someDate" );
 *  
* * @author Greger Olsson */ public class XmlRpcStruct extends HashMap/**/ { /** * Returns the String with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a String. */ public String getString( Object key ) { return ( String ) get( key ); } /** * Returns the boolean with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Boolean. * @throws NullPointerException if a value with the given key does not exist, */ public boolean getBoolean( Object key ) { return ( ( Boolean ) get( key ) ).booleanValue(); } /** * Returns the Boolean wrapper with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Boolean. */ public Boolean getBooleanWrapper( Object key ) { return ( Boolean ) get( key ); } /** * Returns the integer with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Integer. * @throws NullPointerException if a value with the given key does not exist, */ public int getInteger( Object key ) { return ( ( Integer ) get( key ) ).intValue(); } /** * Returns the Integer wrapper with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Integer. */ public Integer getIntegerWrapper( Object key ) { return ( Integer ) get( key ); } /** * Returns the double with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Double. * @throws NullPointerException if a value with the given key does not exist, */ public double getDouble( Object key ) { return ( ( Double ) get( key ) ).doubleValue(); } /** * Returns the Double wrapper with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Double. */ public Double getDoubleWrapper( Object key ) { return ( Double ) get( key ); } /** * Returns the Array with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Array. * @throws NullPointerException if a value at the given key does not exist. */ public XmlRpcArray getArray( Object key ) { return ( XmlRpcArray ) get( key ); } /** * Returns the Struct with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Struct. */ public XmlRpcStruct getStruct( Object key ) { return ( XmlRpcStruct ) get( key ); } /** * Returns the Date with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Date. */ public Date getDate( Object key ) { return ( Date ) get( key ); } /** * Returns the long integer timestamp with the given key from the Struct. * The timestamp represents the number of milliseconds since midnight jan 01, 1970, * as returned by Date.getTime(). * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a Date. */ public long getTimestamp( Object key ) { Date result = ( Date ) get( key ); return result != null ? result.getTime() : 0; } /** * Returns the byte[] with the given key from the Struct. * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a byte[]. */ public byte[] getBinary( Object key ) { return ( byte[] ) get( key ); } /** * Returns the byte[] with the given key from the Struct, as an * input stream (currently, a java.io.ByteArrayInputStream). * * @param key The key of the value to extract. * * @throws ClassCastException if the value with the given key is not a byte[]. */ public InputStream getBinaryAsStream( Object key ) { byte[] result = ( byte[] ) get( key ); return result != null ? new ByteArrayInputStream( result ) : null; } /** Serial version UID. */ private static final long serialVersionUID = 3546359517982963250L; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcInvocationHandler.java0000644000175000017500000000260410435021152025500 0ustar chuckchuck/* Copyright © 2006 by Redstone Handelsbolag All Rights Reserved. The copyright to the source code herein is the property of Redstone Handelsbolag. The source code may be used and/or copied only with written permission from Redstone or in accordance with the terms and conditions stipulated in the agreement/contract under which the source code has been supplied. */ package redstone.xmlrpc; import java.util.List; /** * When receiving XML-RPC messages, XmlRpcServers parse the XML payload and dispatch * control to XmlRpcInvocationHandlers that perform the actual processing. * *

The XML-RPC library includes a reflective handler that other handlers may extend * or use to wrap them up. @see serializers.ReflectiveInvocationHandler

* * @author Greger Olsson */ public interface XmlRpcInvocationHandler { /** * Called by a dipatcher when an XML-RPC invocation has been received * (and processed by any XmlRpcInvocationProcessors). * * @param method The name of the method that is to be invoked. * @param arguments The arguments to supply to the method. * @return The return value from the method. * @throws Throwable Any kind of exception may occurr in the method. */ Object invoke( String method, List arguments ) throws Throwable; }redstone-xmlrpc-1.1/source/redstone/xmlrpc/XmlRpcClient.java0000644000175000017500000004313010660135510023312 0ustar chuckchuck/* Copyright (c) 2007 Redstone Handelsbolag This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package redstone.xmlrpc; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * An XmlRpcClient represents a connection to an XML-RPC enabled server. It * implements the XmlRpcInvocationHandler so that it may be used as a relay * to other XML-RPC servers when installed in an XmlRpcServer. * * @author Greger Olsson */ public class XmlRpcClient extends XmlRpcParser implements XmlRpcInvocationHandler { /** * Creates a new client with the ability to send XML-RPC messages * to the the server at the given URL. * * @param url the URL at which the XML-RPC service is locaed * * @param streamMessages Indicates whether or not to stream messages directly * or if the messages should be completed locally * before being sent all at once. Streaming is not * directly supported by XML-RPC, since the * Content-Length header is not included in the HTTP post. * If the other end is not relying on Content-Length, * streaming the message directly is much more efficient. * @throws MalformedURLException */ public XmlRpcClient( String url, boolean streamMessages ) throws MalformedURLException { this( new URL( url ), streamMessages ); } /** * @see XmlRpcClient(String,boolean) */ public XmlRpcClient( URL url, boolean streamMessages ) { this.url = url; this.streamMessages = streamMessages; if ( !streamMessages ) { writer = new StringWriter( 2048 ); } } /** * Sets the HTTP request properties that the client will use for the next invocation, * and any invocations that follow until setRequestProperties() is invoked again. Null * is accepted and means that no special HTTP request properties will be used in any * future XML-RPC invocations using this XmlRpcClient instance. * * @param requestProperties The HTTP request properties to use for future invocations * made using this XmlRpcClient instance. These will replace * any previous properties set using this method or the * setRequestProperty() method. */ public void setRequestProperties( Map requestProperties ) { this.requestProperties = requestProperties; } /** * Sets a single HTTP request property to be used in future invocations. * @see setRequestProperties() * * @param name Name of the property to set * @param value The value of the property */ public void setRequestProperty( String name, String value ) { if ( requestProperties == null ) { requestProperties = new HashMap(); } requestProperties.put( name, value ); } /** * Invokes a method on the terminating XML-RPC end point. The supplied method name and * argument collection is used to encode the call into an XML-RPC compatible message. * * @param method The name of the method to call. * * @param arguments The arguments to encode in the call. * * @return The object returned from the terminating XML-RPC end point. * * @throws XmlRpcException One or more of the supplied arguments are unserializable. That is, * the built-in serializer connot parse it or find a custom serializer * that can. There may also be problems with the socket communication. * @throws */ public synchronized Object invoke( String method, List arguments ) throws XmlRpcException, XmlRpcFault { beginCall( method ); if ( arguments != null ) { Iterator argIter = arguments.iterator(); while ( argIter.hasNext() ) { try { writer.write( "" ); serializer.serialize( argIter.next(), writer ); writer.write( "" ); } catch ( IOException ioe ) { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcClient.NetworkError" ), ioe ); } } } return endCall(); } /** * Invokes a method on the terminating XML-RPC end point. The supplied method name and * argument vector is used to encode the call into XML-RPC. * * @param method The name of the method to call. * * @param arguments The arguments to encode in the call. * * @return The object returned from the terminating XML-RPC end point. * * @throws XmlRpcException One or more of the supplied arguments are unserializable. That is, * the built-in serializer connot parse it or find a custom serializer * that can. There may also be problems with the socket communication. */ public synchronized Object invoke( String method, Object[] arguments ) throws XmlRpcException, XmlRpcFault { beginCall( method ); if ( arguments != null ) { for ( int i = 0; i < arguments.length; ++i ) { try { writer.write( "" ); serializer.serialize( arguments[ i ], writer ); writer.write( "" ); } catch ( IOException ioe ) { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcClient.NetworkError" ), ioe ); } } } return endCall(); } /** * A asynchronous version of invoke performing the call in a separate thread and * reporting responses, faults, and exceptions through the supplied XmlRpcCallback. * TODO Determine on proper strategy for instantiating Threads. * * @param method The name of the method at the server. * * @param arguments The arguments for the call. This may be either a java.util.List * descendant, or a java.lang.Object[] array. * * @param callback An object implementing the XmlRpcCallback interface. If callback is * null, the call will be performed but any results, faults, or exceptions * will be ignored (fire and forget). */ public void invokeAsynchronously( final String method, final Object arguments, final XmlRpcCallback callback ) { if ( callback == null ) { new Thread() { public void run() { try // Just fire and forget. { if ( arguments instanceof Object[] ) invoke( method, ( Object[] ) arguments ); else invoke( method, ( List ) arguments ); } catch ( XmlRpcFault e ) { /* Ignore, no callback. */ } catch ( XmlRpcException e ) { /* Ignore, no callback. */ } } }.start(); } else { new Thread() { public void run() { Object result = null; try { if ( arguments instanceof Object[] ) result = invoke( method, ( Object[] ) arguments ); else result = invoke( method, ( List ) arguments ); callback.onResult( result ); } catch ( XmlRpcException e ) { callback.onException( e ); } catch ( XmlRpcFault e ) { XmlRpcStruct fault = ( XmlRpcStruct ) result; callback.onFault( fault.getInteger( "faultCode" ), fault.getString( "faultString" ) ); } } }.start(); } } /** * Initializes the XML buffer to be sent to the server with the XML-RPC * content common to all method calls, or serializes it directly over the writer * if streaming is used. The parameters to the call are added in the execute() * method, and the closing tags are appended when the call is finalized in endCall(). * * @param methodName The name of the method to call. */ private void beginCall( String methodName ) throws XmlRpcException { try { if ( streamMessages ) { openConnection(); writer = new BufferedWriter( new OutputStreamWriter( connection.getOutputStream(), XmlRpcMessages.getString( "XmlRpcClient.Encoding" ) ) ); } else { ( ( StringWriter ) writer ).getBuffer().setLength( 0 ); } writer.write( "" ); writer.write( "" ); writer.write( methodName ); writer.write( "" ); } catch( IOException ioe ) { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcClient.NetworkError" ), ioe ); } } /** * Finalizaes the XML buffer to be sent to the server, and creates a HTTP buffer for * the call. Both buffers are combined into an XML-RPC message that is sent over * a socket to the server. * * @return The parsed return value of the call. * * @throws XmlRpcException when some IO problem occur. */ private Object endCall() throws XmlRpcException, XmlRpcFault { try { writer.write( "" ); writer.write( "" ); if ( streamMessages ) { writer.flush(); } else { StringBuffer buffer = ( ( StringWriter ) writer ).getBuffer(); openConnection(); connection.setRequestProperty( "Content-Length", String.valueOf( buffer.length() ) ); OutputStream output = new BufferedOutputStream( connection.getOutputStream() ); output.write( buffer.toString().getBytes() ); output.flush(); output.close(); } handleResponse(); } catch ( IOException ioe ) { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcClient.NetworkError" ), ioe ); } finally { try { writer.close(); } catch( IOException ignore ) { /* Closed or not, we don't care at this point. */ } connection.disconnect(); connection = null; } return returnValue; } /** * Handles the response returned by the XML-RPC server. If the server responds with a * "non-200"-HTTP response or if the XML payload is unparseable, this is interpreted * as an error in communication and will result in an XmlRpcException.

* * If the user does not want the socket to be kept alive or if the server does not * support keep-alive, the socket is closed. * * @param inout The stream containing the server response to interpret. * * @throws IOException If a socket error occurrs, or if the XML returned is unparseable. * This exception is currently also thrown if a HTTP response other * than "200 OK" is received. * @throws XmlRpcFault */ private void handleResponse() throws XmlRpcFault { try { parse( new BufferedInputStream( connection.getInputStream() ) ); } catch ( Exception e ) { throw new XmlRpcException( XmlRpcMessages.getString( "XmlRpcClient.ParseError" ), e ); } if ( isFaultResponse ) { XmlRpcStruct fault = ( XmlRpcStruct ) returnValue; isFaultResponse = false; throw new XmlRpcFault( fault.getInteger( "faultCode" ), fault.getString( "faultString" ) ); } } /** * Override the startElement() method inherited from XmlRpcParser. This way, we may set * the error flag if we run into a fault-tag. * * @param See SAX documentation */ public void startElement( String uri, String name, String qualifiedName, Attributes attributes ) throws SAXException { if ( name.equals( "fault" ) ) { isFaultResponse = true; } else { super.startElement( uri, name, qualifiedName, attributes ); } } /** * Stores away the one and only value contained in XML-RPC responses. * * @param value The contained return value. */ protected void handleParsedValue( Object value ) { returnValue = value; } /** * Opens a connection to the URL associated with the client instance. Any * HTTP request properties set using setRequestProperties() are recorded * with the internal HttpURLConnection and are used in the HTTP request. * * @throws IOException If a connection could not be opened. The exception * is propagated out of any unsuccessful calls made into * the internal java.net.HttpURLConnection. */ private void openConnection() throws IOException { connection = ( HttpURLConnection ) url.openConnection(); connection.setDoInput( true ); connection.setDoOutput( true ); connection.setRequestMethod( "POST" ); connection.setRequestProperty( "Content-Type", "text/xml; charset=" + XmlRpcMessages.getString( "XmlRpcClient.Encoding" ) ); if ( requestProperties != null ) { for ( Iterator propertyNames = requestProperties.keySet().iterator(); propertyNames.hasNext(); ) { String propertyName = ( String ) propertyNames.next(); connection.setRequestProperty( propertyName, ( String ) requestProperties.get( propertyName ) ); } } } /** The server URL. */ private URL url; /** Connection to the server. */ private HttpURLConnection connection; /** HTTP request properties, or null if none have been set by the application. */ private Map requestProperties; /** The parsed value returned in a response. */ private Object returnValue; /** Writer to which XML-RPC messages are serialized. */ private Writer writer; /** Indicates wheter or not we shall stream the message directly or build them locally? */ private boolean streamMessages; /** Indicates whether or not the incoming response is a fault response. */ private boolean isFaultResponse; /** The serializer used to serialize arguments. */ private XmlRpcSerializer serializer = new XmlRpcSerializer(); }redstone-xmlrpc-1.1/.project0000644000175000017500000000063610435021152015122 0ustar chuckchuck xmlrpc utilities org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature redstone-xmlrpc-1.1/.classpath0000644000175000017500000000070210435021152015430 0ustar chuckchuck