java null pointer exception- Occurs at varying points in while loop - java

I have the following Java while loop:
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData());
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
}
System.out.println();
}
}
The intended function of the while loop is to capture any PDUs that are being sent across the network, and display information about them.
When I run the code, I go get the output that I had intended in the console- at least initially... But after it has returned information about a number of the PDUs, I got an error displayed in the console (can't remember what it said now- but I thought it may be because it was trying to capture a PDU when there wasn't one being sent).
I have tried amending my code to account for the occasion that a PDU may not be being received over the network at the time that it is trying to capture the information about the PDU by surrounding the code with the following try- catch loop:
try{
socket = new MulticastSocket(EspduSender.PORT);
address = InetAddress.getByName(EspduSender.DEFAULT_MULTICAST_GROUP);
socket.joinGroup(address);
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData());
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
}
System.out.println();
}
}
catch(Exception e){
System.out.println(e);
System.out.println("This is where the error is being generated");
}
However, when I now run the code- it still displays the first x number of DIS packets it captures (x varies every time I run the code), but then gives me a java.lang.NullPointerException.
As I understand, this will occur either because the PDU that the code has captured does not contain any information, (i.e. an 'empty' PDU), or because it is attempting to receive a PDU when there isn't one being sent over the network.
How can I make the code 'skip' the occasion that it doesn't receive a PDU, and just keep running? Or is there something else I should do to get rid of this error?

This may not fix your problem (won't know until you put a stack trace up), but you could check to see if pdu is null before using it.
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData());
if (pdu != null) {
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
}
System.out.println();
}
}
If you get a stack trace out, I can change this for your actual problem.

You code looks perfectly alright , except the below missing line.
if (pdu != null) {
//execute this
}

Related

Java System.out.println only prints what's after VT character

I'm receiving data from a rabbit queue that I'm trying to convert to String. The message always starts with the SOH character and always ends with a VT character, followed by an ETX character. The data is received correctly and the byte array printed to the console is correct. The problem is that after converting to String, all the characters in the System.out.println before the VT and ETX are omitted. I first thought that the byte[] to String conversion might be done wrong by me, but I think there might be an issue with printing to the console that I'm missing.
Here's all the conversion approaches that I tried:
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
System.out.println("received message");
String message1 = new String(delivery.getBody(), StandardCharsets.US_ASCII);
String message2 = new String(delivery.getBody(), StandardCharsets.UTF_8);
String message3 = new String(delivery.getBody(), StandardCharsets.UTF_16);
String message4 = new String(delivery.getBody(), StandardCharsets.UTF_16BE);
String message5 = new String(delivery.getBody(), StandardCharsets.UTF_16LE);
String message6 = new String(delivery.getBody(), StandardCharsets.ISO_8859_1);
String message7 = new String(delivery.getBody());
String message8 = Base64.getEncoder().encodeToString(delivery.getBody());
String message9 = new String(Base64.getEncoder().encode(delivery.getBody()), StandardCharsets.UTF_8);
System.out.println(Arrays.toString(delivery.getBody()) + " - " + delivery.getBody().length);
System.out.println("1 " + message1 + " - " + message1.length() + " - ");
System.out.println("2 " + message2 + " - " + message2.length() + " - ");
System.out.println("3 " + message3 + " - " + message3.length() + " - ");
System.out.println("4 " + message4 + " - " + message4.length() + " - ");
System.out.println("5 " + message5 + " - " + message5.length() + " - ");
System.out.println("6 " + message6 + " - " + message6.length() + " - ");
System.out.println("7 " + message7 + " - " + message7.length() + " - ");
System.out.println("8 " + message8 + " - " + message8.length() + " - ");
System.out.println("9 " + message9 + " - " + message9.length() + " - ");
};
The System.out.println for messages 1, 2, 6, 7 print only VT, ETX and what is after, but nothing of what is before. The others are not properly converted and print asian characters or other random chars.
Special characters
These are control characters
SOH is start of header, ASCII code 1
VT is vertical tab, ASCII code 11, escaped "\v"
ETX is end of text, ASCII code 3, escaped "\0x3"
See also:
What is a vertical tab?
C0 and C1 control codes for message transmission
These control characters have not only special meaning (semantics) for printing but only for text transmission.
Maybe you need to put a special message-conversion component into place, when receiving data from a RabbitMQ text-message queue.

Multiple MQTT connections using PAHO failing

Am trying to maintain two MQTT connections using PAHO library.If i maintain the same object Subscription hangs on second subscription, but if i create a new client it works but closes the first subscription. Below is my code snippet. What could i be missing?.
try {
logging.info(logPreString + "| "
+ Thread.currentThread().getId() + " | "
+ "Subscribing to topic: ");
// Construct the connection options object that contains connection parameters
connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(true);
connectOptions.setKeepAliveInterval(1000);
// Construct an MQTT blocking mode client
client = new MqttClient(broker, clientID, persistence);
// Set this wrapper as the callback handler
client.setCallback(this);
// Connect to the MQTT server
logging.info(logPreString + "Connecting to broker ..." + broker);
client.connect(connectOptions);
logging.info(logPreString + "Connected and sucscribed ");
// Subscribe to a topic
System.out.println("Subscribe to topic(s): " + "| "
+ Thread.currentThread() + " | "
+ Arrays.toString(topic) + " With QOS of:" + props.getQoS());
client.subscribe(topic, QOS);
} catch (MqttException me) {
logging.error(logPreString + "MqttException caught "
+ "while connecting to broker. Error: "
+ me.getMessage());
}
}
public void subscribeAll(String[] topic, int[] QOS) {
try {
logging.info(logPreString + "subscribing to all ..." + broker);
// Subscribe to a topic
System.out.println("Subscribing to topic(s): " + "| "
+ Thread.currentThread() + " | "
+ Arrays.toString(topic)
+ " With QOS of:" + props.getQoS());
client.subscribe(topic, QOS);
} catch (MqttException me) {
logging.error(logPreString + "MqttException caught "
+ "while connecting to broker. Error: "
+ me.getMessage());
}
}

Output on new line WITHOUT for loop

I am trying to output arrays on a new line through a basic client, server application. However, to accomplish this I have had to use substring to find the # after each word to signal the end of the line. However I want to remove this function and have each section on a new line.
public ClientHandler(Socket socket,Users newUser, int newClientUser)
throws IOException
{
client = socket;
input = new Scanner(client.getInputStream());
output = new PrintWriter(
client.getOutputStream(),true);
user = newUser;
clientUser = newClientUser;
String[] itemName = {user.getItemName(1), user.getItemName(2)};
String[] description = {user.getItemDescription(1), user.getItemDescription(2)};
String[] itemtime = {user.getItemTime(1), user.getItemTime(2)};
output.println(itemName[0] + "#" + itemName[1]
+ "#" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"#"+ itemName[1] +": "+description[1]+
"#"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "#" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"#");
}
private synchronized void getMessage(String response)
{
String message="";
for(int i= count; !response.substring(i, i+1).equals("#"); i++)
{
count = i;
}
}
output.println(itemName[0] + "\n" + itemName[1]
+ "\n" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"\n"+ itemName[1] +": "+description[1]+
"\n"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "\n" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"\n");
Instead of having a "#" signify a new line, you can use "\n". Java will read that from your string as a new line.

Java- store PDUs that are being read by my program in an ArrayList

I have a Java method called receivePdu(), which will listen for any PDUs being sent across a network, and print out the entity ID, and location of each PDU in the simulation, in the console.
I am using a while loop to do this, so that my code is continually listening for PDUs for as long as it is running.
I now want to amend my code, so that as well as printing the information about each individual PDU in the console, it will also store that information in an ArrayList, so that it can be used by another Java class in my program.
My receivePdu() method currently looks like this:
public static void receivePdu(){
try{
/*Specify the socket to receive the data */
socket = new MulticastSocket(EspduSender.PORT);
address = InetAddress.getByName(EspduSender.DEFAULT_MULTICAST_GROUP);
socket.joinGroup(address);
/*Loop infinitely, receiving datagrams */
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData()); /* Commented on 15/04/2014 # 09:15 */
if(pdu != null){
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
} else if(!(pdu instanceof EntityStatePdu)){
System.out.println("There are no PDUs currently being received.");
}
System.out.println();
}
} /*end while */
} /*end try */
catch(Exception e){
System.out.println(e);
e.printStackTrace();
System.out.println("This is where the error is being generated");
/*09/04/2014 # 17:100
* If this exception gets called, presumably it either means that pdu is not an instance of EntityStatePdu, or
* that pdu does not actually hold a packet. */
}
}
I have now added an ArrayList to my class (outside the receivePdu() method), using the line: public static ArrayList<pdu> espdu; and amended my while loop to add each PDU to the ArrayList:
/*Loop infinitely, receiving datagrams */
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData()); /* Commented on 15/04/2014 # 09:15 */
if(pdu != null){
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
espdu.add(pdu);
} else if(!(pdu instanceof EntityStatePdu)){
System.out.println("There are no PDUs currently being received.");
}
System.out.println();
}
} /*end while */
However, when I now run my code, although the first PDU that is received is displayed, I get a java.lang.NullPointerException where the line espdu.add(pdu); is being called- and it is complaining about that line: espdu.add(pdu);.
I don't understand why I'm getting the null pointer exception there- anyone have any ideas? I have declared the ArrayList with the rest of the variables at the top of the class, in the way mentioned above. Any help or guidance with this would be much appreciated.

How to get Latitude and Longitude information from picture

How to get latitude and longitude information from picture store in device or SD Card?
I found very simple solution for this question....So I posted it here to help my friends who have problem like me to get Geo location from Picture.
Bundle bundle = getIntent().getExtras();
if(null != bundle)
{
String filepath = bundle.getString(FILE_PATH_KEY);
try
{
ExifInterface exif = new ExifInterface(filepath);
StringBuilder builder = new StringBuilder();
builder.append("Date & Time: " + getExifTag(exif,ExifInterface.TAG_DATETIME) + "\n\n");
builder.append("Flash: " + getExifTag(exif,ExifInterface.TAG_FLASH) + "\n");
builder.append("Focal Length: " + getExifTag(exif,ExifInterface.TAG_FOCAL_LENGTH) + "\n\n");
builder.append("GPS Datestamp: " + getExifTag(exif,ExifInterface.TAG_FLASH) + "\n");
builder.append("GPS Latitude: " + getExifTag(exif,ExifInterface.TAG_GPS_LATITUDE) + "\n");
builder.append("GPS Latitude Ref: " + getExifTag(exif,ExifInterface.TAG_GPS_LATITUDE_REF) + "\n");
builder.append("GPS Longitude: " + getExifTag(exif,ExifInterface.TAG_GPS_LONGITUDE) + "\n");
builder.append("GPS Longitude Ref: " + getExifTag(exif,ExifInterface.TAG_GPS_LONGITUDE_REF) + "\n");
builder.append("GPS Processing Method: " + getExifTag(exif,ExifInterface.TAG_GPS_PROCESSING_METHOD) + "\n");
builder.append("GPS Timestamp: " + getExifTag(exif,ExifInterface.TAG_GPS_TIMESTAMP) + "\n\n");
builder.append("Image Length: " + getExifTag(exif,ExifInterface.TAG_IMAGE_LENGTH) + "\n");
builder.append("Image Width: " + getExifTag(exif,ExifInterface.TAG_IMAGE_WIDTH) + "\n\n");
builder.append("Camera Make: " + getExifTag(exif,ExifInterface.TAG_MAKE) + "\n");
builder.append("Camera Model: " + getExifTag(exif,ExifInterface.TAG_MODEL) + "\n");
builder.append("Camera Orientation: " + getExifTag(exif,ExifInterface.TAG_ORIENTATION) + "\n");
builder.append("Camera White Balance: " + getExifTag(exif,ExifInterface.TAG_WHITE_BALANCE) + "\n");
builder = null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
We can get all the Exif tag information from picture in one builder string.
You can use the ExifInterface class to read various EXIF metadata from JPEGs:
http://developer.android.com/reference/android/media/ExifInterface.html

Categories

Resources