java.lang.NullPointerException in netbeans - java

i'm writing a bit of code and i keep getting this error, it's to do with where i call network.addstation
here's the code, there are other methods in the network method but i thought i'd just show one, but it appears when you call any method. any help would be much appreaciated. thanks.
public class MyNetworkReader implements NetworkReader {
Network network = null;
#Override
public Network read(InputStream stream) {
Scanner scan = null;
scan = new Scanner(stream);
while (scan.hasNext()) {
String fromStation = scan.next();
if (!fromStation.equalsIgnoreCase("connection:")) ;
network.addStation(fromStation)
System.out.println(fromStation);
}
}
return network;
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class MyNetwork implements Network {
HashMap<String, ArrayList> stations = new HashMap<String, ArrayList>();
public void addStation(String station) {
stations.put(station, null);
}
}

Are you constructing a MyNetwork instance anywhere?
Seems like you want
Network network = null;
To be
MyNetwork network = new MyNetwork();
Because you're trying to call a method on an uninitiated object. But your MyNetwork class needs a constructor.

Note you can also get this error immediately upon running C++ code, with the default NetBeans setup, if your Project's Properties->Run->Console Type is set to Internal Terminal and not External Terminal; at least when using FLTK graphics on Ubuntu. In this case it's a NetBeans internal handshaking problem and not a source code problem.

You're yourself initializing network to null, in second line of your code, then it will obviously throw NullPointerException

As DragonLord said, it is not a source code issue. You will be able to tell because that should happen whenever you run any C++ code. I had the same problem. I did something slightly different than DragonLord, though. I set the output of the program to Project Properties>Run>Console Type and set it to Standard Output.

Related

SnakeYAML loadAs() returns null

I attempted to create a Spigot plugin today and I'm coming up with an error that's hard to fix. When I was trying to create a file system to save some data I downloaded the source code for the library SnakeYAML and put it in my src. Then I followed this tutorial and created a config and followed all the instructions. I'm getting a NullPointerException. It turns out the config object is null. I'm not sure what's happening.
PlayerYML getConfig(File playerYml) {
try {
InputStream ymlStream = new FileInputStream(playerYml.getAbsolutePath());
System.out.println(ymlStream);
PlayerYML config = yaml.loadAs(ymlStream, PlayerYML.class);
return config;
} catch (Exception ex) {
System.out.println("getConfig() error");
ex.printStackTrace();
return null;
}
}
Here is my PlayerYML class:
import java.util.Map;
public class PlayerYML {
private int reputation;
private Map<String/*UUID*/, String/*Date*/> map;
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
I appreciate all help! Thank you :)
You are trying to load an empty file/stream as on object which will result in null using SnakeYAML.
If you want to handle the absense of the file properly instead of just creating an empty file, you should check if it exists and directly create a default instance of the object if the file doesn't exist. If you then want to create the file with defaults for the user to edit them, just store the default instance of the object using one of the Yaml.dump* methods. That way you avoid creating an empty object by yourself. You still have to handle empty files in case of user errors.
What happened to me was that my InputStream was already entirely consumed by a BufferedReader just above, so there was nothing left in the Stream to be treated.
What I had to do was to reset the InputStream or simply open a new one.

ArangoDB java driver on executing AQL sometimes return NULL and other times the correct result

I am unable to wrap my head around this peculiar issue.
I am using arangodb 3.0.10 and arangodb-java-driver 3.0.4.
I am executing a very simple AQL fetch query. (See code below) All my unit tests pass every time and problem never arises when debugging. The problem does not occur all the time (around half the time). It gets even stranger, the most frequent manifestation is NullPointerException at
return cursor.getUniqueResult();
but also got once a ConcurrentModificationException
Questions:
Do I have to manage the database connection? Like closing the driver
connection after each use.
Am i doing something completely wrong
with the ArangoDB query?
Any hint in the right direction is appreciated.
Error 1:
java.lang.NullPointerException
at org.xworx.sincapp.dao.UserDAO.get(UserDAO.java:41)
Error 2:
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437)
at java.util.HashMap$EntryIterator.next(HashMap.java:1471)
at java.util.HashMap$EntryIterator.next(HashMap.java:1469)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:206)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:145)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:208)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:145)
at com.google.gson.Gson.toJson(Gson.java:593)
at com.google.gson.Gson.toJson(Gson.java:572)
at com.google.gson.Gson.toJson(Gson.java:527)
at com.google.gson.Gson.toJson(Gson.java:507)
at com.arangodb.entity.EntityFactory.toJsonString(EntityFactory.java:201)
at com.arangodb.entity.EntityFactory.toJsonString(EntityFactory.java:165)
at com.arangodb.impl.InternalCursorDriverImpl.getCursor(InternalCursorDriverImpl.java:94)
at com.arangodb.impl.InternalCursorDriverImpl.executeCursorEntityQuery(InternalCursorDriverImpl.java:79)
at com.arangodb.impl.InternalCursorDriverImpl.executeAqlQuery(InternalCursorDriverImpl.java:148)
at com.arangodb.ArangoDriver.executeAqlQuery(ArangoDriver.java:2158)
at org.xworx.sincapp.dao.UserDAO.get(UserDAO.java:41)
ArangoDBConnector
public abstract class ArangoDBConnector {
protected static ArangoDriver driver;
protected static ArangoConfigure configure;
public ArangoDBConnector() {
final ArangoConfigure configure = new ArangoConfigure();
configure.loadProperties(ARANGODB_PROPERTIES);
configure.init();
final ArangoDriver driver = new ArangoDriver(configure);
ArangoDBConnector.configure = configure;
ArangoDBConnector.driver = driver;
}
UserDAO
#Named
public class UserDAO extends ArangoDBConnector{
private Map<String, Object> bindVar = new HashMap();
public UserDAO() {}
public User get(#NotNull String objectId) {
bindVar.clear();
bindVar.put("uuid", objectId);
String fetchUserByObjectId = "FOR user IN User FILTER user.uuid == #uuid RETURN user";
CursorResult<User> cursor = null;
try {
cursor = driver.executeAqlQuery(fetchUserByObjectId, bindVar, driver.getDefaultAqlQueryOptions(), User.class);
} catch (ArangoException e) {
new ArangoDaoException(e.getErrorMessage());
}
return cursor.getUniqueResult();
}
As AntJavaDev said, you access bindVar more than once the same time. When one thread modify bindVar and another tried to build the AQL call at the same time by reading bindVar. This leads to the ConcurrentModificationException.
The NullPointerException results from an AQL call with no result. e.g. when you clear bindVar and directly after that, execute the AQL in another thread with no content in bindVar.
To your questions:
1. No, you do not have to close the driver connection after each call.
2. Beside the shared bindVar, everything looks correct.

Aggregation Program

I am trying to learn more about Apache Camel. I found the documentation somewhat helpful but leaves alot of guessing for beginner Camel riders that do not know how small code segments should easily fit into fully functioning programs. Hopefully most people know what I am trying to describe. I have been lost lots of other times in some programming books where segments of code are shown outside of the context of a fully running program.
Anyway here is my program that does not aggregate messages for some reason. I was hoping it would aggregate all my messages but this program does not do that. When running the program I receive an empty file as the output which is not my goal.
package laser.helmet.camel.friend;
import org.apache.camel.builder.RouteBuilder;
public class AggregatingMessagesRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("direct:start")
.aggregate().constant(true)
.completionTimeout(100L)
.groupExchanges()
.to("file:target/this_folder/result?allowNullBody=true");
}
}
Then I call this program from the below class which has the main method of course.
package laser.helmet.camel.friend;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.ProducerTemplate;
public class Main {
public static void main(String[] args) throws Exception {
CamelContext c = new DefaultCamelContext();
c.addRoutes(new AggregatingMessagesRoute());
ProducerTemplate pt = c.createProducerTemplate();
c.start();
pt.sendBody("direct:start", "1");
pt.sendBody("direct:start", "2");
Thread.sleep(5000);
c.stop();
}
}
I was expecting the body of the two messages I create with the ProducerTemplate to be both in the file after the route finishes but it is just a blank file. I had to add the part allowNullBody=true to the route because for some reason the body is null when running this program.
Also if you are a beginner and wondering. I am bringing in the dependencies with Maven instead of putting the camel.jars on my Java classpath.
Thank-you for reading this everyone. :D
So how can I start aggregating messages Stackoverflow? 0_o
Peace,
user_loser
This is an easy one since you provided the code snippet, nice one!
Remove .groupExchanges() since it is becoming deprecated and it is hardly adequate. You always need a AggregationStrategy to have fine grained control over how to aggregate your exchanges. So, add the following class:
class StringAggregationStrategy implements AggregationStrategy {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String oldBody = oldExchange.getIn().getBody(String.class);
String newBody = newExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(oldBody + "+" + newBody);
return oldExchange;
}
}
And then reference it in your route; so it becomes something like this:
public class AggregatingMessagesRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("direct:start")
.aggregate().constant(true)
.completionTimeout(100L)
.aggregationStrategy(new StringAggregationStrategy())
.to("file:target/this_folder/result?allowNullBody=true");
}
}
Hope this helps!
R.

ClassNotFoundException with JGroups

I have an issue with JGroups where after building my project, running it produces this error:
Caused by: java.lang.ClassNotFoundException: org.jgroups.ReceiverAdapter
My class looks something like this -
import org.jgroups.ReceiverAdapter;
import org.jgroups.Channel;
import org.jgroups.JChannel;
public class MyClass extends ReceiverAdapter implements MyInterface {
Channel channel;
String state = "state";
public MyClass() {
super();
start();
}
public void start() {
try {
channel = new JChannel();
channel.setReceiver(this);
channel.connect("ServerCluster");
channel.getState(null, 0);
System.out.println("Connected to cluster");
} catch (Exception e) {
System.out.println("Failed to connect to cluster");
}
}
public void getState(OutputStream output) throws Exception {
System.out.println("get response");
}
public void setState(InputStream input) throws Exception {
System.out.println("set test");
}
}
Running the project from IntelliJ produces no errors, but does not produce the desired prints from getState() and setState() either. I tried creating a brand new project in the Eclipse IDE, but the same is happening there too. Connecting has been working fine, states is a new addition to my project.
Running java MyClass from the command line fires the error seen at the start of this question. The JGroups jar seems to be added to the classpath properly as org.jgroups.Channel and org.jgroups.Channel (among others) are being found.
There is a SimpleChat program provided by the JGroup devs, but when I created a new project for this I encountered the same problem.
Edit
So it turns out I have to explicitly set the classpath when running from the CLI. But still, when running the code it seems like the getState() and setState() methods are never called as there are no print statements. SimpleChat doesn't print received state... like it is meant to.
Does anyone have a solution?
Best.
So, I on the JChannel I was using RpcDispatcher and it seems I can't use the dispatcher and the getState() and setState() methods on the same channel. Simple solution: create a second channel. Seems my knowledge on the fundamentals of JGroups is lacking!

Flex : LCDS Service returning null Asynctoken when executed 2nd time

I'm developing a Flex application using RobotLegs, LiveCycle DS & Java.
I'm trying to implement an update function, using LCDS, but I'm running into some strange behaviour:
This is the ActionScript code within a RobotLegs' execute command,
used to perform the update:
var token:AsyncToken = services.requestService.commit(new Array(model.currentRequestDetail));
responder = new AsyncResponder(resultHandler, faultHandler, token);
if ( token ) token.addResponder(responder);
The model.currentRequestDetail I'm trying to update is a RequestDetail Object:
[Managed]
[RemoteClass(alias="be.fgov.mobilit.td.lcds.vo.RequestDetail")]
public class RequestDetail {
public var id:Number;
public var request:Request;
public var task:Task;
/**
* Constructor
*/
public function RequestDetail() {
}
}
The first time the Actionscript code is executed, everything works fine.
The AsyncToken is nicely returned by the services.requestService.commit() function,
the resultHandler is executed as expected, and my object is updated in the GUI.
However, the second time this code is executed, my services.requestService.commit() function returns a null value, and my resultHandler is never reached.
I suspect we're not even reaching the java assembler.
This is how I declared the DataService:
var requestDetailService:DataService = new DataService("requestDetail");
requestDetailService.autoCommit = false;
Both the resultHandler & the faultHandler have the right signature:
resultHandler(result:Object, token:Object = null)
faultHandler(result:Object, token:Object = null)
We're also using a custom java assembler, this is the code:
package be.fgov.mobilit.td.lcds.assemblers;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import be.fgov.mobilit.td.lcds.vo.RequestDetail;
import flex.data.ChangeObject;
import flex.data.assemblers.AbstractAssembler;
public class RequestAssembler extends AbstractAssembler {
public RequestAssembler() {
// TODO Auto-generated constructor stub
}
public RequestDetail getRequest(Map<String, Object> identity) {
return ServiceUtility.getLcdsService().getRequestDetail(identity);
}
public List<ChangeObject> syncRequest(List<ChangeObject> changes) {
Iterator<ChangeObject> iterator = changes.iterator();
ChangeObject co;
while (iterator.hasNext()) {
co = (ChangeObject) iterator.next();
if (co.isUpdate()) {
co = doUpdate(co);
}
}
return changes;
}
private ChangeObject doUpdate(ChangeObject co) {
RequestDetail requestDetail = (RequestDetail) co.getNewVersion();
co.setNewVersion(ServiceUtility.getLcdsService().updateRequestDetail(requestDetail));
return co;
}
}
This is the assembler's configuration:
<destination id="request">
<properties>
<source>be.fgov.mobilit.td.lcds.assemblers.RequestAssembler</source>
<scope>application</scope>
<metadata>
<identity property="id" />
<identity property="task" />
</metadata>
<server>
<get-method>
<name>getRequest</name>
</get-method>
<sync-method>
<name>syncRequest</name>
</sync-method>
</server>
</properties>
</destination>
Long story short:
Does anyone have a clue/experience, why the 2nd time I execute the services.requestService.commit(); function it returns a null Asynctoken?
Thx in advance!
As requested, I added the (stripped) code from my services class.
As you can see, nothing really special going on:
package be.fgov.mobilit.services {
import mx.data.DataService;
import mx.messaging.Consumer;
import mx.messaging.events.MessageEvent;
import mx.rpc.http.HTTPService;
public class LiveCycleServices {
public var requestService:DataService;
public function LiveCycleServices() {
requestService = new DataService("request");
requestService.autoCommit = false;
}
/**
* #param MessageEvent The event object that is dispatched by the Flex framework
* #return void
*
* This message captures the server push messages that need to trigger an update
* of the task list, since this is specific for every client and cannot be
* determined on the server side, coming from LiveCycle.
*/
private function messageHandler(event:MessageEvent):void {
taskListService.refresh();
}
}
}
This is the chode where my result- & faulthandlers are added:
var token:AsyncToken = services.requestService.commit(new Array(model.currentRequestDetail));
var responder:AsyncResponder = new AsyncResponder(resultHandler, faultHandler, token);
if ( token ) token.addResponder(responder);
The aysnctoken returns null when you have no changes to commit. Hope this helps.
WWW, This isn't really an answer as such, but I need more space than a comment will give me. However, I'm not seeing how all your code is connected well enough to give you a good answer.
In general, the result and fault signatures should not look like what you describe as the "right" signature. The AsyncToken is expecting an IResponder, which whose fault and result mentods have a single parameter that is an Object. In general, this will be called with the fault or result event (as appropriate).
Now I am going into territory that is, for me, purely theoretical. It looks like to me that the DataService Class might possibly create just a single AsyncToken, since the connection is kept open. If that is the case, it is possible that the erroneous method signature damages the AsyncToken to the extent that it can't be returned for use by the method. I didn't see anything in the code that you pasted that looks like it calls your result and fault methods in a custom way.
I strongly doubt that the problem is in the Java code. AFAIK, the AsyncToken is created and set up to call the functions in the responder before the call is even made (at least that is how it seems to work with HTTPService or amf). I would expect that there's some error that is being "helpfully" suppressed, so you might benefit from stepping through the code.
I would suggest that you step back a bit and look a bit harder at the "S" part of the MVCS architecture implied by Robotlegs, and create a separate service Class that manages the whole thing, and merely kick off the process from a Command, rather than trying to pass control back and forth between your commands and services. As a side benefit, you can then swap out instances of the real service for test services when you don't need to be connected to the actual data (such as for doing design work).

Categories

Resources