ParserConfigurationException:
Hi
I am using MessageDrivenBean and WebsphereMq as JMS provider.I wil get the messages as string which are in xml format.using TransformerFactory and Transformer i wil convert the string as Xml,after that i wil parse the nodes of these xml and insert the details in database.For parsing i am using documentbuilder object.
After processing few messages it is throwing ParserConfigurationException and it is happening rarely.Can anyone suggest me what will be the reason and how can i wil overcome this exception.
The below is the code snippet throwing the exception.
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
TransformerFactory transformerFactory = TransformerFactorynewInstance();
Transformer transformer = transformerFactory.newTransformer();
StringReader stingReader = new StringReader(message);
StreamSource src = new StreamSource(stingReader);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(outputStream);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(src, result);
ByteArrayInputStream inputStream = new ByteArrayInputStream(
outputStream.toByteArray());
InputSource inputSource = new InputSource(inputStream);
DocumentBuilder builder = builderFactory.newDocumentBuilder(); ----exception is throwing from here
Document document = builder.parse(inputSource);
I am not having the stack trace.
Similar Messages
-
ParserConfigurationException with javax.xml.parsers.DocumentBuilderFactory
Like many people, I am trying to just read in the contents of a XML file. My code compiles in WS studio and I publish it to the server. However, I keep getting a ParserConfigurationException when I try to get a DocumentBuilder from the factory. Below is my code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse( new File(XMLFILE) );
Any idea why?The xmlfile is valid and here is the partial stacktrace
Root Error-1: javax/xml/parsers/ParserConfigurationException
java.lang.Exception: javax/xml/parsers/ParserConfigurationException
at Search5F_Results_jsp_5._jspService(_Search_5F_Results_jsp_5.java:206)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:127)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.jasper.runtime.JspServlet$JspServletWrapper.service(JspServlet.java:390)
at org.apache.jasper.runtime.JspServlet.serviceJspFile
Do I need to set some system property? -
XML ParserConfigurationException in Weblogic
Hi,
I am getting a SAXParseException in Weblogic 6.1 SP4.
I have put xerces.jar in the classpath but still it seems like it is taking xerces implementation in weblogic.jar.
Is that the reason for this parser error?
Here is the piece of code.
String inParam = stringBuffer.toString();
ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(inParam.getBytes());
org.xml.sax.InputSource source = new InputSource(byteArrayInputStream);
source.setEncoding("ISO8859_1");
ParserConfigurationException while parsing
org.xml.sax.SAXParseException: The encoding "ISO8859_1" is not supported. at weblogic.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1090)
at weblogic.apache.xerces.readers.DefaultEntityHandler.startReadingFromDocument(DefaultEntityHandler.java:549)
at weblogic.apache.xerces.framework.XMLParser.parseSomeSetup(XMLParser.java:318)
at weblogic.apache.xerces.framework.XMLParser.parse(XMLParser.java:974)
THIS WORKS IN OTHER WEBLOGIC INSTANCES IN THE SAME CLUSTER.
Thanks in advance
BGopalFixed it temporarily.
Go to the weblogic console, Select your web application in the left pane,
Click on Other tab in the right pane, Check 'Prefer Web Inf Classes', restart server. -
Javax.xml.parsers.ParserConfigurationException:
Hi,
I have an java Ant task which runs well on my machine but when same task with same directory structure and all files is run on another machine it gives following error;
javax.xml.parsers.ParserConfigurationException: AElfred parser is non-validating
if Any one have the solution please reply...
ThanksWhat is this "AElfred"? Your ant task on the second machine is probably using another XML parser. Print out the parsers name and try to conifigure the same parser from the first machine on the second one.
-
How to read the content in one node of XML in Java? Pls help
My dear brothers,
I am a newbie of XML, I have a exercise which is creating a Tree View from XML file. But the trouble is I do not know how to read the content in one node of XML file. I decide to use the algorithm as following:
1. Create a GUI form which gives the ability for user to choose a XML file (ok)
2. Load XML and return the file (ok)
3. Read the file from node to node to create the node in Tree View (?!)
Please help me, and if you are enough kind, please give me an small example to easy understand. Thanks in advance.
Hoang Yen BinhI hope this one helps you.
<ABC Type="ProductBased" ProdName="One" Location="India">
<CEO>Raj</CEO>
<Finance>Vikram</Finance>
<HR>Karthik</HR>
<Technical>Satish</Technical>
</ABC>
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Attr;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.DOMException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
public class XmlReading {
Document doc;
Element element;
public static void main(String[] args) throws Exception{
XmlReading xr = new XmlReading();
xr.getXmlParser(args);
public void getXmlParser(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
if(args.length != 1) {
System.err.println("Argument Required");
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(new File(args[0]));
}catch(ParserConfigurationException e1) {
}catch(SAXException e2) {
}catch(IOException e3) {
getAttributes();
public void getAttributes() {
// Retrive the entire Document from the Dom Tree
element = doc.getDocumentElement();
// System.out.println(element);
NamedNodeMap attrs = element.getAttributes();
// Get number of attributes in the element
int numAttrs = attrs.getLength();
// Process each attribute
for (int i=0; i<numAttrs; i++) {
Node node = attrs.item(i);
// Get attribute name and value
String attrName = node.getNodeName();
String attrValue = node.getNodeValue();
System.out.println(attrName + ": " + attrValue);
String s1 = element.getTagName();
System.out.println(s1);
// To get all the elements in a DOM Tree
NodeList nl1 = element.getElementsByTagName("*");
int i2 = nl1.getLength();
System.out.println(i2);
for(int i=0; i<i2; i++) {
System.out.println(nl1.item(i) + "\n");
} -
PI Java Mapping NullPointerException
Hi Gurus,
I'm having some troubles doing the mapping through java mapping in PI.
I've done the java class in the SAP NWDS and imported it on PI through the ESR.
Now i'm trying to test through the SOAP and i've found the following error in the "Communication Channel Monitor":
500 Internal Server Error SAP NetWeaver Application Server/Java AS
java.lang.NullPointerException: while trying to invoke the method com.sap.aii.af.sdk.xi.lang.Binary.getBytes() of a null object returned from com.sap.aii.af.sdk.xi.mo.xmb.XMBPayload.getContent()
And the following error in the SXMB_MONI:
<SAP:Category>XIServer</SAP:Category>
<SAP:Code area="INTERNAL">CLIENT_SEND_FAILED</SAP:Code>
<SAP:P1>500</SAP:P1>
<SAP:P2>Internal Server Error</SAP:P2>
<SAP:P3>(See attachment HTMLError for details)</SAP:P3>
<SAP:P4 />
<SAP:AdditionalText />
<SAP:Stack>Error while sending by HTTP (error code: 500 , error text: Internal Server Error) (See attachment HTMLError for details)</SAP:Stack>
I've developed the code below:
public class PI_Mapping_IF extends AbstractTransformation {
public void transform(TransformationInput in, TransformationOutput out) throws StreamTransformationException {
this.execute(in.getInputPayload().getInputStream(), out.getOutputPayload().getOutputStream());
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
try
// Inicio do java mapping
getTrace().addInfo("JAVA Mapping Iniciado"); //Log para o PI/XI
// Declarações referentes ao XML de entrada
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document xml_in = db.parse(in);
// Declarações referentes ao XML de saída
Document xml_out = db.newDocument();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// Remove o standalone
xml_in.setXmlStandalone(true);
// Declara a estrutura que a RFC irá receber
Element root = xml_out.createElement("ns1:ZFSD_VMOI_UPLOAD_CF_PG");
root.setAttribute("xmlns:ns1","urn:sap-com:document:sap:rfc:functions");
xml_out.appendChild(root);
Element i_cenario = xml_out.createElement("I_CENARIO");
root.appendChild(i_cenario);
Element t_input = xml_out.createElement("T_INPUT");
root.appendChild(t_input);
Element item = xml_out.createElement("ITEM");
t_input.appendChild(item);
Element STRING = xml_out.createElement("STRING");
item.appendChild(STRING);
Element t_return = xml_out.createElement("T_RETURN");
root.appendChild(t_return);
Element item_r = xml_out.createElement("ITEM");
t_return.appendChild(item_r);
Element message = xml_out.createElement("MESSAGE");
item_r.appendChild(message);
// Verifica se existe algum filho no nó
NodeList nodos = xml_in.getChildNodes();
if (nodos.item(0) != null)
getTrace().addInfo("O nó(XML) possui filhos"); //Log para o PI/XI
// Declaração de variáveis
String ident = ""; // <Ident>
String buyer = ""; // <BuyerLineItemNum>
String result = ""; // <Ident>;<BuyerLineItemNum>;<Date>;<QuantityValue>
// Inicia a extração das informações do XML
try{
// Recupera o nó ShipToParty
NodeList nodeShip = xml_in.getElementsByTagName("ns0:ShipToParty");
Node node = nodeShip.item(0);
Element elemXML = (Element) node;
try{
NodeList nodeIdent = elemXML.getElementsByTagName("ns0:Ident");
Element nameElement = (Element) nodeIdent.item(0);
nodeIdent = nameElement.getChildNodes();
// Recupera o valor da chave <Ident>
ident = PI_Mapping_IF.VerifyNull(((Node) nodeIdent.item(0)).getNodeValue());
}catch(Exception e){
result += "0.0;";
// Recupera o nó ListOfMaterialGroupedPlanningDetail
NodeList nodeBuyer = xml_in.getElementsByTagName("ns0:MaterialGroupedPlanningDetail");
for (int i = 0; i < nodeBuyer.getLength(); i++) {
node = nodeBuyer.item(i);
elemXML = (Element) node;
try{
// Preenche a chave BuyerLineItemNum
NodeList nodeBuyerLine = elemXML.getElementsByTagName("ns0:BuyerLineItemNum");
Element elemBuyerLine = (Element) nodeBuyerLine.item(0);
nodeBuyerLine = elemBuyerLine.getChildNodes();
buyer = PI_Mapping_IF.VerifyNull(((Node) nodeBuyerLine.item(0)).getNodeValue());
}catch(Exception e){
buyer += "0;";
result = ident+";"+buyer+";";
Node nodeDt_Qnt = nodeBuyer.item(i);
Element elemDt_Qnt = (Element)nodeDt_Qnt;
NodeList nodeValores = elemDt_Qnt.getElementsByTagName("ns0:ScheduleDetail");
for (int j = 0; j < nodeValores.getLength(); j++) {
node = nodeValores.item(j);
elemXML = (Element) node;
try{
// Preenche a chave Date
NodeList modelExtra = elemXML.getElementsByTagName("ns0:Date");
Element extraElement = (Element) modelExtra.item(0);
modelExtra = extraElement.getChildNodes();
result += PI_Mapping_IF.VerifyNull(((Node) modelExtra.item(0)).getNodeValue())+";";
}catch(Exception e){
result += "//;";
try {
// Preenche a chave QuantityValue
NodeList modelURL = elemXML.getElementsByTagName("ns0:QuantityValue");
Element urlElement = (Element) modelURL.item(0);
modelURL = urlElement.getChildNodes();
result += PI_Mapping_IF.VerifyNull(((Node) modelURL.item(0)).getNodeValue())+";";
} catch (Exception e) {
result += "0.0;";
// Marca o final do registro
result += "||";
// Preenche os nós itens
Text srcxml = xml_out.createTextNode(result);
STRING.appendChild(srcxml);
result = "";
buyer = "";
}catch(Exception e){
// Remove o standalone
xml_out.setXmlStandalone(true);
// Preenche o Cenario
Text cenario = xml_out.createTextNode("P&G");
i_cenario.appendChild(cenario);
// Preenche mensagem de retorno
Text msgxml = xml_out.createTextNode("XML lido com sucesso!");
message.appendChild(msgxml);
// Escreve a saida do XML
transformer.transform(new DOMSource(xml_out), new StreamResult(out));
getTrace().addInfo("Fim da execução do Java Mapping");
} catch (ParserConfigurationException e) {
getTrace().addWarning(e.getMessage());
throw new StreamTransformationException("Can not create DocumentBuilder.", e);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
Am i doing anything wrong in the code? Where can this nullpointerexception be triggered?
Thanks.These three xml are the same:
<?xml version="1.0"?><a:xml xmlns:a="urn:123">root</a:xml>
<?xml version="1.0"?><xml xmlns="urn:123">root</xml>
<?xml version="1.0"?><ns0:xml xmlns:ns0="urn:123">root</ns0:xml>
But your code will work only with last one, because it doesn't bound namespace to prefix ns0. -
How do i update an existing XML File?
Hello, I have the following xml file gps.xml:<?xml version="1.0"?>
<!DOCTYPE gps SYSTEM "gps.dtd">
<gps>
<latitude>43.00000</latitude>
<longitude>-83.00000</longitude>
</gps> I already have methods written to get the values. But how can I change these values and update the file to reflect these changes?
thanks for your help!Hi, I already have this following code. I would just like to add a method to it to update the existing XML file with different lat/lon coordinates. Could you please help me out with it? thanks
import java.io.*;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class Gps implements java.io.Serializable {
private double latitude_;
private double longitude_;
public Gps(Document doc) {
setup(doc.getDocumentElement());
public Gps(String uri) throws IOException, SAXException, ParserConfigurationException {
setup(uri);
public void setup(Document doc) {
setup(doc.getDocumentElement());
public void makeElement(Node parent) {
Document doc;
if (parent instanceof Document) {
doc = (Document)parent;
} else {
doc = parent.getOwnerDocument();
Element element = doc.createElement("gps");
int size;
URelaxer.setElementPropertyByDouble(element, "latitude", this.latitude_);
URelaxer.setElementPropertyByDouble(element, "longitude", this.longitude_);
parent.appendChild(element);
public Document makeDocument() throws ParserConfigurationException {
Document doc = UJAXP.makeDocument();
makeElement(doc);
return (doc);
public final double getLatitude() {
return (latitude_);
public final void setLatitude(double latitude) {
this.latitude_ = latitude;
public final double getLongitude() {
return (longitude_);
public final void setLongitude(double longitude) {
this.longitude_ = longitude;
public final void updateXmlFile(double latitude, double longitude) {
// something???
public final void updateXmlFile(double latitude, double longitude) {
this.latitude_ = latitude;
this.longitude_ = longitude;
public String makeTextDocument() {
StringBuffer buffer = new StringBuffer();
makeTextElement(buffer);
return (new String(buffer));
public void makeTextElement(StringBuffer buffer) {
int size;
buffer.append("<gps");
buffer.append(">");
buffer.append("<latitude>");
buffer.append(Double.toString(getLatitude()));
buffer.append("</latitude>");
buffer.append("<longitude>");
buffer.append(Double.toString(getLongitude()));
buffer.append("</longitude>");
buffer.append("</gps>");
public String toString() {
try {
return (makeTextDocument());
} catch (Exception e) {
return (super.toString());
} -
Using a JAR file as a project file
My application allows the user to create projects. Previously, a project file was simply an XML file. Now, a project file needs to also contain many images.
I thought it would be a good idea to simply use a JAR file as my project file.
Since I've really never really worked with JAR files and the java.util.Jar package directly, I have a few questions.
1) Would it be better just to simply store the images as binary in the XML file? I just spent a good amount of time making the XML file very readable so I thought it would be better to keep the images separate while still having a single "project" file.
2) Is there anything inherently wrong with the way I'm working with the JAR file in the code below?
Simple XML file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE project [
<!ELEMENT project (img+)>
<!ELEMENT img EMPTY>
<!ATTLIST img src CDATA #REQUIRED>
]>
<project>
<img src="blah.jpg"/>
</project>
import java.io.*;
import java.util.jar.JarFile;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class LoaderTest {
private String imageName;
public LoaderTest() {
InputStream i = null;
JarFile jf = null;
try {
jf = new JarFile("project.jar");
i = jf.getInputStream(jf.getJarEntry("project.xml"));
// Here's my simple XML parser to load the project and images
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new InputSource(i), new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// Right now we only care about images
if (qName.equalsIgnoreCase("img")) {
imageName = attributes.getValue("src");
// Load the image from the inputstream
java.awt.image.BufferedImage img = javax.imageio.ImageIO.read(jf.getInputStream(jf.getJarEntry(imageName)));
// Display the image in a JFrame
javax.swing.JFrame f = new javax.swing.JFrame();
f.setLayout(new java.awt.BorderLayout());
f.setSize(800, 600);
f.getContentPane().add(new javax.swing.JLabel(new javax.swing.ImageIcon(img)), java.awt.BorderLayout.CENTER);
f.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// Do our best to close the input streams
if (i != null) {
try {
i.close();
} catch (IOException ex) {}
if (jf != null) {
try {
jf.close();
} catch (IOException ex) {}
public static void main(String[] args) {
new LoaderTest();
}Thank you!1) I also think it's much better to keep your images separate from your XML, this prevents a lot of in case you just want to read XML data
2) What's exactly going wrong here? For the project.xml, make sure it's not inside a directory within the JAR file, or else the variable i will be null. Otherwise it looks fine.. -
Passing arraylist between constructors?
Hi guys,
I've pretty new to java, and I think i'm having a little trouble
understanding scope. The program I'm working on is building a jtree
from an xml file, to do this an arraylist (xmlText) is being built and
declared in the function Main. It's then called to an overloaded
constructor which processes the XML into a jtree:
public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
Later, in the second constructor which builds my GUI, I try and call
the same arraylist so I can parse this XML into a set of combo boxes,
but get an error thrown up at me that i'm having a hard time solving- :
public Editor( String title ) throws ParserConfigurationException
// additional code
// Create a read-only combobox- where I get an error.
String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);
JComboBox queryBox = new JComboBox(items);
JComboBox queryBox2 = new JComboBox(items);
JComboBox queryBox3 = new JComboBox(items);
JComboBox queryBox4 = new JComboBox(items);
JComboBox queryBox5 = new JComboBox(items);
This is the way I understand the Arraylist can be converted to a string
to use in the combo boxs. However I get an error thrown up at me here
at about line 206, which as far as I understand, is because when the
overloaded constructor calls the other constructor:
public Editor( String title ) throws ParserConfigurationException -
It does not pass in the variable xmlText.
I'm told that the compiler complains because xmlText is not defined
at that point:
- it is not a global variable or class member
- it has not been passed into the function
and
- it has not been declared inside the current function
Can anyone think of a solution to this problem? As I say a lot of this
stuff is still fairly beyond me, I understand the principles behind the
language and the problem, but the solution has been evading me so far.
If anyone could give me any help or a solution here I'd be very
grateful- I'm getting totally stressed over this.
The code I'm working on is below, I've highlighted where the error
crops up too- it's about line 200-206 area. Sorry for the length, I was
unsure as to how much of the code I should post.
public class Editor extends JFrame implements ActionListener
// This is the XMLTree object which displays the XML in a JTree
private XMLTree XMLTree;
private JTextArea textArea, textArea2, textArea3;
// One JScrollPane is the container for the JTree, the other is for
the textArea
private JScrollPane jScroll, jScrollRt, jScrollUp,
jScrollBelow;
private JSplitPane splitPane, splitPane2;
private JPanel panel;
// This JButton handles the tree Refresh feature
private JButton refreshButton;
// This Listener allows the frame's close button to work properly
private WindowListener winClosing;
private JSplitPane splitpane3;
// Menu Objects
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem newItem, openItem, saveItem,
exitItem;
// This JDialog object will be used to allow the user to cancel an exit
command
private JDialog verifyDialog;
// These JLabel objects will be used to display the error messages
private JLabel question;
// These JButtons are used with the verifyDialog object
private JButton okButton, cancelButton;
private JComboBox testBox;
// These two constants set the width and height of the frame
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 450;
* This constructor passes the graphical construction off to the
overloaded constructor
* and then handles the processing of the XML text
public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
this( title );
textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
for ( int i = 1; i < xmlText.size(); i++ )
textArea.append( ( String )xmlText.get( i ) + "\n" );
try
XMLTree.refresh( textArea.getText() );
catch( Exception ex )
String message = ex.getMessage();
System.out.println( message );
}//end try/catch
} //end Editor( String title, String xml )
* This constructor builds a frame containing a JSplitPane, which in
turn contains two
JScrollPanes.
* One of the panes contains an XMLTree object and the other contains
a JTextArea object.
public Editor( String title ) throws ParserConfigurationException
// This builds the JFrame portion of the object
super( title );
Toolkit toolkit;
Dimension dim, minimumSize;
int screenHeight, screenWidth;
// Initialize basic layout properties
setBackground( Color.lightGray );
getContentPane().setLayout( new BorderLayout() );
// Set the frame's display to be WIDTH x HEIGHT in the middle of
the screen
toolkit = Toolkit.getDefaultToolkit();
dim = toolkit.getScreenSize();
screenHeight = dim.height;
screenWidth = dim.width;
setBounds( (screenWidth-FRAME_WIDTH)/2,
(screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
FRAME_HEIGHT );
// Build the Menu
// Build the verify dialog
// Set the Default Close Operation
// Create the refresh button object
// Add the button to the frame
// Create two JScrollPane objects
jScroll = new JScrollPane();
jScrollRt = new JScrollPane();
// First, create the JTextArea:
// Create the JTextArea and add it to the right hand JScroll
textArea = new JTextArea( 200,150 );
jScrollRt.getViewport().add( textArea );
// Next, create the XMLTree
XMLTree = new XMLTree();
XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION
XMLTree.setShowsRootHandles( true );
// A more advanced version of this tool would allow the JTree to
be editable
XMLTree.setEditable( false );
// Wrap the JTree in a JScroll so that we can scroll it in the
JSplitPane.
jScroll.getViewport().add( XMLTree );
// Create the JSplitPane and add the two JScroll objects
splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
jScrollRt );
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
jScrollUp = new JScrollPane();
jScrollBelow=new JScrollPane();
// Here is were the error is coming up
String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);
JComboBox queryBox = new JComboBox(items);
JComboBox queryBox2 = new JComboBox(items);
JComboBox queryBox3 = new JComboBox(items);
JComboBox queryBox4 = new JComboBox(items);
JComboBox queryBox5 = new JComboBox(items);
* I'm adding the scroll pane to the split pane,
* a panel to the top of the split pane, and some uneditible
combo boxes
* to them. Then I'll rearrange them to rearrange them, but
unfortunately am getting an error thrown up above.
panel = new JPanel();
panel.add(queryBox);
panel.add(queryBox2);
panel.add(queryBox3);
panel.add(queryBox4);
panel.add(queryBox5);
jScrollUp.getViewport().add( panel );
// Now building a text area
textArea3 = new JTextArea(200, 150);
jScrollBelow.getViewport().add( textArea3 );
splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
jScrollUp, jScrollBelow);
splitPane2.setPreferredSize( new Dimension(300, 200) );
splitPane2.setDividerLocation(100);
splitPane2.setOneTouchExpandable(true);
// in here can change the contents of the split pane
getContentPane().add(splitPane2,BorderLayout.SOUTH);
// Provide minimum sizes for the two components in the split pane
minimumSize = new Dimension(200, 150);
jScroll.setMinimumSize( minimumSize );
jScrollRt.setMinimumSize( minimumSize );
// Provide a preferred size for the split pane
splitPane.setPreferredSize( new Dimension(400, 300) );
// Add the split pane to the frame
getContentPane().add( splitPane, BorderLayout.CENTER );
//Put the final touches to the JFrame object
validate();
setVisible(true);
// Add a WindowListener so that we can close the window
winClosing = new WindowAdapter()
public void windowClosing(WindowEvent e)
verifyDialog.show();
addWindowListener(winClosing);
} //end Editor()
* When a user event occurs, this method is called. If the action
performed was a click
* of the "Refresh" button, then the XMLTree object is updated using
the current XML text
* contained in the JTextArea
public void actionPerformed( ActionEvent ae )
if ( ae.getActionCommand().equals( "Refresh" ) )
try
XMLTree.refresh( textArea.getText() );
catch( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
else if ( ae.getActionCommand().equals( "OK" ) )
exit();
else if ( ae.getActionCommand().equals( "Cancel" ) )
verifyDialog.hide();
}//end if/else if
} //end actionPerformed()
// Program execution begins here. An XML file (*.xml) must be passed
into the method
public static void main( String[] args )
String fileName = "";
BufferedReader reader;
String line;
ArrayList xmlText = null;
Editor Editor;
// Build a Document object based on the specified XML file
try
if( args.length > 0 )
fileName = args[0];
if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
".xml" ) )
reader = new BufferedReader( new FileReader( fileName )
xmlText = new ArrayList();
while ( ( line = reader.readLine() ) != null )
xmlText.add( line );
} //end while ( ( line = reader.readLine() ) != null )
// The file will have to be re-read when the Document
object is parsed
reader.close();
// Construct the GUI components and pass a reference to
the XML root node
Editor = new Editor( "Editor 1.0", xmlText );
else
help();
} //end if ( fileName.substring( fileName.indexOf( '.' )
).equals( ".xml" ) )
else
Editor = new Editor( "Editor 1.0" );
} //end if( args.length > 0 )
catch( FileNotFoundException fnfEx )
System.out.println( fileName + " was not found." );
exit();
catch( Exception ex )
ex.printStackTrace();
exit();
}// end try/catch
}// end main()
// A common source of operating instructions
private static void help()
System.out.println( "\nUsage: java Editor filename.xml" );
System.exit(0);
} //end help()
// A common point of exit
public static void exit()
System.out.println( "\nThank you for using Editor 1.0" );
System.exit(0);
} //end exit()
class newMenuHandler implements ActionListener
public void actionPerformed( ActionEvent ae )
textArea.setText( "" );
try
// Next, create a new XMLTree
XMLTree = new XMLTree();
XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION );
XMLTree.setShowsRootHandles( true );
// A more advanced version of this tool would allow the JTree
to be editable
XMLTree.setEditable( false );
catch( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
}//end actionPerformed()
}//end class newMenuHandler
class openMenuHandler implements ActionListener
JFileChooser jfc;
Container parent;
int choice;
openMenuHandler()
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = openItem.getParent();
}//end openMenuHandler()
public void actionPerformed( ActionEvent ae )
// Displays the jfc and sets the dialog to 'open'
choice = jfc.showOpenDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
String fileName, line;
BufferedReader reader;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
reader = new BufferedReader( new FileReader( fileName ) );
textArea.setText( reader.readLine() + "\n" );
while ( ( line = reader.readLine() ) != null )
textArea.append( line + "\n" );
} //end while ( ( line = reader.readLine() ) != null )
// The file will have to be re-read when the Document
object is parsed
reader.close();
XMLTree.refresh( textArea.getText() );
catch ( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
jfc.setCurrentDirectory( new File( fileName ) );
} //end if ( choice == JFileChooser.APPROVE_OPTION )
}//end actionPerformed()
}//end class openMenuHandler
class saveMenuHandler implements ActionListener
JFileChooser jfc;
Container parent;
int choice;
saveMenuHandler()
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = saveItem.getParent();
}//end saveMenuHandler()
public void actionPerformed( ActionEvent ae )
// Displays the jfc and sets the dialog to 'save'
choice = jfc.showSaveDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
String fileName;
File fObj;
FileWriter writer;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
writer = new FileWriter( fileName );
textArea.write( writer );
// The file will have to be re-read when the Document
object is parsed
writer.close();
catch ( IOException ioe )
ioe.printStackTrace();
}//end try/catch
jfc.setCurrentDirectory( new File( fileName ) );
} //end if ( choice == JFileChooser.APPROVE_OPTION )
}//end actionPerformed()
}//end class saveMenuHandler
class exitMenuHandler implements ActionListener
public void actionPerformed( ActionEvent ae )
verifyDialog.show();
}//end actionPerformed()
}//end class exitMenuHandler
class XmlFileFilter extends javax.swing.filechooser.FileFilter
public boolean accept( File fobj )
if ( fobj.isDirectory() )
return true;
else
return fobj.getName().endsWith( ".xml" );
}//end accept()
public String getDescription()
return "*.xml";
}//end getDescription()
}//end class XmlFileFilter
} //end class Editor
Sorry if this post has been a bit lengthy, any help you guys could give
me solving this would be really appreciated.
Thanks,
Iain.Hey. Couple pointers:
When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
That way people don't have to wade through irrelevant stuff and
they have an easier time helping.
http://homepage1.nifty.com/algafield/sscce.html
As for your problem, this is a scope issue. You declare an
ArrayList xmlText in main(). That means that everywhere after
the declaration in main(), you can reference your xmlText.
So far so good. Then, inside main(), you call
Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
Editor(String title, ArrayList xmlText) [which happens to be a
constructor, but that's not important]. When you do that, you
make the two variables title and xmlText available to the whole
Editor(String, ArrayList) method.
This is where you get messed up. You invoke another method
from inside Editor(String, ArrayList). When you call
this(title);you're invoking the method Editor(String title). You aren't passing
in your arraylist, though. You've got code in the Editor(String) method
which is trying to reference xmlText, but you'd need to pass in
your ArrayList in order to do so.
My suggestion would be to merge the two constructor methods into
one, Editor(String title, ArrayList xmlText). -
Problem getting arraylist from another class
I am trying to call information about an arraylist from another class. I am using this code to call the size of an arraylist:
import java.io.*;
public class Test
public static void main(String argv[]) throws IOException
Echo03 thing = new Echo03();
int y=thing.value();
System.out.println(y);
Echo03 thing2 = new Echo03();
int x=thing2.percent.size();
System.out.println(x);
}from another file which starts like this:
public class Echo03 extends DefaultHandler
static ArrayList<String> percent = new ArrayList<String>();
static ArrayList<String> text = new ArrayList<String>();
int a;
public int value(){
return percent.size();
public static void main(String argv[]) throws IOException
{The second file is based on an example piece of code from the Java website. I havent posted the whole thing, but if it is relevant then please ask.
Anyway when I run Echo03 by itself, the arraylist has a size of 2. But when I run it from the Test file, it says a size of 0. Is this because the data is not being transferred between the classes? Or is the Echo03 program not executing (and hence the arraylist is not filling up)?
How can I fix this? I have tried 2 ways of calling the data (As seen in my Test file). Neither work.I didnt post the full bit of the code for the second one. Here it is:
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
public class Echo03 extends DefaultHandler
static ArrayList<String> percent = new ArrayList<String>();
static ArrayList<String> text = new ArrayList<String>();
int a;
public static void main(String argv[]) throws IOException
if (argv.length != 1) {
System.err.println("Usage: cmd filename");
System.exit(1);
// Use an instance of ourselves as the SAX event handler
DefaultHandler handler = new Echo03();
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
// Set up output stream
out = new OutputStreamWriter(System.out, "UTF8");
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(argv[0]), handler);
for (int b=0; b<percent.size();b++){
System.out.println(percent.get(b+1));
} catch (Throwable t) {
System.exit(0);
static private Writer out;
public void startElement(String namespaceURI,
String lName, // local name
String qName, // qualified name
Attributes attrs)
throws SAXException
if (attrs != null) {
StringBuffer sb = new StringBuffer (250);
for (int i = 0; i < attrs.getLength(); i++) {
nl();
emit(attrs.getValue(i));
sb.append (attrs.getValue(i));
String sf = sb.toString ();
percent.add(sf);
System.out.println(" String: "+sf); a++;
public void characters(char buf[], int offset, int len)
throws SAXException
emit(" ");
String s = new String(buf, offset, len);
if (!s.trim().equals("")) {text.add(s); emit(s);}
//===========================================================
// Utility Methods ...
//===========================================================
// Wrap I/O exceptions in SAX exceptions, to
// suit handler signature requirements
private void emit(String s)
throws SAXException
try {
out.write(s);
out.flush();
} catch (IOException e) {
throw new SAXException("I/O error", e);
// Start a new line
private void nl()
throws SAXException
String lineEnd = System.getProperty("line.separator");
try {
out.write(lineEnd);
} catch (IOException e) {
throw new SAXException("I/O error", e);
} -
~~ New XMP CS6 SDK Releases ~~
Hi,
You can now find new versions of our XMP SDKs on Adobe Devnet:
http://www.adobe.com/devnet/xmp/
So please check out the CS6 versions of the SDKs and post your feedback in this forum!
The prior versions are still listed.
Updates:
Updated XMP Specifications [version: April 2012]
New version of the XMP Toolkit SDK (c++) [version: CS6]
Compiler Upgrade: Xcode 4.x, Visual Studio 2010 (VC10)
A plug-in SDK for XMPFiles that allows you to add custom file handlers, or replace existing file handlers with custom ones in XMPFiles
A new version of the file handler for RIFF-based formats that also support AIFF. The AVI handler still uses the old code, but WAVE and AIFF are based in the new file handler
New functions in XMPFiles that allows you to use your own I/O code in XMPFiles
Support of EXIF 2.3 properties
A new XMPFiles function, GetFileModDate(), that retrieves the most recent OS file modification date for the associated metadata of a file
Many bug fixes and minor improvements in XMPFiles
The XMP FileInfo SDK is now available in version CS6
Custom Panel Plugin for Flash builder 4.x
EVE Panel converter (to convert CS 2/3 panels)
Create generic panel without Action Script (XML only)
XMPCore Java is now is now available in version CS6 and seperated from the C++ toolkit (see new Java section)Many bug fixes and minor improvements
The Adobe XMP TeamHi,
i used the previous version of the java XMPCore. I tried to upgrade however i got the following exception (using java 1.5 and 1.6):
java.lang.AbstractMethodError: javax.xml.parsers.DocumentBuilderFactory.setFeature(Ljava/lang/String;Z)V
at com.adobe.xmp.impl.XMPMetaParser.createDocumentBuilderFactory(Unknown Source)
at com.adobe.xmp.impl.XMPMetaParser.<clinit>(Unknown Source)
at com.adobe.xmp.XMPMetaFactory.parseFromBuffer(Unknown Source)
at com.adobe.xmp.XMPMetaFactory.parseFromBuffer(Unknown Source)
On further investigation the problem is, that you are trying to call a method
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
on an abstract class however you are not catching that error, as you propably intended to.
The code has been introduced into the new version:
class XMPMetaParser.java:
try
// honor System parsing limits, e.g.
// System.setProperty("entityExpansionLimit", "10");
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
catch (Exception e)
// Ignore IllegalArgumentException and ParserConfigurationException
// in case the configured XML-Parser does not implement the feature.
The exception is of the type "Error" and thus won't be catched by the "catch (Exception)" block at this point. If you change the following to:
try
// honor System parsing limits, e.g.
// System.setProperty("entityExpansionLimit", "10");
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
catch (Throwable t)
// Ignore AbstractMethodError, IllegalArgumentException and ParserConfigurationException
// in case the configured XML-Parser does not implement the feature.
or to
try
// honor System parsing limits, e.g.
// System.setProperty("entityExpansionLimit", "10");
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
catch(Error e){
// Ignore AbstractMethodError in case there is no implementation at all
catch (Exception e)
// Ignore IllegalArgumentException and ParserConfigurationException
// in case the configured XML-Parser does not implement the feature.
Everything is working as aspected again... -
Urgent: SAX parser bean is not working in JSP page
Hi All,
I have created a bean "ReadAtts" and included into a jsp file using
"useBean", It is not working. I tried all possibilities. But Failed Plz Help me.
Below are the details:
Java Bean: ReadAtts.java
package sax;
import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
public class ReadAtts extends DefaultHandler implements java.io.Serializable
private Vector attNames = new Vector(); //Stores all the att names from the XML
private Vector attValues = new Vector();
private Vector att = new Vector();
private Locator locator;
private static String start="",end="",QueryString="",QString1="",QString2="";
private static boolean start_collecting=false;
public ReadAtts()
public Vector parse(String filename,String xpath) throws Exception
QueryString=xpath;
StringTokenizer QueryString_ST = new StringTokenizer(QueryString,"/");
int stLen = QueryString_ST.countTokens();
while(QueryString_ST.hasMoreTokens())
if((QueryString_ST.countTokens())>1)
QString1 = QueryString_ST.nextToken();
else if((QueryString_ST.countTokens())>0)
QString2 = QueryString_ST.nextToken();
SAXParserFactory spf =
SAXParserFactory.newInstance();
spf.setValidating(false);
SAXParser saxParser = spf.newSAXParser();
// create an XML reader
XMLReader reader = saxParser.getXMLReader();
FileReader file = new FileReader(filename);
// set handler
reader.setContentHandler(this);
// call parse on an input source
reader.parse(new InputSource(file));
att.add("This is now added");
//return attNames;
return att;
public void setDocumentLocator(Locator locator)
this.locator = locator;
public void startDocument() { }
public void endDocument() { }
public void startPrefixMapping(String prefix, String uri) { }
public void endPrefixMapping(String prefix) { }
/** The opening tag of an element. */
public void startElement(String namespaceURI, String localName,String qName, Attributes atts)
start=localName;
if(start.equals(QString2))
start_collecting=true; //start collecting nodes
if(start_collecting)
if((atts.getLength())>0)
for(int i=0;i<=(atts.getLength()-1);i++)
attNames.add((String)atts.getLocalName(i));
attValues.add((String)atts.getValue(i));
/** The closing tag of an element. */
public void endElement(String namespaceURI, String localName, String qName)
end = localName;
if(end.equals(QString2))
start_collecting=false; //stop colelcting nodes
/** Character data. */
public void characters(char[] ch, int start, int length) { }
/** Ignorable whitespace character data. */
public void ignorableWhitespace(char[] ch, int start, int length){ }
/** Processing Instruction */
public void processingInstruction(String target, String data) { }
/** A skipped entity. */
public void skippedEntity(String name) { }
public static void main(String[] args)
String fname=args[0];
String Xpath=args[1];
System.out.println("\n from main() "+(new ReadAtts().parse(fname,Xpath)));
//System.out.println("\n from main() "+new ReadAtts().attNames());
//System.out.println("\n from main() "+new ReadAtts().attValues());
JSP File:
<%@ page import="sax.*,java.io.*,java.util.*,java.lang.*,java.text.*;" %>
<jsp:useBean id="p" class="sax.ReadAtts"/>
Data after Parsing is.....
<%=p.parse"E:/Log.xml","/acq/service/metrics/system/stackUsage")%>
Expected Output:
The jsp file should print all the vector objects from the "ReadAtts" bean
Actual Output:
Data after Parsing.......[]
Thanks for your time.....
Newton
Bangalore. INDIAthe problem is not because of java code insdie jsp page
I have removed all things but the form and it is still not working
here is the modified code:
<!-- add news-->
<%
if(request.getParameter("addBTN") != null){
out.print("addBTN");
%>
<!-- end of add news-->
<form action="" method="post" enctype="multipart/form-data" name="upform" >
<table width="99%" border="0" align="center" cellpadding="1" cellspacing="1">
<tr>
<td colspan="2" align="right" bgcolor="#EAEAEA" class="borderdTable"><p>'6'A) .(1 ,/J/</p></td>
</tr>
<tr>
<td width="87%" align="right"><label>
<input name="title" type="text" class="rightText" id="title">
</label></td>
<td width="13%" align="right">9FH'F 'D.(1</td>
</tr>
<tr>
<td align="right"><textarea name="elm1" cols="50" rows="10" id="elm1" style="direction:rtl" >
</textarea></td>
<td align="right">*A'5JD 'D.(1</td>
</tr>
<tr>
<td align="right"><label>
<input type="file" name="filename" id="filename">
</label></td>
<td align="right">5H1)</td>
</tr>
<tr>
<td align="right"><label>
<input name="addBTN" type="submit" class="btn" id="addBTN" value=" '6'A) .(1 ">
</label></td>
<td align="right"> </td>
</tr>
</table>
</form>
<!-- TinyMCE -->
<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple",
directionality : "rtl"
</script>
<!--end of TinyMCE --> -
How to read/interpret data in xml files
Hi,
I am trying to write a program using DOM to read an xml file - that doesn't have a dtd. My aim is to get the node names and the content enclosed in the node. The xml I have is something like:
<ARTICLE>
<TITLE>
</TITLE>
<DESCRIPTION>
</DESCRIPTION>
<SYNOPSIS>
</SYNOPSIS>
<SOURCE>
<FOOT>
</FOOT>
</SOURCE>
<PARA>
</PARA>
<PARA>
</PARA>
<PARA>
</PARA>
</ARTICLE>
My java code thus far is:
public class Word2dmt {
String fileExt = "";
int fileNameLength = 0;
public void Word2dmt(){
// Default constructor
public void processFiles(){
String fileName = "";
String filePath = "/MyProjects/FOP/word2dmt/";
String[] files = null;
File dirWhereXmlFilesAre = null;
Document document;
DocumentBuilder builder = null;
try {
dirWhereXmlFilesAre = new File(filePath);
files = dirWhereXmlFilesAre.list();
} catch (IllegalArgumentException iae) {
Log.message("Caught iae: " + iae.getMessage());
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// factory.setValidating(true);
// factory.setNamespaceAware(true);
try{
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
for (int z = 0; z < files.length; z++){
fileName = filePath + files[z];
fileNameLength = fileName.length();
fileExt = fileName.substring(fileName.indexOf(".") + 1,
fileNameLength);
if(fileExt.equalsIgnoreCase("xml")){
try {
document = builder.parse(new File(fileName));
if(document.hasChildNodes()){
NodeList nodes = document.getChildNodes();
processNodes(nodes);
} catch (SAXParseException spe) {
// Error generated by the parser
System.out.println("\n** Parsing error" + ", line " +
} catch (SAXException sxe) {
// Error generated during parsing)
} catch (FileNotFoundException fnf) {
Log.message("The file: " + fileName + " is not found");
} catch (IOException e) {
Log.message("IOexception: " + e.getMessage());
} // Ends the main for loop on the files
public static void main(String[] args) {
Word2dmt w2dmt = new Word2dmt();
w2dmt.processFiles();
} // end main()
public void processNodes(NodeList nodes){
Node thisNode = null;
NamedNodeMap nodeMap = null;
Element curElement = null;
int numNodes = nodes.getLength();
String nodeValue = "";
String nodeName = "";
String localName = "";
String prefix = "";
for(int j = 0; j < numNodes; j++){
thisNode = (Node) nodes.item(j);
if(thisNode.hasChildNodes()){
processNodes(thisNode.getChildNodes());
} else {
nodeValue = thisNode.getNodeValue();
nodeName = thisNode.getNodeName();
Log.message("\t\t" + "nodeName is: " + nodeName);
Log.message("\t\t" + "nodeValue is: " + nodeValue);
When I try to print the node name, all I get is: "#test" except for the node ARTICLE, which happens to be the root node. My requirement is that I need the node name (TITLE, SYNOPSIS, DESCRIPTION ..etc) and be able to associate the content in other areas of my larger program. I tried almost all the methods of the class org.w3c.dom.Node, but without luck.
Any help is appreciated.
Thanks.
- SharmaWhen I try to print the node name, all I get is: "#test"I think if you look more carefully you'll see it really says "#text". That's the "name" of a text node, of which you have a lot there. Also, if a node has children then you aren't printing its name, that's why you miss most of your elements.
-
How can i read XML string in a loop???
i changed xml file reader to xml string reader by
looking around this and other forums.
here is the code.
public class XMLTester2 {
public static void main(String[] args) {
String s = "<firsttag><secondtag>123</secondtag></firsttag>";
java.io.Reader reader = new java.io.StringReader(s);
org.xml.sax.InputSource source = new org.xml.sax.InputSource(reader);
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory fact = javax.xml.parsers.DocumentBuilderFactory.newInstance();
try {
javax.xml.parsers.DocumentBuilder builder = fact.newDocumentBuilder();
doc = builder.parse(source);
} catch (javax.xml.parsers.ParserConfigurationException pce) {
} catch (org.xml.sax.SAXException se) {
} catch (java.io.IOException ioe) {
} finally {
try {
reader.close();
} catch (java.io.IOException ignored) {
}i put this stuff into a loop, but i always ends up
having new in the loop.
String inputLine = "Start";
// define what's needed for XML messages
Reader reader = new StringReader(inputLine);
InputSource source = new InputSource(reader);
Document doc = null;
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Node xmlNode = null;
try {
builder = fact.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
// -->
while ( (inputLine = in.readLine()) != null) {
System.out.println("readLine() : {" + inputLine + "}");
reader = new StringReader(inputLine);
source.setCharacterStream(reader);
try {
doc = builder.parse(source);
} catch (SAXException se) {
System.out.println("SAXException : " + se);
System.out.println("SAXException source : " + source.toString() );
se.printStackTrace();
} catch (IOException ioe) {
System.out.println("IOException : " + ioe);
} finally {
try {
reader.close();
} catch (IOException ignored) {
reader = null;i know putting new in the loop is VERY bad.
i gotto get ride of this new from the loop.
can anyone help me?i know putting new in the loop is VERY bad.
i gotto get ride of this new from the loop.Don't design your application based on one-liners you heard somewhere. Do some timings to see if it matters. My guess would be that parsing an XML file would take a fair bit longer than creating a StringReader object. And you do need a new StringReader each time, they aren't reusable, so the alternatives are not obvious. And don't accept my guess about the timings, check it for yourself. -
How do I use doGoogleSearch to connect to Google API
Hello all,
I am trying to do my final year project and I am currently having trouble connecting to the Google API using doGoogleSearch. I dont know how to use http://api.google.com/GoogleSearch.wsdl to fill in the parameters for the doGoogleSearch and then I have to use the http://api.google.com/search/beta2 to connect to Google and perform the test. Any help would be appreciated or code or links
Thanks in advance rgds,
Tony
Here is my code so far...................................
package tony_buckley_project;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.net.URI;
import java.net.URLConnection;
import java.util.*;
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import com.google.soap.search.GoogleSearch;
import com.google.soap.search.GoogleSearchResult;
import com.google.soap.search.GoogleSearchFault;
import com.google.soap.search.GoogleSearchResultElement;
import com.google.soap.search.*;
import javax.xml.soap.*;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;
import org.w3c.dom.*;
import java.io.FileInputStream;
import javax.xml.transform.stream.StreamSource;
import javax.xml.messaging.URLEndpoint;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.*;
* <p>Title: Mr. Tony Buckley</p>
* <p>Description: </p>
* <p>Copyright: Copyright Tony Buckley (c) 2004</p>
* <p>Company: Cork Institute of Technology </p>
* @[email protected]
* @version 1.0
public class Applet2 extends Frame implements WindowListener , ActionListener
TextField searchField;
Button search , quit;
Canvas0 canvas;
public Applet2()
super();
//Set up basic window
setTitle("Tony Buckley Final Year Project");
setBackground(Color.white);
setSize(500 , 400);
addWindowListener(this);
//Set up area with buttons
//Search button
Panel p1 = new Panel();
p1.setLayout(new FlowLayout());
searchField = new TextField("" , 15);
p1.add(searchField);
search = new Button("Search the web for results...");
p1.add(search);
search.addActionListener(this);
//Quit button
Panel p2 = new Panel();
p2.setLayout(new FlowLayout());
Button quit = new Button("Quit");
p2.add(quit);
quit.addActionListener(this);
//Set up search results area
Canvas0 canvas = new Canvas0();
add("Center" , canvas);
Panel p4 = new Panel();
p4.setLayout(new GridLayout(2 , 1));
p4.add(p1);
p4.add(p2);
add("South" , p4);
}//End of constructor method public Applet2()
public void doGoogleSearch()
String key;
String q;
int start;
int maxResults;
boolean filter;
String restrict;
boolean safeSearch;
String lr;
String ie;
String oe;
public static void main(String[] args)
Applet2 app = new Applet2();
app.setVisible(true);
public void actionPerformed(ActionEvent event)
//Deals with "Quit" button
if(event.getSource() == quit)
dispose();
System.exit(0);
else if(event.getSource() == search)
/* try
String suggestion = search_internet .doSpellingSuggestion(spellingRequest);
if(suggestion == null)
System.out.println("There is no spelling suggestion in the database");
else
System.out.println(suggestion);
int startResult = 100;
search_internet.setStartResult(startResult);
int maxResult = 5;
search_internet.setMaxResults(maxResult);
GoogleSearchResult result_search_internet = search_internet.doSearch();
GoogleSearchResultElement[] resultElements = result_search_internet.getResultElements();
int startIndex = result_search_internet.getStartIndex() - 1 - startResult;
int endIndex = result_search_internet.getEndIndex() - 1 - startResult;
for(int i = startIndex ; i <= endIndex; i ++)
GoogleSearchResultElement resultElement = resultElements[(i)];
String title = resultElement.getTitle();
String URL = resultElement.getURL();
System.out.println(title);
System.out.println(URL);
System.out.println("");
System.out.println("Start Index = " + result_search_internet.getStartIndex());
System.out.println("End Index = " + result_search_internet.getEndIndex());
System.out.println(result_search_internet.toString());
int numResults = result_search_internet.getEstimatedTotalResultsCount();
if(result_search_internet.getEstimateIsExact())
System.out.println("Number of results: " +numResults);
else
System.out.println("Estimated number of results: " +numResults);
//catch(GoogleSearchFault gsf)
// System.out.println("Google Search Fault: " +gsf.getMessage());
try
String myKey = "0RK+HoNQFHJlcbNPfxgBpcjESUWV96aO";
String wsdl = "http://api.google.com/GoogleSearch.wsdl";
String url = "http://api.google.com/search/beta2";
String ns1 = "urn:GoogleSearch";
String searchTerm;
searchTerm = "science fiction";
String spellingRequest = searchTerm;
//First create the connection
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnFactory.createConnection();
//Create the actual message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
//Create objects for the message parts
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody body = envelope.getBody();
//Populate the message
SOAPElement bodyElement = body.addChildElement(envelope.createName("doGoogleSearch" , "ns1", ns1));
GoogleSearch search = new GoogleSearch();
search.setKey(myKey);
search.setQueryString(searchTerm);
//Save the message
message.saveChanges();
//Send the message and get a reply
//Set the destination
URLEndpoint destination = new URLEndpoint(url);
//Send the message
SOAPMessage reply = connection.call(message, destination);
SOAPPart sp = reply.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = reply.getSOAPPart().getContent();
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
//Close the connection
connection.close();
catch(Exception e)
System.out.println(e.getMessage());
}//End of method actionPerformed
public void windowClosing(WindowEvent event)
//Deals with the window closing
dispose();
System.exit(0);
}//End of method windowClosing
public void windowOpened(WindowEvent event)
public void windowIconified(WindowEvent event)
public void windowDeiconified(WindowEvent event)
public void windowClosed(WindowEvent event)
public void windowActivated(WindowEvent event)
public void windowDeactivated(WindowEvent event)
}//End of class Applet2
class Canvas0 extends Canvas
public Canvas0()
super();
public void paint(Graphics g)
Dimension d = getSize();
Font f1 = new Font("TimesRoman" , Font.PLAIN , 14);
Font f2 = new Font("TimesRoman" , Font.ITALIC , 14);
FontMetrics fm1 = g.getFontMetrics(f1);
FontMetrics fm2 = g.getFontMetrics(f2);
String s1 = "Hello , ";
String s2 = "World";
int w1 =fm1.stringWidth(s1);
int w2 =fm1.stringWidth(s2);
g.setColor(Color.GREEN);import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.net.URI;
import java.net.URLConnection;
import java.util.*;
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import com.google.soap.search.GoogleSearch;
import com.google.soap.search.GoogleSearchResult;
import com.google.soap.search.GoogleSearchFault;
import com.google.soap.search.GoogleSearchResultElement;
import com.google.soap.search.*;
import javax.xml.soap.*;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;
import org.w3c.dom.*;
import java.io.FileInputStream;
import javax.xml.transform.stream.StreamSource;
import javax.xml.messaging.URLEndpoint;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.*;
Title: Mr. Tony Buckley
Description:
Copyright: Copyright Tony Buckley (c) 2004
Company: Cork Institute of Technology
* @[email protected]
http://beingaplayer.x314.co.uk
* @version 1.0
public class Applet2 extends Frame implements WindowListener , ActionListener
TextField searchField;
Button search , quit;
Canvas0 canvas;
public Applet2()
super();
//Set up basic window
setTitle("Tony Buckley Final Year Project");
setBackground(Color.white);
setSize(500 , 400);
addWindowListener(this);
//Set up area with buttons
//Search button
Panel p1 = new Panel();
p1.setLayout(new FlowLayout());
searchField = new TextField("" , 15);
p1.add(searchField);
search = new Button("Search the web for results...");
p1.add(search);
search.addActionListener(this);
//Quit button
Panel p2 = new Panel();
p2.setLayout(new FlowLayout());
Button quit = new Button("Quit");
p2.add(quit);
quit.addActionListener(this);
//Set up search results area
Canvas0 canvas = new Canvas0();
add("Center" , canvas);
Panel p4 = new Panel();
p4.setLayout(new GridLayout(2 , 1));
p4.add(p1);
p4.add(p2);
add("South" , p4);
}//End of constructor method public Applet2()
public void doGoogleSearch()
String key;
String q;
int start;
int maxResults;
boolean filter;
String restrict;
boolean safeSearch;
String lr;
String ie;
String oe;
public static void main(String[] args)
Applet2 app = new Applet2();
app.setVisible(true);
public void actionPerformed(ActionEvent event)
//Deals with "Quit" button
if(event.getSource() == quit)
dispose();
System.exit(0);
else if(event.getSource() == search)
/* try
String suggestion = search_internet .doSpellingSuggestion(spellingRequest);
if(suggestion == null)
System.out.println("There is no spelling suggestion in the database");
else
System.out.println(suggestion);
int startResult = 100;
search_internet.setStartResult(startResult);
int maxResult = 5;
search_internet.setMaxResults(maxResult);
GoogleSearchResult result_search_internet = search_internet.doSearch();
GoogleSearchResultElement[] resultElements = result_search_internet.getResultElements();
int startIndex = result_search_internet.getStartIndex() - 1 - startResult;
int endIndex = result_search_internet.getEndIndex() - 1 - startResult;
for(int i = startIndex ; i <= endIndex; i ++)
GoogleSearchResultElement resultElement = resultElements[(i)];
String title = resultElement.getTitle();
String URL = resultElement.getURL();
System.out.println(title);
System.out.println(URL);
System.out.println("");
System.out.println("Start Index = " + result_search_internet.getStartIndex());
System.out.println("End Index = " + result_search_internet.getEndIndex());
System.out.println(result_search_internet.toString());
int numResults = result_search_internet.getEstimatedTotalResultsCount();
if(result_search_internet.getEstimateIsExact())
System.out.println("Number of results: " +numResults);
else
System.out.println("Estimated number of results: " +numResults);
//catch(GoogleSearchFault gsf)
// System.out.println("Google Search Fault: " +gsf.getMessage());
try
String myKey = "0RK+HoNQFHJlcbNPfxgBpcjESUWV96aO";
String wsdl = "http://api.google.com/GoogleSearch.wsdl";
String url = "http://api.google.com/search/beta2";
String ns1 = "urn:GoogleSearch";
String searchTerm;
searchTerm = "science fiction";
String spellingRequest = searchTerm;
//First create the connection
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnFactory.createConnection();
//Create the actual message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
//Create objects for the message parts
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody body = envelope.getBody();
//Populate the message
SOAPElement bodyElement = body.addChildElement(envelope.createName("doGoogleSearch" , "ns1", ns1));
GoogleSearch search = new GoogleSearch();
search.setKey(myKey);
search.setQueryString(searchTerm);
//Save the message
message.saveChanges();
//Send the message and get a reply
//Set the destination
URLEndpoint destination = new URLEndpoint(url);
//Send the message
SOAPMessage reply = connection.call(message, destination);
SOAPPart sp = reply.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = reply.getSOAPPart().getContent();
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
//Close the connection
connection.close();
catch(Exception e)
System.out.println(e.getMessage());
}//End of method actionPerformed
public void windowClosing(WindowEvent event)
//Deals with the window closing
dispose();
System.exit(0);
}//End of method windowClosing
public void windowOpened(WindowEvent event)
public void windowIconified(WindowEvent event)
public void windowDeiconified(WindowEvent event)
public void windowClosed(WindowEvent event)
public void windowActivated(WindowEvent event)
public void windowDeactivated(WindowEvent event)
}//End of class Applet2
class Canvas0 extends Canvas
public Canvas0()
super();
public void paint(Graphics g)
Dimension d = getSize();
Font f1 = new Font("TimesRoman" , Font.PLAIN , 14);
Font f2 = new Font("TimesRoman" , Font.ITALIC , 14);
FontMetrics fm1 = g.getFontMetrics(f1);
FontMetrics fm2 = g.getFontMetrics(f2);
String s1 = "Hello , ";
String s2 = "World";
int w1 =fm1.stringWidth(s1);
int w2 =fm1.stringWidth(s2);
g.setColor(Color.GREEN);
Maybe you are looking for
-
I have dragged 2 files to the trash bin but I cannot delete them from the trash bin. It keeps telling me these files are in use when they are not. How do I delete these files? One is a txt file and the other is an xls file
-
I took my iMac to be fixed and when I got it back, mail was not set, so I called Apple and they helped me set up mail. Now the new mail goes to trash and there is no number by the 'inbox' to tell me how many new messages I have. I cannot save a draft
-
Firewire 800 External Hard Drive recomendations for recording
Ok so I posted a week or so ago about a bad experience I had with a firewire 800 external drive. Anyway, Im sending it back and getting a refund but I wanted to confer with you guys about a good, but cheaper (under $100 please) firewire 800 drive tha
-
IMovie can't find events now moved to a new internal drive
I installed a second 1Tbit drive and moved my photos, movies, music and documents from the primary drive to the new drive. I also created alias's for each of these folders. Although iTunes didn't care about the alias, and Aperture reset it's file loc
-
X-Path like Query option for XMLModel?
Hi, is there an option to use x-path-like queries in the XMLModel? E.g. <?xml version="1.0" encoding="UTF-8"?> <main> <config> <mode>1</mode> <ext