I have something like this:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
public class MyClass implements javax.xml.stream.StreamFilter
{
private Map myMap= new HashMap();
public Map getMap()
{
return this.myMap;
}
public void addElement(String text)
{
this.myMap.put(text, "value");
}
public void doSomething(String strValue)
{
try
{
XMLInputFactory xmlif = null;
xmlif = XMLInputFactory.newInstance();
FileInputStream fis = new FileInputStream("myFile.xml");
XMLStreamReader xmlr = xmlif.createFilteredReader(xmlif.createXMLStreamReader(fis),new MyClass());
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
OutputStream fileStream = new FileOutputStream("myFileOutput");
XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(fileStream);
addElement(strValue);
System.out.println(getMap().size()+"Before");
while (xmlr.hasNext())
{
write(xmlr, xmlWriter);
xmlr.next();
}
System.out.println(getMap().size()+"After");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean accept(XMLStreamReader reader)
{
System.out.println(getMap().size()+"inside");
if ( getMap().containsKey("Something") )
{
System.out.println("The value is there");
}
return true;
}
private void write(XMLStreamReader xmlr, XMLStreamWriter writer) throws XMLStreamException
{
switch (xmlr.getEventType()) {
case XMLEvent.START_ELEMENT:
String localName = xmlr.getLocalName();
writer.writeStartElement(localName);
break;
}
}
}
When I create the tagMap as static, it works, but since I will put this class in threads, all the maps will point to the same map, making the comparison useless. Specifically I have seen that inside the function accept, the map has 0 values.
The function accept is part of the interface SteamFilter, so it is called automatically when an event occurs. I have tried changing the map to public, and even setting the values with a constructor, but it is the same.
The way it is being called in the class that creates the class, is this:
Runnable runClass = new Runnable(){
public void run(){
try
{
MyClass myC = new MyClass();
myC.doSomething("value");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Thread myTask = new Thread(runClass);
myTask.start();
Do you know how can I check for the value of the map inside the function accept?
You instanciate your FilterReader with a new Instance of MyClass (one that hasn’t been called
doSomethingyet). If you instead start it with the same instance that is currently be worked on it should work.Change:
to