Java Code Examples for java.rmi.Remote

The following examples show how to use java.rmi.Remote. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdk8u_jdk   Source File: UnicastServerRef.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Export this object, create the skeleton and stubs for this
 * dispatcher.  Create a stub based on the type of the impl,
 * initialize it with the appropriate remote reference. Create the
 * target defined by the impl, dispatcher (this) and stub.
 * Export that target via the Ref.
 */
public Remote exportObject(Remote impl, Object data,
                           boolean permanent)
    throws RemoteException
{
    Class<?> implClass = impl.getClass();
    Remote stub;

    try {
        stub = Util.createProxy(implClass, getClientRef(), forceStubUse);
    } catch (IllegalArgumentException e) {
        throw new ExportException(
            "remote object implements illegal remote interface", e);
    }
    if (stub instanceof RemoteStub) {
        setSkeleton(impl);
    }

    Target target =
        new Target(impl, this, stub, ref.getObjID(), permanent);
    ref.exportObject(target);
    hashToMethod_Map = hashToMethod_Maps.get(implClass);
    return stub;
}
 
Example 2
public Object copy(Object obj) {
    if (obj instanceof Remote) {
        // Yes, so make sure it is connected and converted
        // to a stub (if needed)...
        return Utility.autoConnect(obj,orb,true);
    }

    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream( 10000 ) ;
        ObjectOutputStream oos = new ObjectOutputStream( os ) ;
        oos.writeObject( obj ) ;

        byte[] arr = os.toByteArray() ;
        InputStream is = new ByteArrayInputStream( arr ) ;
        ObjectInputStream ois = new ObjectInputStream( is ) ;

        return ois.readObject();
    } catch (Exception exc) {
        System.out.println( "Failed with exception:" + exc ) ;
        return null ;
    }
}
 
Example 3
Source Project: jdk8u-jdk   Source File: UnicastServerRef.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Discovers and sets the appropriate skeleton for the impl.
 */
public void setSkeleton(Remote impl) throws RemoteException {
    if (!withoutSkeletons.containsKey(impl.getClass())) {
        try {
            skel = Util.createSkeleton(impl);
        } catch (SkeletonNotFoundException e) {
            /*
             * Ignore exception for skeleton class not found, because a
             * skeleton class is not necessary with the 1.2 stub protocol.
             * Remember that this impl's class does not have a skeleton
             * class so we don't waste time searching for it again.
             */
            withoutSkeletons.put(impl.getClass(), null);
        }
    }
}
 
Example 4
public static void main(String[] args) throws Exception {
    System.err.println("\nRegression test for bug 6275081\n");

    Remote impl = new Remote() { };
    long start = System.currentTimeMillis();
    for (int i = 0; i < REPS; i++) {
        System.err.println(i);
        UnicastRemoteObject.exportObject(impl, PORT);
        UnicastRemoteObject.unexportObject(impl, true);
        Thread.sleep(1);    // work around BindException (bug?)
    }
    long delta = System.currentTimeMillis() - start;
    System.err.println(REPS + " export/unexport operations took " +
                       delta + "ms");
    if (delta > TIMEOUT) {
        throw new Error("TEST FAILED: took over " + TIMEOUT + "ms");
    }
    System.err.println("TEST PASSED");
}
 
Example 5
Source Project: JavaRushTasks   Source File: Solution.java    License: MIT License 6 votes vote down vote up
@Override
public void run() {
    //напишите тут ваш код
    try {
        //создание объекта для удаленного доступа
        final Animal cat = new Cat("Barsik");
        final Animal dog = new Dog("Palkan");

        //создание реестра расшареных объетов
        registry = LocateRegistry.createRegistry(2099);

        //создание "заглушки" – приемника удаленных вызовов
        Remote stubCat = UnicastRemoteObject.exportObject(cat, 0);
        Remote stubDog = UnicastRemoteObject.exportObject(dog, 0);

        //регистрация "заглушки" в реесте
        registry.bind(BINDING_NAME1, stubCat);
        registry.bind(BINDING_NAME2, stubDog);

    } catch (RemoteException | AlreadyBoundException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source Project: dragonwell8_jdk   Source File: Activation.java    License: GNU General Public License v2.0 6 votes vote down vote up
synchronized MarshalledObject<? extends Remote>
    activate(ActivationID id,
             boolean force,
             ActivationInstantiator inst)
    throws RemoteException, ActivationException
{
    MarshalledObject<? extends Remote> nstub = stub;
    if (removed) {
        throw new UnknownObjectException("object removed");
    } else if (!force && nstub != null) {
        return nstub;
    }

    nstub = inst.newInstance(id, desc);
    stub = nstub;
    /*
     * stub could be set to null by a group reset, so return
     * the newstub here to prevent returning null.
     */
    return nstub;
}
 
Example 7
Source Project: openjdk-8   Source File: RemoteToCorba.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the CORBA object for a Remote object.
 * If input is not a Remote object, or if Remote object uses JRMP, return null.
 * If the RMI-IIOP library is not available, throw ConfigurationException.
 *
 * @param orig The object to turn into a CORBA object. If not Remote,
 *             or if is a JRMP stub or impl, return null.
 * @param name Ignored
 * @param ctx The non-null CNCtx whose ORB to use.
 * @param env Ignored
 * @return The CORBA object for <tt>orig</tt> or null.
 * @exception ConfigurationException If the CORBA object cannot be obtained
 *    due to configuration problems, for instance, if RMI-IIOP not available.
 * @exception NamingException If some other problem prevented a CORBA
 *    object from being obtained from the Remote object.
 */
public Object getStateToBind(Object orig, Name name, Context ctx,
    Hashtable<?,?> env) throws NamingException {
    if (orig instanceof org.omg.CORBA.Object) {
        // Already a CORBA object, just use it
        return null;
    }

    if (orig instanceof Remote) {
        // Turn remote object into org.omg.CORBA.Object
        try {
            // Returns null if JRMP; let next factory try
            // CNCtx will eventually throw IllegalArgumentException if
            // no CORBA object gotten
            return
                CorbaUtils.remoteToCorba((Remote)orig, ((CNCtx)ctx)._orb);
        } catch (ClassNotFoundException e) {
            // RMI-IIOP library not available
            throw new ConfigurationException(
                "javax.rmi packages not available");
        }
    }
    return null; // pass and let next state factory try
}
 
Example 8
Source Project: jdk8u60   Source File: ExportObjs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Export remote objects.
 * Arguments: <# objects>
 */
public long run(String[] args) throws Exception {
    int size = Integer.parseInt(args[0]);
    Remote[] objs = new Remote[size];
    for (int i = 0; i < size; i++)
        objs[i] = new RemoteObj();

    long start = System.currentTimeMillis();
    for (int i = 0; i < size; i++)
        UnicastRemoteObject.exportObject(objs[i],0);
    long time = System.currentTimeMillis() - start;

    for (int i = 0; i < size; i++)
        UnicastRemoteObject.unexportObject(objs[i], true);
    return time;
}
 
Example 9
public Object copy(Object obj) {
    if (obj instanceof Remote) {
        // Yes, so make sure it is connected and converted
        // to a stub (if needed)...
        return Utility.autoConnect(obj,orb,true);
    }

    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream( 10000 ) ;
        ObjectOutputStream oos = new ObjectOutputStream( os ) ;
        oos.writeObject( obj ) ;

        byte[] arr = os.toByteArray() ;
        InputStream is = new ByteArrayInputStream( arr ) ;
        ObjectInputStream ois = new ObjectInputStream( is ) ;

        return ois.readObject();
    } catch (Exception exc) {
        System.out.println( "Failed with exception:" + exc ) ;
        return null ;
    }
}
 
Example 10
Source Project: dragonwell8_jdk   Source File: TestLibrary.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** routine to unexport an object */
public static void unexport(Remote obj) {
    if (obj != null) {
        try {
            mesg("unexporting object...");
            UnicastRemoteObject.unexportObject(obj, true);
        } catch (NoSuchObjectException munch) {
        } catch (Exception e) {
            e.getMessage();
            e.printStackTrace();
        }
    }
}
 
Example 11
/**
 * <p>Returns an IIOP stub.</p>
 * The stub might not yet be connected to the ORB. The stub will
 * be serializable only if it is connected to the ORB.
 * @return an IIOP stub.
 * @exception IOException if the stub cannot be created - e.g the
 *            RMIIIOPServerImpl has not been exported yet.
 **/
public Remote toStub() throws IOException {
    // javax.rmi.CORBA.Stub stub =
    //    (javax.rmi.CORBA.Stub) PortableRemoteObject.toStub(this);
    final Remote stub = IIOPHelper.toStub(this);
    // java.lang.System.out.println("NON CONNECTED STUB " + stub);
    // org.omg.CORBA.ORB orb =
    //    org.omg.CORBA.ORB.init((String[])null, (Properties)null);
    // stub.connect(orb);
    // java.lang.System.out.println("CONNECTED STUB " + stub);
    return stub;
}
 
Example 12
/**
 * Returns a stub for the given server object.
 * @param obj the server object for which a stub is required. Must either be a subclass
 * of PortableRemoteObject or have been previously the target of a call to
 * {@link #exportObject}.
 * @return the most derived stub for the object.
 * @exception NoSuchObjectException if a stub cannot be located for the given server object.
 */
public static Remote toStub (Remote obj)
    throws NoSuchObjectException {

    if (proDelegate != null) {
        return proDelegate.toStub(obj);
    }
    return null;
}
 
Example 13
Source Project: dragonwell8_jdk   Source File: Target.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a Target for a remote object "impl" with
 * a specific object id.
 *
 * If "permanent" is true, then the impl is pinned permanently
 * (the impl will not be collected via distributed and/or local
 * GC).  If "on" is false, than the impl is subject to
 * collection. Permanent objects do not keep a server from
 * exiting.
 */
public Target(Remote impl, Dispatcher disp, Remote stub, ObjID id,
              boolean permanent)
{
    this.weakImpl = new WeakRef(impl, ObjectTable.reapQueue);
    this.disp = disp;
    this.stub = stub;
    this.id = id;
    this.acc = AccessController.getContext();

    /*
     * Fix for 4149366: so that downloaded parameter types unmarshalled
     * for this impl will be compatible with types known only to the
     * impl class's class loader (when it's not identical to the
     * exporting thread's context class loader), mark the impl's class
     * loader as the loader to use as the context class loader in the
     * server's dispatch thread while a call to this impl is being
     * processed (unless this exporting thread's context class loader is
     * a child of the impl's class loader, such as when a registry is
     * exported by an application, in which case this thread's context
     * class loader is preferred).
     */
    ClassLoader threadContextLoader =
        Thread.currentThread().getContextClassLoader();
    ClassLoader serverLoader = impl.getClass().getClassLoader();
    if (checkLoaderAncestry(threadContextLoader, serverLoader)) {
        this.ccl = threadContextLoader;
    } else {
        this.ccl = serverLoader;
    }

    this.permanent = permanent;
    if (permanent) {
        pinImpl();
    }
}
 
Example 14
Source Project: jdk8u-jdk   Source File: Target.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a Target for a remote object "impl" with
 * a specific object id.
 *
 * If "permanent" is true, then the impl is pinned permanently
 * (the impl will not be collected via distributed and/or local
 * GC).  If "on" is false, than the impl is subject to
 * collection. Permanent objects do not keep a server from
 * exiting.
 */
public Target(Remote impl, Dispatcher disp, Remote stub, ObjID id,
              boolean permanent)
{
    this.weakImpl = new WeakRef(impl, ObjectTable.reapQueue);
    this.disp = disp;
    this.stub = stub;
    this.id = id;
    this.acc = AccessController.getContext();

    /*
     * Fix for 4149366: so that downloaded parameter types unmarshalled
     * for this impl will be compatible with types known only to the
     * impl class's class loader (when it's not identical to the
     * exporting thread's context class loader), mark the impl's class
     * loader as the loader to use as the context class loader in the
     * server's dispatch thread while a call to this impl is being
     * processed (unless this exporting thread's context class loader is
     * a child of the impl's class loader, such as when a registry is
     * exported by an application, in which case this thread's context
     * class loader is preferred).
     */
    ClassLoader threadContextLoader =
        Thread.currentThread().getContextClassLoader();
    ClassLoader serverLoader = impl.getClass().getClassLoader();
    if (checkLoaderAncestry(threadContextLoader, serverLoader)) {
        this.ccl = threadContextLoader;
    } else {
        this.ccl = serverLoader;
    }

    this.permanent = permanent;
    if (permanent) {
        pinImpl();
    }
}
 
Example 15
Source Project: openjdk-jdk8u   Source File: SelfTerminator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        int registryPort =
            Integer.parseInt(System.getProperty("rmi.registry.port"));
        Registry registry =
            LocateRegistry.getRegistry("", registryPort);
        Remote stub = registry.lookup(LeaseCheckInterval.BINDING);
        Runtime.getRuntime().halt(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source Project: hottub   Source File: UnicastServerRef.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Log the details of an incoming call.  The method parameter is either of
 * type java.lang.reflect.Method or java.rmi.server.Operation.
 */
private void logCall(Remote obj, Object method) {
    if (callLog.isLoggable(Log.VERBOSE)) {
        String clientHost;
        try {
            clientHost = getClientHost();
        } catch (ServerNotActiveException snae) {
            clientHost = "(local)"; // shouldn't happen
        }
        callLog.log(Log.VERBOSE, "[" + clientHost + ": " +
                          obj.getClass().getName() +
                          ref.getObjID().toString() + ": " +
                          method + "]");
    }
}
 
Example 17
Source Project: openjdk-jdk9   Source File: Activation.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void activeObject(ActivationID id,
                         MarshalledObject<? extends Remote> mobj)
    throws UnknownObjectException, RemoteException
{
    try {
        checkShutdown();
    } catch (ActivationException e) {
        return;
    }
    RegistryImpl.checkAccess("ActivationSystem.activeObject");
    getGroupEntry(id).activeObject(id, mobj);
}
 
Example 18
Source Project: openjdk-jdk9   Source File: RMIExporterTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Remote exportObject(Remote obj,
                           int port,
                           RMIClientSocketFactory csf,
                           RMIServerSocketFactory ssf)
    throws RemoteException {
    System.out.println("CustomRMIExporter::exportObject():: " +
                       "Remote = " + obj);
    if (obj.toString().startsWith(
            "javax.management.remote.rmi.RMIJRMPServerImpl"))
        rmiServerExported = true;
    if (obj.toString().startsWith(
            "javax.management.remote.rmi.RMIConnectionImpl"))
        rmiConnectionExported = true;
    return UnicastRemoteObject.exportObject(obj, port, csf, ssf);
}
 
Example 19
/**
 * Checks for objects that are instances of java.rmi.Remote
 * that need to be serialized as proxy objects.
 */
protected final Object replaceObject(Object obj) throws IOException {
    if ((obj instanceof Remote) && !(obj instanceof RemoteStub)) {
        Target target = ObjectTable.getTarget((Remote) obj);
        if (target != null) {
            return target.getStub();
        }
    }
    return obj;
}
 
Example 20
public boolean unexportObject(Remote obj, boolean force)
    throws NoSuchObjectException {
    System.out.println("CustomRMIExporter::unexportObject():: " +
                       "Remote = " + obj);
    if (obj.toString().startsWith(
            "javax.management.remote.rmi.RMIJRMPServerImpl"))
        rmiServerUnexported = true;
    if (obj.toString().startsWith(
            "javax.management.remote.rmi.RMIConnectionImpl"))
        rmiConnectionUnexported = true;
    return UnicastRemoteObject.unexportObject(obj, force);
}
 
Example 21
public void runClient(Remote stub) throws IOException {
    System.out.println("Inside HelloClient::runClient");
    // "obj" is the identifier that we'll use to refer
    // to the remote object that implements the "Hello"
    // interface
    Hello obj = (Hello) stub;
    String message = obj.sayHello();
    System.out.println(message);
}
 
Example 22
Source Project: JDKSourceCode1.8   Source File: PortableRemoteObject.java    License: MIT License 5 votes vote down vote up
/**
 * Makes a server object ready to receive remote calls. Note
 * that subclasses of PortableRemoteObject do not need to call this
 * method, as it is called by the constructor.
 * @param obj the server object to export.
 * @exception RemoteException if export fails.
 */
public static void exportObject(Remote obj)
    throws RemoteException {

    // Let the delegate do everything, including error handling.
    if (proDelegate != null) {
        proDelegate.exportObject(obj);
    }
}
 
Example 23
Source Project: java-technology-stack   Source File: RmiClientInterceptor.java    License: MIT License 5 votes vote down vote up
/**
 * Return the RMI stub to use. Called for each invocation.
 * <p>The default implementation returns the stub created on initialization,
 * if any. Else, it invokes {@link #lookupStub} to get a new stub for
 * each invocation. This can be overridden in subclasses, for example in
 * order to cache a stub for a given amount of time before recreating it,
 * or to test the stub whether it is still alive.
 * @return the RMI stub to use for an invocation
 * @throws RemoteLookupFailureException if RMI stub creation failed
 * @see #lookupStub
 */
protected Remote getStub() throws RemoteLookupFailureException {
	if (!this.cacheStub || (this.lookupStubOnStartup && !this.refreshStubOnConnectFailure)) {
		return (this.cachedStub != null ? this.cachedStub : lookupStub());
	}
	else {
		synchronized (this.stubMonitor) {
			if (this.cachedStub == null) {
				this.cachedStub = lookupStub();
			}
			return this.cachedStub;
		}
	}
}
 
Example 24
Source Project: jdk8u-jdk   Source File: RMIJRMPServerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void unexport(Remote obj, boolean force)
        throws NoSuchObjectException {
    RMIExporter exporter =
        (RMIExporter) env.get(RMIExporter.EXPORTER_ATTRIBUTE);
    if (exporter == null)
        UnicastRemoteObject.unexportObject(obj, force);
    else
        exporter.unexportObject(obj, force);
}
 
Example 25
Source Project: JDKSourceCode1.8   Source File: Util.java    License: MIT License 5 votes vote down vote up
/**
     * Removes the associated tie from an internal table and calls {@link
Tie#deactivate}
     * to deactivate the object.
     * @param target the object to unexport.
     */
    public static void unexportObject(java.rmi.Remote target)
        throws java.rmi.NoSuchObjectException
    {

        if (utilDelegate != null) {
            utilDelegate.unexportObject(target);
        }

    }
 
Example 26
Source Project: hottub   Source File: PortableRemoteObject.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a stub for the given server object.
 * @param obj the server object for which a stub is required. Must either be a subclass
 * of PortableRemoteObject or have been previously the target of a call to
 * {@link #exportObject}.
 * @return the most derived stub for the object.
 * @exception NoSuchObjectException if a stub cannot be located for the given server object.
 */
public static Remote toStub (Remote obj)
    throws NoSuchObjectException {

    if (proDelegate != null) {
        return proDelegate.toStub(obj);
    }
    return null;
}
 
Example 27
Source Project: openjdk-8   Source File: DGCImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Void run() {
    ClassLoader savedCcl =
        Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(
            ClassLoader.getSystemClassLoader());

        /*
         * Put remote collector object in table by hand to prevent
         * listen on port.  (UnicastServerRef.exportObject would
         * cause transport to listen.)
         */
        try {
            dgc = new DGCImpl();
            ObjID dgcID = new ObjID(ObjID.DGC_ID);
            LiveRef ref = new LiveRef(dgcID, 0);
            UnicastServerRef disp = new UnicastServerRef(ref);
            Remote stub =
                Util.createProxy(DGCImpl.class,
                                 new UnicastRef(ref), true);
            disp.setSkeleton(dgc);
            Target target =
                new Target(dgc, disp, stub, dgcID, true);
            ObjectTable.putTarget(target);
        } catch (RemoteException e) {
            throw new Error(
                "exception initializing server-side DGC", e);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(savedCcl);
    }
    return null;
}
 
Example 28
public Object invoke(Remote obj,
                     Method method,
                     Object[] params,
                     long opnum)
{
    throw new UnsupportedOperationException();
}
 
Example 29
public Object invoke(Remote obj,
                     Method method,
                     Object[] params,
                     long opnum)
{
    throw new UnsupportedOperationException();
}
 
Example 30
Source Project: jdk8u-jdk   Source File: Activation.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void rebind(String name, Remote obj)
    throws RemoteException, AccessException
{
    if (name.equals(NAME)) {
        throw new AccessException(
            "binding ActivationSystem is disallowed");
    } else {
        super.rebind(name, obj);
    }
}