How to resolve UnsupportedOperationException? - java

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.

Related

SNMP response is null [SNMP4j]

I've hit kind of a brick wall. I got a small system that communicate with DSLAM's by SNMP.
Everything has worked fine for a couple of months, but when I recently added a new DSLAM to the system, I couldn't get an answer from it. Tried the other IP's and didn't have a problem.
After an hour or so, suddenly on of the other DSLAM's stopped answering me too. So now I've got two units without any communication, which kinda sucks. So of course I checked the units, and didn't find a problem. By my MIB-browser, I can reach all of the units... But not via my software. So the error lies somewhere in my software. So I checked Wireshark, and see that the getNext requests are going out, but I don't seem to get an answer. When I do it via the MIB browser, there comes an answer. But the funny thing is: the two requests are identical. So I must not be listening - and yes, it is listening.
Why in the world is this specific to some IP's, and dear Lord why do they contaminate eachother?
Let's look at some code:
public String GetNextValue(String OID, Dslam dslam) throws IOException {
Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
snmp.listen();
CommunityTarget target = initializeTarget(dslam);
PDU request = new PDU();
request.setType(PDU.GETNEXT);
OID oid= new OID(OID);
request.add(new VariableBinding(oid));
PDU responsePDU=null;
ResponseEvent responseEvent;
responseEvent = snmp.send(request, target);
if (responseEvent != null){
System.out.println("resonse event not null..");
responsePDU = responseEvent.getResponse();
if ( responsePDU != null){
System.out.println("pdu not null..");
#SuppressWarnings("unchecked")
Vector <VariableBinding> tmpv = (Vector<VariableBinding>) responsePDU.getVariableBindings();
if(tmpv != null){
System.out.println("tmpv not null..");
VariableBinding vb = (VariableBinding) tmpv.get(0);
if(!vb.isException()){
return vb.getVariable().toString()
}
}
}
}
_errorHandler.criticalError("Response error in DSLAM communication");
return null;
}
And the initializer:
private CommunityTarget initializeTarget(Dslam dslam){
Address addr = new UdpAddress(dslam.getAddress() + "/" + dslam.getManagementPort() );
System.out.println("IP: " + dslam.getAddress() + " port: " + dslam.getManagementPort());
CommunityTarget target = new CommunityTarget(addr, new OctetString("public"));
target.setVersion(SnmpConstants.version2c);
target.setTimeout(3000);
target.setRetries(3);
return target;
}
And if we run a test upon a working DSLAM:
#Test
public void Lowtest() throws IOException{
SnmpController snmpController = SnmpController.GetInstance();
DslamGrabber dslamGrabber = new DslamGrabber();
Dslam dslam = dslamGrabber.getByDslamId("test5xda5");
String result = snmpController.GetNextValue(".1.3.6.1.4.1.637.61.1.39.3.3.1.1.2", dslam);
System.out.println(result);
}
Result:
IP: 195.215.96.135 port: 161
resonse event not null..
pdu not null..
tmpv not null..
OID: 1.3.6.1.4.1.637.61.1.39.3.3.1.1.2.1
BF512_2048
The we try against test5xda9 (the second one to succumb to this hideous disease-like error)
We get 3 retries in Wireshark, and the following output:
IP: 192.215.96.139 port: 161
resonse event not null..
Response error in DSLAM communication
null
I really hope somebody here can help me. I'm a few hours away to either break down in tears or break a DSLAM..
Best regards
Ben
Well, as a friend pointed out 192 does not equal 195.

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

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...

How can I create a node recursively using zookeeper client library on Java?

I know this question has been already asked and answered for a zookeeper using python. The answer was good, however, I want something more related with the code. I've already implemented a method to create a node, but I want to do it recursively. The structure for my nodes will be like this:
ZOOKEEPER
WEB SERVER
SERVER1
SERVER2
MODULE CONNECTED
DATABASE MODULE
COMPUTER1
COMPUTER2
SERVICE MODULE
COMPUTER3
SEARCH MODULE
COMPUTER4
I have something like:
Zookeeper zk = new Zookeeper(...);
public void createNodeRecursively(String type) {
final String node = "/" + type + "/" + info.getIP() + ":" + info.getPort(); // Correct line
if (zk.exists("/" + type, null) == null) {
Object ctx = new Object();
StringCallback cb = new StringCallback() {
public void processResult(int rc, String path,
Object ctx, String name) {
if (name.equals("/" + type))// just in case
try {
zk.create(node, info.getBytes(),
Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
} catch (Exception e) {
e.printStackTrace();
}
}
};
zk.create("/" + type, info.getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT, cb, ctx);
} else
zk.create(node, info.getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL);
}
}
As you can see I am using zk.create many times, so I want to make the method recursive in order to gain performance and have a better code, but I don't know how to start, I'll be very grateful if somebody can help me with this. Thank you very much in advance.
Zookeeper has useful properties:
Total order of (write) requests
Its asynchronous nature.
You can put on use that.
Simply issue whole tree as a bunch of asynchronous requests in correct order and then wait, until all of them successfully execute. Of course, you can ignore 'NodeExists' exceptions (but it is not good, due of the fact, that such errors will be written to logs).
I managed to achieve a better performance:
public void createNode(NodePath nodePath, NodeData nodeData, NodeRights nodeRights, NodeCreationHandler nodeCreationHandler) throws KeeperException, InterruptedException, ZookeeperCreationException {
if (zk == null) {
throw new ZookeeperCreationException("The zookeeper client has not been instanced.");
}
String targetPath = nodePath.getFullNodePath();
targetPath = targetPath.substring(1, targetPath.length());
byte[] serializedData = nodeData.serialize(new Object());
String[] array = targetPath.split(ICoordinationConstants.BASE_ROOT_SPTR);
String acum="";
for (int i = 0; i < array.length-1; i++) {
acum+=(ICoordinationConstants.BASE_ROOT_SPTR+array[i]);
if (zk.exists(acum, null) == null) {
zk.create(acum, serializedData, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
zk.create(acum+ICoordinationConstants.BASE_ROOT_SPTR+array[array.length-1], serializedData, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
}

Java 1.6 has runtime errors reading a file when 1.7 is fine

i have been working on an assignment on my own PC using JDK v1.7, and i have to submit my assignment on my uni's Unix computer with java version 1.6.
All of my code executes fine on my machine, and when i SSH into my uni's computer and transfer my code across, it compiles fine, too. however, when I go to run it, i receive a
NoSuchElementException: No line found
about 1000-1200 characters into the .xml file I need to read (the file is much longer than this).
the offending method is
private CDAlbum CDread(Scanner inLine) {
String tempTitle = "Unknown CD";
String tempGenre = "Unknown Genre";
String tempArtist = "Unknown Artist";
ArrayList<String> tempTracks = new ArrayList<String>();
do {
lineBuffer = inLine.nextLine();
if (lineBuffer.equals("<Title>")) {
tempTitle = inLine.nextLine();
System.out.println("reading in a CD, just read title: " + tempTitle);
} else if (lineBuffer.equals("<Genre>")) {
tempGenre = inLine.nextLine();
} else if (lineBuffer.equals("<Artist>")) {
tempArtist = inLine.nextLine();
//System.out.println("Which has artist: " + tempArtist);
} else if (lineBuffer.equals("<Tracks>")) {
//populate tracks array
lineBuffer = inLine.nextLine();
while (!(lineBuffer.equals("</Tracks>"))) {
tempTracks.add(lineBuffer);
//System.out.println("Read track: " + lineBuffer);
lineBuffer = inLine.nextLine();
}
}
} while (!(lineBuffer.equals("</CD>")));
System.out.println(tempTracks);
CDAlbum tempdisc = new CDAlbum(tempTitle, tempGenre, tempArtist, tempTracks);
return tempdisc;
}
with the error occurring at
lineBuffer = inLine.nextLine();
I'm a bit out of my debugging depth here, and any suggestions as to what could be causing this are welcome.
screenshot of console output: http://puu.sh/YXKN
entire source code (just in case, and because it's easy to do with dropbox): https://www.dropbox.com/sh/zz8vdzqgw296s3d/v_cfW5svHG
Answer not required any more - turns out i was mistaken, and the assignment is being marked on a windows 7 machine running java 1.7.

How to implement a Java compiler and DEX converter into an Android app?

While trying to find an answer to Android Jasper Reporting I found out that there are two other questions to be answered therefor, which I been asked to ask as a question, not as an answer ;):
My questions are now: "Is there any compiler to use directly on the device" AND "how to execute such without rooting the device.
If anybody could give me a hint I would really appreciate it...
I looked a little time forward on this approach, and found apps which makes it possible to create APKs directly on an Android device which is NOT rooted:
TerminalIDE - https://play.google.com/store/apps/details?id=com.spartacusrex.spartacuside&hl=de
JavaIDEdroid - http://code.google.com/p/java-ide-droid/
AIDE - https://play.google.com/store/apps/details?id=com.aide.ui&hl=en
Looks like they're using the compiler from eclipse and a ported dex converter. Now I'm trying to figure out how to do the same.
Sure: get the source code and look into it. But while I'm having curious problems to get a connection to the servers and trying to solve it, I follow the plea to ask this question here. Hoping both to help others with it and also getting an answer for myself ;)
I took the org.eclipse.jdt.core_3.7.3.v20120119-1537.jar from the plugin directory of my indigo and tried following code:
org.eclipse.jdt.internal.compiler.batch.Main ecjMain = new org.eclipse.jdt.internal.compiler.batch.Main(new PrintWriter(System.out), new PrintWriter(System.err), false/*noSystemExit*/, null, progress);
System.err.println("compiling...");
ecjMain.compile(new String[] {"-classpath", "/system/framework", storage.getAbsolutePath()+"/Test.java"});
ecjMain.compile(new String[] {storage.getAbsolutePath()+"/Test.java"});
System.err.println("compile succeeded!!!");
Sometimes the Exception was thrown that java.lang.Object could not be found and othertimes it stuck doing nothing while heating up my processor with 100% usage ... ...
At this time i could not figure out what is happening and why. And in cause that i have other work to do this part has to wait a little.
I succeeded after taking inspiration from source of JavaIDEdroid and realizing that I'm dumb (for a time I tried to uses the compiler with the dexified framework classes on the device - which naturtally could not work).
After i succeeded compiling my Test.java with a copy of ADTs android-jar on sdcard I just had to load the classes with the DexClassLoader.
While informing myselft about how to do that I found this nice article Custom Class Loading in Dalvik which inspired me at least to write this piece of code:
File storage = getDir("all41", Context.MODE_PRIVATE);
System.err.println("copying the android.jar from asssets to the internal storage to make it available to the compiler");
BufferedInputStream bis = null;
OutputStream dexWriter = null;
int BUF_SIZE = 8 * 1024;
try {
bis = new BufferedInputStream(getAssets().open("android.jar"));
dexWriter = new BufferedOutputStream(
new FileOutputStream(storage.getAbsolutePath() + "/android.jar"));
byte[] buf = new byte[BUF_SIZE];
int len;
while((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
dexWriter.write(buf, 0, len);
}
dexWriter.close();
bis.close();
} catch (Exception e) {
System.err.println("Error while copying from assets: " + e.getMessage());
e.printStackTrace();
}
System.err.println("instantiating the compiler and compiling the java file");
org.eclipse.jdt.internal.compiler.batch.Main ecjMain = new org.eclipse.jdt.internal.compiler.batch.Main(new PrintWriter(System.out), new PrintWriter(System.err), false/*noSystemExit*/, null);
ecjMain.compile(new String[] {"-classpath", storage.getAbsolutePath()+"/android.jar", Environment.getExternalStorageDirectory().getAbsolutePath() + "/Test.java"});
System.err.println("calling DEX and dexifying the test class");
com.android.dx.command.Main.main(new String[] {"--dex", "--output=" + storage.getAbsolutePath() + "/Test.zip", Environment.getExternalStorageDirectory().getAbsolutePath() + "/./Test.class"});
System.err.println("instantiating DexClassLoader, loading class and invoking toString()");
DexClassLoader cl = new DexClassLoader(storage.getAbsolutePath() + "/Test.zip", storage.getAbsolutePath(), null, getClassLoader());
try {
Class libProviderClazz = cl.loadClass("Test");
Object instance = libProviderClazz.newInstance();
System.err.println(instance.toString());
} catch (Exception e) {
System.err.println("Error while instanciating object: " + e.getMessage());
e.printStackTrace();
}
The Test.java only contains one method:
public String toString() {
return "Hallo Welt!";
}
To get it running you need the jars jdt-compiler-x.x.x.jar (found in plugins directory of eclipse) and dx.jar (found in directory platform-tools/lib of Android SDK)
Not really hard ;) And now I will find out what to change in source of JasperReports to get it work on our beloved Android devices :D

Categories

Resources