I'm trying to make a new thread for parsing xml from an rss feed. When I click run it says there are errors please correct them etc. I have 2 classes in my project. The other class has no errors and this class below has only warnings that a lot of the things in the try/catch statements may be uninitialized. I understand that and figured I should still be able to run the program anyways, I expect them to be initialized and if they're not that's fine I want to know about it. Is this really what's going on or am I missing something? I thought it would compile if something may be uninitialized but its not certainly uninitialized.
public class RssParse extends Thread {
Thread th=new Thread() {
public void run(){
System.out.println("1");
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("2");
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("3");
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.setNamespaceAware(true);
System.out.println("4");
XmlPullParser xpp;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("5");
try {
xpp.setInput(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("6");
int eventType;
try {
eventType = xpp.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(eventType+"!!!!!!!!!!!!!!!!");
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_DOCUMENT){
System.out.println("start");
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//method
};//thread
}//class
Look at this try/catch block for example :
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
}
If iotd = new URL("...") fails, iotd will remain uninitialized.
There are two ways to deal with this :
Assign a default value to iotd, like : URL iotd = null; However, it's bad here because if you use iotd later its value may be null and can throw a NullPointerException.
Stop the execution of your function if something failed instead of just printing the stack trace. For example you can add a return statement in the catch block :
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
All the warnings you are getting are because all your catch blocks are not dealing with the exception at all (just printing the stacktrace to standard out).
Let's see it through an example:
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
at that snipped you are declaring a iotd variable as a URL but without initializing it (not assigning any value), you do it inside the try block - which isn't wrong by the way. However if for any reason the statement inside the try block throws an exception program flow will go to the catch block leaving the iotd variable with its initial value (unassigned).
So, in that case, execution of the program will continue and when reaching this statement:
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
it will find no value assigned to the iotd variable.
To remove the warning regarding the uninitialized value you can either assign a null value to the variable when declaring it or rethrow another exception inside the catch block, stopping the program flow.
In the other hand, the snippet you posted here is not just one class, it's actually two as you are extending the Thread class and then creating an anonymous one inside its body. Using threads is easier than that in Java, just implement the Runnable interface and then instantiate a new thread from that interface:
public class MyRunnable implements Runnable {
public void run() {
// do stuff
}
}
and then:
new Thread(new MyRunnable()).start();
cheers
you need to initialize the variables above the try catch block, or give them a value in catch or finally block
find updated code here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class RssParse extends Thread {
Thread th=new Thread() {
public void run(){
System.out.println("1");
URL iotd=null;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("2");
BufferedReader in=null;
try {
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("3");
XmlPullParserFactory factory=null;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.setNamespaceAware(true);
System.out.println("4");
XmlPullParser xpp=null;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("5");
try {
xpp.setInput(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("6");
int eventType=-1; // set to a default value of your choice
try {
eventType = xpp.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(eventType+"!!!!!!!!!!!!!!!!");
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_DOCUMENT){
System.out.println("start");
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//method
};//thread
}//class
Related
I am working on a multi threaded application where i get some request from JMS, threads are running to receive the message. Here how my thread is working:
Model mapper in the try block is causing the issue i think:
patientAdder.addPatient(patientAddMessage, authResult, queueSender, baseUrl, modelMapper);
here is complete code:
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
while (true) {
SonicQueueMessageSender queueSender = null;
try {
queueSender = new SonicQueueMessageSender(queueConnProvider);
} catch (JMSException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
String patientAddMessage = null;
try {
patientAddMessage = new SonicMessageReceiver(connectionProvider)
.getAddJsonMessage("MirthMessage");
} catch (JMSException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
final AuthModel auth = new AuthModel();
String authResult = null;
final PatientAdder patientAdder = new PatientAdder();
SecurityTokenModel securityToken = null;
String authPostString = null;
try {
authPostString = new ObjectMapper()
.writeValueAsString(auth);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Auth post string is: "+ authPostString);
System.out.println("base url is: " + baseUrl);
String authPostOutput = client
.doGetAuthRestPost(authPostString, url);
try {
securityToken = getAuth(authPostOutput);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
authResult = securityToken.getAccessToken();
try {
patientAdder.addPatient(patientAddMessage, authResult, queueSender, baseUrl, modelMapper);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// poster.postMessage(patientAddMessage, authResult);
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
});
I need to map the message i'm getting in request to a bean class and for that i'm creating a ModelMapper class object that has a function to map properties but when i try to create new object of my mapper class i'm getting a NPE:
Exception in thread "pool-1-thread-1" java.lang.NullPointerException
at com.prnreferral.util.commons.ModelMapper.mapCanonicalMessageToPatientModel(ModelMapper.java:82)
at com.prnreferral.patientprocess.add.PatientAdder.addPatient(PatientAdder.java:52)
at com.prnreferral.patientprocess.add.PIXSAddPatient$1.run(PIXSAddPatient.java:148)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
I'm sure that object is created as i checked it by adding some conditions, but there is something that i'm missing causing this issue
I also tried to add a new function to check if there is any issue with this function, but getting
Exception in thread "pool-1-thread-1" java.lang.NoSuchMethodError: com.prnreferral.util.commons.ModelMapper.printString()V
at com.prnreferral.patientprocess.add.PatientAdder.addPatient(PatientAdder.java:49)
at com.prnreferral.patientprocess.add.PIXSAddPatient$2.run(PIXSAddPatient.java:173)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
I'm stuck on this issue, no idea what to do, can anyone help me. Thanks in advance.
I am new to websocket, and trying out with few examples. The application I created works fine for sometime say 10 - 15 mins, and from then on, it throws the timeout exception when sendText method is called on websocket session. I changed the value for "org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT" to -1 and now it hangs.
could you please help me to resolve this issue.
The code I have written to send the data to websocket is as below:
public void update() {
Dashboard dashboardData = tunnelDataService.getDashboardData();
ObjectWriter ow = new ObjectMapper().writer();
String json = null;
try {
json = ow.writeValueAsString(dashboardData);
} catch (JsonGenerationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
synchronized (lock) {
if (session.isOpen()) {
session.getBasicRemote().sendText(json);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am deploying this application on JBoss EAP 6.3.
Hi guys I open in my java application I open a browser page with this code:
String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now I have to turn off the browser, Is there a code to do that?
No, there is no Java API to close the browser.
There sort-of is but it's not very reliable. But if you have to, you can try with keyboard shortcuts and mouse clicks using Java Robot API.
public class RobotTest {
public static void main(String[] args) {
String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(3*1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Robot javaRobot;
try {
javaRobot = new Robot();
javaRobot.keyPress(KeyEvent.VK_ALT);
javaRobot.keyPress(KeyEvent.VK_F4);
javaRobot.keyRelease(KeyEvent.VK_ALT);
javaRobot.keyRelease(KeyEvent.VK_F4);
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have 2 classes serial1 and serial 2. serial1 implements Serializable whereas serial2 does not.As per theory i should get an Exception for the following code, but it is working fine. why is it so ?
import java.io.*;
public class SerialTest {
public static void main(String args[]){
FileOutputStream fos=null;
ObjectOutputStream oos =null;
serial1 se = new serial1();
serial1 sd = null;
se.mets();
try {
fos= new FileOutputStream("serialtest");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos =new ObjectOutputStream(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.writeObject(se);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis=null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("serialtest");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois = new ObjectInputStream(fis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sd = (serial1) ois.readObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sd.mets();
}
}
import java.io.Serializable;
public class serial1 implements Serializable{
/* public static void main(String []args){
serial1 ss = new serial1();
ss.mets();
}*/
public void mets(){
serial2 s2 = new serial2();
System.out.println( "serial 1 + mets");
s2.met1();
}
}
public class serial2 {
public void met1(){
System.out.println("serial2 + met1");
}
}
---------------------------*
The output is
serial 1 + mets
serial2 + met1
serial 1 + mets
serial2 + met1
You don't actually serialize serial2. Your mets method creates a local variable but as soon as the method returns it goes out of scope and becomes eligible for garbage collection.
If you had an instance variable of type serial2 inside serial1 then you would see an exception when you try to serialize (assuming it's a non-null value), but a local variable will not be a problem.
I don't see you ever serializing serial2
while trying to create a progressbar in android i came across this problem.
i am following this example : http://developer.android.com/reference/android/widget/ProgressBar.html
my problem is that one of my methods i want to call has to be inside a try and catch
how do i do that inside of a runnable?
Runnable SendThread = new Runnable()
{
try
{
GetAndConvertImagesToPdf();
mProgStatus = 30;
mProgress.setProgress(mProgStatus);
title.setText(R.string.sendingTitle);
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
};
i get this error:
"Syntax error on token try, delete this token"
how can i resolve this?
thank you
u put the try in the class body its not in any method or block
this is more like it
Runnable SendThread = new Runnable() {
public void run() {
try {
GetAndConvertImagesToPdf();
mProgStatus = 30;
mProgress.setProgress(mProgStatus);
title.setText(R.string.sendingTitle);
}
catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Sorry I am not able to answer your question but I have one advice,Try to explore about AsyncTask it will help you to run a background thread and it will let you update your UI thread as well at same time. however good luck for your current question.
link : http://developer.android.com/reference/android/os/AsyncTask.html
Happy Coding!