NoSuchPortException using RXTX Java library on Windows? - java

I have followed the instructions to setup rxtx on windows from http://www.jcontrol.org/download/readme_rxtx_en.html.
What I did exactly was copy rxtxSerial.dll to "C:\Program Files\Java\jdk1.6.0_07\jre\bin"
and copied RXTXcomm.jar to "C:\Program Files\Java\jdk1.6.0_07\jre\lib\ext"
(my JAVA_HOME variable is set to C:\Program Files\Java\jdk1.6.0_07\jre)
I also added RXTXcomm.jar to my eclipse project.
But when I run it, it still says "NoSuchPortException"
Devel Library
=========================================
Native lib Version = RXTX-2.0-7pre1
Java lib Version = RXTX-2.0-7pre1
java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver
gnu.io.NoSuchPortException
at gnu.io.CommPortIdentifier.getPortIdentifier(CommPortIdentifier.java:218)
at TwoWaySerialComm.connect(TwoWaySerialComm.java:20)
at TwoWaySerialComm.main(TwoWaySerialComm.java:107)
In my java file, I tell it:
try
{
(new TwoWaySerialComm()).connect("COM4");
}
and I've also tried the Java Comm API. Both cannot recognize my serial port but I am sure I followed the instruction correctly. There files are there.
Does anybody have any idea what it could be?

Try putting rxtxSerial.dll in
C:\Program Files\Java\jdk1.6.0_07\jre\lib\bin
^^^

you can use
CommPortIdentifier.getPortIdentifiers()
to identify all possible ports your system finds.

I am not too familiar with RXTX, but is this normal?
java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver
Otherwise maybe the problem is not with the port itself after all, but something with the classes themselves?
Just a guess.

You can also try an alternative solution that was specifically implemented for Windows. There should be plenty available, one of them you can get from http://www.caerustech.com/JCommWin32.php
Shultz

It may be that your system does not have a COM4 defined or it's not accessible. It's hard to guess what may be wrong, because you haven't posted you port init code - what you posted looks like wrapper code.
Here is my working init code using the javax.comm API (but using SerialPort from serialio.com):
// name comes from config and is "COM1", "COM2", ...
SerialPort port=(SerialPort)CommPortIdentifier.getPortIdentifier(name).open("YourPortOwnerIdHere",5000); // owner and ms timeout
port.setSerialPortParams(bau,dtb,stb,par);
port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN|SerialPort.FLOWCONTROL_RTSCTS_OUT);
port.enableReceiveTimeout(1000);
Hopefully this points you in the right direction.

I agree that you're problem looks like a ClassCastException and not the other.
For windows, I'm using "Windows Java Serial Com Port Driver" at http://www.engidea.com/blog/informatica/winjcom/winjcom.html and it is much easier for me to set up.
In either case, you want the DLL in the BIN directory, not LIB\BIN as was suggested. At least that's what's working for me. I'm using NetBeans and I've also found it helpful to put the jar and dll into various bin and lib\ext folders in the JDK.
Note that if you have multiple versions of the JRE on your machine, you might not be using the one that you think you are using. Also, as a practical matter I've found it more helpful to just copy both the jar and dll into the various bin and lib\ext folders. Makes it just a paste, paste, paste operation.
For windows, I recommend "Windows Java Serial Com Port Driver" because it solved my problems with USB serial ports. I had fits with RXTX because it would crash when the USB was unplugged. winjcom solved that problem and others as well. It has very helpful error exceptions.
Also, make sure your serial drivers are up-to-date. Downloading an update fixed my other bug.
-Stosh

I also had a problem when closing the serialPort within the serialEvent function.
Maybe it's a deadlock problem, where the close method waits forever for serialEvent's lock to be released.
Starting a new thread to close the port worked for me.

For your question, my code is the following:
if (idPuerto == null)
{
formulario = form;
boolean encontrado = false;
listaPuertos = CommPortIdentifier.getPortIdentifiers();
while( listaPuertos.hasMoreElements() && encontrado == false )
{
idPuerto = (CommPortIdentifier)listaPuertos.nextElement();
//System.out.println(idPuerto.getName());
if( idPuerto.getPortType() == CommPortIdentifier.PORT_SERIAL )
{
if( idPuerto.getName().equals(RFIDBascApp.ComBasc) )
{
encontrado = true;
logger.AddInfoUser("Puerto serie encontrado");
}
}
}

You had NoSuchPortException, so first of all iterate on all available ports!
import gnu.io.CommPortIdentifier;
import java.util.Enumeration;
public class ListAvailablePorts {
public void list() {
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
while(ports.hasMoreElements()){
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
System.out.println(port.getName());
}
}
public static void main(String[] args) {
new ListAvailablePorts().list();
}
}

#Pinheiro you might want to take a look at this

Related

Ensuring files are available to the JVM

I'm trying to install TensorFlow for Java on Windows 10 using this Article
. I followed the steps carefully but the windows commands didn't work with me so I decided to do it manually.
The first command is to make the .jar part of the classpath and I did it manually
but the second step was to ensure that the following two files are available to the JVM: the .jar file and the extracted JNI library
but I don't know how to do that manually
The code:
package securityapplication;
import org.tensorflow.TensorFlow;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
public class SecurityApplication {
public static void main(String[] args) throws Exception {
try (Graph g = new Graph()) {
final String value = "Hello from " + TensorFlow.version();
// Construct the computation graph with a single operation, a constant
// named "MyConst" with a value "value".
try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
// The Java API doesn't yet include convenience functions for adding operations.
g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
}
// Execute the "MyConst" operation in a Session.
try (Session s = new Session(g);
Tensor output = s.runner().fetch("MyConst").run().get(0)) {
System.out.println(new String(output.bytesValue(), "UTF-8"));
}
}
}
}
could someone help? cuz my program that uses TensorFlow still have the following error
The text in the image is :
Exception in thread "main" java.lang.UnsatisfiedLinkError: Cannot find TensorFlow native library for OS: windows, architecture: x86. See https://github.com/tensorflow/tensorflow/tree/master/tensorflow/java/README.md for possible solutions (such as building the library from source). Additional information on attempts to find the native library can be obtained by adding org.tensorflow.NativeLibrary.DEBUG=1 to the system properties of the JVM.
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.TensorFlow.init(TensorFlow.java:36)
at org.tensorflow.TensorFlow.<clinit>(TensorFlow.java:40)
at org.tensorflow.Graph.<clinit>(Graph.java:194)
at securityapplication.SecurityApplication.main(SecurityApplication.java:15) Java Result: 1 BUILD SUCCESSFUL (total time: 4 seconds)
The result after running the first command in cmd:
The result after running the second command in Windows PowerShell:
Any suggestions?!
Thank you
The first command failure (javac) suggests that the javac command is not in your PATH environment variables. See for example, this StackOverflow question
For the second command failure, I believe the space after -D is what is causing you trouble as Holger suggested.
IDEs like Eclipse and others also provide a means to set the java.library.path property for the JVM (see this StackOverflow answer for example).
Background: TensorFlow for Java consists of a Java library (packaged in a .jar file) and a native library (.dll on Windows, distributed in a .zip file). You need to ensure that the .jar file is in the classpath and the directory containing the .dll is in included in the java.library.path of the JVM when executing a program.
Hope that helps.

What is a valid COM structure for JACOB library?

I'm using the JACOB (Java COM Bridge) library to call registered COM Objects from my Windows OS.
It took me a while until I figured out how JACOB works and to set up everything. So my current problem is that:
ActiveXComponent comp = new ActiveXComponent("iTunes.Application");
for example works, my iTunes starts properly etc.
If I want to call a self generated and registered COM Object written in C# JACOB responds the following error:
Exception in thread "main" com.jacob.com.ComFailException: Can't co-create object
That my iTunes started was an indicator for me that everything is set up right, I'm not sure why JACOB can't call my own .dll
Currently I'm using the Visual Studio 2015 on build register for COM interop function which worked pretty good in the past for me. The COM object looks as following:
[Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83F")]
public interface ComClass1Interface
{
}
[Guid("7BD20046-DF8C-44A6-8F6B-687FAA26FA71"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ComClass1Events
{
}
[ComVisible(true)]
[Guid("0D53A3E8-E51A-49C7-944E-E72A2064F938"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(ComClass1Events))]
[ProgId("test.Application")]
public class ComClass1 : ComClass1Interface
{
}
Is anything wrong with my C# dll or does JACOB require a certain type of structure in this dll?
Unfortunately I could not find any COM examples for JACOB.
Thanks in advance.
EDIT:
If i change my first line to:
ActiveXComponent comp = new ActiveXComponent("CLSID:{C9888A8E-8D23-4185-9D7D-A1E0B812803D}");
I'm getting following Exception:
Exception in thread "main" com.jacob.com.ComFailException: Can't find moniker
My .dll should be registered though.
I would first write a VBS (VB script) program to test your DLL and make sure it runs.
set obj = CreateObject("test.application")
MsgBox TypeName(obj)
Make sure it succeeds. If it fails, then (assuming a 64-bit OS), try running it with c:\windows\syswow64\wscript.exe path\to\your\script.vbs.
Check to see whether your Java process is a 64-bit or 32-bit process. Your C# DLL has to be registered with the same bit-ness as your Java process for it to succeed.
Thanks for the hint, I was able to find a solution:
Visual Studio apparently registered my COM-Object as 32 bit.
I'm not sure if this is a default setting(?).
So two simple steps to solve the problem:
open your windows cmd as admin.
Run the following Command:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe /verbose /nologo /codebase "path to your dll"
The command will register the .dll in 64 bit and not 32.
This solved the problem for me and I could use it via JACOB.

Error while compiling java file with GCC

I wrote a small java program in Netbeans. It compiles and runs perfectly. But I also need to compile it in javac in Linux because this homework is tested there. Whenever I attempt, I get the following compile error message. Do you have any idea about this message?
/usr/lib64/gcc/x86_64-suse-linux/4.6/../../../../lib64/crt1.o: In function `_start':
/home/abuild/rpmbuild/BUILD/glibc-2.14.1/csu/../sysdeps/x86_64/elf/start.S:109: undefined reference to `main'
I just write the following line for import a library
import java.sql.*;
I am just using println except sql operations. The beginning of my code is below:
Connection conn = null;
try{
String username = ".....";
String password = "....";
String url = "jdbc:mysql://localhost:3306/.....";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
System.out.println("Database connection extablished.");
}
catch(Exception e){
System.out.println("Cannot connect to database server");
}
After this part of code, nothing special, just ordinary lines.
It seems that error may be because you're not defining a main method, and the compiler therefore can't find it.
However, I have to ask why you're using GCC? Normal JDK is available on Linux and should be your preferred choice unless you have a very good reason otherwise! If Netbeans isn't compiling your application on Linux then it's probably because you haven't set something up properly or installed the JDK - you can (and should) use the JDK rather than GCJ, which is now largely unmaintained.
You can either grab it through your package manager or download it separately here.
You don't need to (re-)compile it for linux. It's Java. The generated class file (from windows) will run on Linux and Windows, you just need a JRE or JDK on the target host.
Compile with javac, not GCC (or GCJ if you really want something "GCCish").

Open a path with Desktop.open() from java on ubuntu (linux)

From my application written in java I want to open a folder, using the operating system file explorer.
I use Desktop.open(new File(path))
This works fine on windows, but on ubuntu 11.10 (linux) it doesn't work.
Using the Desktop.open to open a file does work, both on ubuntu and windows.
Using a step in between:
File fPath=new File(fPath)
and testing it with fPath.exists() and fPath.isDirectory() both gives true.
using the Desktop.open(new File(path)) gives me this exception:
java.io.IOException: Failed to show URI:file:/and/here/the/path/I/use/
at sun.awt.X11.XDesktopPeer.launch(Unknown Source)
at sun.awt.X11.XDesktopPeer.open(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
I was not able to test this on an apple computer yet, but I hoped the Desktop.open(new File(path)) was system independent.....
by the way, the complete code:
Desktop desktop = null;
// Before more Desktop API is used, first check
// whether the API is supported by this particular
// virtual machine (VM) on this particular host.
if (!Desktop.isDesktopSupported()) {
// show Error
return;
}
desktop = Desktop.getDesktop();
String path = "here the path ";
// by the way: I use System.getProperty("file.separator") as file seperator
try {
File fPath=new File(path);
if(!fPath.exists()){
// show Error
return;
}
if(!fPath.isDirectory()){
// show Error
return;
}
desktop.open(new File(path));
} catch (IOException e) {
log.severe(e.getMessage());
e.printStackTrace();
// show Error
return;
}
Some extra information:
OS: Linux (3.0.0-16-generic - amd64)
Java: 1.6.0_30-b12
Java home: /opt/java/64/jre1.6.0_30
I had the same problem. But in my case it was Ubuntu 18.04 and java 1.8.0_161-b12
In Windows 10, everything is working fine. But on Ubuntu
Desktop.getDesktop().open(new file)
the program stopped responding.
I decided to wrap the call in the executor:
private ExecutorService executorService;
BasicThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern("YourPatternIndeficator")
.build();
executorService = Executors.newSingleThreadExecutor(factory);
if (Desktop.isDesktopSupported()) {
File myFile = new File(path);
executorService.execute(() -> {
try {
Desktop.getDesktop().open(myFile);
} catch (IOException e) {
e.printStackTrace();
}
});
}
I was running into what sounds like the same issue on Mint 13. From what I can tell, changes to mime handling for opening directories has broken the java Desktop api. I was able to work around the problem by editing
~/.local/share/applications/defaults.list
and adding this line
x-directory/normal=nautilus.desktop
I'm running Mint 13 Cinnamon with java version "1.7.0_05"
I can't confirm the error. I took your code and constructed a main method around it, and everything works as expected. I don't exactly know where the default applications are set (in my case PCMan was opened instead of usual Nautilus, but it should fulfil its purpose in the end).
Over at java.awt.Desktop.open doesn’t work with PDF files? I have found a link pointing to an issue in Suns (Oracles) bug tracker stating that the method for opening files using AWT isn't reliable even on Windows. Maybe you should think of alternative ways of opening such applications. Furthermore AWT is deprecating soon almost for sure.
If you are utilizing SWT in your application, you could use org.eclipse.swt.program.Program.
I was running into the same issue and decided to give Java 7 a whirl. I'm running java version "1.7.0_147-icedtea" on Ubuntu 11.10_x64 and am able to open file locations in Nautilus quite happily now.
I have the same issue on my Linux Mint (and not in Windows).
That link helped me :
Troubles with java.awt.Desktop browse() method.
This seems to work on my Linux Mint-KDE.
I changed the line
Desktop.getDesktop().desktop.open(new File("/home/user/mypath"));// this throws IOException: Failed to show URI (except in Windows)
with
Desktop.getDesktop().desktop.open(new File("///home/user/mypath"));// this launches Dolphin
or with
Desktop.getDesktop().desktop.open(new File(new URI("file:///home/user/mypath").getPath()));// this launches Dolphin
Dolphin was launched with my folder "mypath". But I found no way to open a file like a pdf or txt on my Linux while it works on Windows with the first code.
(Java 1.8.0_25, Netbeans 8.02, Linux Mint 12 KDE)
I have the issue with Kubuntu 18.04 and java 11. It was solved with
sudo apt install libgnome2-0 gvfs
see https://bugs.launchpad.net/ubuntu/+source/openjdk-8/+bug/1574879/comments/5 for details. java.awt.Desktop works with Gnome not with KDE.

RMI Registry Issue: rmiregistry may cause unintended exceptions when binding with codebase using the "file:" URL scheme

Please see the passage "RMI Registry Issue" of this article for the background on Java Update 1.6.0_29 first.
If I understand correctly (I'm german), the update introduces a bug in the rmiregistry which fails to work with the file: pattern in the codebase.
I.E. the following won't work any more with 1.6.0_29:
-Djava.rmi.server.codebase="file:myproject/bin/ ..."
We are currently using the feature of having a codebase with file: syntax. Does anyone know a workaround for making this work?
Note: No, we do not want to start a local webserver or ftp server.
Update:
On Naming.bind this exception is thrown:
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
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:400)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:248)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
I had the same problem, and can confirm that downgrading JDK to earlier version solves the problem. I know, it's not a solution you're looking for, but at least it makes it to work.
Take running in windows as an example:
Step 1. In C:\Users\Jimmy.java.policy (create it if not exist), append below content:
grant { permission java.security.AllPermission; };
Of course "C:\Users\Jimmy\" is the user home, please change to your home accordingly.
Adding AllPermission is just for quick resolving your issue. you'd better config a more accurate FilePermission here.
Step 2. Start rmiregistry:
C:\JDK\bin>rmiregistry -J-Djava.rmi.server.codebase=file://C:/workspaces/MyLab/target/classes/
(Please note codebase must ended with "/")
Step 3. Run your server and client program.
References:
http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/codebase.html
http://docs.oracle.com/javase/7/docs/technotes/guides/security/spec/security-spec.doc3.html
http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/enhancements-7.html
It looks like there is no workaround because it is a bug, so wait for the fix
See details at
https://bugzilla.redhat.com/show_bug.cgi?id=751203
Code fix
http://icedtea.classpath.org/hg/icedtea6/rev/67df573b0734
If you do not need dynamic code downloading (in which case you can use ftp codebase) the solution is simply to set CLASSPATH environment variable to the path to your jar file:
Windows:
set CLASSPATH="path_to_jarfile"
Linux (batch):
CLASSPATH="path_to_jarfile"
export CLASSPATH
Best place to do it is in some script that invokes the RMI server.
Setting class path in the command line (-cp option) when starting RMI server does not help because it does not affect rmiregistry classpath!
If you start the rmiregistry in the working directory of your project, it works.
So essentially working directory of your project and current directory for rmiregistry should be same.
I recently encountered this issue as well. I can confirm that when using the file: protocol the rmiregistry must either:
be started in the root of the directory containing the shared classes; or
set the classpath to point to the shared classes or shared class jar; or
use a protocol other than file:// (I set up ngnix and served the jar from that).
Maybe not what you want, but you could resolve this with classpath rather than codebase. The client JVM will work fine if you add the required classes to its classpath. If you are using the file: URL scheme, then the classes must already be available on the localhost.
I had the same problem but I couldn't change the JDK version. Turns out you can solve it by running/starting the rmiregistry from the same directory as your code base, which in my case was target/classes. So cd project/target/classes and then run rmiregistry &

Categories

Resources