Error unmarshalling return nested exception is

java.rmi.UnmarshalException: error unmarshalling return; nested exception i Is there anyone out there that can help with RMI issues. When trying to pass an object, which is Serializable, I get the error below. It happens when I change, prior to compile, the size of one of the fields in the communication object. java.rmi.UnmarshalException: error unmarshalling […]

Содержание

  1. java.rmi.UnmarshalException: error unmarshalling return; nested exception i
  2. Comments
  3. java.rmi.UnmarshalException: error unmarshalling return; nested exception
  4. UnmarshalException:error unmarshalling return;nested exception ClassNotFoun
  5. Comments
  6. Динамическая загрузка кода, используя Java™ RMI (Используя java.rmi.server.codebase Свойство)
  7. 1.0 Начинаясь
  8. 2.0 Какова кодовая база?
  9. 3.0 Как это работает?
  10. 3.1 Как кодовая база используется в апплетах
  11. 3.2 Как кодовая база используется в Java RMI
  12. 4.0 Используя кодовую базу в Java RMI для больше чем только тупиковой загрузки
  13. 5.0 Примеры командной строки
  14. Примеры
  15. 6.0 Поиск и устранение неисправностей подсказок
  16. 6.1 Если Вы встречаетесь с проблемой, выполняющей Ваш Java сервер RMI
  17. 6.2 Если Вы встречаетесь с проблемой, выполняющей Ваш Java клиент RMI

java.rmi.UnmarshalException: error unmarshalling return; nested exception i

Is there anyone out there that can help with RMI issues. When trying to pass an object, which is Serializable, I get the error below. It happens when I change, prior to compile, the size of one of the fields in the communication object.

java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.io.EOFException
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:157)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:179)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132)
at $Proxy0.getSim(Unknown Source)
at swf.generic.SwarmfareClient.getJob(SwarmfareClient.java:243)
at swf.generic.SwarmfareClient.runMe(SwarmfareClient.java:158)
at swf.generic.SwarmfareClient.main(SwarmfareClient.java:93)
Caused by: java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2498)
at java.io.ObjectInputStream.skipCustomData(ObjectInputStream.java:1861)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1835)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:290)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:139)
. 6 more

Thanks for the help,
Dnowakaf

They say, god helps those who help themselves.

Источник

java.rmi.UnmarshalException: error unmarshalling return; nested exception

getting the following exception when i run my application

java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.io.InvalidClassException: jisp.base.RateGroupInfo; Local class not compatible: stream classdesc serialVersionUID=-4194683926821053521 local class serialVersionUID=-4463005701135703527

java.io.InvalidClassException: jisp.base.RateGroupInfo; Local class not compatible: stream classdesc serialVersionUID=-4194683926821053521 local class serialVersionUID=-4463005701135703527

at java.io.ObjectStreamClass.validateLocalClass(Unknown Source)

at java.io.ObjectStreamClass.setClass(Unknown Source)

at java.io.ObjectInputStream.inputClassDescriptor(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at java.io.ObjectInputStream.inputClassDescriptor(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at java.io.ObjectInputStream.inputObject(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at java.io.ObjectInputStream.inputArray(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at java.io.ObjectInputStream.inputClassFields(Unknown Source)

at java.io.ObjectInputStream.defaultReadObject(Unknown Source)

at java.io.ObjectInputStream.inputObject(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at sun.rmi.server.UnicastRef.unmarshalValue(Unknown Source)

at sun.rmi.server.UnicastRef.invoke(Unknown Source)

at jisp.cvms.server.CVMSRateGroupManagerImpl_Stub.getByRateGroupID(Unknown Source)

at jisp.base.client.GeneralRateGroupScreen.openScreen(Unknown Source)

at jisp.base.client.BaseInternalFrame$1.actionPerformed(Unknown Source)

at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)

at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Unknown Source)

at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)

at javax.swing.DefaultButtonModel.setPressed(Unknown Source)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)

at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)

at java.awt.Component.processMouseEvent(Unknown Source)

at java.awt.Component.processEvent(Unknown Source)

at java.awt.Container.processEvent(Unknown Source)

at java.awt.Component.dispatchEventImpl(Unknown Source)

at java.awt.Container.dispatchEventImpl(Unknown Source)

at java.awt.Component.dispatchEvent(Unknown Source)

at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)

at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)

at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)

at java.awt.Container.dispatchEventImpl(Unknown Source)

at java.awt.Component.dispatchEvent(Unknown Source)

at java.awt.EventQueue.dispatchEvent(Unknown Source)

at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)

at java.awt.EventDispatchThread.pumpEvents(Unknown Source)

at java.awt.EventDispatchThread.run(Unknown Source)

what could be the possible error please help me
Thanks in advance

Источник

UnmarshalException:error unmarshalling return;nested exception ClassNotFoun

Hi,
I have written a client for an enterprise application. The client communicates with the application using APIs provided by the application that internally make RMI calls to the application server.

I am getting the following error when the client invokes a remote method. The class ‘a.b.c.MyClass’ is included in the client JAR as well as in the server installation directory. The classes in this directory will be added by server into its classpath automatically. The client and server are running on the same machine but have different classpaths.

The remote method uses class ‘a.b.c.MyClass’ in both input parameter and return type.
This method returns a list of objects found as specified by the input parameters. The input parameter and the result both use the ‘a.b.c.MyClass’.

The code is able to make the call, the server processes the call, but it is failing wihle returning the result. I am not able to understand why it is failing for Unmarshalling the class that it has already (marshalled) used while sending the input parameters.

The code was working fine previously. I am not able to find out what has made it not working.

Waiting for your valuable help.

Providing the complete stack trace for reference Regards,
jsk1

did you get the answer, can you share that, am stuck with similar problem
My remote call returns an object of some pojo which is generated from the class in a jar file. I get this exception

Client exception: java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: com.xx.fir.xxxx.entity.Crdxx (no security manager: RMI class loader disabled)
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: com.xx.fir.xxxx.entity.Crdxx (no security manager: RMI class loader disabled)

Also my ant traget:

jar file where the pojo resides

Источник

Динамическая загрузка кода, используя Java™ RMI
(Используя java.rmi.server.codebase Свойство)

Это учебное руководство организуется следующим образом:

1.0 Начинаясь

Одна из старших значащих возможностей платформы Java™ является возможностью динамически загрузить программное обеспечение Java с любого Универсального Локатора Ресурса (URL) к виртуальной машине (VM), работающий в отдельном процессе, обычно на различной физической системе. Результат состоит в том, что удаленная система может выполнить программу, например апплет, который никогда не устанавливался на его диске. Для первых немногих разделов этого документа будет обсуждена кодовая база относительно апплетов, чтобы помочь описать кодовую базу относительно Java Удаленный Вызов метода (Java RMI).

Например, VM, работающий изнутри веб-браузера, может загрузить байт-коды для подклассов java.applet.Applet и любые другие классы необходимы тому апплету. Система, на которой работает браузер, наиболее вероятно никогда не выполняла этот апплет прежде, ни устанавливала его на его диске. Как только все необходимые классы были загружены с сервера, браузер может запустить выполнение программы апплета, используя локальные ресурсы системы, на которой работает клиентский браузер.

RMI Java использует в своих интересах эту возможность загрузить и выполнить классы и на системах, где те классы никогда не устанавливались на диске. Используя Java API RMI любой VM, не только те в браузерах, может загрузить любой файл класса Java включая специализированный Java классы тупика RMI, которые включают выполнению вызовов метода на удаленном сервере, используя системные ресурсы сервера.

Понятие кодовой базы происходит из использования ClassLoader s в языке программирования Java. Когда программа Java использует a ClassLoader , тот загрузчик класса должен знать расположение (я), из которого нужно позволить загрузить классы. Обычно, загрузчик класса используется в соединении с сервером HTTP, который подает скомпилированные классы для платформы Java. Наиболее вероятно, первое ClassLoader / кодовая база, соединяющая это, Вы вошли в контакт с, был AppletClassLoader , и часть «кодовой базы» HTML-тэг, таким образом, это учебное руководство предположит, что у Вас есть некоторый опыт с Java программирование RMI, так же как запись файлов HTML, которые содержат теги апплета. Например, источник HTML будет содержать что-то как:

2.0 Какова кодовая база?

Кодовая база может быть определена как источник, или место, из которого можно загрузить классы в виртуальную машину. Например, если бы Вы пригласили нового друга к себе на обед, то Вы должны были бы дать тому другу направления месту, где Вы жили, так, чтобы он или она мог определить местоположение Вашего дома. Точно так же можно думать о кодовой базе как о направлениях, которые Вы даете VM, таким образом, это может найти Ваш [потенциально отдаляют] классы.

Можно думать о Вашем CLASSPATH как «локальная кодовая база», потому что это — список мест на диске, из которого Вы загружаете локальные классы. Загружая классы из локального находящегося на диске источника, Вашего CLASSPATH с переменной консультируются. Ваш CLASSPATH может быть установлен взять или относительные или абсолютные пути к каталогам и/или архивам файлов класса. Так так же, как CLASSPATH своего рода «локальная кодовая база», кодовая база, используемая апплетами и удаленными объектами, может считаться «удаленной кодовой базой».

3.0 Как это работает?

3.1 Как кодовая база используется в апплетах

Чтобы взаимодействовать с апплетом, тот апплет и любые классы, которые это должно выполнить, должны быть доступными удаленными клиентами. В то время как к апплетам можно получить доступ от» ftp:// «или локальный» file:/// «URL, к ним обычно получают доступ от удаленного сервера HTTP.

  1. Клиентский браузер запрашивает класс апплета, который не находится в клиенте CLASSPATH
  2. Определение класса апплета (и любой другой класс (ы), в котором это нуждается) загружается от сервера до клиента, использующего HTTP
  3. Апплет выполняется на клиенте

Рисунок 1: Загрузка апплетов

Кодовая база апплета всегда относительно URL страницы HTML в который тег содержится.

3.2 Как кодовая база используется в Java RMI

Используя Java RMI, приложения могут создать удаленные объекты, которые принимают вызовы метода от клиентов в другом VMs. Для клиента, чтобы вызвать методы на удаленном объекте, у клиента должен быть способ связаться с удаленным объектом. Вместо того, чтобы иметь необходимость программировать клиент, чтобы говорить протокол удаленного объекта, Java, RMI использует специальные классы, названные тупиками, которые могут быть загружены на клиент, которые используются, чтобы связаться с (сделайте вызовы метода на), удаленный объект. java.rmi.server.codebase значение свойства представляет одно или более расположений URL, с которых могут быть загружены эти тупики (и любые классы, необходимые тупикам).

Как апплеты, должны были выполниться классы, удаленные вызовы метода могут быть загружены с» file:/// «URL, но как апплеты,» file:/// «URL обычно требует, чтобы клиент и сервер находились на том же самом физическом узле, если файловая система, упомянутая URL, не делается доступным использованием некоторого другого протокола, такого как NFS.

Обычно, классы должны были выполниться, удаленные вызовы метода должны быть сделаны доступными из сетевого ресурса, такого как сервер FTP или HTTP.

Рисунок 2: Загрузка Java тупики RMI

  1. Кодовая база удаленного объекта определяется сервером удаленного объекта, устанавливая java.rmi.server.codebase свойство. Java сервер RMI регистрирует удаленный объект, связанный с именем, с Java реестр RMI. Набор кодовой базы на сервере VM аннотируется к ссылке удаленного объекта в Java реестр RMI.
  2. Java клиент RMI запрашивает ссылку на именованный удаленный объект. Ссылка (тупиковый экземпляр удаленного объекта) — то, что клиент будет использовать, чтобы сделать удаленные вызовы метода удаленного объекта.
  3. Java реестр RMI возвращает ссылку (тупиковый экземпляр) к требуемому классу. Если определение класса для тупикового экземпляра может быть найдено локально в клиенте CLASSPATH , который всегда ищется перед кодовой базой клиент загрузит класс локально. Однако, если определение для тупика не находится в клиенте CLASSPATH , клиент попытается получить определение класса от кодовой базы удаленного объекта.
  4. Клиент запрашивает определение класса от кодовой базы. Кодовой базой, которую использует клиент, является URL, который аннотировался к тупиковому экземпляру, когда тупиковый класс был загружен реестром. Назад в шаге 1, аннотируемый тупик для экспортируемого объекта был тогда зарегистрирован в Java реестр RMI, связанный с именем.
  5. Определение класса для тупика (и любой другой класс (ы), в котором это нуждается) загружается на клиент. Отметьте:Шаги 4 и 5 являются шагами sames, которые реестр сделал, чтобы загрузить класс удаленного объекта, когда удаленный объект был связан с именем в (зарегистрированный в) Java реестр RMI. Когда реестр, предпринятый, чтобы загрузить тупиковый класс удаленного объекта, это запрашивало определение класса от кодовой базы, связанной с тем удаленным объектом.
  6. Теперь у клиента есть вся информация, что она должна вызвать удаленные методы на удаленный объект. Тупиковый экземпляр действует как прокси к удаленному объекту, который существует на сервере; так в отличие от апплета, который использует кодовую базу, чтобы выполнить код в его локальном VM, Java, клиент RMI использует кодовую базу удаленного объекта, чтобы выполнить код в другом, потенциально отдалить VM, как иллюстрировано в рисунке 3:

Рисунок 3: Java клиент RMI, делающий удаленный вызов метода

4.0 Используя кодовую базу в Java RMI для больше чем только тупиковой загрузки

В дополнение к загрузке тупиков и их связанных классов клиентов, java.rmi.server.codebase свойство может использоваться, чтобы определить расположение, с которого может быть загружен любой класс, не только тупики.

Когда клиент делает вызов метода удаленного объекта, метод, который это вызывает, мог быть записан, чтобы не принять параметры или много параметров. Есть три отличных случая, которые могут произойти, основанные на типе (ах) данных параметра (ов) метода.

В первом случае все параметры метода (и возвращаемое значение) являются примитивными типами данных, таким образом, удаленный объект знает, как интерпретировать их как параметры метода, и нет никакой потребности проверить CLASSPATH или любая кодовая база.

Во втором случае, по крайней мере одном удаленном параметре метода или возвращаемом значении объект, для которого удаленный объект может найти определение класса локально в CLASSPATH .

В третьем случае (показанный как Шаг 6, в рисунке 4), удаленный метод получает объектный экземпляр, для которого удаленный объект не может найти определение класса локально в CLASSPATH . Этот тип удаленного вызова метода иллюстрируется в рисунке 4. Класс объекта, отправленного клиентом, будет подтипом объявленного типа параметра. Подтип также:

  • Реализация интерфейса, который объявляется как параметр метода (или возврат) тип
  • Подкласс класса, который объявляется как параметр метода (или возврат) тип

Рисунок 4: Java клиент RMI, делающий удаленный вызов метода, передавая неизвестный подтип как параметр метода

7. Как кодовая база апплета, определенная клиентом кодовая база используется, чтобы загрузить Remote классы, неудаленные классы, и интерфейсы к другому VMs. Если codebase свойство устанавливается на клиентском приложении, тогда та кодовая база аннотируется к экземпляру подтипа, когда класс подтипа загружается клиентом. Если кодовая база не будет установлена на клиенте, то удаленный объект будет по ошибке использовать свою собственную кодовую базу.

5.0 Примеры командной строки

В случае апплета значение кодовой базы апплета встраивается в страницу HTML, как мы видели в примере HTML в первом разделе этого учебного руководства.

В случае Java кодовая база RMI, вместо того, чтобы иметь ссылку на класс, встроенный в страницу HTML, клиент первые контакты Java реестр RMI для ссылки на удаленный объект. Поскольку кодовая база удаленного объекта может обратиться к любому URL, не только тому, который является относительно известного URL, значения Java, кодовой базой RMI должен быть абсолютный URL к расположению тупикового класса и любых других классов, необходимых тупиковому классу. Это значение codebase свойство может обратиться к:

  • URL каталога, в котором классы организуются в названных в честь пакета подкаталогах
  • URL файла JAR, в котором классы организуются в названных в честь пакета каталогах
  • Разграниченная пространством строка, содержащая многократные экземпляры файлов JAR и/или каталогов, которые соответствуют критериям выше

Отметьте: Когда codebase значение свойства устанавливается в URL каталога, значение должно быть завершено «/».

Примеры

Если расположение Ваших загружаемых классов находится на сервере HTTP, названном «webvector», в каталоге «экспорт» (под веб-корнем), Ваш codebase установка свойства могла бы быть похожей на это:

Если расположение Ваших загружаемых классов находится на сервере HTTP, названном «webline», в файле JAR, названном «mystuff.jar», в каталоге «общественность» (под веб-корнем), Ваш codebase установка свойства могла бы быть похожей на это:

Теперь давайте предположим, что расположение Ваших загружаемых классов было разделено между двумя файлами JAR, «myStuff.jar» и «myOtherStuff.jar». Если эти файлы JAR располагаются на различных серверах (названный «webfront» и «webwave»), Ваш codebase установка свойства могла бы быть похожей на это:

6.0 Поиск и устранение неисправностей подсказок

Любой сериализуемый класс, включая Java тупики RMI, может быть загружен, если Ваш Java программы RMI конфигурируется должным образом. Вот условия, при которых будет работать динамическая тупиковая загрузка:

  1. Тупиковый класс и любой из классов, на которые полагается тупик, подаются от URL, достижимого от клиента.
  2. java.rmi.server.codebase свойство было установлено на программе сервера (или в случае активации, программы «установки»), который делает звонок bind или rebind , так, что:
    • Значение codebase свойством является URL в шаге A
  • Если URL, определенный как значение codebase свойство является каталогом, оно должно закончиться в запаздывании «/»
  • rmiregistry не может найти тупиковый класс или любой из классов, на которые тупик полагается в CLASSPATH . Это — так кодовая база, аннотируется к тупику, когда реестр делает свою загрузку класса тупика, в результате звонков bind или rebind в сервере или коде установки.
  • Клиент установил a SecurityManager это позволяет тупику быть загруженным. В Java 2 SDK, Standard Edition, v1.2 и позже, это означает, что у клиента должен также быть должным образом сконфигурированный файл политики безопасности.
  • Есть две типичных проблемы, связанные с java.rmi.server.codebase свойство, которые обсуждаются затем.

    6.1 Если Вы встречаетесь с проблемой, выполняющей Ваш Java сервер RMI

    Первой проблемой, с которой Вы могли бы встретиться, является получение a ClassNotFoundException пытаясь к bind или rebind удаленный объект к имени в реестре. Это исключение обычно происходит из-за уродливого codebase свойство, приводящее к реестру, не бывшему способному определять местоположение тупиков удаленного объекта или других классов, необходимых тупику.

    Важно отметить, что тупик удаленного объекта реализует весь одинаковый интерфейсы как удаленный объект непосредственно, таким образом, те интерфейсы, так же как любые другие пользовательские классы, объявленные как параметры метода или возвращаемые значения, должны также быть доступными для скачивания от указанной кодовой базы.

    Наиболее часто это исключение выдается в результате исключения запаздывающей наклонной черты со значения URL свойства. Другие причины включали бы: значением свойства не является URL; путь к классам, определенным в URL, является неправильным или написанным c орфографическими ошибками; тупиковый класс или любые другие необходимые классы не все доступны от указанного URL.

    Исключение, с которым можно встретиться в таком случае, было бы похоже на это:

    6.2 Если Вы встречаетесь с проблемой, выполняющей Ваш Java клиент RMI

    Второй проблемой, с которой Вы могли встретиться, является получение a ClassNotFoundException пытаясь к lookup удаленный объект в реестре. Если Вы получаете это исключение в stacktrace, следующем из попытки выполнить Ваш Java клиентский код RMI, то Ваша проблема CLASSPATH с которого Ваш Java был запущен реестр RMI. См. требование C в разделе 6.0. Вот то, на что будет похоже исключение:

    Источник

    Перейти к содержанию

    На чтение 2 мин Просмотров 403 Опубликовано 19.05.2010

    Java RMI(Java Remote Method Invocation) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), it allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine. It provides for remote communication where all participating applications are written by Java.

    Today, when I ran a “hello world” example, unfortunately I got the following error messages:

    Exception in thread "main" java.rmi.MarshalException: error marshalling arguments; nested exception is:
    java.io.NotSerializableException: server.Hello
    at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
    at java.rmi.Naming.rebind(Naming.java:160)
    at server.HelloServer.main(HelloServer.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)
    Caused by: java.io.NotSerializableException: server.Hello
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1081)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:302)
    ... 8 more

    The Java RMI server ran on IDEA9.0 and the Java version is “1.6.0_18″. I confused a lot why this error occurs, my initial understanding was, perhaps, caused by that the JVM engine is not able to detect where are the serialized class or data, but quickly I learned that a required class was missing in classpath.

    A Java class can be turned to be remotely accessible by implementing a custom remote interface, it have to extend uka.karmi.rmi.Remote and UnicastRemoteObjectUnicastRemoteObject both, UnicastRemoteObject is exported in constructor, but my remote object has not implemented class UnicastRemoteObject. I extended UnicastRemoteObject for calss Hello then “java rmi error unmarshalling arguments” error was gone.
    This is code what the error unmarshalling arguments occurs:

    public class Hello implements HelloInterface {
      public Hello() throws RemoteException {
      }
    
      public String sayHello() throws RemoteException {
        return "good hello";
      }
    }

    I fixed code as below to resolve error unmarshalling arguments:

    public class Hello extends UnicastRemoteObject implements HelloInterface {
      public Hello() throws RemoteException {
      }
    
      public String sayHello() throws RemoteException {
        return "good hello";
      }
    
    }

    5 ответов

    Похоже, что вы не используете менеджера безопасности:

    У вас есть файл политики (my.policy):

    grant {
      permission java.security.AllPermission;
    };
    

    и запустите свою программу, используя

    java -Djava.security.manager -Djava.security.policy=/some/path/my.policy MyClass
    

    beny23
    08 сен. 2011, в 23:14

    Поделиться

    У меня была эта проблема, потому что у меня были разные имена пакетов в клиентском и серверном коде:

    package my.pkg; 
    // server side interface definition...
    
    // ------------- //
    
    package my.pkg.something;
    // client side interface definition...
    

    Я изменил имя клиентского пакета и установил его как имя серверного пакета:

    package my.pkg; 
    // server side interface definition...
    
    // ------------- //
    
    package my.pkg; // renamed to the name of package in server-side .
    // client side interface definition...
    

    и проблема исчезла.

    AminSaghi
    20 июнь 2014, в 21:01

    Поделиться

    У меня были рабочие RMI Client и Server для моего Java-класса. Я решил разместить их в своих собственных пакетах, а не работать как пакет по умолчанию.

    После того, как я поместил их в свои пакеты, ошибка java.rmi.UnmarshalException: error unmarshalling return; nested exception is: java.lang.ClassNotFoundException: начала происходить при подключении.

    Я вернул программы обратно в пакет по умолчанию, и все это снова заработало.

    Я понимаю, что для этого, вероятно, есть техническая причина, но это сработало для меня!

    Canadian_Republican
    08 авг. 2012, в 02:30

    Поделиться

    Существует три случая.

    • Если вы получаете ошибку при привязке к реестру, реестр не имеет доступа к этому классу в своем пути к классам или с помощью функции кодовой базы.

    • Если вы обнаружите ошибку при поиске реестра, ваш клиент не имеет доступа к этому классу в своем пути к классам или через функцию кодовой базы.

    • Если вы используете функцию codebase, это, в свою очередь, может быть вызвано тем, что реестр имеет доступ к этому классу в своем пути к классам, что заставляет его не использовать кодовую базу, что приводит к потере аннотации кода, поэтому ваш клиент не знает, как использовать кодовую базу для этого класса.

    • Если вы не используете функцию codebase, игнорируйте предыдущий абзац; -)

    EJP
    09 сен. 2011, в 00:23

    Поделиться

    я решил его с именем переименования. сервер и клиент находятся в двух разных проектах, но с тем же наименованием пакетов.

    DanialAbdi
    24 апр. 2017, в 07:41

    Поделиться

    Ещё вопросы

    • 1Установить ХПК на Android-сервере Bluetooth
    • 0В чем разница при использовании выходного буфера на PHP?
    • 1JSON десериализация для типов C #
    • 1Как бы я отсортировал список строк по целым числам в этой строке? *Ява*
    • 1Многопоточный код для работы с использованием настроенного количества потоков
    • 0не может запрашивать значения из реестра Windows
    • 0Laravel 4 Неопределенные ошибки переменных
    • 1убить сервер узла после тестирования gitlab
    • 0Блоки кода запускаются с помощью инструментов разработчика Visual C ++
    • 0Получить метку элемента json с его идентификатором
    • 1Перемещение мыши Java mouseListener не работает
    • 0Карта Google AngularJS не обновляет свой контент при первом просмотре
    • 1субплот с использованием автоматического изменения размера
    • 0Запрашиваемая на определенное время?
    • 0C ++ Array функция и манипулирование
    • 0Обнаружение жеста смахивания с скачком движения
    • 1Противоречивые методы на множественном наследовании интерфейса
    • 0Использование базы данных MySQL из плагина Artifactory
    • 1Может ли скала код, скомпилированный с JDK 7, работать на JVM 8?
    • 0Node.js API с Express & MySQL — поиск нескольких значений в параметре поиска
    • 1То же действие по добавлению, но разные результаты в Javascript
    • 1Проблемы при векторизации TFIDF токенизированных документов?
    • 0Как я могу написать модульный тест для angularJs Factory
    • 0удалить дубликаты Camma из запроса MySQL
    • 0MySQL запрос количества записей в основной таблице с несколькими атрибутами во второй таблице
    • 1Стандартное отклонение числа между n строками и n столбцами 3 массивов
    • 1Может ли Javascript прочитать размер шрифта текстового элемента SVG? [Дубликат]
    • 0Синтаксическая ошибка триггера MySQL в БД Мария
    • 0Как сохранить HTML-контент в файл, не сохраняя в базе данных
    • 0выпадающий список выпадающего списка настолько мал, что рядом с ним появляются обновленные стрелки
    • 0Ошибка сегментации (дамп ядра) при поиске свертки изображений в opencv c ++
    • 0Циклы C ++ и логические выражения
    • 0Угловой стол к CSV
    • 0Необязательный параметр jBBCode?
    • 0Как запустить скрипт с правами root из веб-сервиса на apache
    • 1Передача запроса SWI-Prolog из программы Java
    • 1эмулятор Android ==> изменить размер кучи?
    • 1Облачные функции для Firebase — Удалить старшего ребенка
    • 0Могу ли я использовать функцию eval в этом случае?
    • 1Javascript — как обнаружить отличие от двух массивов
    • 0простой скрипт Jquery не работает: /
    • 0Массив в XML такой же ключевой вопрос
    • 1Разбиение многострочного блока текста с регулярными выражениями в c # на matchcollection
    • 1Член PropertyChanged для INotifyPropertyChanged всегда равен нулю
    • 0kineticJS children — Jquery, перетаскиваемый
    • 1Построить мультииндексированный фрейм данных из фреймов данных
    • 0CKEDITOR — используйте клавишу Backspace для выделения текста
    • 1Как я могу получить массив всех допустимых значений данного свойства CSS?
    • 1повторное приведение унаследованного поля
    • 1способ отладки Java-фреймворков на консоли

    Client-Server Troubleshooting

    This page contains common problems and exceptions that occur when running the Protege client-sever and is part of the Protege client-server tutorial. This page is being updated as issues arise.

    Contents

    • 1 Basics
    • 2 Versioning Problems and UnmarshalExceptions
    • 3 RMI Registry Synchronization
    • 4 Java 1.6.0_29 and 1.7 rmiregistry issue
    • 5 Networks, Firewalls and Telnet
      • 5.1 Configuration
    • 6 See Also

    Basics

    In troubleshooting, it is very useful to understand that the client will first connect to the rmi registry to get a reference to the server and then will use the server reference to contact the server.
    This protocol is discussed here (ignore the black magic tricks unless they help you get a better understanding).

    The first thing to do is to look at any messages on the client and server console. The most fundamental error that can arise is the following exception which appears on the client console:

    SEVERE: java.rmi.ConnectException: Connection refused to host: localhost; nested exception is: 
    	java.net.ConnectException: Connection refused
    	at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:574)
    	at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:185)
    	at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:171)
    	at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:306)
    	at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    	at java.rmi.Naming.lookup(Naming.java:84)
    	at edu.stanford.smi.protege.server.ServerPanel.connectToHost(ServerPanel.java:140)
    

    Note that the exception happens when trying to call Naming.lookup. Usually the client will pop up a window that says Unable to Connect to Server. This means that the client could not connect to the rmiregistry. Possibly the rmiregistry is not running or there is a firewall or other network problem.

    An alternate very different error that appears on the client console is the following exception

    SEVERE: java.rmi.ConnectException: Connection refused to host: 67.180.198.51; nested exception is: 
    	java.net.ConnectException: Connection timed out
    	at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:574)
    	at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:185)
    	at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:171)
    	at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:94)
    	at edu.stanford.smi.protege.server.Server_Stub.openSession(Unknown Source)
    	at edu.stanford.smi.protege.server.ServerPanel.createSession(ServerPanel.java:154))
    

    This is usually accompanied by the message Failed to create a session because of either an invalid username/password combination, or a firewall problem. Unfortunately this pop up dialog is very ambiguous and can mean many things. It is for this reason that we have tried to add some additional information to help. In any case the exception tells us two very important things. First the problem occurs during an attempt ot create a session (ServerPanel.createSession) when the client makes a call to the server (Server_Stub.openSession(Unknown Source). In particular, since the client is talking to the server, it means that it has already talked to the rmiregistry to obtain a pointer to the client. That is, this exception means that the client has gotten quite a bit further than it had in the previous case.

    Note that the connection is being refused to the host 67.180.198.51. It is important to look at this because this is often the problem — the connection is being made to the wrong place. There is another message that amplifies on this issue:

    Server ref = Server_Stub[UnicastRef2 [liveRef: [endpoint:[67.180.198.51:38547,edu.stanford.smi.protege.server.socket.RmiSocketFactory@2](remote),objID:[-4da377e5:122e64da065:-8000, 0]]]]
    

    This is a printout of the server reference that (1) the server passed to the rmiregistry at server startup and (2) the rmiregistry gave to the client to tell it how to contact the server. Not the endpoint:

        67.180.198.51:38547.
    

    This is the host and port that the rmiregistry thinks should be used to connect to the server. The Connection Refused exception suggests that there is some problem with this.

    One problem that can occur is that the server misrepresents itself when talking to the rmiregistry. At this point it is worth taking a glance at the first few paragraphs of description of the rmi protocol. The server decides how to represent itself to the based on the line:

        -Djava.rmi.server.hostname=`hostname`
    

    Sometimes this line doesn’t do the right thing because the hostname command returns the wrong value. For instance, perhaps the hostname parameter returns smi-tredmond-li instead of smi-tredmond-li.stanford.edu. Perhaps, depending on your network configuration, first of these can be resolved by the client and the second cannot. Another thing that the hostname command sometimes returns is localhost which will not work for any client on a different machine than the server.

    The client console/log is not the only place to look for hints about a problem. The server console can also have useful information. For example, if I simply supply the wrong user name or password, the server prints out a message

      WARNING: Failed login for user Timothy Redmond IP: 127.0.1.1 -- Server.openSession()
    

    In addition no server or client-side exceptions are generated.
    This means that the client successfully contacted the server, the server successfully processed the request but rejected it because the credentials were wrong.

    Versioning Problems and UnmarshalExceptions

    In order to have a Protege client work reliably with a Protege server, both must be running exactly the same version of Protege. There are several things that can go wrong when the version numbers are different. But the most obvious exception is an UnmarshalException which looks something like the following:

    WARNING: Could not connect to remote project Collaborative Pizza -- java.lang.RuntimeException: java.rmi.UnmarshalException: error unmarshalling return; nested exception is: 
    	java.io.InvalidClassException: edu.stanford.smi.protege.server.update.ValueUpdate; local class incompatible: stream classdesc serialVersionUID = -7753881900765528485, local class serialVersionUID = -4059275656078639103
    	at edu.stanford.smi.protege.server.framestore.RemoteClientFrameStore.convertException(RemoteClientFrameStore.java:388)
    	at edu.stanford.smi.protege.server.framestore.RemoteClientFrameStore.getFrame(RemoteClientFrameStore.java:509)
    	at edu.stanford.smi.protege.model.framestore.ModificationFrameStore.getFrame(ModificationFrameStore.java:26)
    	at edu.stanford.smi.protege.model.framestore.ArgumentCheckingFrameStore.getFrame(ArgumentCheckingFrameStore.java:107)
    

    There are some other things that can go wrong when the client and the server have different versions. In particular another type of error that we saw recently involved a client that used certain remote jobs that the server did not know about. This raised the following exception (seen on the client):

    WARNING: edu.stanford.smi.protege.exception.ProtegeIOException: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: 
    	java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: 
    	java.lang.ClassNotFoundException: null class
    	at edu.stanford.smi.protege.server.framestore.RemoteClientFrameStore.executeProtegeJob(RemoteClientFrameStore.java:1691)
    	at edu.stanford.smi.protege.util.ProtegeJob.execute(ProtegeJob.java:94)
             ...
    

    The key hint here is that the error occurred during executeProtegeJob. The error happened on the server (who is not able to find a class passed to it from the client) and is displayed on the client. This type of exception suggests that the client and server are running different versions of Protege or that the server needs to be running a plugin that is running on the client.

    Another unmarshalling exception that you may get is related to not finding the class Server_Stub.

    SEVERE: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
            java.lang.ClassNotFoundException: edu.stanford.smi.protege.server.Server_Stub
            at sun.rmi.server.UnicastServerRef.oldDispatch(Unknown Source)
            at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
            ...
    

    This happens if rmiregistry does not find the path to the protege.jar, which is specified in the CODEBASE_URL in your run_protege_server script. Especially if running the server on a Windows machine, please make sure that you edit this line from your run_protege_server script to match the path to the protege.jar from your Protege installation folder:

    set CODEBASE_URL=file:/c:/program%%20files/protege_3.4.7/protege.jar
    

    (space is encoded as %%20).

    RMI Registry Synchronization

    Sometime, not very often, a problem arises where the rmiregistry needs to be restarted. So if the client-server has been running fine and you are suddenly having mysterious problems, try killing the rmiregistry and restarting it. I don’t know anyone who understands this issue.

    Java 1.6.0_29 and 1.7 rmiregistry issue

    There is a known bug in Java 1.6.0_29 and Java 1.7 that occurs when a RMI server attempts to bind an exported object which includes codebase annotations using the «file:» URL scheme. There is no workaround for this issue, except using a different scheme (e.g. http or ftp) for specifying the code base, or using a different version of Java.

    If this issue affects you, you will get an exception when starting the Protege server with a stack trace similar to this:

    SEVERE: server startup failed -- java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
        java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
        java.lang.ClassNotFoundException: access to class loader denied
    Caused by
    .....
    Caused by: java.security.AccessControlException: access denied (java.io.FilePermission C:UserscsnyulasworkspaceProtege-corebuilddist- read)
    

    To avoid getting this exception you can run the Protege server with a different version of Java that does not contain this bug (i.e. until the bug is fixed in one of the upcoming Java versions, you will need to downgrade to Java 1.6.0_26 or earlier). Another workaround is to serve the protege code base from a different location (e.g. http or ftp) and edit the run_protege script accordingly.

    Networks, Firewalls and Telnet

    It is out of scope for the Protege team to diagnose network problems. There are simply too many things that can go wrong and too many things to know. The primary indicator that you need to start thinking about netowrk issues is that the server works fine on localhost or on the lan but not from outside the lan. In this case, telnet is a useful tool for quickly evaluating where a problem is located. All real operating systems with possibly (grudgingly admitted) one exception have a telnet command. If your operating system is under configured you can try this link for enabling telnet or [1]. I haven’t tried either but you should also feel free to complain to your vendor for leaving out such a basic diagnostic command.

    What telnet does is to allow you to connect to a hostname and a port. If you know a protocol in detail it is also possible (usually not recommended) to talk a bit with a server this way. For example, using the host www.google.com and port 80 you can try GET /. There are also instructions on various web pages for talking with mail servers, etc. In our case, all we are interested in is whether the client can connect. So depending on your telnet client, a successful connection will look something like this:

    [tredmond@smi-tredmond-li org.protege.osgi.jdbc.prefs]$ telnet smi-tredmond-li 5100
    Trying 127.0.1.1...
    Connected to smi-tredmond-li.
    Escape character is '^]'.
    

    At this point, with this client, type control-] and then quit and telnet will exit. In the case of a problem, it may take a bit of time for telnet to realize that it cannot connect. In the case that it can connect, it usually connects very quickly.

    There are two connections that need to be tested. The first connection is the connection to the rmiregistry. By default the rmi registry runs on port 1099 but it can be changed when the rmi registry is invoked with the command

        rmiregisty [port #].
    

    In addition the server is configured to talk to a particular rmiregistry port with the jvm definition

         -Dprotege.rmi.registry.port=[port #].
    

    The rmi registry port that the server is using can also be seen in the server console message near the top:

        Server port = 5200, registry port = 5100, compressed stream
    

    The other connection that needs to be tested is the server connection. The server port can be determined if you have a server reference message in some clients logs:

    Server ref = Server_Stub[UnicastRef2 [liveRef: [endpoint:[67.180.198.51:38547,edu.stanford.smi.protege.server.socket.RmiSocketFactory@2](remote),objID:[-4da377e5:122e64da065:-8000, 0]]]]
    

    but the easiest way to know the server port is to set it with a jvm definition:

        -Dprotege.rmi.server.port=5200.
    

    If telnet cannot connect then neither will Protege and the problem is to figure out why the connection failed. This telnet test can be run from different machines on your network to determine exactly what is causing a problem with the network.

    Configuration

    To resolve configuration issues arising from NAT firewalls, here’s a simple walkthrough that hopefully helps someone.

    • In your Protege client application, edit the «protege.properties» file in the installation directory and add the line (or modify if it already exists), where hostname is the HOSTNAME (not the domain name) and RMI_REG_PORT is the RMI Registry Port. By default this is 1099, but can be changed from the server configuration. The global IP Address of the server also works in place of the hostname, but a common mistake is to set this to the local IP address of the server.
    edu.stanford.smi.protege.server.ServerPanel.host_name=hostname:RMI_REG_PORT
    
    • In your Protege Server installation, make the following changes to «run_protege_server.sh»:
      • For the HOSTNAME_PARAM variable, replace `hostname` with the actual hostname of your machine (same as specified from the client side so you know its globally-routable). A common mistake is to set this to «localhost» or to a locally routable hostname.
      • Add the following lines before the PORTOPTS variable is defined:
    RMI_REG_PORT=1099
    RMI_SERV_PORT=5200
    
      • Uncomment the line defining the PORTOPTS variable and change it to:
    PORTOPTS="-Dprotege.rmi.server.port=$RMI_SERV_PORT -Dprotege.rmi.registry.port=$RMI_REG_PORT"
    
      • Add the RMI_REG_PORT argument to the rmiregistry command, like this:
    $JAVA_PATH/rmiregistry $RMI_REG_PORT &
    
    • Make sure you configure your firewall to allow TCP traffic to the RMI_REG_PORT and RMI_SERV_PORT

    See Also

    • Protege Client Server Tutorial Advanced

    Понравилась статья? Поделить с друзьями:
  • Error unmarshaling json
  • Error unmappable character for encoding utf8
  • Error unmappable character 0x98 for encoding windows 1251 javadoc
  • Error unmappable character 0x98 for encoding windows 1251 gradle
  • Error unmappable character 0x81 for encoding windows 1252