How to work with multiple rss files in j2me(java) - java-me

i am developing Rss Feed Reader App in j2me(java) for 2 xml files,but my for loop is
having a problem,xml file is giving null,when i run my application ,control is not going to this method in my loop getXMLFeed(url1); ,instead of that it is completing for loop.can any one help?is my looping is correct?once check my source Code?i am having problem with for loop
check my source code:
urls = new String[2];//Array Declaration
urls[0] = "http://www.teluguone.com/news/tonefeeds/topnews/topnews-20.rss";
urls[1] = "http://www.teluguone.com/news/tonefeeds/topstory/topstory-25.rss";
for (int i = 0; i < urls.length; i++) //iterration
{
myThread = new ParseThread(this);
myThread.getXMLFeed(url1);
myDysplay.setCurrent(mform);
}
public void getXMLFeed(final String url) {
Thread t = new Thread() {
public void run() {
myConnection = (HttpConnection) Connector.open(url);//HttpConnection
InputStream stream = myConnection.openInputStream();
ParseXMLFeed(stream);
}

Maybe you just forgot to paste the line, but it seems that you are no calling t.start() inside getXMLFeed method.

Related

Getting value from thread running in while loop

I have a java thread which is running a path-finding algorithm in a constant while loop. Then, every so often I want to retrieve the most updated path from the thread. However, I am unsure how to do this, and think I might be doing it wrong.
My thread consists of the following code:
public class BotThread extends Thread {
Bot bot;
AStar pathFinder;
Player targetPlayer;
public List<boolean[]> plan;
public BotThread(Bot bot) {
this.bot = bot;
this.plan = new ArrayList<>();
pathFinder = new AStar(bot, bot.getLevelHandler());
}
public void run() {
while (true) {
System.out.println("THREAD RUNNING");
targetPlayer = bot.targetPlayer;
plan = pathFinder.optimise(targetPlayer);
}
}
public boolean[] getNextAction() {
return plan.remove(0);
}
}
I then create an object of BotThread, and call start(). Then when I call getNextAction() on the thread, I seem to receive a null pointer. Is this because I am not able to call another method on the thread whilst it is in the main loop? How should I do this properly?
This is because you are not giving enough time to thread to initialise plan Arraylist. You need to add sleeping time to the threads. Something like this while calling BotThread class from main:
int num_threads = 8;
BotThread myt[] = new BotThread[num_threads];
for (int i = 0; i < num_threads; ++i) {
myt[i] = new BotThread();
myt[i].start();
Thread.sleep(1000);
myt[i].getNextAction();
}

iText7 for .NET - error while merging files

I've created simple method that allows me to merge multiple PDF files.
Below is my code:
private void Merge(List<string> src, string dest)
{
Stopwatch sw = new Stopwatch();
sw.Start();
PdfDocument pdfDocument1 = new PdfDocument(new PdfReader(src[0]), new PdfWriter(dest));
for (int i = 1,max=src.Count; i < max; i++)
{
PdfDocument pdfDocument2 = new PdfDocument(new PdfReader(src[i]));
var pagesCount = pdfDocument2.GetNumberOfPages();
pdfDocument2.CopyPagesTo(1, pagesCount, pdfDocument1);
pdfDocument2.Close();
}
pdfDocument1.Close();
sw.Stop();
Debug.WriteLine(sw.Elapsed);
}
I've based my code on example from iText book: http://developers.itextpdf.com/examples/merging-pdf-documents/clone-merging-documents-bookmarks
For test purpose I've attached that method to button and I'm caling it like this:
private void button1_Click(object sender, EventArgs e)
{
try
{
string dest = #"E:\final.pdf";
var files = Directory.GetFiles(#"E:\PDFS", "*.pdf").Take(100).ToList();
Merge(files,dest);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
From time to time (after n'th click on that button) I get exception saying:
Cant cast from 'iText.Kernel.Pdf.PdfNumber' to
'iText.Kernel.Pdf.PdfStream'.
Also first time I click my application takes about 100MB of memory, next time I click it increase to 150MB, next click and I get 230MB of memory used, so it look like it isn't releasing memory.
Is there a better way to merge multiple PDF's into one using iTextSharp 7?
As per request I'm adding StackTrace:
w iText.Kernel.Pdf.PdfPage.GetContentStream(Int32 index)
w iText.Kernel.Pdf.PdfPage.Flush(Boolean flushXObjects)
w iText.Kernel.Pdf.PdfPage.Flush()
w iText.Kernel.Pdf.PdfDocument.Close()
w iTextSharp7_Merge.Form1.Merge(List`1 src, String dest)
w c:\Users\Misiu\Documents\Visual Studio 2013\Projects\iTextSharp7_Merge\Form1.cs:wiersz 75
And here are exception details:
EDIT:
I've changed button click function so now it loads 100 file names from directory and calls Merge method 10 times with same list:
private void button1_Click(object sender, EventArgs e)
{
try
{
string dest = #"E:\final.pdf";
var files = Directory.GetFiles(#"E:\PDFS", "*.pdf").OrderBy(x => x).Skip(0).Take(100).ToList();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 1; i <= 10; i++)
{
Debug.WriteLine(i);
Merge(files, dest1);
}
sw.Stop();
Debug.WriteLine(sw.Elapsed);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
This way I've excluded random sort of Directory.GetFiles.
Here is sample output that comes from Visual Studio:
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll'
1
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Users\Misiu\documents\visual studio 2013\Projects\iTextSharp7_Merge\bin\Debug\itext.kernel.dll'
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Users\Misiu\documents\visual studio 2013\Projects\iTextSharp7_Merge\bin\Debug\itext.io.dll'
A first chance exception of type 'System.NullReferenceException' occurred in itext.kernel.dll
2
3
The thread '<No Name>' (0x2dd0) has exited with code 0 (0x0).
4
5
A first chance exception of type 'System.InvalidCastException' occurred in itext.kernel.dll

BufferedReader is sometimes empty

I have Loader class where I load txt file into BufferedReader from resources and return this field. I use this method but it acts really strange(for me). When I don't put
String str = bufferReader.readLine(); after
bufferReader = new BufferedReader(fileReader);
(in Loader class) than bufferReader in another class is empty, and readLine() returns null. When I write that piece of code in Loader class, I can read each line from txt, except the 1. one which is read in Loader class. Also, I can't read last line if I dont put enter at the end.
public BufferedReader loadFromFileToBufferReader(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
System.out.print(getClass().getClassLoader().getResource("resources/" + fileName));
File file = new File(classLoader.getResource("resources/" + fileName).getFile());
BufferedReader bufferReader = null;
try (FileReader fileReader = new FileReader(file)) {
bufferReader = new BufferedReader(fileReader);
String str = bufferReader.readLine();
} catch (IOException e) {
System.err.println("Something went terribly wrong with file reading");
}
return bufferReader;
}
and usage:
public Database() {
productsInDatabse = new ArrayList<>();
codesList = new ArrayList<>();
loader = new LoadFromFile();
BufferedReader output = loader.loadFromFileToBufferReader("database.txt");
Product product;
String line;
String[] array;
try {
line = output.readLine();
while (line != null) {
You should paste your code here because it's hard to deduce all the possible causes of this without seeing the code on 100% but I am guessing you have it the same file open at the same time from multiple sources without closing it before from one? Could be literally millions of little things, just telling you how the same error happened to me.

Writing a decompression mechanism to be used in a Web API MessageHandler

I'm trying to write a decompression mechanism for a Web API MessageHandler. However, despite a little research I can't seem to make this work :-(
The problem is reproducible with the following test:
[Test]
public void Deflate()
{
using (var outStream = new MemoryStream())
{
using (var compressionStream = new DeflateStream(outStream, CompressionMode.Compress, true))
{
using (var original = new MemoryStream(Encoding.UTF8.GetBytes("original content")))
{
original.CopyTo(compressionStream);
}
}
//this passes
Assert.IsTrue(outStream.Length > 0);
var compressedStream = outStream;
var decompressionResultStream = compressedStream.DeflateDecompressor();
//this fails
Assert.IsTrue(decompressionResultStream.Length > 0);
var output = Encoding.UTF8.GetString(decompressionResultStream.ToArray());
Assert.AreEqual("original content", output);
}
}
and the following Decompression Handler
public static class DecompressionHandlers
{
public static MemoryStream DeflateDecompressor(this Stream compressedStream)
{
var decompressionResultStream = new MemoryStream();
using (var decompressionStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
{
decompressionStream.CopyTo(decompressionResultStream);
decompressionStream.Flush();
}
return decompressionResultStream;
}
public static MemoryStream GZipDecompressor(this Stream compressedStream)
{
var decompressionResultStream = new MemoryStream();
using (var decompressionStream = new GzipStream(compressedStream, CompressionMode.Decompress, true))
{
decompressionStream.CopyTo(decompressionResultStream);
decompressionStream.Flush();
}
return decompressionResultStream;
}
}
Hopefully, this is a straight ID-ten-T problem and any advice is gratefully received!
That this is to be used in a Web API MessageHandler may well be a red herring but is included for completeness
In your code, try resetting the position of the compressedStream before you invoke decompression on it.
compressedStream.Position = 0;
var decompressionResultStream = compressedStream.DeflateDecompressor();
Note that you seem to be using DeflateStream instead of GZipStream in your GZipDecompressor method.

.NET 4.0 BackgroundWorker class and unusual behavior

I am running into some strange behavior in the backgroundworker class that leads me to believe that I don't fully understand how it works. I assumed that the following code sections were more or less equal except for some extra features that the BackgroundWorker implements (like progress reporting, etc.):
section 1:
void StartSeparateThread(){
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
//Execute some code asynchronous to the thread that owns the function
//StartSeparateThread() but synchronous to itself.
var SendCommand = "SomeCommandToSend";
var toWaitFor = new List<string>(){"Various","Possible","Outputs to wait for"};
var SecondsToWait = 30;
//this calls a function that sends the command over the NetworkStream and waits
//for various responses.
var Result=SendAndWaitFor(SendCommand,toWaitFor,SecondsToWait);
}
Section 2:
void StartSeparateThread(){
Thread pollThread = new Thread(new ThreadStart(DoStuff));
pollThread.Start();
}
void DoStuff(object sender, DoWorkEventArgs e)
{
//Execute some code asynchronous to the thread that owns the function
//StartSeparateThread() but synchronous to itself.
var SendCommand = "SomeCommandToSend";
var toWaitFor = new List<string>(){"Various","Possible","Outputs to wait for"};
var SecondsToWait = 30;
//this calls a function that sends the command over the NetworkStream and waits
//for various responses.
var Result=SendAndWaitFor(SendCommand,toWaitFor,SecondsToWait);
}
I was using Section 1 to run some code that sent a string over a networkstream and waited for a desired response string, capturing all output during that time. I wrote a function to do this that would return the networkstream output, the index of the the sent string, as well as the index of the desired response string. I was seeing some strange behavior with this so I changed the function to only return when both the send string and the output string were found, and that the index of the found string was greater than the index of the sent string. It would otherwise loop forever (just for testing). I would find that the function would indeed return but that the index of both strings were -1 and the output string was null or sometimes filled with the expected output of the previous call. If I were to make a guess about what was happening, it would be that external functions called from within the bw_DoWork() function are run asynchronously to the thread that owns the bw_DoWork() function. As a result, since my SendAndWaitFor() function was called multiple times in succession. the second call would be run before the first call finished, overwriting the results of the first call after they were returned but before they could be evaluated. This seems to make sense because the first call would always run correctly and successive calls would show the strange behavior described above but it seems counter intuitive to how the BackgroundWorker class should behave. Also If I were to break within the SendAndWaitFor function, things would behave properly. This again leads me to believe there is some multi-threading going on within the bwDoWork function itself.
When I change the code in the first section above to the code of the second section, things work entirely as expected. So, can anyone who understands the BackgroundWorker class explain what could be going on? Below are some related functions that may be relevant.
Thanks!
public Dictionary<string, string> SendAndWaitFor(string sendString, List<string> toWaitFor, int seconds)
{
var toReturn = new Dictionary<string, string>();
var data = new List<byte>();
var enc = new ASCIIEncoding();
var output = "";
var FoundString = "";
//wait for current buffer to clear
output = this.SynchronousRead();
while(!string.IsNullOrEmpty(output)){
output = SynchronousRead();
}
//output should be null at this point and the buffer should be clear.
//send the desired data
this.write(enc.GetBytes(sendString));
//look for all desired strings until timeout is reached
int sendIndex=-1;
int foundIndex = -1;
output += SynchronousRead();
for (DateTime start = DateTime.Now; DateTime.Now - start < new TimeSpan(0, 0, seconds); )
{
//wait for a short period to allow the buffer to fill with new data
Thread.Sleep(300);
//read the buffer and add it to the output
output += SynchronousRead();
foreach (var s in toWaitFor)
{
sendIndex = output.IndexOf(sendString);
foundIndex = output.LastIndexOf(s);
if (foundIndex>sendIndex)
{
toReturn["sendIndex"] = sendIndex.ToString();
toReturn["foundIndex"] = sendIndex.ToString();
toReturn["Output"] = output;
toReturn["FoundString"] = s;
return toReturn;
}
}
}
//Set this to loop infinitely while debuging to make sure the function was only
//returning above
while(true){
}
toReturn["sendIndex"]="";
toReturn["foundIndex"]="";
toReturn["Output"] =output;
toReturn["FoundString"] = "";
return toReturn;
}
public void write(byte[] toWrite)
{
var enc = new ASCIIEncoding();
var writeString = enc.GetString(toWrite);
var ns = connection.GetStream();
ns.Write(toWrite, 0, toWrite.Length);
}
public string SynchronousRead()
{
string toReturn = "";
ASCIIEncoding enc = new ASCIIEncoding();
var ns = connection.GetStream();
var sb = new StringBuilder();
while (ns.DataAvailable)
{
var buffer = new byte[4096];
var numberOfBytesRead = ns.Read(buffer, 0, buffer.Length);
sb.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, numberOfBytesRead));
toReturn += sb.ToString();
}
return toReturn;
}
All data to be used by a background worker should be passed in through the DoWorkEventArgs and nothing should be pulled off of the class (or GUI interface).
In looking at your code I could not identify where the property(?) connnection was being created. My guess is that connection is created on a different thread, or may be pulling read information, maybe from a GUI(?) and either one of those could cause problems.
I suggest that you create the connection instance in the dowork event and not pull an existing one off of a different thread. Also verify that the data connection works with does not access any info off of a GUI, but its info is passed in as its made.
I discuss an issue with the Background worker on my blog C# WPF: Linq Fails in BackgroundWorker DoWork Event which might show you where the issue lies in your code.

Resources