java.rmi.Remote Java Examples

The following examples show how to use java.rmi.Remote. 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 File: Solution.java    From JavaRushTasks with 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 #2
Source File: Activation.java    From dragonwell8_jdk with 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 #3
Source File: RapidExportUnexport.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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 #4
Source File: RemoteToCorba.java    From openjdk-8 with 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 #5
Source File: UnicastServerRef.java    From jdk8u-jdk with 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 #6
Source File: ExportObjs.java    From jdk8u60 with 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 #7
Source File: JavaStreamObjectCopierImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source File: UnicastServerRef.java    From jdk8u_jdk with 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 #9
Source File: JavaStreamObjectCopierImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 File: Target.java    From dragonwell8_jdk with 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 #11
Source File: SelfTerminator.java    From TencentKona-8 with 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 #12
Source File: RmiClientInterceptor.java    From java-technology-stack with 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 #13
Source File: RMIJRMPServerImpl.java    From jdk8u-jdk with 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 #14
Source File: Util.java    From JDKSourceCode1.8 with 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 #15
Source File: PortableRemoteObject.java    From hottub with 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 #16
Source File: DGCImpl.java    From openjdk-8 with 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 #17
Source File: UnrecognizedRefType.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Object invoke(Remote obj,
                     Method method,
                     Object[] params,
                     long opnum)
{
    throw new UnsupportedOperationException();
}
 
Example #18
Source File: UnrecognizedRefType.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public Object invoke(Remote obj,
                     Method method,
                     Object[] params,
                     long opnum)
{
    throw new UnsupportedOperationException();
}
 
Example #19
Source File: Activation.java    From jdk8u-jdk with 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);
    }
}
 
Example #20
Source File: RemoteObject.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the stub for the remote object <code>obj</code> passed
 * as a parameter. This operation is only valid <i>after</i>
 * the object has been exported.
 * @param obj the remote object whose stub is needed
 * @return the stub for the remote object, <code>obj</code>.
 * @exception NoSuchObjectException if the stub for the
 * remote object could not be found.
 * @since 1.2
 */
public static Remote toStub(Remote obj) throws NoSuchObjectException {
    if (obj instanceof RemoteStub ||
        (obj != null &&
         Proxy.isProxyClass(obj.getClass()) &&
         Proxy.getInvocationHandler(obj) instanceof
         RemoteObjectInvocationHandler))
    {
        return obj;
    } else {
        return sun.rmi.transport.ObjectTable.getStub(obj);
    }
}
 
Example #21
Source File: TestLibrary.java    From jdk8u_jdk with 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 #22
Source File: Util.java    From Java8CN with Apache License 2.0 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 #23
Source File: Activation.java    From openjdk-jdk8u with 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 {
        RegistryImpl.checkAccess("ActivationSystem.rebind");
        super.rebind(name, obj);
    }
}
 
Example #24
Source File: SelfTerminator.java    From dragonwell8_jdk with 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 #25
Source File: RmiSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void rmiInvokerWithSpecialLocalMethods() throws Exception {
	String serviceUrl = "rmi://localhost:1090/test";
	RmiProxyFactoryBean factory = new RmiProxyFactoryBean() {
		@Override
		protected Remote lookupStub() {
			return new RmiInvocationHandler() {
				@Override
				public String getTargetInterfaceName() {
					return null;
				}
				@Override
				public Object invoke(RemoteInvocation invocation) throws RemoteException {
					throw new RemoteException();
				}
			};
		}
	};
	factory.setServiceInterface(IBusinessBean.class);
	factory.setServiceUrl(serviceUrl);
	factory.afterPropertiesSet();
	IBusinessBean proxy = (IBusinessBean) factory.getObject();

	// shouldn't go through to remote service
	assertTrue(proxy.toString().contains("RMI invoker"));
	assertTrue(proxy.toString().contains(serviceUrl));
	assertEquals(proxy.hashCode(), proxy.hashCode());
	assertTrue(proxy.equals(proxy));

	// should go through
	try {
		proxy.setName("test");
		fail("Should have thrown RemoteAccessException");
	}
	catch (RemoteAccessException ex) {
		// expected
	}
}
 
Example #26
Source File: MarshalAfterUnexport.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Remote impl2 = null;
    try {
        Remote impl = new MarshalAfterUnexport();
        System.err.println("created impl extending URO: " + impl);

        Receiver stub = (Receiver) RemoteObject.toStub(impl);
        System.err.println("stub for impl: " + stub);

        UnicastRemoteObject.unexportObject(impl, true);
        System.err.println("unexported impl");

        impl2 = new MarshalAfterUnexport();
        Receiver stub2 = (Receiver) RemoteObject.toStub(impl2);

        System.err.println("marshalling unexported object:");
        MarshalledObject mobj = new MarshalledObject(impl);

        System.err.println("passing unexported object via RMI-JRMP:");
        stub2.receive(stub);

        System.err.println("TEST PASSED");
    } finally {
        if (impl2 != null) {
            try {
                UnicastRemoteObject.unexportObject(impl2, true);
            } catch (Throwable t) {
            }
        }
    }
}
 
Example #27
Source File: ORBStreamObjectCopierImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }

    OutputStream out = (OutputStream)orb.create_output_stream();
    out.write_value((Serializable)obj);
    InputStream in = (InputStream)out.create_input_stream();
    return in.read_value();
}
 
Example #28
Source File: ReuseDefaultPort.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.err.println("\nRegression test for bug 6269166\n");
    RMISocketFactory.setSocketFactory(new SF());
    Remote impl = new ReuseDefaultPort();
    Remote stub = UnicastRemoteObject.exportObject(impl, 0);
    System.err.println("- exported object: " + stub);
    try {
        Registry registry = LocateRegistry.createRegistry(PORT);
        System.err.println("- exported registry: " + registry);
        System.err.println("TEST PASSED");
    } finally {
        UnicastRemoteObject.unexportObject(impl, true);
    }
}
 
Example #29
Source File: RMIIIOPServerImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <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 #30
Source File: TestLibrary.java    From dragonwell8_jdk with 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();
        }
    }
}