Java sax example

Hello All
I need a xml, sax example.....
If I have a XML document like
Input.xml
<film>
     <artistes>
          <name>Art1</name>
          <name>Art2</name>
     <artistes>
     <technicians>
          <tech> Camera </tech>
          <tech> Direction </tech>
     <technicians>
</film>
I want the xml to be verified against a DTD (please come up with the DTD for the above xml, sorry). And the output xml should be of the form
<finearts>
     <artistes>
          <name>Art1</name>
          <name>Art2</name>
     <artistes>
     <technicians>
          <tech> Camera </tech>
          <tech> Direction </tech>
     <technicians>
<finearts>
Basically film node is replaced by finearts.
I can appreciate if I can get a java program which does this.
The java class should have 2 methods, one whch takes input xml as string, and the other which takes as filename. I need this to be using SAX parser.
Repeating
1. Take xmlinput either as a string or as a file.
2. Validate against DTD.
3. Perform the transform.
4. Write the result to a file.
Thanks

Forte can auto generate a sax parser for you. Just mount the correct directory and right click on the dtd, and select SAX handler wizard.

Similar Messages

  • Java SAX parser. How to get raw XML code of the currently parsing event?

    Java SAX parser, please need a clue how to get the raw XML code of the currently parsing event... needed for logging, debugging purposes.
    Here's and example, letting me clarify exactly what i need: (see the comments in source)
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
         //..Here... or maybe somewhere elsewhere I need on my disposal the raw XML code of
         //..every XML tags received from the XML stream. I need simply to write it down
         //..in a log file, for debugging purposes, while parsing. Can anyone give me a suggestion
         //..how can i implement such logging while the SAX parser only returns me the tagname and
         //..attributes. While parsing I want to log the XML code for every tag in
         //..its 'pure form', like it is comming from the server directly on the
         //..socket's input reader.
         if ("p".equals(qName)) {
              etc...
    }Than you in advance.

    YES!
    I've solved my problem using class RecordingInputStream that wraps the InputStream
    here is the class source code:
    import java.io.ByteArrayOutputStream;
    import java.io.FilterInputStream;
    import java.io.InputStream;
    import java.io.IOException;
    * @author Unknown
    class RecordingInputStream  extends  FilterInputStream {
         protected ByteArrayOutputStream sink;
        RecordingInputStream(InputStream in) {
            this(in, new ByteArrayOutputStream());
        RecordingInputStream(InputStream in, ByteArrayOutputStream sink) {
            super(in);
            this.sink = sink;
        public synchronized int read() throws IOException {
            int i = in.read();
            sink.write(i);
            return i;
        public synchronized int read(byte[] buf, int off, int len) throws IOException {
            int l = in.read(buf, off, len);
            sink.write(buf, off, l);
            return l;
        public synchronized int read(byte[] buf) throws IOException {
            return read(buf, 0, buf.length);
        public synchronized long skip(long len) throws IOException {
            long l = 0;
            int i = 0;
            byte[] buf = new byte[1024];
            while (l < len) {
                i = read(buf, 0, (int)Math.min((long)buf.length, len - l));
                if (i == -1) break;
                l += i;
            return l;
        byte[] getBytes() {
            return sink.toByteArray();
        void resetSink() {
            sink.reset();
    } Then here is the initialization before use with SAX:
    this.psock = new Socket(this.profile.httpServer, Integer.parseInt(this.profile.httpPort));
    this.out = new PrintWriter(this.psock.getOutputStream(), true);
    this.ris=new RecordingInputStream(this.psock.getInputStream());
    this.in=new BufferedReader(new InputStreamReader(this.ris));
    try {
         this.parser = SAXParserFactory.newInstance().newSAXParser();
         this.parser.parse(new InputSource(this.in),new XMLCommandsHandler());
    catch (IOException ioex) {  }
    catch (Exception ex) {  }Then the handler class looks like this (it will be an inner class, so you can access ris, from the parent class):
    class XMLCommandsHandler extends DefaultHandler {
         public void startDocument() throws SAXException {
              //...nothing
         public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
              // BEGIN - Synchronized logging of raw XML source code in parallel with SAX parsing :)
              byte[] bs=ris.getBytes();
              logger.warn(new String(bs));
              ris.resetSink();
              // End logging
              if ("expectedTagThatTriggersMeToDoSomething".equals(qName)) {
                   //...Do smth.
    }Edited by: patladj on Jul 3, 2008 12:30 PM

  • JAVA Sax mapping replaces &_amp; with & causing mapping to fail

    Hi all,
    I have the following mapping scenario:
    Source XML -> Java Sax Mapping -> Graphical Mapping -> Target structure
    The source XML is valid and caters for special characters like & which appear as &_amp; in the XML (ignore the underscore _ without it the editor strips the amp;, isn't that ironic!).
    The second step of the interface mapping, which is the graphical map, is failing. It seems that the Java Sax mapping is replacing &_amp; with & in the XML, which is then causing the graphical map to fail as it cannot handle the special character &.
    Is there anyway I can prevent the Java Sax mapping from changing &amp; to &
    Or is the only solution for me to write extra code in the Java map to convert & back to &_amp; before passing to the second mapping step????
    Any help appreciated.
    Che
    Edited by: Che Eky on Feb 18, 2009 11:05 PM

    Hi..
    Use this in your source xml file for '&' ->"&_amp;" remove the underscore
    Regards..
    Krishna..
    Edited by: PrasannaKrishna Mynam on Feb 19, 2009 2:20 PM
    Edited by: PrasannaKrishna Mynam on Feb 19, 2009 2:20 PM

  • Simple Java DB example

    I am using Java 1.6 and Eclipse Galelio on Vista, Do I need to configure anything is there any story of setting path?
    How to check my Java DB is working or not or everything is fine or not?
    I found many totorial with simple Java DB example but they seem dealing with previous version of JDK, I guess SUN too on http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/ , kindly provide me the simplest example which uses Java DB.
    I am not able to figure out the whole thing of JAVA DB , how it works, in plain language I want to know is there any way of interacting with database from Command prompt? If so how?

    When I am running a simpleApp.java
    I am getting this error:
    Unable to load the JDBC driver org.apache.derby.jdbc.EmbeddedDriver
    Please check your CLASSPATH.
    java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at SimpleApp.loadDriver(SimpleApp.java:414)
         at SimpleApp.go(SimpleApp.java:125)
         at SimpleApp.main(SimpleApp.java:93)
    ----- SQLException -----
    SQL State: 08001
    Error Code: 0
    Message: No suitable driver found for jdbc:derby:derbyDB;create=true
    SimpleApp starting in embedded mode
    SimpleApp finished

  • UML diagrams for Java petstore example

    Hi,
    In this forum and elsewhere I've notice requests for the UML diagrams for the java petstore example. I've posted some uml diagrams at
    http://weblog.neeraj.name/weblog/2004/9/9/java-petstore-uml-diagrams.html
    Your comments are welcome.
    thanks.
    - Neeraj
    http://weblog.neeraj.name

    Hi,
    I browsed through some of your UML. Its a great start! Would you be interested in starting a project on java.net and hosting your uml there? We now have the BluePrints projects out on java.net https://blueprints.dev.java.net/ and would like to encourage others to add their projects as well.
    Lots of people have done cool stuff with Java Petstore and other blueprints projects, and lots of people have created additions to these projects. These UML diagrams would seem to be a great addition to the J2EE community on java.net http://community.java.net/java-enterprise/.
    Its easy to join java.net and to create a new project. They give you a cvs repository where you can store your uml diagrams. We could include a reference to it from the blueprints since it is really useful supplemental material. By making it a project as part of the J2EE community on java.net it makesd it accessible to a larger audience of people. Not everyone will read this forum, and lots more people might find your project useful. So if you wish we had more UML for the Petstore, ....then now is your chance to make a difference :-) Maybe a project called UML4Petstore?
    This page has some explanations of how to add a project if interested.
    https://java-enterprise.dev.java.net/
    hope that helps,
    Sean

  • Whenever I use something which uses Java (for example, an online game) and then click the address bar, it seems that the address bar is disabled.

    Whenever I use something which uses Java (for example, an online game) and then click the address bar, it seems that the address bar is disabled. I cannot highlight or type in the address bar unless I interact with another program and then switch back to Firefox. When I interact with Java again, the same problem persists! Help!
    Sorry, I didn't know what category this should be under, but it's urgent.

    Perform the suggestions mentioned in the following articles:
    * [https://support.mozilla.com/en-US/kb/Template:clearCookiesCache/ Clear Cookies & Cache]
    * [[Troubleshooting extensions and themes]]
    Check and tell if its working.
    Some of your Firefox Plugins are out-dated
    * Update All your Firefox Plugins -> [https://www.mozilla.org/en-US/plugincheck/]
    * '''When Downloading Plugins Update setup files, Remove Checkmark from Downloading other Optional Softwares with your Plugins (e.g. Toolbars, McAfee, Google Chrome, etc.)'''

  • Help w/SAX Example from JWSDP1.1

    I have been trying to execute the SAX Parser example from the WSDP1.1 tutorial -- Echo01.java with slideSample.xml and I keep getting the following exception even though the program has compiled successfully:
    C:\j2sdk1.4.2\programs>java Echo01 slideSample.xml
    Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/parsers/SAXParser
    I have a gut feeling this has something to do with my classpath variable, but I just can't seem to figure it out. I have placed all the required .jar files in the <JAVA_HOME>/jre/lib/endorsed directory.
    My classpath variable holds the following information, but when I try to view it in DOS, I get the following JVM error:
    Failed to load Main-Class mainfest attribute from C:\j2sdk1.4.2\jre\lib\endorsed\sax.jar
    My CLASSPATH variable reads as follows:
    C:\j2sdk1.4.2\jre\lib\endorsed\sax.jar;C:\j2sdk1.4.2\jre\lib\endorsed\dom.jar;C:\j2sdk1.4.2\jre\lib\endorsed\xalan.jar;C:\j2sdk1.4.2\jre\lib\endorsed\xercesImpl.jar;C:\j2sdk1.4.2\jre\lib\endorsed\xsltc.jar;C:\j2sdk1.4.2\programs
    PLEASE ADVISE!!!!!!!!!

    I came across this problem before. The problem maybe you have used an old version of java.exe. I am using Windows XP and I realise that there is another java.exe in the path "C:\WINDOWS\system32". Therefore, if the path "C:\j2sdk1.4.2\bin" is put after "C:\WINDOWS\system32" in your Path variable, your computer will always load the java.exe in "C:\WINDOWS\system32", which is an older version shipped with your Windows. So, try to move "C:\j2sdk1.4.2\bin" in front of "C:\WINDOWS\system32 in the Path variable.
    I hope this works!!

  • Having problem compiling JAXP - SAX example

    I am new to this technology. I am trying to run all the examples which are in JWSDP1.1. Can anybody tell How to solve the following error.
    C:\jwsdp-1.1\docs\tutorial\examples\jaxp\sax\samples>javac Echo01.java
    Echo01.java:74: cannot resolve symbol
    symbol : method parse (java.io.File,org.xml.sax.helpers.DefaultHandler)
    location: class javax.xml.parsers.SAXParser
    saxParser.parse( new File(argv[0]), handler);
    ^
    1 error

    In the command line include these files:
    sax.jar
    jaxp-api.jar
    I mean like this :
    javac -classpath ......\sax.jar;.....\jaxp-api.jar Echo01.java

  • PI 7.1 + Java SAX

    Hi all,
    we have recently installed PI 7.1 SPS 6. But now we are having issues with XSL mappings. Every XSL mapping results in this error:
    SAXException during XSLT processing, cannot create source for input: Thrown: org.xml.sax.SAXException: SAX2 driver class org.apache.xerces.parsers.SAXParser not found at org.xml.sax.helpers.XMLReaderFactory.loadClass(XMLReaderFactory.java:189)
    Are we missing a deployment or anything else?
    Any ideas?
    Tanks in advance!
    Regards,
    Benjamin

    Hi Benjamin,
    Confimr whether you have the below jar files imported in your PI server.
    jaxp.jar, crimson.jar, and xalan.jar
    Thanks
    Prabhakar

  • A Toplink Java code example in Jdev 10.1.2

    Hello every body
    I have just begun using Toplink 10g in Jdev 10.1.2, and I want examples of Java code to insert, edit and show information from struts application whose model is Toplink.
    Thanks

    If you are using toplink 9045 which ships with Jdev 1012, and just starting out then you might consider using Jdev1013 along with toplink 1013 since there is some measurable difference between the two releases.
    Information about toplink and examples.
    http://www.oracle.com/technology/products/ias/toplink/examples/index.html
    http://www.oracle.com/technology/products/ias/toplink/technical/index.html

  • Java SAX mapping "&" problem

    Hi, I'm using SAX mapping, but in case that some field has "&" as content, for example company name,
         public void characters(char buf[], int offset, int len)
              throws SAXException {
              String s = new String(buf, offset, len);
    for string "name m&s" returns only "s". It loops(splits this string into 3) trough:
    1. "name m"
    2. "&"
    3. "s"
    and in this case, I get only "s" what is completely wrong. How to avoid that?
    br
    mario

    Hi
      Can you convert the character & to   "& a m p ;" whithout white spaces?
      "& a m p ;" is the correct value for some XML parsers, or try to use other character set.
    Regards
    Ivá

  • Question about Java Sound example?

    Hello,
    I found this example AudioPlayer, when searching for an example of how to play .wav files in Java.
    The code seems quite long, and wondered if anyone could advise if this is the best way to play a wav file?
    And could anyone explain if the EXTERNAL_BUFFER_SIZE should allows be set to 128000;
    Thank you
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.SourceDataLine;
    public class SimpleAudioPlayer
         private static final int     EXTERNAL_BUFFER_SIZE = 128000;
         public static void main(String[] args)
                We check that there is exactely one command-line
                argument.
                If not, we display the usage message and exit.
              if (args.length != 1)
                   printUsageAndExit();
                Now, that we're shure there is an argument, we
                take it as the filename of the soundfile
                we want to play.
              String     strFilename = args[0];
              File     soundFile = new File(strFilename);
                We have to read in the sound file.
              AudioInputStream     audioInputStream = null;
              try
                   audioInputStream = AudioSystem.getAudioInputStream(soundFile);
              catch (Exception e)
                     In case of an exception, we dump the exception
                     including the stack trace to the console output.
                     Then, we exit the program.
                   e.printStackTrace();
                   System.exit(1);
                From the AudioInputStream, i.e. from the sound file,
                we fetch information about the format of the
                audio data.
                These information include the sampling frequency,
                the number of
                channels and the size of the samples.
                These information
                are needed to ask Java Sound for a suitable output line
                for this audio file.
              AudioFormat     audioFormat = audioInputStream.getFormat();
                Asking for a line is a rather tricky thing.
                We have to construct an Info object that specifies
                the desired properties for the line.
                First, we have to say which kind of line we want. The
                possibilities are: SourceDataLine (for playback), Clip
                (for repeated playback)     and TargetDataLine (for
                recording).
                Here, we want to do normal playback, so we ask for
                a SourceDataLine.
                Then, we have to pass an AudioFormat object, so that
                the Line knows which format the data passed to it
                will have.
                Furthermore, we can give Java Sound a hint about how
                big the internal buffer for the line should be. This
                isn't used here, signaling that we
                don't care about the exact size. Java Sound will use
                some default value for the buffer size.
              SourceDataLine     line = null;
              DataLine.Info     info = new DataLine.Info(SourceDataLine.class,
                                                                 audioFormat);
              try
                   line = (SourceDataLine) AudioSystem.getLine(info);
                     The line is there, but it is not yet ready to
                     receive audio data. We have to open the line.
                   line.open(audioFormat);
              catch (LineUnavailableException e)
                   e.printStackTrace();
                   System.exit(1);
              catch (Exception e)
                   e.printStackTrace();
                   System.exit(1);
                Still not enough. The line now can receive data,
                but will not pass them on to the audio output device
                (which means to your sound card). This has to be
                activated.
              line.start();
                Ok, finally the line is prepared. Now comes the real
                job: we have to write data to the line. We do this
                in a loop. First, we read data from the
                AudioInputStream to a buffer. Then, we write from
                this buffer to the Line. This is done until the end
                of the file is reached, which is detected by a
                return value of -1 from the read method of the
                AudioInputStream.
              int     nBytesRead = 0;
              byte[]     abData = new byte[EXTERNAL_BUFFER_SIZE];
              while (nBytesRead != -1)
                   try
                        nBytesRead = audioInputStream.read(abData, 0, abData.length);
                   catch (IOException e)
                        e.printStackTrace();
                   if (nBytesRead >= 0)
                        int     nBytesWritten = line.write(abData, 0, nBytesRead);
                Wait until all data are played.
                This is only necessary because of the bug noted below.
                (If we do not wait, we would interrupt the playback by
                prematurely closing the line and exiting the VM.)
                Thanks to Margie Fitch for bringing me on the right
                path to this solution.
              line.drain();
                All data are played. We can close the shop.
              line.close();
                There is a bug in the jdk1.3/1.4.
                It prevents correct termination of the VM.
                So we have to exit ourselves.
              System.exit(0);
         private static void printUsageAndExit()
              out("SimpleAudioPlayer: usage:");
              out("\tjava SimpleAudioPlayer <soundfile>");
              System.exit(1);
         private static void out(String strMessage)
              System.out.println(strMessage);
    }

    I didnot go thru the code you posted but I know that the following workstry {
            // From file
            AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile"));
            // From URL
            stream = AudioSystem.getAudioInputStream(new URL("http://hostname/audiofile"));
            // At present, ALAW and ULAW encodings must be converted
            // to PCM_SIGNED before it can be played
            AudioFormat format = stream.getFormat();
            if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
                format = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED,
                        format.getSampleRate(),
                        format.getSampleSizeInBits()*2,
                        format.getChannels(),
                        format.getFrameSize()*2,
                        format.getFrameRate(),
                        true);        // big endian
                stream = AudioSystem.getAudioInputStream(format, stream);
            // Create the clip
            DataLine.Info info = new DataLine.Info(
                Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize()));
            Clip clip = (Clip) AudioSystem.getLine(info);
            // This method does not return until the audio file is completely loaded
            clip.open(stream);
            // Start playing
            clip.start();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } catch (LineUnavailableException e) {
        } catch (UnsupportedAudioFileException e) {
        }

  • OS level calls in Java.. example.

    Simple and perhaps idiotic question... but here it goes.
    Is there a way to make OS level calls in Java (i.e such as the cp, mv or ls/dir commands)?
    What class due I need to instantiate do to this? and is it the same for UNIX and win32 systems?
    Here is what I attempted to do:
    ================
    import java.io.*;
    public class Test {
    private static void main(String args[]) {
    String cmd[] =
    {"copy", "c:\\temp\\test.txt", "c:\\temp\\test2.txt"};
    try {
    Process p = Runtime.getRuntime().exec("copy test.txt test2.txt");
    p = Runtime.getRuntime().exec(cmd);
    } catch (Exception e) {
    e.printStackTrace();
    However, the above code results in the following error at runtime...
    =============
    java.io.IOException: CreateProcess: copy c:\temp\test.txt c:\temp\test2.txt error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:61)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    at java.lang.Runtime.exec(Runtime.java:356)
    at java.lang.Runtime.exec(Runtime.java:320)
    at Test.main(Test.java:7)
    ==============
    Thoughts?
    Any help is greatly appreciated.
    Regards
    echardrd

    Almost right...
    "copy" is a shell builtin for Windows, so you need to call it as an argument to cmd.exe (or command.com on older systems). E.g. in Win2000 you can go:
    Runtime.getRuntime().exec( "cmd /c copy c:\\test1.txt c:\\test2.txt" );Where the /c is the parameter to tell cmd to carry out the given command. You could run this with the "start" command to push it into the background.
    Unix behaviour is roughly similar: cp is a Bash builtin for example, so you probably need to execute a shell process and pass it cp (I'm not sure about that one, I didn't test it)

  • Java ThreadPool Example

    Some people asked at this forum: "How to write Java Threadpool?" Here is an example, which I have tested on the computer with two CPU. This example also runs well with J#.
    TPTest.java
    package demo.test;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintStream;
    import java.util.Calendar;
    import thread.util.ThreadPool;
    class ShutdownHook extends Thread {
        public void run() {
            try {
                MyRunnable.fout.flush();
                Thread.sleep(1000);
                MyRunnable.fout.close();
            catch (Exception e) {
                e.printStackTrace();
    class MyRunnable implements Runnable {
        public static File file;
        public static FileWriter fout;
         public static PrintStream out;
        static {
            try {
                file = new File(".\\ThreadPool.log");
                fout = new FileWriter(file);
                   out = System.out;
                //Uncomment the next line in J#
                //Runtime.getRuntime().runFinalizersOnExit(true);
                //Comment the next line in J#
                Runtime.getRuntime().addShutdownHook(new ShutdownHook());
            catch (IOException e) {
                e.printStackTrace();
        static int n = 0;
        int i;
        public MyRunnable(int i) {
            this.i = i;
        public void run() {
            try {
                synchronized(fout) {
                    n++;
                    fout.write("Sample No." + n + "\t" + Calendar.getInstance().getTime().getMinutes() + ":" +
                    Calendar.getInstance().getTime().getSeconds() + ":" +
                    Calendar.getInstance().get(Calendar.MILLISECOND) +  
                    ":" + "Executed: " + this + Thread.currentThread() + "\r\n");
                        out.println("Sample No." + n + "\t" + Calendar.getInstance().getTime().getMinutes() + ":" +
                    Calendar.getInstance().getTime().getSeconds() + ":" +
                    Calendar.getInstance().get(Calendar.MILLISECOND) +  
                    ":" + "Executed: " + this + Thread.currentThread());
            catch (IOException e) {
                e.printStackTrace();
            synchronized(this) {
                notify();
        public String toString() {
            return "Task No." + i;
    public class TPTest {
        public static void main(String[] args) {
            ThreadPool thp = new ThreadPool(100);
            int count = 10000;
            for (int i = 0; i < count; i++) {
                if(i == count - 1)
                    // Wait for the last Invoke
                    ThreadPool.invokeAndWait(thp, new MyRunnable(i));
                else
                    ThreadPool.invokeLater(thp, new MyRunnable(i));
            try {
                MyRunnable.fout.flush();
                MyRunnable.fout.close();
            }catch(Exception e) {
            System.exit(0);
    Queue.java
    package thread.util;
    import java.util.Enumeration;
    class NoSuchElementException extends RuntimeException {
        public NoSuchElementException() {
            super();
        public NoSuchElementException(String s) {
            super(s);
    class QueueElement {
        QueueElement next = null;
        QueueElement prev = null;
        Object obj = null;
        QueueElement(Object obj) {
            this.obj = obj;
        public String toString() {
            return "QueueElement[obj="
                + obj
                + (prev == null ? " null" : " prev")
                + (next == null ? " null" : " next")
                + "]";
    final class LIFOQueueEnumerator implements Enumeration {
        Queue queue;
        QueueElement cursor;
        LIFOQueueEnumerator(Queue q) {
            queue = q;
            cursor = q.head;
        public boolean hasMoreElements() {
            return (cursor != null);
        public Object nextElement() {
            synchronized (queue) {
                if (cursor != null) {
                    QueueElement result = cursor;
                    cursor = cursor.next;
                    return result.obj;
            throw new NoSuchElementException("NoSuchElement");
    final class FIFOQueueEnumerator implements Enumeration {
        Queue queue;
        QueueElement cursor;
        FIFOQueueEnumerator(Queue q) {
            queue = q;
            cursor = q.tail;
        public boolean hasMoreElements() {
            return (cursor != null);
        public Object nextElement() {
            synchronized (queue) {
                if (cursor != null) {
                    QueueElement result = cursor;
                    cursor = cursor.prev;
                    return result.obj;
            throw new NoSuchElementException("FIFOQueueEnumerator");
    public class Queue {
        int length = 0;
        QueueElement head = null;
        QueueElement tail = null;
        public Queue() {
        public synchronized void enqueue(Object obj) {
            QueueElement newElt = new QueueElement(obj);
            if (head == null) {
                head = newElt;
                tail = newElt;
                length = 1;
            else {
                newElt.next = head;
                head.prev = newElt;
                head = newElt;
                length++;
        public synchronized Object dequeue() {
            QueueElement elt = tail;
            tail = elt.prev;
            if (tail == null) {
                head = null;
            else {
                tail.next = null;
            length--;
            return elt.obj;
        public synchronized boolean isEmpty() {
            return (tail == null);
        public final synchronized Enumeration elements() {
            return new LIFOQueueEnumerator(this);
        public final synchronized Enumeration reverseElements() {
            return new FIFOQueueEnumerator(this);
        public synchronized void dump(String msg) {
            System.err.println(">> " + msg);
            System.err.println(
                    + length
                    + " elt(s); head = "
                    + (head == null ? "null" : (head.obj) + "")
                    + " tail = "
                    + (tail == null ? "null" : (tail.obj) + ""));
            QueueElement cursor = head;
            QueueElement last = null;
            while (cursor != null) {
                System.err.println("  " + cursor);
                last = cursor;
                cursor = cursor.next;
            if (last != tail) {
                System.err.println("  tail != last: " + tail + ", " + last);
            System.err.println("]");
    QueueException.java
    package thread.util;
    public class QueueException extends RuntimeException {
    ThreadPool.java
    package thread.util;
    * A thread pool with a bounded task queue and fixed number of worker threads.
    public class ThreadPool {
        public static ThreadPool currentThreadPool = null;
        public Queue queue;
        public ThreadPool(int threads) {
            queue = new Queue();
            /* create the worker threads */
            for (int i = 0; i < threads; ++i) {
                Thread t = new Thread(new WorkerThread(), "WorkerThread: " + (i + 1));
                t.setDaemon(true);
                t.start();
         * Queues a task to be executed by this ThreadPool. If the task queue is
         * full, the task will run in the calling thread. (Could easily be modified
         * to throw an exception instead.)
        public void doTask(Runnable task) {
            synchronized (queue) {
                queue.enqueue(task);
                queue.notify();
         * Tests if the task queue is empty.  Useful if you want to wait for all
         * queued tasks to complete before terminating your program.
        public boolean queueEmpty() {
            synchronized (queue) {
                return queue.isEmpty();
        private class WorkerThread implements Runnable {
            public void run() {
                Runnable task;
                while (true) {
                    task = null;
                    synchronized (queue) {
                        try {
                            if (queue.isEmpty()) {
                                queue.wait();
                            else {
                                task = (Runnable)queue.dequeue();
                        catch (InterruptedException e) {
                            break;
                    if (task != null) {
                        task.run();
        } /* end inner class WorkerThread */
        public static void invokeLater(ThreadPool thp, Runnable task) {
            thp.doTask(task);
        public static void invokeAndWait(ThreadPool thp, Runnable task) {
            TaskWrapper tw = new TaskWrapper(task);
            synchronized(tw.task) {
                try {
                    thp.doTask(tw);
                    tw.task.wait();
                catch (InterruptedException e) {
                tw = null;
        public static void invokeLater(Runnable task) {
            if(ThreadPool.currentThreadPool == null) {
                ThreadPool.currentThreadPool = new ThreadPool(20);
            ThreadPool.currentThreadPool.doTask(task);
        public static void invokeAndWait(Runnable task) {
            if(ThreadPool.currentThreadPool == null) {
                ThreadPool.currentThreadPool = new ThreadPool(20);
            TaskWrapper tw = new TaskWrapper(task);
            synchronized(tw.task) {
                try {
                    ThreadPool.currentThreadPool.doTask(tw);
                    tw.task.wait();
                catch (InterruptedException e) {
                tw = null;
    } /* end class ThreadPool */
    class TaskWrapper implements Runnable {
        public Runnable task;
        public TaskWrapper(Runnable task) {
            this.task = task;
        public void run() {
            synchronized(task) {
                task.run();
                task.notify();

    Thanks for the example. I was wondering how to do this.
    I am running it right now on Fedora Linux.
    When I run the demo TPTest.java
    as written
    ThreadPool thp = new ThreadPool(100);
    int count = 10000;
    I get and error at the very end of the run like this :
    Sample No.10000     32:36:289:Executed: Task No.652Thread[WorkerThread: 10,5,main]
    java.io.IOException: Stream closed
         at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:38)
         at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:151)
         at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:213)
         at demo.test.ShutdownHook.run(TPTest.java:14)
    Is this correct behaviour?
    General this the only error I see. If I start changing the count and Threadpool size to
    other combinations, I occasionally get other errors similar to this one as well.
    java.io.IOException: Stream closed
         at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:38)
         at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:129)
         at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:146)
         at java.io.OutputStreamWriter.write(OutputStreamWriter.java:204)
         at java.io.Writer.write(Writer.java:126)
         at demo.test.MyRunnable.run(TPTest.java:53)
         at thread.util.ThreadPool$WorkerThread.run(ThreadPool.java:58)
         at java.lang.Thread.run(Thread.java:534)
    Is there a way to increase thread size with java on Fedora Linux (Core 3)?
    Would like to know. This example was interesting to me because I am trying to push
    the limit for load testing purposes.
    Thanks again for the example. Let me know if you have any updates to this one.

  • Berkeley DB master-slave replication basic java code example

    Hi,
    I am new user of berkeley db and I have limited knowledge of Java programming. Can someone help me with basic Java example code of how to do master-slave replication without elections.
    Thanx,
    Jani

    Hello,
    Please clarify a few points about your program:
    1. What platform and Berkeley DB version are you using?
    2. Are you planning on using the replication framework
    or base replication API for your application?
    3. When you say you want replication without elections,
    what exactly does that mean. For example, if you are using
    the replication framework elections are held transparently
    without any input from your application's code. In this case,
    DB will determine which environment is the master and which
    are replicas. Is that what you are thinking about or
    something else?
    Thanks,
    Sandra

Maybe you are looking for