Java grph library: Exception on toools.os.OperatingSystem.getLocalOS() - java

I'm using grph library for a university project (www.i3s.unice.fr/~hogie/grph/)
but i have a problem only on Linux with that library, when i create a new Graph object, i receive the following exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.elendev.wesproject.graph.GraphFactory.main(GraphFactory.java:19)
Caused by: java.lang.NullPointerException
at toools.os.OperatingSystem.getLocalOS(OperatingSystem.java:47)
at grph.Grph.setCompilationDirectory(Grph.java:353)
at grph.Grph.<clinit>(Grph.java:246)
... 1 more
I tried to call directly getLocalOS function, with:
System.out.println(toools.os.OperatingSystem.getLocalOS());
and i receive the same exception. I cannot find information about that library, and the project launched on a macbook works perfectly.
The operating system i'm currently using is gentoo linux 32bit.
And the jdk version is: 1.7.0_65
Any idea of what could be the problem?

Not sure whether this can count as an answer, but it could at least help to solve the issue:
The exception comes from the toools.os.OperatingSystem.getLocalOS method. Although the .JAR file from the website that you mentioned has a whopping 39 megabytes, the source code of this class is not contained in it.
There seems to be no information available about this class at all. Neither Google nor Maven finds anything related to the toools package. One has to assume that it is an abandoned utility class that passed away a long time ago.
However, the method in question can be disassembled to the following code:
public static OperatingSystem getLocalOS()
{
if (localOS == null)
{
if (new RegularFile("/etc/passwd").exists())
{
if (new Directory("/proc").exists())
{
if (new RegularFile("/etc/fedora-release").exists()) {
localOS = new FedoraLinux();
} else if (ExternalProgram.commandIsAvailable("ubuntu-bug")) {
localOS = new UbuntuLinux();
} else {
localOS = new Linux();
}
}
else if (new Directory("/Applications").exists()) {
localOS = new MacOSX();
} else {
localOS = new Unix();
}
}
else if (System.getProperty("os.name").startsWith("Windows")) {
localOS = new Windows();
} else {
localOS = new OperatingSystem();
}
localOS.name = System.getProperty("os.name");
localOS.version = System.getProperty("os.version");
}
return localOS;
}
From this, you can possibly derive the conditions that must be met in order to properly detect your OS as a linux OS. Particularly, when there is a file named /etc/passwd, and a directory /proc, this should be sufficient to identify the OS as a Linux. You may want to give it a try...

Related

Integrating Groovy RootLoader with Java 8 SystemClassLoader

The following is deep inside a library I use. In 2015 this worked with Groovy 2.3 and early versions of 2.4, probably with Java 6 or 7! I wanted to update to Java 8 before trying to modify for Java9+.
final class DynamicClassLoader extends ClassLoader {
final NodeID originatingNode;
NetChannelOutput requestClassData;
NetChannelInput classDataResponse = NetChannel.net2one();
final Hashtable classes = new Hashtable();
DynamicClassLoader(NodeID originator, NetChannelLocation requestLocation) {
super(ClassLoader.getSystemClassLoader());
this.originatingNode = originator;
this.requestClassData = NetChannel.one2net(requestLocation);
}
...
}
When I try to invoke the code from Groovy I get the following error:
org.codehaus.groovy.tools.RootLoader cannot be cast to jcsp.net2.mobile.DynamicClassLoader
The Point where this is called from is given in the following code at the line indicated by **
public byte[] filterTX(Object obj)
throws IOException
{
ClassLoader loader = obj.getClass().getClassLoader();
byte[] bytes = this.internalFilter.filterTX(obj);
if (loader == ClassLoader.getSystemClassLoader() || loader == null)
{
DynamicClassLoaderMessage message = new DynamicClassLoaderMessage(Node.getInstance().getNodeID(),
(NetChannelLocation) ClassManager.in.getLocation(), bytes);
byte[] wrappedData = this.internalFilter.filterTX(message);
return wrappedData;
}
**DynamicClassLoader dcl = (DynamicClassLoader)loader;**
DynamicClassLoaderMessage message = new DynamicClassLoaderMessage(dcl.originatingNode,
(NetChannelLocation) ClassManager.in.getLocation(), bytes);
byte[] wrappedData = this.internalFilter.filterTX(message);
return wrappedData;
}
After discussion with the Groovy community I discoverd that the problem lay in the way the Intellij invokes Groovy scripts. The code works in Eclipse without any problem. In Intellij it was necessary to create a jar artifact for each of the scripts I wanted to run in parallel, which I could then run from a command line interface. I recoded the application in Java 8 and it worked with no problem. Hope that helps.

How to resolve UnsupportedOperationException?

I'm trying to develop a simple SNMP GET/SET program in java using SNMP4j. I've followed the following tutorials
http://www.developer-tricks.com/2012/11/how-to-get-started-with-snmp4j.html
https://blog.jayway.com/2010/05/21/introduction-to-snmp4j/
I have also read through the 'Getting started with SNMP4J' stackoverflow thread.
Every tutorial and program I've tried to replicate so far to get me started has resulted in "Error:java: java.lang.UnsupportedOperationException" when I compile. I can't figure out why. I used the exact code in both the tutorials I listed above, and both resulted in the same error as soon as I compile. I've read up on other threads involving the exception, but haven't found anything relevant to SNMP4j, a lot of what I read involved something with lists using the AsList method, which isn't used at all.
The code im trying to run is directly copied from the 'developer-tricks' link I posted earlier. The only difference is I changed the OID and IP address to ones for my own machine.
If anyone else has some experience in how to solve this exception, I would realy appreciate any advice.
Here is the console output when I try to compile.
Information:javac 10 was used to compile java sources
Information:3/29/2018 4:19 PM - Compilation completed with 1 error and
0 warnings in 716ms Error:java:
java.lang.UnsupportedOperationException
Here is my code, nearly identical to the 'how-to-get-started-with-snmp4j' tutorial i linked to.
public static void main(String[] args) throws IOException {
try {
Snmp snmp4j = new Snmp(new DefaultUdpTransportMapping());
snmp4j.listen();
Address add = new UdpAddress("192.168.1.10" + "/" + "161");
CommunityTarget target = new CommunityTarget();
target.setAddress(add);
target.setTimeout(500);
target.setRetries(3);
target.setCommunity(new OctetString("public"));
target.setVersion(SnmpConstants.version2c);
PDU request = new PDU();
request.setType(PDU.GET);
OID oid = new OID(".1.3.6.1.4.1.34832.512.1.1.1.2");
request.add(new VariableBinding(oid));
PDU responsePDU = null;
ResponseEvent responseEvent;
responseEvent = snmp4j.send(request, target);
if (responseEvent != null) {
responsePDU = responseEvent.getResponse();
if (responsePDU != null) {
Vector tmpv = responsePDU.getVariableBindings();
if (tmpv != null) {
for (int k = 0; k < tmpv.size(); k++) {
VariableBinding vb = (VariableBinding) tmpv.get(k);
String output = null;
if (vb.isException()) {
String errorstring = vb.getVariable().getSyntaxString();
System.out.println("Error:" + errorstring);
} else {
String sOid = vb.getOid().toString();
Variable var = vb.getVariable();
OctetString oct = new OctetString((OctetString) var);
String sVar = oct.toString();
System.out.println("success:" + sVar);
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
Turns out the error had nothing to do with SNMP4j. It happened with any program I compiled.
In order to fix this, I uninstalled JDK 10 and installed JDK 9 instead. I was using Intellij. Not sure exactly what caused this, but uninstalling and reinstalling was the solution.

unable to determine the MIME type of a file

I'm new to Java and is trying to learn how to determine the MIME type of a file. I'm using Mac OS. Below is the code I came up with. However, when I run the code, the IDE output error:
'/Users/justin/Desktop/Codes Netbean/JavaRandom/xanadu.txt' has an unknown filetype.
Why is this happening? The file does exist. Am I doing something wrong?
public class DeterminingMIMEType {
public static void main(String[] args) {
Path filename = Paths.get("/Users/justin/Desktop/Codes Netbean/JavaRandom/xanadu.txt");
try {
String type = Files.probeContentType(filename);
if (type == null) {
System.err.format("'%s' has an" + " unknown filetype.%n", filename);
} else if (!type.equals("text/plain")) {
System.err.format("'%s' is not" + " a plain text file.%n", filename);
}
} catch (IOException x) {
System.err.println(x);
}
}
}
The documentation for Files reveals that a FileTypeDetector is loaded by ServiceLoader. A wee bit of googling leads to:
http://blog.byjean.eu/java/2013/08/22/making-jdk7-nio-filetypedetection-work-on-mac-osx.html
which says that this is a problem with the default FileTypeDetector provided by the Oracle Java7 jvm for Mac OS.
The link also has a way of providing your own FileTypeDetector, though upgrading to Java 8 (maybe?) also will fix the problem.

Java Printing Tray Selection Saga

While there are several questions regarding tray selection out there, none of them relate to my problem.
Here's the code I'm using to print:
private static void finalPrint(PDDocument pdoc, boolean pbStationary)
throws BigBangJewelException
{
PrintService lrefSvc;
PrinterJob lrefPJob;
Media lrefMedia;
HashPrintRequestAttributeSet lobjSet;
lrefSvc = getPrinter();
lrefPJob = PrinterJob.getPrinterJob();
try
{
lrefPJob.setPrintService(lrefSvc);
lrefPJob.setPageable(pdoc);
lrefMedia = null;
if ( pbStationary )
lrefMedia = getTray(lrefSvc);
if ( lrefMedia != null )
{
lobjSet = new HashPrintRequestAttributeSet();
lobjSet.add(lrefMedia);
lrefPJob.print(lobjSet);
}
else
lrefPJob.print();
}
catch (Throwable e)
{
throw new BigBangJewelException(e.getMessage(), e);
}
}
private static PrintService getPrinter()
throws BigBangJewelException
{
String lstrPrinter;
PrintService[] larrServices;
int i;
try
{
lstrPrinter = (String)Engine.getUserData().get("Printer");
larrServices = PrinterJob.lookupPrintServices();
for ( i = 0; i < larrServices.length; i++ )
{
if (larrServices[i].getName().indexOf(lstrPrinter) != -1)
return larrServices[i];
}
}
catch (Throwable e)
{
throw new BigBangJewelException(e.getMessage(), e);
}
throw new BigBangJewelException("Impressora definida (" + lstrPrinter + ") não encontrada.");
}
private static Media getTray(PrintService prefSvc)
{
Media[] larrMedia;
String lstrAux;
int i;
larrMedia = (Media[])prefSvc.getSupportedAttributeValues(Media.class, null, null);
if ( larrMedia == null )
return null;
for ( i = 0; i < larrMedia.length; i++ )
{
lstrAux = larrMedia[i].toString().toLowerCase();
if (lstrAux.contains("tray") && lstrAux.contains("3"))
{
return larrMedia[i];
}
}
return null;
}
The baffling thing is, this code used to work. The machine had a bunch of Xerox printers defined, and the code would correctly identify the wanted printer, and the wanted tray, and everything worked wonderfully.
Then, one day, overnight, it stopped working. It still finds the right printer, but now, it always prints to tray 1.
The only thing that changed was that an extra HP printer was added to the machine.
I can confirm that the code is finding the tray and sending it to the print job, but it's getting ignored.
Again, there are many questions out there regarding this issue, but my problem is that the code worked well for four years, then stopped working for no apparent reason.
Can anyone shed any light on this subject?
Edit: New information: Uninstalling the HP printer made the Xerox printers work right again. Why would installing one driver affect Java's ability to communicate with a different driver?
Edit 2: Further information: If we install the HP global printer driver instead of the specific printer driver, everything works correctly. I'll leave the question unanswered to see if anyone can come up with a good explanation before the bounty expires, then I'm going to put this edit in an answer and accept it.
If I got you question correctly, you the content of lobjSet is unchanged, yet it the print result is different, with the new driver installed.
I checked the code for PnterJob.print(PrintRequestAttributeSet) and was surprised that it completely ignores the attribute set.
So I looked at where the PrintService is coming from, the code is a little lengthy, but I guess it interacts somehow with the installed printer drivers to create appropriate instances. So the new driver changes this, returning a different PrintService. There is no way I can tell in what exact way this thing changes, but if you can recreate both scenarios (and it seems you can), it should be fairly easy to use a debugger to find the exact place where the behavior of the code changes.
The solution to our particular situation was to change the printer drivers for the HP printer.
Originally, we had installed the specific driver for the printer in question, which caused this behavior. Installing HP's global driver instead made the problem go away.
Unfortunately, we do not know why. Jens Schauder's answer contains clues as to how to go about finding out.

R - Connecting R and java using Rserve

I have build an application connecting R and java using the Rserve package.
In that, i am getting the error as "evaluation successful but object is too big to transport". i have tried increasing the send buffer size value in Rconnection class also. but that doesn't seem to work.
The object size which is being transported is 4 MB
here is the code from the R connection file
public void setSendBufferSize(long sbs) throws RserveException {
if (!connected || rt == null) {
throw new RserveException(this, "Not connected");
}
try {
RPacket rp = rt.request(RTalk.CMD_setBufferSize, (int) sbs);
System.out.println("rp is send buffer "+rp);
if (rp != null && rp.isOk()) {
System.out.println("in if " + rp);
return;
}
} catch (Exception e) {
e.printStackTrace();
LogOut.log.error("Exception caught" + e);
}
//throw new RserveException(this,"setSendBufferSize failed",rp);
}
The full java class is available here :Rconnection.java
Instead of RServe, you can use JRI, that is shipped with rJava package.
In my opinion JRI is better than RServe, because instead of creating a separate process it uses native calls to integrate Java and R.
With JRI you don't have to worry about ports, connections, watchdogs, etc... The calls to R are done using an operating system library (libjri).
The methods are pretty similar to RServe, and you can still use REXP objects.
Here is an example:
public void testMeanFunction() {
// just making sure we have the right version of everything
if (!Rengine.versionCheck()) {
System.err.println("** Version mismatch - Java files don't match library version.");
fail(String.format("Invalid versions. Rengine must have the same version of native library. Rengine version: %d. RNI library version: %d", Rengine.getVersion(), Rengine.rniGetVersion()));
}
// Enables debug traces
Rengine.DEBUG = 1;
System.out.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) no callback class will be used
engine = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine", new String[] { "--no-save" }, null, false);
System.out.println("Rengine created...");
engine.parseAndEval("rVector=c(1,2,3,4,5)");
REXP result = engine.parseAndEval("meanVal=mean(rVector)");
// generic vectors are RVector to accomodate names
assertThat(result.asDouble()).isEqualTo(3.0);
}
I have a demo project that exposes a REST API and calls R functions using this package.
Take a look at: https://github.com/jfcorugedo/RJavaServer

Categories

Resources