incubator-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From hamm...@apache.org
Subject cvs commit: incubator-altrmi/src/java/org/apache/altrmi/server/impl/adaptors InvocationHandlerAdaptor.java MarshalledInvocationHandlerAdapter.java PublicationAdaptor.java
Date Tue, 15 Jul 2003 07:33:41 GMT
hammant     2003/07/15 00:33:41

  Added:       src/java/org/apache/altrmi/server/impl/adaptors
                        InvocationHandlerAdaptor.java
                        MarshalledInvocationHandlerAdapter.java
                        PublicationAdaptor.java
  Log:
  Big Refactor. Removal of accidental duplicate instances. Make comps more fail-safe
  
  Revision  Changes    Path
  1.1                  incubator-altrmi/src/java/org/apache/altrmi/server/impl/adaptors/InvocationHandlerAdaptor.java
  
  Index: InvocationHandlerAdaptor.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1997-2003 The Apache Software Foundation. All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *    "This product includes software developed by the
   *    Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software
   *    itself, if and wherever such third-party acknowledgments
   *    normally appear.
   *
   * 4. The names "Incubator", "AltRMI", and "Apache Software Foundation"
   *    must not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation. For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.altrmi.server.impl.adaptors;
  
  
  import org.apache.altrmi.server.impl.classretrievers.NoClassRetriever;
  import org.apache.altrmi.server.impl.DefaultServerSideClientContextFactory;
  import org.apache.altrmi.server.impl.Session;
  import org.apache.altrmi.server.impl.DefaultMethodInvocationHandler;
  import org.apache.altrmi.server.impl.ConsoleServerMonitor;
  import org.apache.altrmi.server.impl.DefaultAuthenticator;
  import org.apache.altrmi.server.ServerInvocationHandler;
  import org.apache.altrmi.server.ClassRetriever;
  import org.apache.altrmi.server.ServerMonitor;
  import org.apache.altrmi.server.ServerSideClientContextFactory;
  import org.apache.altrmi.server.MethodInvocationHandler;
  import org.apache.altrmi.server.ClassRetrievalException;
  import org.apache.altrmi.server.Authenticator;
  
  import org.apache.altrmi.common.Reply;
  import org.apache.altrmi.common.Request;
  import org.apache.altrmi.common.SuspendedReply;
  import org.apache.altrmi.common.RequestConstants;
  import org.apache.altrmi.common.MethodRequest;
  import org.apache.altrmi.common.MethodFacadeRequest;
  import org.apache.altrmi.common.MethodAsyncRequest;
  import org.apache.altrmi.common.OpenConnectionRequest;
  import org.apache.altrmi.common.PingReply;
  import org.apache.altrmi.common.RequestFailedReply;
  import org.apache.altrmi.common.Contextualizable;
  import org.apache.altrmi.common.ClientContext;
  import org.apache.altrmi.common.ReplyConstants;
  import org.apache.altrmi.common.MethodReply;
  import org.apache.altrmi.common.MethodFacadeReply;
  import org.apache.altrmi.common.NoSuchSessionReply;
  import org.apache.altrmi.common.MethodNameHelper;
  import org.apache.altrmi.common.NotPublishedReply;
  import org.apache.altrmi.common.MethodFacadeArrayReply;
  import org.apache.altrmi.common.GroupedMethodRequest;
  import org.apache.altrmi.common.LookupRequest;
  import org.apache.altrmi.common.AuthenticationException;
  import org.apache.altrmi.common.ExceptionReply;
  import org.apache.altrmi.common.LookupReply;
  import org.apache.altrmi.common.ClassRequest;
  import org.apache.altrmi.common.ClassReply;
  import org.apache.altrmi.common.ClassRetrievalFailedReply;
  import org.apache.altrmi.common.SameVMReply;
  import org.apache.altrmi.common.OpenConnectionReply;
  import org.apache.altrmi.common.ListReply;
  import org.apache.altrmi.common.GarbageCollectionRequest;
  import org.apache.altrmi.common.InvocationExceptionReply;
  import org.apache.altrmi.common.GarbageCollectionReply;
  import org.apache.altrmi.common.ListMethodsRequest;
  import org.apache.altrmi.common.ListMethodsReply;
  
  import java.rmi.server.UID;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.Vector;
  
  /**
   * Class InvocationHandlerAdaptor
   *
   *
   * @author Paul Hammant
   * @version $Revision: 1.1 $
   */
  public class InvocationHandlerAdaptor extends PublicationAdaptor
      implements ServerInvocationHandler
  {
  
      private static long c_session = 0;
      private static final UID U_ID = new UID((short)20729);
      private Long m_lastSession = new Long( 0 );
      private HashMap m_sessions = new HashMap();
      private boolean m_suspend = false;
      private ClassRetriever m_classRetriever = new NoClassRetriever();
      private Authenticator m_authenticator = new DefaultAuthenticator();
      private ServerMonitor m_serverMonitor;
  
      private ServerSideClientContextFactory m_clientContextFactory;
  
  
      public InvocationHandlerAdaptor(ClassRetriever classRetriever,
                                      Authenticator authenticator,
                                      ServerMonitor serverMonitor,
                                      ServerSideClientContextFactory clientContextFactory)
{
          this.m_classRetriever = classRetriever;
          this.m_authenticator = authenticator;
          this.m_serverMonitor = serverMonitor;
          this.m_clientContextFactory = clientContextFactory;
      }
  
      /**
       * Handle an invocation
       *
       *
       * @param request The request
       *
       * @return The reply.
       *
       */
      public Reply handleInvocation( Request request, Object connectionDetails )
      {
  
          try
          {
              if( m_suspend == true )
              {
                  return new SuspendedReply();
              }
  
              // Method request is positioned first as
              // it is the one we want to be most speedy.
              if( request.getRequestCode() == RequestConstants.METHODREQUEST )
              {
  
                  MethodRequest methodRequest = (MethodRequest) request;
                  setClientContext(methodRequest);
                  return doMethodRequest( methodRequest, connectionDetails );
  
              }
              else if( request.getRequestCode() == RequestConstants.METHODFACADEREQUEST )
              {
                  MethodFacadeRequest methodFacadeRequest = ( MethodFacadeRequest ) request;
                  setClientContext(methodFacadeRequest);
                  return doMethodFacadeRequest( methodFacadeRequest, connectionDetails );
  
              }
              else if( request.getRequestCode() == RequestConstants.METHODASYNCREQUEST )
              {
                  MethodAsyncRequest methodAsyncRequest = ( MethodAsyncRequest ) request;
                  setClientContext(methodAsyncRequest);
                  return doMethodAsyncRequest( methodAsyncRequest, connectionDetails );
  
              }
              else if( request.getRequestCode() == RequestConstants.GCREQUEST )
              {
  
                  return doGarbageCollectionRequest( request );
  
              }
              else if( request.getRequestCode() == RequestConstants.LOOKUPREQUEST )
              {
                  return doLookupRequest( request );
  
              }
              else if( request.getRequestCode() == RequestConstants.CLASSREQUEST )
              {
                  return doClassRequest( request );
  
              }
              else if( request.getRequestCode() == RequestConstants.OPENCONNECTIONREQUEST
)
              {
                  OpenConnectionRequest openConnectionRequest = (OpenConnectionRequest) request;
                  return doOpenConnectionRequest(openConnectionRequest.getMachineID());
  
              }
              else if( request.getRequestCode() == RequestConstants.PINGREQUEST )
              {
  
                  // we could communicate back useful state info in this transaction.
                  return new PingReply();
              }
              else if( request.getRequestCode() == RequestConstants.LISTREQUEST )
              {
                  return doListRequest();
              }
              else if(request.getRequestCode()== RequestConstants.LISTMETHODSREQUEST)
              {
                  return doListMethodsRequest(request);
              }
              else
              {
                  return new RequestFailedReply( "Unknown request :" + request.getClass().getName()
);
              }
          }
          catch (NullPointerException npe)
          {
              npe.printStackTrace();
              if (request instanceof MethodRequest)
              {
                  String methd = ((MethodRequest) request).getMethodSignature();
                  getServerMonitor().unexpectedException(InvocationHandlerAdaptor.class,"InvocationHandlerAdaptor.handleInvocation()
NPE processing method " + methd,npe);
                  throw new NullPointerException("Null pointer exception, processing method
" + methd);
              }
              else
              {
                  getServerMonitor().unexpectedException(InvocationHandlerAdaptor.class,"InvocationHandlerAdaptor.handleInvocation()
NPE",npe);
                  throw npe;
              }
          }
      }
  
      protected synchronized ServerSideClientContextFactory getClientContextFactory()
      {
          if (m_clientContextFactory == null) {
              m_clientContextFactory = new DefaultServerSideClientContextFactory();
          }
          return m_clientContextFactory;
      }
  
      private void setClientContext( Contextualizable request )
      {
          Long session = request.getSession();
          ClientContext clientSideClientContext = request.getContext();
  
          // *always* happens before method invocations.
          getClientContextFactory().set(session, clientSideClientContext);
  
      }
  
  
  
      /**
       * Do a Method Facade Request
       * @param facadeRequest the request
       * @return The reply
       */
      private Reply doMethodFacadeRequest( MethodFacadeRequest facadeRequest, Object connectionDetails
)
      {
  
          if (!sessionExists(facadeRequest.getSession()))
          {
              return new NoSuchSessionReply(facadeRequest.getSession());
          }
  
          String publishedThing = facadeRequest.getPublishedServiceName() + "_"
              + facadeRequest.getObjectName();
  
          if( !isPublished( publishedThing ) )
          {
              return new NotPublishedReply();
          }
  
          //if( !sessionExists( facadeRequest.getSession() ) )
          //{
          //    return new ExceptionReply(
          //        new InvocationException( "TODO - you dirty rat/hacker" ) );
          //}
  
          MethodInvocationHandler methodInvocationHandler =
              getMethodInvocationHandler( publishedThing );
          Reply ar = methodInvocationHandler.handleMethodInvocation( facadeRequest, connectionDetails
);
  
          if( ar.getReplyCode() == ReplyConstants.EXCEPTIONREPLY )
          {
              return ar;
          }
          else if( ar.getReplyCode() >= ReplyConstants.PROBLEMREPLY )
          {
              return ar;
          }
          else if( ar.getReplyCode() == ReplyConstants.METHODREPLY )
          {
              Object methodReply = ( (MethodReply)ar ).getReplyObject();
  
              if( methodReply == null )
              {
                  return new MethodFacadeReply( null, null );    // null passing
              }
              else if( !methodReply.getClass().isArray() )
              {
                  return doMethodFacadeRequestNonArray( methodReply, facadeRequest );
              }
              else
              {
                  return doMethodFacadeRequestArray( methodReply, facadeRequest );
  
              }
          }
          else
          {
              // unknown reply type from
              return new RequestFailedReply( "TODO" );
          }
      }
  
      /**
       * Do a method facade request, returning an array
       * @param methodReply The array to process.
       * @param methodFacadeRequest The request
       * @return The reply
       */
      private Reply doMethodFacadeRequestArray(
              Object methodReply, MethodFacadeRequest methodFacadeRequest )
      {
          Object[] beanImpls = (Object[])methodReply;
          Long[] refs = new Long[ beanImpls.length ];
          String[] objectNames = new String[ beanImpls.length ];
  
          if (!sessionExists(methodFacadeRequest.getSession()))
          {
              return new NoSuchSessionReply(methodFacadeRequest.getSession());
          }
  
          for( int i = 0; i < beanImpls.length; i++ )
          {
              Object impl = beanImpls[ i ];
              MethodInvocationHandler mainMethodInvocationHandler =
                getMethodInvocationHandler(methodFacadeRequest.getPublishedServiceName() +
"_Main" );
  
              objectNames[ i ] = MethodNameHelper.encodeClassName(
                      mainMethodInvocationHandler.getMostDerivedType( beanImpls[ i ] ).getName()
);
  
              MethodInvocationHandler methodInvocationHandler2 =
                  getMethodInvocationHandler( methodFacadeRequest.getPublishedServiceName()
+ "_"
                        + objectNames[ i ] );
  
              if( methodInvocationHandler2 == null )
              {
                  return new NotPublishedReply();
              }
  
              //TODO a decent ref number for main?
              if( beanImpls[ i ] == null )
              {
                  refs[ i ] = null;
              }
              else
              {
                  refs[ i ] =
                      methodInvocationHandler2.getOrMakeReferenceIDForBean( beanImpls[ i ]
);
  
                  Session sess = (Session)m_sessions.get(
                          methodFacadeRequest.getSession() );
  
                  sess.addBeanInUse( refs[ i ], beanImpls[ i ] );
              }
          }
  
          return new MethodFacadeArrayReply( refs, objectNames );
      }
  
      /**
       * Do a method facade request, returning things other that an array
       * @param beanImpl The returned object to process.
       * @param methodFacadeRequest The request
       * @return The reply
       */
      private Reply doMethodFacadeRequestNonArray(
              Object beanImpl, MethodFacadeRequest methodFacadeRequest )
      {
  
          if (!sessionExists(methodFacadeRequest.getSession()))
          {
              return new NoSuchSessionReply(methodFacadeRequest.getSession());
          }
  
          MethodInvocationHandler mainMethodInvocationHandler = getMethodInvocationHandler(
                  methodFacadeRequest.getPublishedServiceName() + "_Main" );
  
          String objectName = MethodNameHelper.encodeClassName(
                  mainMethodInvocationHandler.getMostDerivedType( beanImpl ).getName() );
  
          MethodInvocationHandler methodInvocationHandler =  getMethodInvocationHandler (
                  methodFacadeRequest.getPublishedServiceName() + "_" + objectName );
  
          if( methodInvocationHandler == null )
          {
              return new NotPublishedReply();
          }
  
          //if( !sessionExists( methodFacadeRequest.getSession() ) )
          //{
          //    return new ExceptionReply(
          //        new InvocationException( "TODO - you dirty rat/hacker" ) );
          //}
  
          //TODO a decent ref number for main?
          Long newRef = methodInvocationHandler.getOrMakeReferenceIDForBean( beanImpl );
  
          // make sure the bean is not garbage collected.
          Session sess = (Session)m_sessions.get( methodFacadeRequest.getSession() );
  
          sess.addBeanInUse( newRef, beanImpl );
  
          //long newRef2 = asih2.getOrMakeReferenceIDForBean(beanImpl);
          return new MethodFacadeReply( newRef, objectName );
      }
  
      /**
       * Do a method request
       * @param methodRequest The request
       * @return The reply
       */
      private Reply doMethodRequest( MethodRequest methodRequest, Object connectionDetails
)
      {
  
          if (!sessionExists(methodRequest.getSession()))
          {
              return new NoSuchSessionReply(methodRequest.getSession());
          }
  
          String publishedThing = methodRequest.getPublishedServiceName() + "_" + methodRequest.getObjectName();
  
          if( !isPublished( publishedThing ) )
          {
              return new NotPublishedReply();
          }
  
          MethodInvocationHandler methodInvocationHandler =
              getMethodInvocationHandler( publishedThing );
  
          return methodInvocationHandler.handleMethodInvocation( methodRequest, connectionDetails
);
      }
  
      private Reply doMethodAsyncRequest(MethodAsyncRequest methodRequest, Object connectionDetails)
      {
  
          if (!sessionExists(methodRequest.getSession()))
          {
              return new NoSuchSessionReply(methodRequest.getSession());
          }
  
          String publishedThing = methodRequest.getPublishedServiceName() + "_" + methodRequest.getObjectName();
  
          if( !isPublished( publishedThing ) )
          {
              return new NotPublishedReply();
          }
  
          MethodInvocationHandler methodInvocationHandler =
              getMethodInvocationHandler( publishedThing );
  
          GroupedMethodRequest[] requests = methodRequest.getGroupedRequests();
          for (int i = 0; i < requests.length; i++)
          {
              GroupedMethodRequest rawRequest = requests[i];
              methodInvocationHandler.handleMethodInvocation(
                      new MethodRequest(
                              methodRequest.getPublishedServiceName(),
                              methodRequest.getObjectName(),
                              rawRequest.getMethodSignature(),
                              rawRequest.getArgs(),
                              methodRequest.getReferenceID(),
                              methodRequest.getSession()),
                      connectionDetails
              );
          }
  
          return new MethodReply();
  
      }
  
  
      /**
       * DO a lokkup request
       * @param request The request
       * @return The reply
       */
      private Reply doLookupRequest( Request request )
      {
          LookupRequest lr = (LookupRequest)request;
  
          try
          {
              m_authenticator.checkAuthority( lr.getAuthentication(),
                                                   lr.getPublishedServiceName() );
          }
          catch( AuthenticationException aae )
          {
              return new ExceptionReply( aae );
          }
  
          //TODO a decent ref number for main?
          return new LookupReply( new Long( 0 ) );
      }
  
      /**
       * Do a class request
       * @param request The request
       * @return The reply
       */
      private Reply doClassRequest( Request request )
      {
          ClassRequest cr = (ClassRequest)request;
          String publishedThing = cr.getPublishedServiceName() + "_" + cr.getObjectName();
  
          try
          {
              return new ClassReply( m_classRetriever.getProxyClassBytes( publishedThing ));
          }
          catch( ClassRetrievalException e )
          {
              return new ClassRetrievalFailedReply( e.getMessage() );
          }
      }
  
      /**
       * Do an OpenConnection request
       * @return The reply.
       */
      private Reply doOpenConnectionRequest(UID machineID)
      {
          if (machineID != null && machineID.equals(U_ID))
          {
              return new SameVMReply();
          }
          else
          {
              Long session = getNewSession();
              m_sessions.put( session, new Session( session ) );
              return new OpenConnectionReply( m_authenticator.getTextToSign(), session );
          }
      }
  
      /**
       * Do a ListRequest
       * @return The reply
       */
      private Reply doListRequest()
      {
          //return the list of published objects to the server
          Iterator iterator = getIteratorOfPublishedObjects();
          Vector vecOfPublishedObjectNames = new Vector();
  
          while( iterator.hasNext() )
          {
              final String item = (String)iterator.next();
  
              if( item.endsWith( "_Main" ) )
              {
                  vecOfPublishedObjectNames.add( item.substring( 0, item.lastIndexOf( "_Main"
) ) );
              }
          }
  
          String[] listOfPublishedObjectNames = new String[ vecOfPublishedObjectNames.size()
];
  
          System.arraycopy( vecOfPublishedObjectNames.toArray(), 0, listOfPublishedObjectNames,
                            0, vecOfPublishedObjectNames.size() );
  
          return new ListReply( listOfPublishedObjectNames );
      }
  
      /**
       * Do a GarbageCollection Request
       * @param request The request
       * @return The reply
       */
      private Reply doGarbageCollectionRequest( Request request )
      {
          GarbageCollectionRequest gcr = (GarbageCollectionRequest)request;
          String publishedThing = gcr.getPublishedServiceName() + "_" + gcr.getObjectName();
  
          if( !isPublished( publishedThing ) )
          {
              return new NotPublishedReply();
          }
  
          Long session = gcr.getSession();
          if( !sessionExists( session ) )
          {
              return new InvocationExceptionReply("TODO - you dirty rat/hacker");
          }
  
          Session sess = (Session) m_sessions.get( session );
          if( sess == null )
          {
              System.err.println( "DEBUG- GC on missing session - " + session );
          }
          else
          {
              if( gcr.getReferenceID() == null )
              {
                  System.err.println( "DEBUG- GC on missing referenceID -" + gcr.getReferenceID()
);
              }
              else
              {
                  sess.removeBeanInUse( gcr.getReferenceID() );
              }
          }
  
          MethodInvocationHandler methodInvocationHandler =
              getMethodInvocationHandler( publishedThing );
  
          return new GarbageCollectionReply();
      }
  
      /**
       * Do a ListMethods Request
       * @param request The request
       * @return The reply
       */
      private Reply doListMethodsRequest( Request request )
      {
          ListMethodsRequest lReq = (ListMethodsRequest)request;
          String publishedThing = lReq.getPublishedName() + "_Main";
  
          if( !isPublished( publishedThing ) )
          {
              //Should it throw an exception back?
              return new  ListMethodsReply(new String[0]);
          }
  
          DefaultMethodInvocationHandler methodInvocationHandler =
              (DefaultMethodInvocationHandler)getMethodInvocationHandler( publishedThing );
  
          return new ListMethodsReply(methodInvocationHandler.getListOfMethods());
      }
  
      /**
       * Does a session exist
       * @param session The session
       * @return true if it exists
       */
      private boolean sessionExists( Long session )
      {
  
          if( m_lastSession.equals( session ) )
          {
  
              // buffer last session for performance.
              return true;
          }
          else
          {
              if( m_sessions.containsKey( session ) )
              {
                  m_lastSession = session;
  
                  return true;
              }
          }
  
          return false;
      }
  
  
      /**
       * Get a new session ID
       * @return The session
       */
      private Long getNewSession()
      {
          // approve everything and set session identifier.
          return new Long((++c_session  << 16) + ((long) (Math.random() * 65536)));
      }
  
      /**
       * Suspend an AltRMI service
       *
       */
      public void suspend()
      {
          m_suspend = true;
      }
  
      /**
       * Resume an AltRMI service
       *
       */
      public void resume()
      {
          m_suspend = false;
      }
  
      public void setServerMonitor(ServerMonitor serverMonitor)
      {
          m_serverMonitor = serverMonitor;
      }
  
      public synchronized ServerMonitor getServerMonitor()
      {
          if (m_serverMonitor == null)
          {
              m_serverMonitor = new ConsoleServerMonitor();
          }
          return m_serverMonitor;
      }
  
  }
  
  
  
  1.1                  incubator-altrmi/src/java/org/apache/altrmi/server/impl/adaptors/MarshalledInvocationHandlerAdapter.java
  
  Index: MarshalledInvocationHandlerAdapter.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1997-2003 The Apache Software Foundation. All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *    "This product includes software developed by the
   *    Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software
   *    itself, if and wherever such third-party acknowledgments
   *    normally appear.
   *
   * 4. The names "Incubator", "AltRMI", and "Apache Software Foundation"
   *    must not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation. For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.altrmi.server.impl.adaptors;
  
  import java.io.IOException;
  import org.apache.altrmi.common.Reply;
  import org.apache.altrmi.common.Request;
  import org.apache.altrmi.common.SerializationHelper;
  import org.apache.altrmi.server.ServerInvocationHandler;
  import org.apache.altrmi.server.ServerMarshalledInvocationHandler;
  
  import javax.swing.*;
  
  /**
   * Class MarshalledInvocationHandlerAdapter
   *
   *
   * @author Paul Hammant
   * @version $Revision: 1.1 $
   */
  public class MarshalledInvocationHandlerAdapter implements ServerMarshalledInvocationHandler
  {
  
      /**
       * The invocation hamdeler
       */
      private ServerInvocationHandler m_invocationHandler;
      /**
       * The class loader.
       */
      private ClassLoader m_classLoader;
  
      /**
       * Constructor MarshalledInvocationHandlerAdapter
       *
       *
       * @param invocationHandler The invocation handler
       *
       */
      public MarshalledInvocationHandlerAdapter( ServerInvocationHandler invocationHandler
)
      {
          m_invocationHandler = invocationHandler;
          m_classLoader = getClass().getClassLoader();
      }
  
      /**
       * Constructor MarshalledInvocationHandlerAdapter
       *
       *
       * @param invocationHandler The invocation handler
       * @param classLoader The classloader
       *
       */
      public MarshalledInvocationHandlerAdapter( ServerInvocationHandler invocationHandler,
                                                 ClassLoader classLoader )
      {
          m_invocationHandler = invocationHandler;
          m_classLoader = classLoader;
      }
  
      /**
       * Handle an Invocation
       *
       *
       * @param request The request
       *
       * @return The reply
       *
       */
      public byte[] handleInvocation( byte[] request, Object connectionDetails )
      {
  
          try
          {
              Request ar =
                      (Request) SerializationHelper.getInstanceFromBytes(
                              request, m_classLoader );
              Reply reply = m_invocationHandler.handleInvocation( ar, connectionDetails );
  
              return SerializationHelper.getBytesFromInstance( reply );
          }
          catch( ClassNotFoundException e )
          {
              e.printStackTrace();
  
              return null;
          }
      }
  }
  
  
  
  1.1                  incubator-altrmi/src/java/org/apache/altrmi/server/impl/adaptors/PublicationAdaptor.java
  
  Index: PublicationAdaptor.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1997-2003 The Apache Software Foundation. All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *    "This product includes software developed by the
   *    Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software
   *    itself, if and wherever such third-party acknowledgments
   *    normally appear.
   *
   * 4. The names "Incubator", "AltRMI", and "Apache Software Foundation"
   *    must not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation. For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.altrmi.server.impl.adaptors;
  
  import java.lang.reflect.Method;
  import java.util.HashMap;
  import java.util.Iterator;
  
  import org.apache.altrmi.common.MethodRequest;
  import org.apache.altrmi.common.MethodNameHelper;
  import org.apache.altrmi.server.*;
  import org.apache.altrmi.server.impl.DefaultMethodInvocationHandler;
  
  /**
   * Class PublicationAdaptor
   *
   *
   * @author Paul Hammant
   * @version $Revision: 1.1 $
   */
  public class PublicationAdaptor implements Publisher
  {
  
      /**
       * A map of published objects.
       */
      protected HashMap m_publishedObjects = new HashMap();
  
      /**
       * Is the object published
       * @param publishedObjectName The published object name
       * @return true if published.
       */
      public boolean isPublished(String publishedObjectName)
      {
          return m_publishedObjects.containsKey(publishedObjectName);
      }
  
      /**
       * Get an iterator of published objects
       * @return The iterator
       */
      public Iterator getIteratorOfPublishedObjects()
      {
          return m_publishedObjects.keySet().iterator();
      }
  
      /**
       * Publish an Object
       *
       *
       * @param impl The implementaion to publish
       * @param asName as this name.
       * @param interfaceToExpose The interface to expose.
       * @throws PublicationException if a problem during publication.
       *
       */
      public void publish(Object impl, String asName, Class interfaceToExpose)
              throws PublicationException
      {
          publish(impl, asName,
                  new PublicationDescription(interfaceToExpose));
      }
  
      /**
       * Publish an object
       *
       *
       * @param impl The implementaion to publish
       * @param asName as this name.
       * @param publicationDescription a description of the publication.
       * @throws PublicationException if a problem during publication.
       *
       */
      public void publish(Object impl, String asName,
                          PublicationDescription publicationDescription) throws PublicationException
      {
  
          PublicationDescriptionItem[] interfacesToExpose = publicationDescription.getInterfacesToExpose();
          PublicationDescriptionItem[] additionalFacades = publicationDescription.getAdditionalFacades();
  
          if (m_publishedObjects.containsKey(asName + "_Main"))
          {
              throw new PublicationException("Service '" + asName + "' already published");
          }
  
          String[] interfaceNames = new String[interfacesToExpose.length];
  
          for (int i = 0; i < interfacesToExpose.length; i++)
          {
              interfaceNames[i] = interfacesToExpose[i].getFacadeClass().getName();
          }
  
          // add method maps for main lookup-able service.
          HashMap mainMethodMap = new HashMap();
          DefaultMethodInvocationHandler mainMethodInvocationHandler =
                  new DefaultMethodInvocationHandler(this, asName + "_Main",
                          mainMethodMap, publicationDescription);
  
          mainMethodInvocationHandler.addImplementationBean(new Long(0), impl);
  
          for (int x = 0; x < interfacesToExpose.length; x++)
          {
              Class clazz = interfacesToExpose[x].getFacadeClass();
  
              Method methods[] = null;
              try
              {
                  Method ts = Object.class.getMethod("toString", new Class[0]);
                  Method hc = Object.class.getMethod("hashCode", new Class[0]);
                  Method eq = Object.class.getMethod("equals", new Class[]{Object.class});
                  Method[] interfaceMethods = clazz.getMethods();
                  methods = new Method[interfaceMethods.length + 3];
                  System.arraycopy(interfaceMethods, 0, methods, 0, interfaceMethods.length);
                  methods[interfaceMethods.length] = ts;
                  methods[interfaceMethods.length + 1] = hc;
                  methods[interfaceMethods.length + 2] = eq;
              }
              catch (NoSuchMethodException e)
              {
                  // never!
              }
  
              for (int y = 0; y < methods.length; y++)
              {
                  Method method = methods[y];
                  String methodSignature = MethodNameHelper.getMethodSignature(method);
  
                  if (!mainMethodMap.containsKey(methodSignature.toString()))
                  {
                      mainMethodMap.put(methodSignature.toString(), methods[y]);
                  }
              }
          }
  
          // as the main service is lookup-able, it has a prexisting impl.
          m_publishedObjects.put(asName + "_Main", mainMethodInvocationHandler);
  
          // add method maps for all the additional facades.
          for (int x = 0; x < additionalFacades.length; x++)
          {
              Class facadeClass = additionalFacades[x].getFacadeClass();
              String encodedClassName = MethodNameHelper.encodeClassName(additionalFacades[x].getFacadeClass().getName());
              HashMap methodMap = new HashMap();
              MethodInvocationHandler methodInvocationHandler =
                      new DefaultMethodInvocationHandler(this, asName + "_" + encodedClassName,
                              methodMap, publicationDescription);
  
              Method methods[] = null;
              try
              {
                  Method ts = Object.class.getMethod("toString", new Class[0]);
                  Method hc = Object.class.getMethod("hashCode", new Class[0]);
                  Method eq = Object.class.getMethod("equals", new Class[]{Object.class});
                  Method[] interfaceMethods = facadeClass.getMethods();
                  methods = new Method[interfaceMethods.length + 3];
                  System.arraycopy(interfaceMethods, 0, methods, 0, interfaceMethods.length);
                  methods[interfaceMethods.length] = ts;
                  methods[interfaceMethods.length + 1] = hc;
                  methods[interfaceMethods.length + 2] = eq;
              }
              catch (NoSuchMethodException e)
              {
                  // never!
              }
  
  
              for (int y = 0; y < methods.length; y++)
              {
                  Method method = methods[y];
                  String methodSignature = MethodNameHelper.getMethodSignature(method);
  
                  if (!methodMap.containsKey(methodSignature.toString()))
                  {
                      methodMap.put(methodSignature.toString(), methods[y]);
                  }
              }
  
              m_publishedObjects.put(asName + "_" + encodedClassName, methodInvocationHandler);
          }
      }
  
      /**
       * UnPublish an object
       *
       *
       * @param impl the object to unpublish
       * @param publishedName The name it was published as
       * @throws PublicationException if a problem during publication.
       *
       */
      public void unPublish(Object impl, String publishedName) throws PublicationException
      {
  
          if (!m_publishedObjects.containsKey(publishedName + "_Main"))
          {
              throw new PublicationException("Service '" + publishedName + "' not published");
          }
  
          m_publishedObjects.remove(publishedName + "_Main");
      }
  
      /**
       * Replace a published impl
       *
       *
       * @param oldImpl the old published object
       * @param publishedName The name it was published as
       * @param withImpl The new published impl
       * @throws PublicationException if a problem during publication.
       *
       */
      public void replacePublished(Object oldImpl, String publishedName, Object withImpl)
              throws PublicationException
      {
  
          if (!m_publishedObjects.containsKey(publishedName + "_Main"))
          {
              throw new PublicationException("Service '" + publishedName + "' not published");
          }
  
          MethodInvocationHandler asih =
                  (MethodInvocationHandler) m_publishedObjects.get(publishedName + "_Main");
  
          asih.replaceImplementationBean(oldImpl, withImpl);
      }
  
      /**
       * Get a Server's  InvocationHandler
       *
       *
       * @param methodRequest The method Request.
       * @param objectName The object name.
       *
       * @return the method invoation handler
       *
       */
      public MethodInvocationHandler getMethodInvocationHandler(MethodRequest methodRequest,
                                                                String objectName)
      {
          return (MethodInvocationHandler) m_publishedObjects.get(
                  methodRequest.getPublishedServiceName() + "_" + objectName);
      }
  
      /**
       * Get a method's InvocationHandler
       *
       *
       * @param publishedName The name of a published object
       *
       * @return the method invoation handler
       *
       */
      public MethodInvocationHandler getMethodInvocationHandler(String publishedName)
      {
          return (MethodInvocationHandler) m_publishedObjects.get(publishedName);
      }
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: cvs-unsubscribe@incubator.apache.org
For additional commands, e-mail: cvs-help@incubator.apache.org


Mime
View raw message