XmlReader returning null on all occasions - java

i have a code which is to get dat from active mq and display the data on Rss feed, but the code give me no data on the feed, i get an empty list and the reason seems to be that XmlReader reader= null; i have set this line an dthe reder seems to be null during the whole execution.
public List<RssFeedMessage> readRssFeeds(#PathVariable String sourceName) {
XmlReader reader = null;
RssFeedMessage rssFeedMessage = null;
StringBuffer feedUrl = new StringBuffer("http://").append(ipaddress).append(":")
.append(port).append("/admin/queueBrowse/").append(sourceName).append("?view=rss&feedType=rss_2.0");
List<RssFeedMessage> rssFeedMessages = new ArrayList<RssFeedMessage>();
try {
URL url = new URL(feedUrl.toString());
reader = new XmlReader(url);
SyndFeed feedMsg = new SyndFeedInput().build(reader);
List<SyndEntry> feedEntries = feedMsg.getEntries();
for (SyndEntry entry : feedEntries) {
rssFeedMessage = new RssFeedMessage();
rssFeedMessage.setTitle(entry.getTitle());
rssFeedMessage.setDescription(entry.getDescription().getValue());
rssFeedMessage.setDate(OptimerUtil.simpleDateHourTimeInd.format(entry.getPublishedDate()));
rssFeedMessages.add(rssFeedMessage);
}
} catch(IOException e){
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (FeedException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return rssFeedMessages;
}
}
it just exits coz reader remains null the wole time an i get io exception on reader = new XmlReader(url);

Check what feedUrl contains in line URL url = new URL(feedUrl.toString());
There is probably a problem with the string.
Also, make you you manage conditions like String equals null or unreachable, before parsing it

Related

Reading from a file but getting null in java

I want to read from a file and store it in a string.
This is my method:
public static String createJsonFileFromNode(String filename, JsonNode root) {
String dirName = "src/test/resources/json/";
File dir = new File (dirName);
File actualFile = new File (dir, filename);
try (Writer writer = new BufferedWriter(new OutputStreamWriter (
new FileOutputStream(actualFile), "utf-8")))
{
writer.write(String.valueOf(root));
log.info(actualFile.getPath());
String updatedJson = FileUtils.readFileToString(actualFile, "UTF-8");
return updatedJson;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
} catch (FileNotFoundException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
I have two problems in the above method:
In String dirName = "src/test/resources/json/" I am passing an entire path, which I dont want to. I want to pass it as "/json/"
updatedJson is retuning null even though the file is getting saved to the particular direction. Not sure what is going on. Can someone please help me?
Thank you.

Why I can't test for FileNotFoundException in java JUnit 4.13

I am facing some difficulties with testing constructor of my class using JUnit 4.13. What I am trying to do is to test that constructor is throwing FileNotFoundExeption when I pass wrong file name.
This is my constructor (parameter 'file' is name of file where I store languages):
public LanguageManager(String file) {
this.languages = new ArrayList<Language>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
String line;
while((line = in.readLine()) != null) {
line = line.trim();
if (line.equals("") || line.startsWith("#"))
continue;
Language j = new Language(line);
this.languages.add(j);
}
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my function for testing this constructor:
#Test(expected=FileNotFoundException.class)
public void testLanguageManager() {
LanguageManager ajm = new LanguageManager("non_existing_file.txt");
}
I suspect that there is problem with try catch block in constructor but can't figure out what I am doing wrong. Any help is appreciated.

Avoid same try catch blocks in Java

I am developing a project which involves JSON manipulation in Java using JSON API. There are many places where I need to read values from JSON file. The API provides checked exceptions for the same. Everytime I use the API to read JSON values, I am forced to write try catch block. As a result, there is a large number of try catch blocks. It makes the code look messy.
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
}
catch(Exception e) {
System.out.println("File Not found");
}
try {
while((line = read.readLine() ) != null) {
Content = Content+line;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
ResponseArr = new JSONArray( Content );
} catch (JSONException e) {
e.printStackTrace();
}
try {
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
}
try {
StoreResponse = ResponseArr.getJSONObject(0).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
}
Is there any way to avoid this ?A single try catch block would not suffice and the statements are not dependent. Each read statement requires a separate try catch block as I have to log the details of places while catching the exception. Can I invoke a common method whenever I have a code to read JSON data, like sending the code as a paramater to a method which would take care of the exception handling or some other way round ?
Since (all?) the subsequent statements are dependent on the previous it makes no sense having that many try/catch blocks. I would rather put the code inside one try/catch and handle the exceptions by type
Pseudo-code:
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
} catch(FileNotFoundException)
System.out.println("File Not found");
}
// and so on
As some are suggesting, you might want to let all these exceptions bubble up (not catching them) since you're not doing anything meaningful when catching them. However, I think that depends on the calling context.
If you are handling all exceptions in the same way, why not combine them in one try/ catch clause
for example like this :
try {
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (Exception e) {
e.printStackTrace();
}
Try like this
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
catch(Exception e) {
System.out.println("File Not found");
}

android - return ignored in try-statement

I have a class called RetreiveHttpStringResponse. It's used to get an InputStream from an URL containing JSON data. The class extends AsyncTask<String, Void, InputStream>. So the strange problem here is that null is always returned. No matter what. There is even no Exception. I checked out the program behaviour with the debugger and could see that at point (1) the processing is jumping immediately to the finally-statement and continues with return null;. And again there are no Errors and no Exceptions are going on. The programm is running normally.
I'm using Android 4.4 (SDK version 19), the response code is 200 and the following lines are set in the Manifest file.
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
The problem is happening on the emulator and on a real device with internet connection. Here is the code:
#Override
protected InputStream doInBackground(String... arg0) {
URL url = null;
InputStream is = null;
HttpURLConnection urlConn = null;
int responseCode = 0;
try {
url = new URL(arg0[0]);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setReadTimeout(10000);
urlConn.setConnectTimeout(15000);
urlConn.setRequestMethod("GET");
urlConn.connect();
responseCode = urlConn.getResponseCode();
Log.d("DataHandlerInternet:RESPONSE_CODE", "The response is: " + responseCode);
is= urlConn.getInputStream(); //-->(1)<--
return is;
}
catch ( MalformedURLException e ) { // new URL() went wrong!
//TODO error message. URL is not correct!
e.printStackTrace();
}
catch (SocketTimeoutException e) { // Timeout while connecting or holding connection to URL.
//TODO error message. Timeout happened!
e.printStackTrace();
}
catch ( IOException e ) { // openConnection() failed!
//TODO error message. Couldn't connect to URL!
e.printStackTrace();
}
catch( Exception e ) { // Any other Exception!
e.printStackTrace();
}
finally {
try { if(is != null) { is.close(); } } catch(Exception e) {e.printStackTrace();}
try { if(urlConn != null) { urlConn.disconnect(); } } catch(Exception e) {e.printStackTrace();}
}
return null;
}
One bad solution is to delete the finally-statement. Well, not the best way to solve this problem.
Now I changed the code. I've put the reading in it and return just the String.
#Override
protected String doInBackground(String... arg0) {
URL url = null;
InputStream is = null;
HttpURLConnection urlConn = null;
int responseCode = 0;
try {
url = new URL(arg0[0]);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setReadTimeout(10000);
urlConn.setConnectTimeout(15000);
urlConn.setRequestMethod("GET");
urlConn.connect();
responseCode = urlConn.getResponseCode();
Log.d("DataHandlerInternet:RESPONSE_CODE", "The response is: " + responseCode);
is= urlConn.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ( (line = br.readLine()) != null ) {
sb.append(line);
}
return sb.toString();
}
catch ( MalformedURLException e ) { // new URL() went wrong!
//TODO error message. URL is not correct!
e.printStackTrace();
}
catch (SocketTimeoutException e) { // Timeout while connecting or holding connection to URL.
//TODO error message. Timeout happened!
e.printStackTrace();
}
catch ( IOException e ) { // openConnection() failed!
//TODO error message. Couldn't connect to URL!
e.printStackTrace();
}
catch( Exception e ) { // Any other Exception!
e.printStackTrace();
}
finally {
try { if(is != null) { is.close(); } } catch(Exception e) {e.printStackTrace();}
try { if(urlConn != null) { urlConn.disconnect(); } } catch(Exception e) {e.printStackTrace();}
}
return null;
}
And still, after going through the while loop the return line; is completely ignored. I've checked the data in the String with the debugger and it was correct! No Errors no Exceptions.
finally will run in either case, also during normal return without exceptions. And you call .close in the finally statement clause.
So your code always returns the closed stream. Probably this is not that you intend.
Your description ("jumps to finally statement") still looks very much like a exception has been thrown by urlConn.getInputStream(). Strange you do not observe it.
I dont see why you get your null result but, one thing you are doing wrong is actually returning InputStream:
is= urlConn.getInputStream(); //-->(1)<--
return is;
you should read your stream in doInBackground (on worker thread), otherwise reading it in onPostExecute (UI Thread), will possibly cause NetworkOnMainThreadException, or at least ANR. Reading data from InputStream is still a network operation - data you download can be several MBs.

How to read line from txt?

How can I read line from text? Look at my code:
public static String getTemplateFromFile() {
String name = null;
try {
BufferedReader reader = new BufferedReader(new
FileReader(
"http://localhost:8080/blog/resources/cache/templateName.txt"));
name = reader.readLine();
//name="TEST";
//NULL anyway
reader.close();
}
catch (Exception e) {
}
return name;
}
Also I have got secnod version, but my server freeze.
public static String getTemplateFromFile() {
String name = null;
/*
try {
URL url = new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
Scanner s = new Scanner(url.openStream());
name=s.nextLine();
s.close();
}
catch(IOException ex) {
ex.printStackTrace();
}*/
return name;
}
I think it can't close connection or something.
It returns me NULL even I say name="TEST"; in try construction.
FileReader is exactly that – a class that reads from files, not HTTP requests.
You're getting an invalid file path exception, which you're then ignoring in your evil empty catch block.
Instead, you should use URLConnection.
Try this
try{
URL reader=new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(reader.openStream()));
name = br.readLine();
//name="TEST";
br.close();
}catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
AFAIK, URL#openStream() internally calls URL#openConnection() which creates an instance of URLConnection and calls URLConnection#getInputStream() on it.

Categories