XPath for Java
Hi all,
I have an xml and i would like to do some query to the xml.
Is there any XPath API that i can use in java ?
Currently using 1.4.2
Is there any other recommendations?
Thanks
Xalan and Jaxen are two possibilities:
http://xml.apache.org/xalan-j/
http://jaxen.org/
Similar Messages
-
ANN: XML Parser for Java v2.0.2.6
The v2.0.2.6 of the XML Parser for Java is now available for download. The following features and bug fixes are included:
Changes:
Conformance to the XSLT/XPATH October REC.
New API in XSLStylesheet class:
removeParam(String param)
resetParams()
Bug fixes:
Bug #1111423: OutOfMemory exception, if multiple calls made to document()
Bug #1101028: Unexpected character error in DTD parsing document using Docbook DTD
Bug #1101021: #default not supported in exclude-result-prefixes
Bug #1099830: Extra characters inserted into output using the XML Parser
Bug #1099663: HTML output does not allow only doctype-public to be specified
Bug #1099536: HTML output does not disable escaping for script, style unless lowercase
Bug #1098738: ArrayOutOfBoundsException xsl:if test="not(@a)'"
Bug #1095047: XSLProcessor NPE'S on named templates with non-empty namespaces
Bug #1094971: XSLStylesheet needs methods for removing parameters
Bug #1092351: Using valueof() shuffles order of elements in my source document
Bug #1086663: xsl:sort data-type attribute can now be a namespace-prefixed name
Bug #1086661: xsl:version attribute now required on literal result element
Bug #1064692: Default xml-serialization should use empty-element syntax
Bug #1064689: Current() function doesn't work correctly
This is the sixth production patch release for v2.
Oracle XML Team http://technet.oracle.com
Oracle Technology Network
nullThe link has been fixed. You will go to the v2 download page
now. Sorry for the inconvience.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
Renilton Oliveira (guest) wrote:
: I didn't find the file for version 2.0.0.0 as well.
: Renilton
: Andrei Filimonov (guest) wrote:
: : I tried to download XML Parser for Java v2 it seems that
only
: v
: : 1.0.1.4 is available. Could you please give an exact URL for
: v2
: : download?
: : Andrei Filimonov
: : Oracle XML Team wrote:
: : : The Oracle XML v2 parser is now available for download
here
: as
: : : an early beta release and is written in Java. It features
: an
: : : improved architecture over the Oracle XML v1 parser and
has
: : : shown better performance on small to large XML documents.
: It
: : : will also be able to format the XML document according to
a
: : : stylesheet, having integrated an XSLT processor.
: : : Version 2 of the XML Parser for Java, besides
incorporating
: an
: : : XSLT processor, has been re-architected from version 1.
This
: : has
: : : resulted in a number of changes to the class names
: especially
: : : those that support Namespaces. See v2changes.txt and
: the .diff
: : : difference files in the sample directory.
: : : Oracle XML Team
: : : http://technet.oracle.com
: : : Oracle Technology Network
null -
This question falls into the category of 'I know it's possible, I just need to find the idom in Java'.
I'm coming from a MSFT world were the DOM-centric model of XML processing makes heavy use of XPATH for node selection. Basically using the method element.selectNodes(XPathExpresson) allows one to quickly extract the relevant subset of the parsed tree in the DOM as a nodeList. I've become accustomed to using XML for all strucutured storage that doesn't require a full database.
The W3C DOM Level 3 spec supports evaluateExpression() for this purpose, but I can't believe that Java developers are still using tree traversal waiting for the spec to be implemented. I suppose that I could use getNodesByTagName(), but this is a chainsaw, and I need a scalpel. Anyway, I'm trying to figure out how, exactly, this gets done in Java.
I figure the following are possibilities:
1) It's in JAXP and I missed it
2) One or more of the XML parsers supports XPATH as an extention
3) There's a common package that sits on top of the DOM Document.
4) There's a standard way to apply and XSLT methods to the DOM document
5) Something I've never thought of.
This is a generalized problem for me, so I can't rely on object serialization, Java-XML data mapping, etc. Any guidance would be greatly appreciated.I've written a Config file reader for XML in java,
and it extracts values using XPath. This is
some of the code you'll need:
imports:
import javax.xml.transform.TransformerException;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.*;
Document doc=....;
* returns a single DOM Node from the config file.
public Node getNode(String xpath) throws ConfigException {
try {
return XPathAPI.selectSingleNode(doc, xpath);
} catch (TransformerException e) {
throw new ConfigException("Can't find '"+xpath+"' ("+e.getMessage()+")"); -
Hello,
I'd like to ask you if and how it is possible to use XPath expressions in Java Mapping. There is a way with Xalan but SAP is using their own XML parser...
Many Thanks,
Milanactually he can't use XPath with Java 1.4 DOM and SAX based parsers.
For example, suppose you want to get the value of field <value> of XML below:
<xml>
<data>
<field>F001</field>
<value>123</value>
</data>
</xml>
In DOM parser, after parsing, you do something like:
Node xml = doc.getDocumentElement();
xml.normalize();
String value = xml.getFirstChild().getChildNodes().item(1).getNodeValue();
With XALAM, you do something like:
doc.getNoveValue("xmldatavalue");
They work pretty differently.
Regards,
Henrique. -
ANN: XML Parser for Java v2.0.2.5
The v2.0.2.5 of the XML Parser for Java is now available for
download. The following features and bug fixes are included:
Conformance to the XSLT/XPATH October PR.
Support for internationalized error messages has been added. The
locale can be set using setLocale(java.util.Locale) function in
XSLProcessor, SAXParser, and DOMParser.
New APIs in XMLNode class:
value-of(String pattern)
selectNodes(String pattern)
selectSingleNode(String pattern)
selectSingleNode(String pattern, NSResolver ns)
New API in XSLStylesheet class
setParam(String param, String value)
Bug fixes:
Bug #957465: Missing a way to set stylesheet-level param-
variables
Bug #962290: selectNodes() improvements
Bug #1033472: Html output prints empty elements for non-empty
elements
Bug #1040717: Character entity for greater that in html output
style
Bug #1046003: Bug is parsing text nodes larger than 16K
Bug #1051671: 'xsl:namespace-alias' not supported
Bug #1052387: Disable-output-escaping doesn't flush while
printing
Bug #1053273: 'xsl:message' terminate attribute not supported
Bug #1058004: No access to media-type and encoding on xsl:output
Bug #1058008: xsl:version attribute not copied to result
Bug #1061159: Exclude-result-prefixes not supported
Bug #1067965: Bug in Non-validating parser while reading QNames
in DTD
This is the fifth production patch release for v2.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
nullThe link has been fixed. You will go to the v2 download page
now. Sorry for the inconvience.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
Renilton Oliveira (guest) wrote:
: I didn't find the file for version 2.0.0.0 as well.
: Renilton
: Andrei Filimonov (guest) wrote:
: : I tried to download XML Parser for Java v2 it seems that
only
: v
: : 1.0.1.4 is available. Could you please give an exact URL for
: v2
: : download?
: : Andrei Filimonov
: : Oracle XML Team wrote:
: : : The Oracle XML v2 parser is now available for download
here
: as
: : : an early beta release and is written in Java. It features
: an
: : : improved architecture over the Oracle XML v1 parser and
has
: : : shown better performance on small to large XML documents.
: It
: : : will also be able to format the XML document according to
a
: : : stylesheet, having integrated an XSLT processor.
: : : Version 2 of the XML Parser for Java, besides
incorporating
: an
: : : XSLT processor, has been re-architected from version 1.
This
: : has
: : : resulted in a number of changes to the class names
: especially
: : : those that support Namespaces. See v2changes.txt and
: the .diff
: : : difference files in the sample directory.
: : : Oracle XML Team
: : : http://technet.oracle.com
: : : Oracle Technology Network
null -
ANN: Oracle XML Parser for Java v2.0.2
The new version of the Oracle XML Parser for Java v2 is
available for download and has the following features and
changes:
1. Conformance to the XSLT/XPATH August WD.
Note that there are several changes between April99 XSLT draft
and the August99 XSLT/Xpath draft and these changes have been
implemented in the XSL Processor. The XSL Processor has been
modified to accept XPath syntax for expressions and patterns.
Stylesheets might have to be modified to be conformant to the
August XSLT/XPath draft before they can be used with this
release.
Some of the changes between April draft and the August draft
are:
a. Expressions in the stylesheet must match the XPath
production Expr.
b. Some of the attribute names and element names in XSL
namespace have changed.
c. Some new functions have been added to XPath CORE function
library.
Please refer to the August XSLT/XPath draft for more details.
This is the first production release for v2.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
nullThe link has been fixed. You will go to the v2 download page
now. Sorry for the inconvience.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
Renilton Oliveira (guest) wrote:
: I didn't find the file for version 2.0.0.0 as well.
: Renilton
: Andrei Filimonov (guest) wrote:
: : I tried to download XML Parser for Java v2 it seems that
only
: v
: : 1.0.1.4 is available. Could you please give an exact URL for
: v2
: : download?
: : Andrei Filimonov
: : Oracle XML Team wrote:
: : : The Oracle XML v2 parser is now available for download
here
: as
: : : an early beta release and is written in Java. It features
: an
: : : improved architecture over the Oracle XML v1 parser and
has
: : : shown better performance on small to large XML documents.
: It
: : : will also be able to format the XML document according to
a
: : : stylesheet, having integrated an XSLT processor.
: : : Version 2 of the XML Parser for Java, besides
incorporating
: an
: : : XSLT processor, has been re-architected from version 1.
This
: : has
: : : resulted in a number of changes to the class names
: especially
: : : those that support Namespaces. See v2changes.txt and
: the .diff
: : : difference files in the sample directory.
: : : Oracle XML Team
: : : http://technet.oracle.com
: : : Oracle Technology Network
null -
Reading more than one value with XPath and java 1.5
Hello, I'm using XPath with Java 1.5 and I've some problems.
I do these things:
File xmlDocument = new File("c:/test.xml");
InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
int replication = Integer.parseInt(xPath.evaluate("/simulation/setup/replication", inputSource));
System.out.println(replication); // THIS WORKS!
warmuptime = Integer.parseInt(xPath.evaluate("/simulation/setup/warmuptime", inputSource));
System.out.println(warmuptime); // THIS DON'T WORK: javax.xml.xpath.XPathExpressionException
As I had written in the comments, the first time I call ".evaluate", it works, the second time it raises an exception.
The Xml is correct! The string "/simulation/setup/warmuptime" is correct!
I tryed to place a:
xPath.reset()
between the two "evaluate", but still doesn't work.
Can you give me an help? or suggest me an url where these things are explained in a simple way?
I just need to get some data from an XML file and XPath seems to be the quickest and easiest way.
Thanks for the help.Are all the files in one directory? If so you can make a File object of the directory, get an array of all files in that directory (File has a method to do this). Then loop over your array and call a method that reads the File that you pass as a parameter.
-
Getting outOfMemory while using Xpath for 6MB file
Hi ,
Requirement:
I have thousands of xml files of variable size (mostly around 5MB), Total size is around 20GB .The structure of xml content is as follows.
filename: xaaaa
<file>
<page>
<title>AmericanSamoa</title>
<id>6</id>
<revision>
<id>133452270</id>
<timestamp>2007-05-25T17:12:06Z</timestamp>
<contributor>
<username>Gurch</username>
<id>241822</id>
</contributor>
<minor />
<comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Docu|Docu]]</comment>
<text xml:space="preserve">#REDIRECT [[American Samoa]]{{R from CamelCase}}</text>
</revision>
</page>
My task is to retrieve the ID , filename in which it exists and the position of node in the page, and i have to write it to a file.
ex: 6:xaaaa:1
My approach:
I am using Xpath for this. The code is as follows.
*/*XPathReader.java*/*
package preprocess;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XPathReader {
private String xmlFile;
private Document xmlDocument;
private XPath xPath;
public XPathReader(String xmlFile) {
this.xmlFile = xmlFile;
initObjects();
private void initObjects(){
try {
xmlDocument = DocumentBuilderFactory.
newInstance().newDocumentBuilder().
parse(xmlFile);
xPath = XPathFactory.newInstance().
newXPath();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
public Object read(String expression,
QName returnType){
try {
XPathExpression xPathExpression =
xPath.compile(expression);
return xPathExpression.evaluate
(xmlDocument, returnType);
} catch (XPathExpressionException ex) {
ex.printStackTrace();
return null;
XpathReaderTest.java
/* it takes directory name as argument, this directory contains xml file*/
package preprocess;
import java.io.*;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.*;
public class XPathReaderTest {
public XPathReaderTest() {
public static void main(String[] args) throws IOException{
if (args.length <= 0) {
System.out.println(
"Usage: java PreProcess dir_name"
return;
String dir=null;
if (args.length >= 1) dir = args[0];
int indexno=0;
File directory = new File(dir);
File[] files = directory.listFiles();
FileWriter fstream = new FileWriter("index"+indexno+".txt");
BufferedWriter out = new BufferedWriter(fstream);
XPathReaderTest xt=new XPathReaderTest();
/*for (int index = 0; index < files.length; index++)
System.out.println(files[index].toString());
for (int index = 0,i=1; index < files.length; index++)
/*if(index/100>indexno){
indexno++;
out.close();
fstream = new FileWriter("index"+indexno+".txt");
out = new BufferedWriter(fstream);
xt.extract(files[index].toString(),index,i,out);
System.gc();
out.close();
public void extract(String completepath,int index,int i,BufferedWriter out)
throws IOException
System.out.println(index+" "+completepath);
XPathReader reader = new XPathReader(completepath);
String separator = File.separator;
int pos = completepath.lastIndexOf(separator);
String temp_fname=completepath.substring(0,pos);
pos=temp_fname.lastIndexOf(separator);
String f_name= completepath.substring(pos+1);
i=1;
while(true)
String expression = "/file/page["+i+"]/id";
String id_value= (String) reader.read(expression, XPathConstants.STRING);
if(id_value=="")
break;
out.write( id_value + ":"+ f_name+ ":"+i+ "\n" );
i++;
Problem:
This code works fine for xml files < 6MB, but its giving outOfMemory for 6MB and above file.
I have tried with -Xms256m -Xmx512m option.
Please suggest the work around , or any modification to code that will resolve my problem.
I am new to java world , so problem root cause will be very helpful for me.
ThanksHi ,
Requirement:
I have thousands of xml files of variable size (mostly around 5MB), Total size is around 20GB .The structure of xml content is as follows.
/*filename: xaaaa*/
<file>
<page>
<title>AmericanSamoa</title>
<id>6</id>
<revision>
<id>133452270</id>
<timestamp>2007-05-25T17:12:06Z</timestamp>
<contributor>
<username>Gurch</username>
<id>241822</id>
</contributor>
<minor />
<comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Docu|Docu]]</comment>
<text xml:space="preserve">#REDIRECT [[American Samoa]]{{R from CamelCase}}</text>
</revision>
</page>
</file>My task is to retrieve the ID , filename in which it exists and the position of node in the page, and i have to write it to a file.
ex: 6:xaaaa:1
My approach:
I am using Xpath for this. The code is as follows.
*/*XPathReader.java*/*
package preprocess;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XPathReader {
private String xmlFile;
private Document xmlDocument;
private XPath xPath;
public XPathReader(String xmlFile) {
this.xmlFile = xmlFile;
initObjects();
private void initObjects(){
try {
xmlDocument = DocumentBuilderFactory.
newInstance().newDocumentBuilder().
parse(xmlFile);
xPath = XPathFactory.newInstance().
newXPath();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
public Object read(String expression,
QName returnType){
try {
XPathExpression xPathExpression =
xPath.compile(expression);
return xPathExpression.evaluate
(xmlDocument, returnType);
} catch (XPathExpressionException ex) {
ex.printStackTrace();
return null;
XpathReaderTest.java
/* *it takes directory name as argument, this directory contains xml file**/
package preprocess;
import java.io.*;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.*;
public class XPathReaderTest {
public XPathReaderTest() {
public static void main(String[] args) throws IOException{
if (args.length <= 0) {
System.out.println(
"Usage: java PreProcess dir_name"
return;
String dir=null;
if (args.length >= 1) dir = args[0];
int indexno=0;
File directory = new File(dir);
File[] files = directory.listFiles();
FileWriter fstream = new FileWriter("index"+indexno+".txt");
BufferedWriter out = new BufferedWriter(fstream);
XPathReaderTest xt=new XPathReaderTest();
/*for (int index = 0; index < files.length; index++)
System.out.println(files[index].toString());
for (int index = 0,i=1; index < files.length; index++)
/*if(index/100>indexno){
indexno++;
out.close();
fstream = new FileWriter("index"+indexno+".txt");
out = new BufferedWriter(fstream);
xt.extract(files[index].toString(),index,i,out);
System.gc();
out.close();
public void extract(String completepath,int index,int i,BufferedWriter out)
throws IOException
System.out.println(index+" "+completepath);
XPathReader reader = new XPathReader(completepath);
String separator = File.separator;
int pos = completepath.lastIndexOf(separator);
String temp_fname=completepath.substring(0,pos);
pos=temp_fname.lastIndexOf(separator);
String f_name= completepath.substring(pos+1);
i=1;
while(true)
String expression = "/file/page["+i+"]/id";
String id_value= (String) reader.read(expression, XPathConstants.STRING);
if(id_value=="")
break;
out.write( id_value + ":"+ f_name+ ":"+i+ "\n" );
i++;
}Problem:
This code works fine for xml files < 6MB, but its giving outOfMemory for 6MB and above file.
I have tried with -Xms256m -Xmx512m option.
Please suggest the work around , or any modification to code that will resolve my problem.
I am new to java world , so problem root cause will be very helpful for me.
Thanks -
Step by step installation for java card kit 2.2.2
can anyone help me with a complete step by step installation information for java card kit 2.2.2, i already tried to follow the instruction given in the software i download n still stuck in setting the java path. any recommendation
thanks for the helpThe javacard API is for developing applets on card. Java 6 is for developing clients off-card.
yes u can use any java IDEs like netbeans or jcreator. But you will have to select the libraries within the downloaded java card kit folder for ur IDE in order to compile successfully.
try reading up the documentation and run the samples in the java card kit. thats a good place to start. -
KM Scheduler Task vs SAP Netweaver Scheduler for java
Hi Experts,
I need to know the key differences between KM Scheduler task implementation and SAP Netweaver Scheduler for java task implementation. Which one is better and why?
Thanks for looking into this and for you patience in answering the question.
Regards,
Kiran K Grandhi.Hi,
Please look at this help
[SAP NetWeaver Scheduler for Java|http://help.sap.com/saphelp_nwce10/helpdata/en/44/03d66015ee10b3e10000000a11466f/content.htm] and [KM Scheduler task|http://help.sap.com/saphelp_nw04s/helpdata/en/3a/bc37b5789dee4eaa8005bff84f14cf/content.htm]
Best Regards
Vijay K -
I am sure that many of you experienced developers have read requests in the past concerning implmentation of Ward Christenen's XModem protocol over a TCP socket. If not, well... you are about to...
This is a major hack... but it is starting to come together... thanks to Fred Potter for his source code to start this project...
Objective:
Basically, I want to create a console application which accepts an incoming connection and starts the receive mode for a XModem file transfer. I am using CGTerm (for Commodore retrocomputing) but can test with HyperTerminal as well...
The user who connects to the server selects SEND and the FILE to send for a XModem file transfer... and the transfer begins...
The incoming blocks of 128 bytes are written to a file
After the transfer is over the server disconnects the client terminal.
Here is what I have so far:
import java.net.*;
import java.lang.*;
import java.io.*;
// X-Modem Server implementation via TCP/IP socket
public class XServer {
public static FileWriter fw;
public static void main(String[] args) throws IOException {
// define the file
try {
fw = new FileWriter("filename.txt");
} catch (Exception e) {
System.out.println(e);
System.exit(0);
int port = Integer.parseInt(args[0]);
ServerSocket server = new ServerSocket(port);
System.out.println("X-Server v1.0 - waiting for connection");
Socket client = server.accept();
// Handle a connection and exit.
try {
InputStream inputStream = client.getInputStream();
OutputStream outputStream = client.getOutputStream();
new PrintStream(outputStream).println("Go to send file mode!"); // sent to client
System.out.println("Ready to receive file via X-Modem...");
* BEGIN TRANSFER HERE!
// set the debug flag
XModem.debug = true;
* Here we are instantiating a new InputStream that represents the remote
* file that we are receiving. In this single line we are attempting to
* start the flow.
* Behind The Scenes: We're sending a NAK across the serial line repeatedly
* until we finaly start seeing the data flow. If we don't see the data
* flow, then we throw an exception.
System.out.println("Sending NAK to start receive mode...");
InputStream incomingFile;
try {
incomingFile = new XModemRXStream(inputStream, outputStream);
} catch (IOException e) {
System.out.println("ERROR! Unable to start file transfer!");
e.printStackTrace();
return;
System.out.println("Starting file transfer...");
* Here we are reading from the incoming file, byte by byte, and printing out.
* Behind The Scenes: Internally, the read() method is handling the task of
* asking for the next data block from the remote computer, processing it (i.e.
* parsing, running checksums), and then putting it in an internal buffer. Not
* all calls to read() will request a new data block as each block contains at
* least 128 bytes of data. Sometimes you will only hit the buffer.
try {
for (;;) {
int c = incomingFile.read();
if (c==-1)
break; // End of File
// print character / byte
System.out.print(c+",");
// write to file
try {
//System.out.print(".");
fw.write(c);
} catch (Exception e) {
System.out.println(e);
System.exit(0);
} catch (IOException e) {
System.out.println("error while reading the incoming file.");
e.printStackTrace();
return;
// done
System.out.println("File sent.");
new PrintStream(outputStream).println("");
new PrintStream(outputStream).println("transfer successful!");
} finally {
//client.close();
// save the file
try {
fw.close();
System.out.println("file saved.");
} catch (Exception e) {
System.out.println(e);
System.exit(0);
* XModem keeps track of settings that the Receive and Transmit Stream classes will
* reference.
* <p>Copyright: Copyright (c) 2004</p>
* @author Fred Potter
* @version 0.1
class XModem {
public static boolean debug = false;
* XModemRXStream is an easy to use class for receiving files via the XModem protocol.
* @author Fred Potter
* @version 0.1
class XModemRXStream
extends InputStream {
// CONSTANTS
private static final int SOH = 0x01;
private static final int EOT = 0x04;
private static final int ACK = 0x06;
private static final int NAK = 0x15;
private static final int CAN = 0x18;
private static final int CR = 0x0d;
private static final int LF = 0x0a;
private static final int EOF = 0x1a;
// block size - DON'T CHANGE - I toyed with the idea of adding 1K support but the code is NOT there yet.
private static final int bs = 128;
// PRIVATE STUFF
private int ebn; // expected incoming block #
private byte[] data; // our data buffer
private int dataPos; // our position with the data buffer
private InputStream in;
private OutputStream out;
* Creates a new InputStream allowing you to read the incoming file. All of the XModem
* protocol functions are handled transparently.
* As soon as this class is instantiated, it will attempt to iniatate the transfer
* with the remote computer - if unsuccessful, an IOException will be thrown. If it
* is successful, reading may commense.
* NOTE: It is important not to wait too long in between calls to read() - the remote
* computer will resend a data block if too much time has passed or even just give up
* on the transfer altogether.
* @param in InputStream from Serial Line
* @param out OutputStream from Serial Line
public XModemRXStream(InputStream in, OutputStream out) throws
IOException {
this.in = in;
this.out = out;
// Initiate the receive sequence - basically, we send a NAK until the data
// starts flowing.
init:for (int t = 0; t < 10; t++) {
if (XModem.debug) {
System.out.println("Waiting for response [ try #" + t + " ]");
long mark = System.currentTimeMillis();
out.write(NAK);
// Frequently check to see if the data is flowing, give up after a couple seconds.
for (; ; ) {
if (in.available() > 0) {
break init;
try {
Thread.sleep(10);
catch (Exception e) {}
if (System.currentTimeMillis() - mark > 2000) {
break;
// We have either successfully negotiated the transfer, OR, it was
// a failure and timed out. Check in.available() to see if we have incoming
// bytes and that will be our sign.
if (in.available() == 0) {
throw new IOException();
// Initialize some stuff
ebn = 1; // the first block we see should be #1
data = new byte[bs];
dataPos = bs;
* Reads the next block of data from the remote computer. Most of the real XModem protocol
* is encapsulated within this method.
* @throws IOException
private synchronized void getNextBlock() throws IOException {
if (XModem.debug) {
//System.out.println("Getting block #" + ebn);
// Read block into buffer. There is a 1 sec timeout for each character,
// otherwise we NAK and start over.
byte[] buffer;
recv:for (; ; ) {
buffer = new byte[bs + 4];
for (int t = 0; t < 10; t++) {
System.out.println("\nReceiving block [ #" + ebn + " ]");
// Read in block
buffer = new byte[buffer.length];
for (int i = 0; i < buffer.length; i++) {
int b = readTimed(1);
// if EOT - don't worry about the rest of the block.
if ( (i == 0) && (b == EOT)) {
buffer[0] = (byte) (b & 0xff);
break;
// if CAN - the other side has cancelled the transfer
if (b == CAN) {
throw new IOException("cancelled");
if (b < 0) {
if (XModem.debug) {
System.out.println("Time out... NAK'ing");
out.write(NAK);
continue recv;
else {
buffer[i] = (byte) (b & 0xFF);
break;
int type = buffer[0] & 0xff; // either SOH or EOT
if (type == EOT) {
if (XModem.debug) {
System.out.println("EOT!");
out.write(ACK);
break;
int bn = buffer[1] & 0xff; // block number
int bnc = buffer[2] & 0xff; // one's complement to block #
if (
(bn != ebn) && (bn != (ebn - 1)) ||
(bn + bnc != 255)) {
if (XModem.debug) {
System.out.println("NAK'ing type = " + type + " bn = " + bn +
" ebn = " +
ebn + " bnc = " + bnc);
out.write(NAK);
continue recv;
byte chksum = buffer[ (buffer.length - 1)];
byte echksum = 0;
for (int i = 3; i < (buffer.length - 1); i++) {
echksum = (byte) ( ( (echksum & 0xff) + (buffer[i] & 0xff)) & 0xff);
if (chksum != echksum) {
out.write(NAK);
continue recv;
out.write(ACK);
if (ebn == 255) {
ebn = 0;
else {
ebn++;
break;
// We got our block, now save it in our data buffer.
data = new byte[bs];
for (int i = 3; i < (buffer.length - 1); i++) {
data[(i - 3)] = buffer;
dataPos = 0;
public synchronized int read() throws IOException {
// If at the end of our buffer, refill it.
if (dataPos == bs) {
try {
getNextBlock();
catch (IOException e) {
throw new IOException();
// If we're still at end of buffer, say so.
if ( dataPos == bs) {
return -1;
int d = data[dataPos];
if (d == EOF)
return -1;
dataPos++;
return d;
* A wrapper around the native read() call that provides the ability
* to timeout if no data is available within the specified timeout value.
* @param timeout timeout value in seconds
* @throws IOException
* @return int an integer representing the byte value read.
private int readTimed(int timeout) throws IOException {
long start = System.currentTimeMillis();
for (; ; ) {
if (in.available() > 0) {
return (in.read());
try {
Thread.sleep(10);
catch (InterruptedException ex) {
//if (System.currentTimeMillis() - start > timeout * 1000) {
if (System.currentTimeMillis() - start > timeout * 5000) {
return -1;
Here was the output...
Original file:
(Commodore CBM SEQ file exported to PC using DirMaster)
��
� �
� ��� �� �� ��� ��
� �� �� ���� �� ��� ��
� ��� ����������������������������������������������
�� ����� ������� ����� �� ����� ������ ����� ���
� �� ������ ������ ��� ��� �� ��� ���� �� ������
� � ���
����
� � ��OWERED BY �OLOR 64 ��� V8
�UNNING �ETWORK64 V1.26A
�
�UPPORTING 38400 �AUD �ATES
�����/����/�������
�
�ESTING �CHO-�ET V1 BETA
�
�EATURING �ESSAGES, �ILES,
�ET�AIL, AND �NLINE �AMES!
�YS�P: � � � � � � � � �
�
�RESS ANY KEY TO LOGIN\C�
The result when the file was uploaded and received by my XServer:
? ? ??OWERED BY ?OLOR 64 ??? V8
?UNNING ?ETWORK64 V1.26A
?UPPORTING 38400 ?AUD ?ATES
?ESTING ?CHO-?ET V1 BETA
?EATURING ?ESSAGES, ?ILES,
?ET?AIL, AND ?NLINE ?AMES!
?YS?P: ? ? ? ? ? ? ? ? ?
?RESS ANY KEY TO LOGIN\C?
The result is different!
Can someone help me along here... I have been trying to figure out how to do this for approx. a year or so... it has been a very slow process.
I could use a guru to help me out so I can write the upload and download routines for my Commodore BBS PETSCII Emulation Server.
Visit http://www.retrogradebbs.com for details.
Thanks.
Please help out a dedicated developer who is in over his head...
-DaveOk. Fair enough. What about general information about Xmodem. This is a hard project because of how obscure the legacy technology is that I am having to implement using Java and MySQL.
I have two major issues which I have to figure out how to troubleshoot and debug, if possible.
1. The 23+ blocks exception when a file is being received
2. The exception which is thrown immediately if I try to receive a binary file instead of an ASCII file.
I read that telnet is a 7-bit technology and that is why Xmodem, which is an 8-bit technology is not that popular as a viable protocol via telnet, whereas Kermit is, since it was developed for 7-bit systems, i.e. mainframes and minicomputers.
Is this correct?
If that is the case, why does www.serio.com have a viable X-Y-ZModem library available (for several hundred $$$ of course) which can be used with both RS-232 serial ports and TCP socket ports? Obviously, it can be done. They are the ONLY company with this library for sale for Java to do this. I cannot justify that $$$ amount for a mere hobby (writing the BBS emulation server for supporting Commodore PETSCII (CG) callers via CGTerm or a native C-64 terminal program using Jim Brain's TCPSER middleware, which emulates a Hayes modem via telnet for telBBSing/retrocomputing.
I really want to learn how to implement a file transfer protocol, since back in the 80s, I used Xmodem, Punter, Y/Z Modem, etc., a lot to upload and download files via modem at baud rates of 2400, 14.4, 19.2, and 38.4, respectively.
It's fun to learn how the old skool gurus of telecommunications technology did it. It is one thing to run a BBS which supports these technologies and features, and it is an entirely other thing to learn how to design and develop them yourself for implementation into a project such as I taken on.
It CAN be done. It WILL be done. However, I have just started my exhaustive research on how it needs to be done. I have read up as much as I could on XModem by Ward C., the father of the protocol.
But, I have no information to help me figure out why the communications are acting as they do so far.
Can someone please download the xserver.zip file on my website at:
www.retrogradebbs.com/projects/xserver.zip
Compile it. Run it. Connect using HyperTerminal, Netrunner, or another telnet terminal emulation program which supports Xmodem file transfers using WinSock.
See what happens. With finals due in the next two days, this project will have to be put on hold until after I submit my two final projects.
If anyone knows what needs to be done to support both ASCII and BINARY file transfers via Xmodem via a socket instead of a modem with RTS/CTS hardware flow control, please respond.
I know for a fact that this can be done.
- Dave -
Get the relative path for java class
How to get Relative path for java class which is inside in web-inf directory in webapps
ajay.manchu wrote:
Hi gimbal2,
My Requirement is i need to run a java class from batch file,when i created batch file in that i need to mention the complete path of the java class,so instead of mentioning that i want to provide only java class name,thats why i asked that one..
can u help me regarding that....
Thanks in advanceI wonder how that would work then. Let's take a fictive example. You have a class com.mycompany.myapp.Foo. This would mean that the class is stored in some directory like this:
c:/webrootdir/myapp/WEB-INF/classes/com/mycompany/myapp/Foo.classTo be able to run such a class from the commandline using Java, you would have to invoke this command:
java -cp c:/webrootdir/myapp/WEB-INF/classes com.mycompany.myapp.FooHow would knowing the exact path to this class help you? -
How to create a report with data using the Crystal Reports for Java SDK
Hi,
How do I create a report with data that can be displayed via the Crystal Report for Java SDK and the Viewers API?
I am writing my own report designer, and would like to use the Crystal Runtime Engine to display my report in DHTML, PDF, and Excel formats. I can create my own report through the following code snippet:
ReportClientDocument boReportClientDocument = new ReportClientDocument();
boReportClientDocument.newDocument();
However, I cannot find a way to add data elements to the report without specifying an RPT file. Is this possible? I seems like it is since the Eclipse Plug In allows you to specify your database parameters when creating an RPT file.
is there a way to do this through these packages?
com.crystaldecisions.sdk.occa.report.data
com.crystaldecisions.sdk.occa.report.definition
Am I forced to create a RPT file for the different table and column structures I have?
Thank you in advance for any insights.
Ted JenneyHi Rameez,
After working through the example code some more, and doing some more research, I remain unable to populate a report with my own data and view the report in a browser. I realize this is a long post, but there are multiple errors I am receiving, and these are the seemingly essential ones that I am hitting.
Modeling the Sample code from Create_Report_From_Scratch.zip to add a database table, using the following code:
<%@ page import="com.crystaldecisions.sdk.occa.report.application.*"%>
<%@ page import="com.crystaldecisions.sdk.occa.report.data.*"%>
<%@ page import="com.crystaldecisions.sdk.occa.report.document.*"%>
<%@ page import="com.crystaldecisions.sdk.occa.report.definition.*"%>
<%@ page import="com.crystaldecisions.sdk.occa.report.lib.*" %>
<%@ page import = "com.crystaldecisions.report.web.viewer.*"%>
<%
try {
ReportClientDocument rcd = new ReportClientDocument();
rcd.newDocument();
// Setup the DB connection
String database_dll = "Sqlsrv32.dll";
String db = "qa_start_2012";
String dsn = "SQL Server";
String userName = "sa";
String pwd = "sa";
// Create the DB connection
ConnectionInfo oConnectionInfo = new ConnectionInfo();
PropertyBag oPropertyBag1 = oConnectionInfo.getAttributes();
// Set new table logon properties
PropertyBag oPropertyBag2 = new PropertyBag();
oPropertyBag2.put("DSN", dsn);
oPropertyBag2.put("Data Source", db);
// Set the connection info objects members
// 1. Pass the Logon Properties to the main PropertyBag
// 2. Set the Server Description to the new **System DSN**
oPropertyBag1.put(PropertyBagHelper.CONNINFO_CRQE_LOGONPROPERTIES, oPropertyBag2);
oPropertyBag1.put(PropertyBagHelper.CONNINFO_CRQE_SERVERDESCRIPTION, dsn);
oPropertyBag1.put("Database DLL", database_dll);
oConnectionInfo.setAttributes(oPropertyBag1);
oConnectionInfo.setUserName(userName);
oConnectionInfo.setPassword(pwd);
// The Kind of connectionInfos is CRQE (Crystal Reports Query Engine).
oConnectionInfo.setKind(ConnectionInfoKind.CRQE);
// Add a Database table
String tableName = "Building";
Table oTable = new Table();
oTable.setName(tableName);
oTable.setConnectionInfo(oConnectionInfo);
rcd.getDatabaseController().addTable(oTable, null);
catch(ReportSDKException RsdkEx) {
out.println(RsdkEx);
catch (Exception ex) {
out.println(ex);
%>
Throws the exception
com.crystaldecisions.sdk.occa.report.lib.ReportSDKException: java.lang.NullPointerException---- Error code:-2147467259 Error code name:failed
There was other sample code on SDN which suggested the following - adding the table after calling table.setDataFields() as in:
String tableName = "Building";
String fieldname = "Building_Name";
Table oTable = new Table();
oTable.setName(tableName);
oTable.setAlias(tableName);
oTable.setQualifiedName(tableName);
oTable.setDescription(tableName) ;
Fields fields = new Fields();
DBField field = new DBField();
field.setDescription(fieldname);
field.setHeadingText(fieldname);
field.setName(fieldname);
field.setType(FieldValueType.stringField);
field.setLength(40);
fields.add(field);
oTable.setDataFields(fields);
oTable.setConnectionInfo(oConnectionInfo);
rcd.getDatabaseController().addTable(oTable, null);
This code succeeds, but it is not clear how to add that database field to a section. If I attempt to call the following:
FieldObject oFieldObject = new FieldObject();
oFieldObject.setDataSourceName(field.getFormulaForm());
oFieldObject.setFieldValueType(field.getType());
// Now add it to the section
oFieldObject.setLeft(3120);
oFieldObject.setTop(120);
oFieldObject.setWidth(1911);
oFieldObject.setHeight(226);
rcd.getReportDefController().getReportObjectController().add(oFieldObject, rcd.getReportDefController().getReportDefinition().getDetailArea().getSections().getSection(0), -1);
Then I get an error (which is not unexpected)
com.crystaldecisions.sdk.occa.report.lib.ReportDefControllerException: The field was not found.---- Error code:-2147213283 Error code name:invalidFieldObject
How do I add one of the table.SetDataFields() to my report to be displayed?
Are there any other pointers or suggestions you may have?
Thank you -
I was just watching / streaming TV off Safari on my actual TV.
I'm using a Mini-Display Port to HDMI cable for the connection to the external display.
Software update popped-up and said there was an update for Java and for SMC.
I ran the update and upon the computer restarting, my external display (my TV) is no longer working. It is now flickering.
It won't work in Mirroring or set up as an extended display.
I've reset SMC / PRAM / Safe Mode / Even restored from a Time Machine backup (From before the updates were done).
What could it be?!I keep saying this over and over, in the hope that people who do a search will find it. Apple cannot possibly test for or be reponsible for the bazillion combinations of adapter, cables, and TV's out there. The only monitors that are 100% guaranteed to work with the MacBook Pro are the Cinema Displays and Thunderbolt Displays, because, they're made by Apple. They're expensive, but they work perfectly.
My guess is that you bought a cheap MDP to HDMI cable, or have a defective one. From my reading of these boards over the past few months, cheap cables have a high failure rate. And the regular priced ones have only a slightly less of one. Try a new one. Make sure you do not damage the Thunderbolt port. -
Unable to Print Purchase order automatically using SAP GUI for JAVA
Hi SAP gurus,
Some of the PC's in our company use windows and some LINUX. Therefore we use two types of SAP GUI. One for windows and the other one JAVA. PO approval was set to print automatically. In a windows setting, there are no problems with this setup. But in SAP GUI for JAVA, no print outs are produced and no error messages are displayed. I am using SAP GUI for JAVA version 7.10 ver 6. and I use Front end printing for linux access method G.
please help,
gungertzhi gungertz,
You can use U type access method for printing SAP document using linux desktop.
Please refer to my blog posting here (http://sapbasis.wordpress.com/2007/08/23/print-sap-documents-using-linux/)
ardhian
http://ardhian.kioslinux.com
http://sapbasis.wordpress.com
Maybe you are looking for
-
Service entry sheet creation from PO without selecting line item of PO?
Dear SAPIENTS, While creating service entry sheet for one frame work order (PO) i do not want to select line item of PO. I want all the service of PO line item should come automatically in single service entry sheet number. At present whenm i enter t
-
I enter history, type a name of a site I've been to in 'search' or 'find' field (I'm using polish version so I don't know the exact name of that field) and it does not find anything. I haven't cleared my history, it's all there when I open 'today', '
-
AnyChart Version 4 - Upgrade Options in APEX 3.0?
General Production Question The AnyChart people have released a version 4 and 4.06 of their charting tool. Is there any way to upgrade our existing APEX 3.0 to the new AnyChart 4? - How would we obtain the new version of AnyChart? - From AnyChart dir
-
Macbook as external drive?
Can I use my Macbook (white) as an external drive for my macbook pro. I dropped the macbook pro on the corner where the cd drive is and it is bent out of shape. The Apple store want to charge me to start ie. just look at it $650.00. I don't want to p
-
Hi, I use JDeveloper 9.0.3 and I deployed a BC4J UIX application to Oracle9Ias 9.0.3 J2ee Containers (Standalone) on NT 4.0 I have this error when I try to access to the application module page.... JBO-33001: Cannot find the configuration file PkgPar