/**
   * Adapts the source object to a view object.
   *
   * @param mapper An action that is invoked for each source object in the graph that is to be
   *     adapted. The action can influence how the source object is adapted via the provided {@link
   *     SourceObjectMapping}.
   */
  public <T, S> T adapt(
      Class<T> targetType, S sourceObject, Action<? super SourceObjectMapping> mapper) {
    if (sourceObject == null) {
      return null;
    }
    Class<? extends T> wrapperType = targetTypeProvider.getTargetType(targetType, sourceObject);
    DefaultSourceObjectMapping mapping =
        new DefaultSourceObjectMapping(sourceObject, targetType, wrapperType);
    mapper.execute(mapping);
    wrapperType = mapping.wrapperType.asSubclass(targetType);
    if (wrapperType.isInstance(sourceObject)) {
      return wrapperType.cast(sourceObject);
    }
    if (targetType.isEnum()) {
      return adaptToEnum(targetType, sourceObject);
    }

    MixInMethodInvoker mixInMethodInvoker = null;
    if (mapping.mixInType != null) {
      mixInMethodInvoker =
          new MixInMethodInvoker(
              mapping.mixInType, new AdaptingMethodInvoker(mapper, new ReflectionMethodInvoker()));
    }
    MethodInvoker overrideInvoker = chainInvokers(mixInMethodInvoker, mapping.overrideInvoker);
    Object proxy =
        Proxy.newProxyInstance(
            wrapperType.getClassLoader(),
            new Class<?>[] {wrapperType},
            new InvocationHandlerImpl(sourceObject, overrideInvoker, mapper));
    if (mixInMethodInvoker != null) {
      mixInMethodInvoker.setProxy(proxy);
    }
    return wrapperType.cast(proxy);
  }
    public Object invoke(Object target, Method method, Object[] params) throws Throwable {
      if (EQUALS_METHOD.equals(method)) {
        Object param = params[0];
        if (param == null || !Proxy.isProxyClass(param.getClass())) {
          return false;
        }
        InvocationHandler other = Proxy.getInvocationHandler(param);
        return equals(other);
      } else if (HASHCODE_METHOD.equals(method)) {
        return hashCode();
      }

      MethodInvocation invocation =
          new MethodInvocation(
              method.getName(),
              method.getReturnType(),
              method.getGenericReturnType(),
              method.getParameterTypes(),
              delegate,
              params);
      invoker.invoke(invocation);
      if (!invocation.found()) {
        String methodName =
            method.getDeclaringClass().getSimpleName() + "." + method.getName() + "()";
        throw Exceptions.unsupportedMethod(methodName);
      }
      return invocation.getResult();
    }
 /** Unpacks the source object from a given view object. */
 public Object unpack(Object viewObject) {
   if (!Proxy.isProxyClass(viewObject.getClass())
       || !(Proxy.getInvocationHandler(viewObject) instanceof InvocationHandlerImpl)) {
     throw new IllegalArgumentException("The given object is not a view object");
   }
   InvocationHandlerImpl handler = (InvocationHandlerImpl) Proxy.getInvocationHandler(viewObject);
   return handler.delegate;
 }
 private PersonBean getNonOwnerProxy(PersonBean person) {
   return (PersonBean)
       Proxy.newProxyInstance(
           person.getClass().getClassLoader(),
           person.getClass().getInterfaces(),
           new NonOwnerInvocationHandler(person));
 }
 /**
  * Builds a new AgentMBeanServerConnectionFactory and returns the underlying
  * MBeanServerConnection
  *
  * @return a new MBeanServerConnection
  */
 public MBeanServerConnection build() {
   final String key = buildKey();
   MBeanServerConnection conn = INSTANCES.get(key);
   if (conn == null) {
     synchronized (INSTANCES) {
       conn = INSTANCES.get(key);
       if (conn == null) {
         conn =
             (MBeanServerConnection)
                 Proxy.newProxyInstance(
                     Thread.currentThread().getContextClassLoader(),
                     new Class[] {MBeanServerConnection.class},
                     new AgentMBeanServerConnectionFactory(this));
         INSTANCES.put(key, conn);
         channel
             .getCloseFuture()
             .addListener(
                 new ChannelFutureListener() {
                   @Override
                   public void operationComplete(ChannelFuture future) throws Exception {
                     INSTANCES.remove(key);
                   }
                 });
       }
     }
   }
   return conn;
 }
Example #6
0
 public static Robot newNullRobot(Class<? extends Robot> type) {
   return (Robot)
       Proxy.newProxyInstance(
           NullRobot.class.getClassLoader(),
           new Class[] {Null.class, Robot.class},
           new NullRobotProxyHandler(type));
 }
Example #7
0
 public void write(ONL.Writer wrtr) throws java.io.IOException {
   wrtr.writeString(host);
   wrtr.writeInt(port);
   short cid = 0;
   if (proxy != null) cid = proxy.getConnectionID(this);
   wrtr.writeShort(cid);
 }
Example #8
0
 public boolean connect() {
   ExpCoordinator.printer.print("NCCPConnection.connect", 3);
   if (host.length() == 0) {
     ExpCoordinator.printer.print("NCCPConnection.connect host is not set", 6);
     return false;
   }
   if (proxy == null && nonProxy == null) {
     ExpCoordinator.printer.print("NCCPConnection.connect proxy null");
     return false;
   }
   if (ExpCoordinator.isSPPMon()) return (connectSPPMon());
   if (state == ConnectionEvent.CONNECTION_CLOSED || state == ConnectionEvent.CONNECTION_FAILED) {
     state = ConnectionEvent.CONNECTION_PENDING;
     if (proxy != null) {
       proxy.openConnection(this);
     }
   }
   /*
   if (nonProxy != null && proxy == null)
   {
   	return (nonProxy.connect());
   }
   */
   return true;
 }
Example #9
0
 ConnectionWrapper(Connection con) {
   this.connection =
       (Connection)
           Proxy.newProxyInstance(
               con.getClass().getClassLoader(), con.getClass().getInterfaces(), this);
   m_originConnection = con;
 }
  /**
   * Create a default object of the given type. Prefers constructors with as few arguments as
   * possible. Creates an empty proxy for interfaces.
   *
   * @param type type to instantiate
   * @return default instance
   * @throws Exception if the default instance could not be created
   */
  private static Object instantiateType(Class<?> type) throws Exception {
    if (type.isPrimitive()) return Defaults.defaultValue(type);
    else if (type == Void.class) return null;
    else if (type.isArray()) return Array.newInstance(type, 0);
    else if (type.isInterface())
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          new Class[] {type},
          new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
              return null;
            }
          });

    // Take a constructor with as few params as possible
    Constructor constructor = type.getDeclaredConstructors()[0];
    for (Constructor<?> c : type.getDeclaredConstructors()) {
      if (c.getParameterTypes().length < constructor.getParameterTypes().length) constructor = c;
    }

    Object[] params = new Object[constructor.getParameterTypes().length];
    for (int i = 0; i < constructor.getParameterTypes().length; i++) {
      params[i] = instantiateType(constructor.getParameterTypes()[i]);
    }
    return constructor.newInstance(params);
  }
Example #11
0
 public static SnapshotMBeanServerConnection newSnapshot(MBeanServerConnection mbsc) {
   final InvocationHandler ih = new SnapshotInvocationHandler(mbsc);
   return (SnapshotMBeanServerConnection)
       Proxy.newProxyInstance(
           Snapshot.class.getClassLoader(),
           new Class[] {SnapshotMBeanServerConnection.class},
           ih);
 }
  /**
   * Creates a new proxy with the specified URL. The returned object is a proxy with the interface
   * specified by api.
   *
   * <pre>
   * String url = "http://localhost:8080/ejb/hello");
   * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url);
   * </pre>
   *
   * @param api the interface the proxy class needs to implement
   * @param url the URL where the client object is located.
   * @return a proxy to the object with the specified interface.
   */
  public Object create(Class api, String urlName, ClassLoader loader) throws MalformedURLException {
    URL url = new URL(urlName);

    HessianProxy handler = new HessianProxy(this, url);

    return Proxy.newProxyInstance(
        api.getClassLoader(), new Class[] {api, HessianRemoteObject.class}, handler);
  }
Example #13
0
  public void registerMockedClass(@Nonnull Class<?> mockedType) {
    if (!isMockedClass(mockedType)) {
      if (Proxy.isProxyClass(mockedType)) {
        mockedType = mockedType.getInterfaces()[0];
      }

      mockedClasses.add(mockedType);
    }
  }
Example #14
0
 /**
  * Unwraps the proxy and returns the underlying {@link Dom} object.
  *
  * @return null if the given instance is not actually a proxy to a DOM.
  */
 public static Dom unwrap(ConfigBeanProxy proxy) {
   ConfigBeanProxy configBeanProxy = ConfigSupport.revealProxy(proxy);
   InvocationHandler ih = Proxy.getInvocationHandler(configBeanProxy);
   if (ih instanceof Dom) return (Dom) ih;
   if (ih instanceof ConfigView) {
     return (Dom) ((ConfigView) ih).getMasterView();
   }
   return null;
 }
Example #15
0
 public void read(ONL.Reader rdr) throws java.io.IOException {
   setHost(new String(rdr.readString()));
   setPort(rdr.readInt());
   short cid = (short) rdr.readShort();
   ExpCoordinator.print(
       new String("NCCPConnection.read host:" + getHost() + " port:" + getPort() + " cid:" + cid),
       5);
   if (proxy != null) proxy.setConnectionID(this, cid);
 }
  /**
   * Creates a {@link Proxy} implementation for a given interface, in which all methods are empty.
   * Non-void methods will return a default value according to the return type: {@literal 0} for
   * {@code int}, {@literal null} for a reference type, and so on.
   *
   * <p>The {@code equals}, {@code hashCode}, and {@code toString} methods inherited from {@code
   * java.lang.Object} are overridden with an appropriate implementation in each case: {@code
   * equals} is implemented by comparing the two object references (the proxy instance and the
   * method argument) for equality; {@code hashCode} is implemented to return the identity hash code
   * for the proxy instance; and {@code toString} returns the standard string representation that
   * {@code Object#toString} would have returned.
   *
   * <p>This method is just a convenience for some uses of the <em>Mockups</em> API. In <em>JMockit
   * Expectations</em> in particular, mocked instances will be automatically created and assigned to
   * any mock fields or parameters.
   *
   * @param loader the class loader under which to define the proxy class; usually this would be the
   *     application class loader, which can be obtained from any application class
   * @param interfaceToBeProxied a {@code Class} object for an interface
   * @return the created proxy instance
   * @see #newEmptyProxy(Class)
   * @see #newEmptyProxy(Type...)
   * @see <a
   *     href="http://code.google.com/p/jmockit/source/browse/trunk/samples/orderMngmntWebapp/test/orderMngr/domain/order/OrderRepository_MockupsAPI_Test.java#186">
   *     Example</a>
   */
  public static <E> E newEmptyProxy(ClassLoader loader, Class<E> interfaceToBeProxied) {
    Class<?>[] interfaces =
        loader == null
            ? new Class<?>[] {interfaceToBeProxied}
            : new Class<?>[] {interfaceToBeProxied, EmptyProxy.class};

    //noinspection unchecked
    return (E) Proxy.newProxyInstance(loader, interfaces, MockInvocationHandler.INSTANCE);
  }
  private ConnectivitySettings proxyToCs(Proxy proxy, URI uri) {
    ConnectivitySettings cs = new ConnectivitySettings();
    InetSocketAddress isa = (InetSocketAddress) proxy.address();
    switch (proxy.type()) {
      case HTTP:
        setupProxy(cs, ConnectivitySettings.CONNECTION_VIA_HTTPS, isa);
        break;
      case SOCKS:
        setupProxy(cs, ConnectivitySettings.CONNECTION_VIA_SOCKS, isa);
        break;
      default:
    }

    String prosyUser = NetworkSettings.getAuthenticationUsername(uri);
    if (prosyUser != null && !prosyUser.isEmpty()) {
      cs.setProxyUsername(prosyUser);
      cs.setProxyPassword(Keyring.read(NetworkSettings.getKeyForAuthenticationPassword(uri)));
    }
    return cs;
  }
Example #18
0
 public void setConnectionID(short cid) {
   ExpCoordinator.print(
       new String(
           "NCCPConnection.setConnectionID host:"
               + getHost()
               + " port:"
               + getPort()
               + " cid:"
               + cid),
       5);
   if (proxy != null) proxy.setConnectionID(this, cid);
 }
Example #19
0
 public static void main(String[] args) {
   RealObject real = new RealObject();
   consumer(real);
   // Insert a proxy and call again:
   Interface proxy =
       (Interface)
           Proxy.newProxyInstance(
               Interface.class.getClassLoader(),
               new Class[] {Interface.class},
               new DynamicProxyHandler(real));
   consumer(proxy);
 }
Example #20
0
 /**
  * Helper method used to weed out dynamic Proxy types; types that do not expose concrete method
  * API that we could use to figure out automatic Bean (property) based serialization.
  */
 public static boolean isProxyType(Class<?> type) {
   // Then: well-known proxy (etc) classes
   if (Proxy.isProxyClass(type)) {
     return true;
   }
   String name = type.getName();
   // Hibernate uses proxies heavily as well:
   if (name.startsWith("net.sf.cglib.proxy.") || name.startsWith("org.hibernate.proxy.")) {
     return true;
   }
   // Not one of known proxies, nope:
   return false;
 }
Example #21
0
 public void sendMessage(NCCP.Message msg) {
   if (isClosed() || isFailed()) connect();
   if (isConnected()) {
     ExpCoordinator.printer.print("NCCPConnection::sendMessage", 5);
     if (proxy != null) proxy.sendMessage(msg, this);
     else {
       if (nonProxy != null) nonProxy.sendMessage(msg);
     }
   } else // still can't connect
   {
     pendingMessages.add(msg);
   }
 }
Example #22
0
 private static void checkStub(Remote stub, Class<? extends Remote> stubClass) {
   // Check remote stub is from the expected class.
   //
   if (stub.getClass() != stubClass) {
     if (!Proxy.isProxyClass(stub.getClass())) {
       throw new SecurityException("Expecting a " + stubClass.getName() + " stub!");
     } else {
       InvocationHandler handler = Proxy.getInvocationHandler(stub);
       if (handler.getClass() != RemoteObjectInvocationHandler.class) {
         throw new SecurityException(
             "Expecting a dynamic proxy instance with a "
                 + RemoteObjectInvocationHandler.class.getName()
                 + " invocation handler!");
       } else {
         stub = (Remote) handler;
       }
     }
   }
   // Check RemoteRef in stub is from the expected class
   // "sun.rmi.server.UnicastRef2".
   //
   RemoteRef ref = ((RemoteObject) stub).getRef();
   if (ref.getClass() != UnicastRef2.class) {
     throw new SecurityException(
         "Expecting a " + UnicastRef2.class.getName() + " remote reference in stub!");
   }
   // Check RMIClientSocketFactory in stub is from the expected class
   // "javax.rmi.ssl.SslRMIClientSocketFactory".
   //
   LiveRef liveRef = ((UnicastRef2) ref).getLiveRef();
   RMIClientSocketFactory csf = liveRef.getClientSocketFactory();
   if (csf == null || csf.getClass() != SslRMIClientSocketFactory.class) {
     throw new SecurityException(
         "Expecting a "
             + SslRMIClientSocketFactory.class.getName()
             + " RMI client socket factory in stub!");
   }
 }
Example #23
0
 public void close() {
   if (proxy != null && isConnected()) {
     proxy.closeConnection(this);
     setConnected(false);
   } else {
     if (nonProxy != null && isConnected()) {
       try {
         Thread.sleep(1000);
       } catch (java.lang.InterruptedException e2) {
       }
       nonProxy.close();
       setConnected(false);
     }
   }
 }
Example #24
0
 public static final Connection getConnection() throws SQLException {
   Connection conn = conns.get();
   if (conn == null || conn.isClosed()) {
     conn = _getConnection();
     if (conn == null) throw new SQLException("Unabled to get connection.");
     conns.set(conn);
     // RequestContext ctx = RequestContext.get();
     // connectionContext.put(
     // Thread.currentThread().getId(),
     // new ConnectionContext(new Exception(), (ctx != null) ? ctx
     // .ip() : null, (ctx != null) ? ctx.uri() : null,
     // (ctx != null) ? ctx.request().getParameterMap()
     // : null));
   }
   return (show_sql && !Proxy.isProxyClass(conn.getClass()))
       ? new _DebugConnection(conn).getConnection()
       : conn;
 }
Example #25
0
    @Override
    public ConfigBeanProxy compute(final Class<?> proxyType) throws ComputationErrorException {

      ClassLoader cl;
      if (System.getSecurityManager() != null) {
        cl =
            AccessController.doPrivileged(
                new PrivilegedAction<ClassLoader>() {
                  @Override
                  public ClassLoader run() {
                    return proxyType.getClassLoader();
                  }
                });
      } else {
        cl = proxyType.getClassLoader();
      }

      ConfigBeanProxy retVal =
          (ConfigBeanProxy) Proxy.newProxyInstance(cl, new Class[] {proxyType}, dom);

      return retVal;
    }
  /**
   * Create {@link us.ihmc.simulationconstructionset.gui.actions.ActionsTest.MethodCallTester} with
   * a proxy object for the given interface that logs all method calls.
   *
   * @param interfaceClass interface to proxy
   * @param forwardInstance interface implementation that will be called when a call is logged (can
   *     be null)
   * @param <T> interface type
   * @return method tester instance
   */
  private static <T> MethodCallTester<T> createMethodTesterForInterface(
      Class<T> interfaceClass, final T forwardInstance) {
    final List<MethodInvocation> invocations = new ArrayList<>();

    //noinspection unchecked
    T mock =
        (T)
            Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class[] {interfaceClass},
                new InvocationHandler() {
                  @Override
                  public Object invoke(Object proxy, Method method, Object[] args)
                      throws Throwable {
                    invocations.add(new MethodInvocation(method.getName(), args));
                    if (forwardInstance != null) return method.invoke(forwardInstance, args);
                    return null;
                  }
                });

    return new MethodCallTester<>(mock, interfaceClass, invocations);
  }
  /** ** XAConnection interface *** */
  public Connection getConnection() throws SQLException {
    if (logger.logDebug()) debug("PGXAConnection.getConnection called");

    Connection conn = super.getConnection();

    // When we're outside an XA transaction, autocommit
    // is supposed to be true, per usual JDBC convention.
    // When an XA transaction is in progress, it should be
    // false.
    if (state == STATE_IDLE) conn.setAutoCommit(true);

    /*
     * Wrap the connection in a proxy to forbid application from
     * fiddling with transaction state directly during an XA transaction
     */
    ConnectionHandler handler = new ConnectionHandler(conn);
    return (Connection)
        Proxy.newProxyInstance(
            getClass().getClassLoader(),
            new Class[] {Connection.class, PGConnection.class},
            handler);
  }
Example #28
0
 public short getConnectionID() {
   if (proxy != null) return ((short) proxy.getConnectionID(this));
   else return ((short) 0);
 }
Example #29
0
 public void setProxy(Proxy p) {
   proxy = p;
   proxy.addConnection(this);
 }
Example #30
0
 /**
  * Returns the conn.
  *
  * @return Connection
  */
 public Connection getConnection() {
   return (Connection)
       Proxy.newProxyInstance(
           conn.getClass().getClassLoader(), conn.getClass().getInterfaces(), this);
 }