SQLJ Iterator vs java.util.Iterator

Hi -
I'm trying to start using SQLJ a bit more, and I was wondering if anybody had some code samples for implementing a java.util.Collection or java.util.Iterator interface for a SQLJ Iterator? Lots of my utility code works on the standard collection/iterator/enumeration trio. Any great ideas out there for putting a standard interface on a SQLJ iterator?
Thanks!
-best-darr-
null

Sounds intriguing - other than a similarity of name, these currently do not have anything in common.
There is one approach currently available to you: you can subclass the iterator class to provide your own functionality and use that subclass. See:
http://technet.oracle.com/tech/java/sqlj_jdbc/htdocs/sqlj-primer06i.htm
Source is in the distribution in:
.../sqlj/demo/SubclassIterDemo.sqlj
Your take -if I understand correctly - on this is to have the SQLJ translator automatically create implementations of the the various collection types from an iterator when you specify:
#sql iterator Iter implements SomeCollectionType (...);
In that case I am still unsure as to what the elements of the collection are.

Similar Messages

  • Iterator List Error "java.util.ConcurrentModificationException"

    Hi,
    I'm with a problem. I've got a set of objects in a List. I'm iterating the list and during this process, I have to add more objects to the list. The system returns the exception "java.util.ConcurrentModificationException".
    What is the solution to this problem, that is, how can I iterate a list, adding or removig elements without error
    Thanx
    MP

    You cannot add to a list while iterators are in progress. You can remove elements by calling the remove method on the iterator.
    If you need to both iterate and add, consider iterating a copy of the list, like so:
    List copy = new ArrayList(originalList);
    for (Iterator it = copy.iterator(); it.hasNext(); ) {
       // call originalList.add here
    }You could also consider indexing into the list (if it's an ArrayList), and then "bumping" your indices as you add elements.

  • Report cannot be rendered (com/sun/java/util/collections/Iterator)

    Hello all
    I'm new both to Weblogic Server and BI Publisher.
    A few days ago I thought that I managed to install BI Publisher on top of Weblogic. It turns out to be untrue because I am not able to view any report, being it a sample or a newly created one.
    Platform: Windows 2003 32-bit
    Weblogic version: 10.3.3.0
    BI Publisher version: 10.1.3.4.1 (doesn't work both w/ and w/o the latest patchset 9791839)
    And now to the problem. Whenever I try to view a report, I get an error message stating "The report cannot be rendered because of an error, please contact the administrator". Being both the user and the administrator, I am forced to press the "Error Detail" link, upon which the only thing that pops below is "com/sun/java/util/collections/Iterator" (in red).
    The same non-verbose error message appears also when running in debug mode. Weblogic logs are empty from warnings, errors, etc.
    As for the Weblogic Server, it claims that the xmlpserver application has been deployed and started successfully.
    It seems to me that the BI Publisher application is trying to use java class that doesn't exist (com.sun.java.util.collections.Iterator). Of course I have no clue how to prove that because I do not have the source code for this app.
    Oracle support is hardly able to understand the problem, so I thought maybe one of you could give me some answer.
    Any Ideas?
    Jonathan

    By the way, I deployed the app under Oracle Report's cluster. Don't know whether it matters.

  • Invalid data returned when iterating a java.util.Properties

    Hi all,
    I'm having trouble iterating thru the values in a java.util.Properties object.
    This problem only occurs when passing in a java.util.Properties object into the constructor of a java.util.Properties.
    Here's some example code. (A picture is worth....)
    <pre>
    import java.util.Properties;
    import java.util.Iterator;
    public class PropertyTest {
    public static void main(String[] args) {
    Properties validProp = new Properties();
    //add some data
    validProp.put("key1", "key1Value");
    validProp.put("key2", "key2Value");
    validProp.put("key3", "key3Value");
    System.out.println("This will iterate...");
    dumpPropertyFile(validProp); //This will iterate correctly
    Properties inValidProp = new Properties(validProp);
    System.out.println("This doesn't iterate correctly");
    dumpPropertyFile(inValidProp); //This will not iterate
    public static void dumpPropertyFile(Properties prop) {
    Iterator iter = prop.keySet().iterator();
    while (iter.hasNext()) {
    String key = (String)iter.next();
    System.out.println(key + "=" + prop.getProperty(key));
    </pre>
    I have searched the bug database, but didn't find any open bugs related to this issue.
    Could someone let me know if this is a existing bug or has this bug already been addressed.
    My setup.
    NT 4.0 / jdk1.3.1
    Thanks,

    I found this works.
    Iterator e = _props.keySet().iterator();
    while(e.hasNext())
    String str = (String)e.next();
    System.out.println("key(" + str + ")=" + _props.getProperty(str));
    but the display sequence is always in descending order ???
    Anyone has a clue ?
    Input :
    catch#2 Prop catch#2
    prop2 Properties.test.2
    catch#6 Prop catch#6
    catch#3 Prop catch#3
    catch#5 Prop catch#5
    catch#4 Prop catch#4
    prop3 test Properties
    prop4 test Properties4
    prop1 Properties.test.1
    catch#1 Prop catch#1
    Output:
    prop4=test Properties4<
    prop3=test Properties<
    prop2=Properties.test.2<
    prop1=Properties.test.1<
    catch#6=Prop catch#6<
    catch#5=Prop catch#5<
    catch#4=Prop catch#4<
    catch#3=Prop catch#3<
    catch#2=Prop catch#2<
    catch#1=Prop catch#1<

  • Cannot use winzip to unzip the zip file zipped by java.util.zip

    Hi all,
    I use the followcode to create a zip file, and i downlaod it and try to use winzip to unzip this file but fail. The path is correct and i got the zip file. but it just cannot unzip.
    pls help
    thanks alot.
    Kin
              int count = 0;
              count = ContentDocuments.size();
              for (int i = 0; i < bb; i++)     {
                   System.out.println(filenames[i] + "");
              // Create a buffer for reading the files
              byte[] buf = new byte[10*1024*1024];
              try {      
                   String outFilename = MyDir + "zipfile/" + getContentID2()+".zip";
                   System.out.println("outFilename = " + outFilename);
                   ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
                   for (int i=0; i<filenames.length; i++) {           
                        FileInputStream in = new FileInputStream(filenames);
                        out.putNextEntry(new ZipEntry(filenames[i]));
                        int len;
                        while ((len = in.read(buf)) != -1) {               
                             out.write(buf, 0, len);
                        out.closeEntry();
                        in.close();
                   out.close();
              } catch (IOException e)     {
                   System.err.println("zipprocess " + e.getMessage());

    I've written a replacement zip file creator class. Not much tested but it seems to work, however I've yet to try it with the version of WINZIP that rejected my previous attempts. Oh, and the stored dates are garbage.
    * ZipOutputFile.java
    * Created on 25 March 2004, 13:08
    package zip;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    * <p>Creates a ZIP archive in a file which WINZIP should be able to read.</p>
    * <p>Unfortunately zip archives generated by the standard Java class
    * {@link java.util.zip.ZipOutputStream}, while adhering to PKZIPs format specification,
    * don't appear to be readable by some versions of WinZip and similar utilities. This is
    * probably because they use
    * a format specified for writing to a non-seakable stream, where the length and CRC of
    * a file is writen to a special block following the data. Since the length of the binary
    * date is unknown this makes an archive quite complicated to read, and it looks like
    * WinZip hasn't bothered.</p>
    * <p>All data is Deflated. Close completes the archive, flush terminates the current entry.</p>
    * @see java.util.zip.ZipOutputStream
    * @author  Malcolm McMahon
    public class ZipOutputFile extends java.io.OutputStream {
        byte[] oneByte = new byte[1];
        java.io.RandomAccessFile archive;
        public final static short DEFLATE_METHOD = 8;
        public final static short VERSION_CODE = 20;
        public final static short MIN_VERSION = 10;
        public final static int  ENTRY_HEADER_MAGIC = 0x04034b50;
        public final static int  CATALOG_HEADER_MAGIC = 0x02014b50;
        public final static int  CATALOG_END_MAGIC = 0x06054b50;
        private final static short DISC_NUMBER = 0;
        ByteBuffer entryHeader = ByteBuffer.wrap(new byte[30]);
        ByteBuffer entryLater = ByteBuffer.wrap(new byte[12]);
        java.util.zip.CRC32 crcAcc = new java.util.zip.CRC32();
        java.util.zip.Deflater def = new java.util.zip.Deflater(java.util.zip.Deflater.DEFLATED, true);
        int totalCompressed;
        long MSEPOCH;
        byte [] deflateBuf = new byte[2048];
        public static final long SECONDS_TO_DAYS = 60 * 60 * 24;
         * Entry stores info about each file stored
        private class Entry {
            long offset;        // position of header in file
            byte[] name;
            long crc;
            int compressedSize;
            int uncompressedSize;
            java.util.Date date;
             * Contructor also writes initial header.
             * @param fileName Name under which data is stored.
             * @param date  Date to label the file with
             * @TODO get the date stored properly
            public Entry(String fileName, java.util.Date date) throws IOException {
                name = fileName.getBytes();
                this.date = date == null ? new java.util.Date() : date;
                entryHeader.position(10);
                putDate(entryHeader);
                entryHeader.putShort(26, (short)name.length);
                offset = archive.getFilePointer();
                archive.write(entryHeader.array());
                archive.write(name);
                catalog.add(this);
                crcAcc.reset();
                totalCompressed = 0;
                def.reset();
             * Finish writing entry data. Save the lenghts & crc for catalog
             * and go back and fill them in in the entry header.
            public void close() throws IOException {
                def.finish();
                while(!def.finished())
                    deflate();
                entryLater.position(0);
                crc = crcAcc.getValue();
                compressedSize = totalCompressed;
                uncompressedSize = def.getTotalIn();
                entryLater.putInt((int)crc);
                entryLater.putInt(compressedSize);
                entryLater.putInt(uncompressedSize);
                long eof = archive.getFilePointer();
                archive.seek(offset + 14);
                archive.write(entryLater.array());
                archive.seek(eof);
             * Write the catalog data relevant to this entry. Buffer is
             * preloaded with fixed data.
             * @param buf Buffer to organise fixed lenght part of header
            public void writeCatalog(ByteBuffer buf) throws IOException {
                buf.position(12);
                putDate(buf);
                buf.putInt((int)crc);
                buf.putInt(compressedSize);
                buf.putInt(uncompressedSize);
                buf.putShort((short)name.length);
                buf.putShort((short)0);  // extra field length
                buf.putShort((short)0);  // file comment length
                buf.putShort(DISC_NUMBER);  // disk number
                buf.putShort((short)0); // internal attributes
                buf.putInt(0);      // external file attributes
                buf.putInt((int)offset); // file position
                archive.write(buf.array());
                archive.write(name);
             * This writes the entries date in MSDOS format.
             * @param buf Where to write it
             * @TODO Get this generating sane dates
            public void putDate(ByteBuffer buf) {
                long msTime = (date.getTime() - MSEPOCH) / 1000;
                buf.putShort((short)(msTime % SECONDS_TO_DAYS));
                buf.putShort((short)(msTime / SECONDS_TO_DAYS));
        private Entry entryInProgress = null; // entry currently being written
        private java.util.ArrayList catalog = new java.util.ArrayList(12);  // all entries
         * Start a new output file.
         * @param name The name to store as
         * @param date Date - null indicates current time
        public java.io.OutputStream openEntry(String name, java.util.Date date) throws IOException{
            if(entryInProgress != null)
                entryInProgress.close();
            entryInProgress = new Entry(name, date);
            return this;
         * Creates a new instance of ZipOutputFile
         * @param fd The file to write to
        public ZipOutputFile(java.io.File fd) throws IOException {
            this(new java.io.RandomAccessFile(fd, "rw"));
         * Create new instance of ZipOutputFile from RandomAccessFile
         * @param archive RandomAccessFile
        public ZipOutputFile(java.io.RandomAccessFile archive) {
            this.archive = archive;
            entryHeader.order(java.nio.ByteOrder.LITTLE_ENDIAN);  // create fixed fields of header
            entryLater.order(java.nio.ByteOrder.LITTLE_ENDIAN);
            entryHeader.putInt(ENTRY_HEADER_MAGIC);
            entryHeader.putShort(MIN_VERSION);
            entryHeader.putShort((short)0);  // general purpose flag
            entryHeader.putShort(DEFLATE_METHOD);
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.clear();
            cal.set(java.util.Calendar.YEAR, 1950);
            cal.set(java.util.Calendar.DAY_OF_MONTH, 1);
    //        def.setStrategy(Deflater.HUFFMAN_ONLY);
            MSEPOCH = cal.getTimeInMillis();
         * Writes the master catalogue and postamble and closes the archive file.
        public void close() throws IOException{
            if(entryInProgress != null)
                entryInProgress.close();
            ByteBuffer catEntry = ByteBuffer.wrap(new byte[46]);
            catEntry.order(java.nio.ByteOrder.LITTLE_ENDIAN);
            catEntry.putInt(CATALOG_HEADER_MAGIC);
            catEntry.putShort(VERSION_CODE);
            catEntry.putShort(MIN_VERSION);
            catEntry.putShort((short)0);
            catEntry.putShort(DEFLATE_METHOD);
            long catStart = archive.getFilePointer();
            for(java.util.Iterator it = catalog.iterator(); it.hasNext();) {
                ((Entry)it.next()).writeCatalog(catEntry);
            catEntry.position(0);
            catEntry.putInt(CATALOG_END_MAGIC);
            catEntry.putShort(DISC_NUMBER);
            catEntry.putShort(DISC_NUMBER);
            catEntry.putShort((short)catalog.size());
            catEntry.putShort((short)catalog.size());
            catEntry.putInt((int)(archive.getFilePointer() - catStart));
            catEntry.putInt((int)catStart);
            catEntry.putShort((short)0);
            archive.write(catEntry.array(), 0, catEntry.position());
            archive.setLength(archive.getFilePointer());  // truncate if old file
            archive.close();
            def.end();
         * Closes entry in progress.
        public void flush() throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            entryInProgress.close();
            entryInProgress = null;
         * Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
        public void write(byte[] b) throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            crcAcc.update(b);
            def.setInput(b);
            while(!def.needsInput())
                deflate();
         * Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
        public void write(int b) throws IOException{
            oneByte[0] = (byte)b;
            crcAcc.update(b);
            write(oneByte, 0, 1);
         *  Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
         * @param off Start offset
         * @param len Byte count
        public void write(byte[] b, int off, int len) throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            crcAcc.update(b, off, len);
            def.setInput(b, off, len);
            while(!def.needsInput())
                deflate();
        * Gets a buffer full of coded data from the deflater and writes it to archive.
        private void deflate() throws IOException {
            int len = def.deflate(deflateBuf);
            totalCompressed += len;
            if(len > 0)
                archive.write(deflateBuf, 0, len);

  • Import the classes in the package java.util

    I haven't taken a class in two years so I have ideas but am unsure of myself, and I most likely am way off base, but is this how you import the classes in the package java.util
    import java.util.*;
    I would appreciate anyone's help. I have a lot of questions.
    Thanks,
    rp

    My assignment is below so that you will know exactly what I am asking. I am being asked to create an instance of LinkedList. I know that this is a part of the java.util. So when you create an instance of LinkedList would that be similar to instance variables? or am I misunderstanding something. I have several ideas, so I will start with the first one.
    LinkList();
    I really appreciate your taking the time to answer my questions to help me to rebuild my confidence in doing this.
    Thanks,
    // 2. import the classes in the package java.util
    public class MyProgram
         public static void main(String [] args)
              // 3. Create an instance of LinkedList
              // 4. add 5 entries to the list so that it contains
              //     Ann, Bart, Carl, Dirk, Zak
              // 5. display the list on one line using a loop and ADT list methods
              System.out.println("\n\n3. ");
              // 6. display the list using one println
              System.out.println("\n\n4. ");
              // 7. create a ListIterator object for the list
              // 8. display the list on one line using the iterator
              System.out.println("\n\n6. ");
              // 9. restore the iterator to the first item in the list
              // 10. retrieve and display the first item in the iteration,
              //      then advance the iterator to the next item
              System.out.println("\n\n8. ");
              // 11. advance the iterator to the end of the list without displaying anything;
              //      do not use the length of the list
              // 12. display the last item in the list
              System.out.println("\n\n10. ");
              // 13. move back to the beginning of the list without displaying anything;
              //      do not use the length of the list
              // 14. display the first item in the list
              System.out.println("\n\n12. ");
              // 15. advance the iterator to the end of the list without displaying anything;
              // 16. advance the iterator - what happens?
              System.out.println("\n\n14. ");
              // 17. advance the iterator within a try block; catch the exception, display a message,,
              //      and set the iterator back to the beginning of the list.
              System.out.println("\n\n15. ");
              // 18. what does nextIndex and previousIndex return?
              System.out.println("\n\n16. ");
              // 19. move the iterator to the third item in the list; if you were to
              //      execute next(), the third item would be returned and the iterator
              //      would advance to the 4th item.
              System.out.println("\n\n17. ");
              // 20. add the string "New" to the list; where is it inserted relative to
              //      the current item in the iteration?
              System.out.println("\n\n18. ");
              // 21. remove the current item; what happens?
              System.out.println("\n\n19. ");
              // 22. display the current item in the list without advancing the iteration
              //      in 2 ways, as follows:
              // 22A - using only iterator methods
              System.out.println("\n\n20A. ");
              // 22B using an iterator method and list methods
              System.out.println("\n\n20B. ");
              // 23. advance the iterator and remove the current item; which one is removed?
              System.out.println("\n\n21. ");
              // 24. move the iterator back and remove the current item; which one is removed?
              System.out.println("\n\n22. ");
              // 25. move the iterator to the first item in the list and change it to "First"
              System.out.println("\n\n23. ");
         } // end main
    } // end MyProgram

  • Java.util.ConcurrentModification Exception

    Hi
    I am trying to write a caching object for my web application. I have a CacheMAnger thread which is started when Tomcat starts. I put objects onto the cache and give them a TTL. My thread occasionaly goes through and checks all the cached objects to see if they are expired. I thought this was a syncronization problem but I can't find where.
    It bombs when an object expires and gets removed form the cache. The error output is below as well as a copy of the CacheManager source.
    Thanks
    Michael
    <pre>
    2003-04-15 12:55:15,161 DEBUG cache.CacheManager$1 82 - CacheManager: CustomerList in Cache... expi
    ry?
    EXPIRY:Tue Apr 15 17:55:04 GMT 2003CURRENT:Tue Apr 15 17:55:15 GMT 2003
    2003-04-15 12:55:15,161 INFO cache.CacheManager$1 90 - CacheManager Removed CustomerList
    java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:750)
    at java.util.HashMap$KeyIterator.next(HashMap.java:786)
    at net.talisen.tsr.cache.CacheManager$1.run(CacheManager.java:77)
    at java.lang.Thread.run(Thread.java:536)
    </pre>
    =====================================================================
    <pre>
    package net.talisen.tsr.cache;
    import java.util.HashMap;
    import java.util.Set;
    import java.util.Iterator;
    import org.apache.log4j.Logger;
    * Title: Caching
    * Description:
    * Copyright: Copyright (c) 2001
    * @author Michael Holly based on code from Jonathan Lurie in July 2001 Article in JavaWorld
    * @version 1.0
    public class CacheManager
    // This is the HashMap that contains all objects in the cache.
    private static java.util.HashMap cacheHashMap = new java.util.HashMap();
    // This object acts as a semaphore, which protects the HashMap
    // RESERVED FOR FUTURE USE private static Object lock = new Object();
    static
    try
    //Create background thread, which will be responsible for purging expired items.
    Thread threadCleanerUpper = new Thread( new Runnable()
    // The default time the thread should sleep between scans. The sleep
    // method takes in a millisecond value so 5000 = 5 Seconds.
    final static int milliSecondSleepTime = 20000;
    public void run()
    Logger log = Logger.getLogger(CacheManager.class);
    try
    // Sets up an infinite loop.
    while (true)
    log.debug( "CacheManager Scanning For Expired Objects...");
    // Get the set of all keys that are in cache. These are the unique
    // identifiers
    Set keySet = null;
    Iterator keys = null;
    Object key = null;
    Cacheable value = null;
    synchronized ( cacheHashMap )
    keySet = cacheHashMap.keySet();
    // An iterator is used to move through the Keyset //
    synchronized( keySet )
    keys = keySet.iterator();
    // Sets up a loop that will iterate through each key in the KeySet
    while(keys.hasNext())
    // Get the individual key. We need to hold on to this key
    // in case it needs to be removed
    synchronized ( keys )
    key = keys.next();
    // Get the cacheable object associated with the key inside the cache
    value = (Cacheable)cacheHashMap.get(key);
    log.debug( "CacheManager: " + value.getIdentifier() + " in Cache... expiry?");
    // Is the cacheable object expired?
    if (value.isExpired())
    //Yes it's expired! Remove it from the cache
    cacheHashMap.remove(key);
    cacheHashMap.notifyAll();
    log.info( "CacheManager Removed " + key.toString() );
    ***** A LRU (least-recently used) or
    LFU (least-frequently used) *****
    ******* would best be inserted here *****
    // Puts the thread to sleep. Don't need to check it continuously
    Thread.sleep( this.milliSecondSleepTime);
    catch (Exception e)
    e.printStackTrace();
    return;
    } // End run method
    }); // End class definition and close new thread definition
    // Sets the thread's priority to the minimum value.
    threadCleanerUpper.setPriority( Thread.MIN_PRIORITY );
    // Starts the thread.
    threadCleanerUpper.start();
    catch(Exception e)
    System.out.println( "CacheManager.Static Block: " + e);
    } // End static block
    // default constructor
    public CacheManager()
    * Used to add an object to the Cache
    * @param object the object to be added to the cache
    public static void putCache(Cacheable object)
    Logger log = Logger.getLogger(CacheManager.class);
    // Remember if the HashMap previously contains a mapping for the key, the old value
    // will be replaced. This is valid functioning.
    if ( object == null ) {
    log.debug("object to be cached is null. Caching was not attempted");
    return;
    if ( object.getIdentifier() == null ) {
    log.debug("object to be cached has a null key. Caching was not attempted");
    return;
    else
    synchronized ( cacheHashMap ) {
    cacheHashMap.put(object.getIdentifier(), object);
    log.debug( object.getIdentifier() + " cached");
    * Used to get an object from the cache
    * @param object the object to be retrieved from the cache
    * @return the cached object
    public static Cacheable getCache(Object identifier)
    Logger log = Logger.getLogger(CacheManager.class);
    if (identifier == null ) {
    log.debug( "Cache key was null" );
    return null;
    log.debug("Looking for " + identifier.toString() );
    //synchronized (lock) // UNCOMMENT LINE XXX
    //{                    // UNCOMMENT LINE XXX
    Cacheable object = null;
    synchronized ( cacheHashMap ) {
    object = ( Cacheable )cacheHashMap.get(identifier);
    // The code to create the object would be placed here.
    //} // UNCOMMENT LINE XXX
    if (object == null) {
    log.debug( "object not found in cache");
    return null;
    if (object.isExpired())
    log.debug( "object in cache was expired");
    synchronized ( cacheHashMap ) {
    cacheHashMap.remove(identifier);
    return null;
    else
    log.debug( object.getIdentifier() + " found");
    object.incrementCacheHits(); // track the performance
    return object;
    * Used to clear all objects from the cache
    public static void emptyCache()
    Logger log = Logger.getLogger(CacheManager.class);
    synchronized ( cacheHashMap ) {
    cacheHashMap.clear();
    log.debug( "Cache cleared");
    * Used to remove a particular object from the cache
    * @param identifier the object to be removed from the cache
    public static void removeEntry(Object identifier)
    Logger log = Logger.getLogger(CacheManager.class);
    if (identifier == null ) {
    log.debug( "Cache key was null" );
    return;
    synchronized ( cacheHashMap ) {
    cacheHashMap.remove(identifier);
    log.debug( identifier + " removed");
    * Used to get a count of cached objects
    * @return number of objects in the cache
    public static int getCount()
    synchronized ( cacheHashMap ) {
    return cacheHashMap.size();
    * Used to get a set of the entries in the cache
    * @param Set a set of the objects in the cache
    public static Set getEntrySet()
    synchronized ( cacheHashMap ) {
    return cacheHashMap.entrySet();
    * Used to get a html page on the status of the cache
    public static String getStatus()
    Set keySet = null;
    Iterator keys = null;
    synchronized (cacheHashMap) {
    keySet = cacheHashMap.keySet();
    keys = keySet.iterator();
    String status = new String();
    status += ( "<html><head>");
    status += ( "<meta http-equiv=\"Cache-Control\" content=\"no-cache\" />");
    status += ( "<meta http-equiv=\"Pragma\" content=\"no-cache\" />");
    status += ( "<meta http-equiv=\"Expires\" content=\"0\" /> ");
    status += ( "<meta http-equiv=\"refresh\" content=\"10\" /> ");
    status += ( "</head><body>" );
    status += ( "<p><h4>Cache Status " + (new java.util.Date()).toString() + "</h4>" );
    status += ( "<br>Page automagically refreshed every 10 seconds<br>" );
    status += ( getCount() + " object(s) cached" );
    status += ( "<p>Cache contains: " );
    while(keys.hasNext())
    Object key = keys.next();
    // Get the cacheable object associated with the key inside the cache
    Cacheable object = null;
    synchronized ( cacheHashMap ) {
    object = (Cacheable)cacheHashMap.get(key);
    status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i>" );
    status += ( "<br>   <b>Class of:</b><i>" + object.toString() + "</i>");
    status += ( "<br>   <b> Expires at:</b><i>" + object.getExpireDate() + "</i>");
    status += ( "<br>   <b> Cache Hits:</b><i>" + object.getCacheHits().toString() + "</i>");
    status += ( "<br>   <b> Object Size:</b><i>" + object.getByteCount(object).toString() + "</i>");
    int bytesServed = object.getCacheHits().intValue() * object.getByteCount(object).intValue();
    double eff = 0.0;
    // handle divide by 0
    if ( bytesServed > 0 ) {
    eff = ( bytesServed - object.getByteCount(object).intValue() ) / bytesServed;
    status += ( "<br>   <b> Cache Efficiency:</b><i>" + eff + "</i><br><br>");
    status += ( "</body></html>" );
    return status;
    * Used to get a html page on the status of the cache
    public static String flushCache()
    Set keySet = null;
    Iterator keys = null;
    synchronized ( cacheHashMap ) {
    keySet = cacheHashMap.keySet();
    keys = keySet.iterator();
    String status = new String();
    status += ( "<html><head>");
    status += ( "<meta http-equiv=\"Cache-Control\" content=\"no-cache\" />");
    status += ( "<meta http-equiv=\"Pragma\" content=\"no-cache\" />");
    status += ( "<meta http-equiv=\"Expires\" content=\"0\" /> ");
    status += ( "</head><body>" );
    status += ( "<p><h4>Cache status before cache reset " + (new java.util.Date()).toString() + "</h4>" );
    status += ( "<p>Cache size: " + getCount() + " object(s) cached" );
    status += ( "<p>Cache contains: " );
    while(keys.hasNext())
    Object key = keys.next();
    // Get the cacheable object associated with the key inside the cache
    Cacheable object = null;
    synchronized ( cacheHashMap ) {
    object = (Cacheable)cacheHashMap.get(key);
    status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i> <b>Class of:</b><i>" + object.toString() );
    status += ( "</i><b> Expires at:</b>" + object.getExpireDate() + "</i>");
    CacheManager.emptyCache();
    status += ( "<p><h4>Cache status after cache reset " + (new java.util.Date()).toString() + "</h4>" );
    status += ( "<p>Cache size: " + CacheManager.getCount() + " object(s) cached" );
    status += ( "<p>Cache contains: " );
    Set newKeySet = null;
    Iterator newKeys = null;
    synchronized ( cacheHashMap ) {
    newKeySet = cacheHashMap.keySet();
    newKeys = newKeySet.iterator();
    // this really never gets executed
    while(newKeys.hasNext())
    Object key = newKeys.next();
    // Get the cacheable object associated with the key inside the cache
    Cacheable object = null;
    synchronized ( cacheHashMap ) {
    object = (Cacheable)cacheHashMap.get(key);
    status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i> <b>Class of:</b><i>" + object.toString() );
    status += ( "</i><b> Expires at:</b>" + object.getExpireDate() + "</i>");
    status += ( "</body></html>" );
    return status;
    </pre>

    I think my problem is that I am iterating through all the values of the hashMap and when I find one and delete it then the iterator becomes invalid? Checkout the while loop in the thread.
    I'm not sure that this scenario is consistant with the error I'm getting.
    I had tried something similar to what you described... maybe I missed something. Let me try it again...
    I have reposted my code below with the proper tags to render the code if you need to reference for any more suggestions.
    Michael
    package net.talisen.tsr.cache;
    import java.util.HashMap;
    import java.util.Set;
    import java.util.Iterator;
    import org.apache.log4j.Logger;
    * Title:        Caching
    * Description:
    * Copyright:    Copyright (c) 2001
    * @author Michael Holly based on code from Jonathan Lurie in July 2001 Article in JavaWorld
    * @version 1.0
    public class CacheManager
       // This is the HashMap that contains all objects in the cache.
       private static java.util.HashMap cacheHashMap = new java.util.HashMap();
       // This object acts as a semaphore, which protects the HashMap
       // RESERVED FOR FUTURE USE  private static Object lock = new Object();
       static
          try
             //Create background thread, which will be responsible for purging expired items.
             Thread threadCleanerUpper = new Thread( new Runnable()
                //  The default time the thread should sleep between scans.  The sleep
                //  method takes in a millisecond value so 5000 = 5 Seconds.
                final static int milliSecondSleepTime = 20000;
                public void run()
                   Logger log = Logger.getLogger(CacheManager.class);
                   try
                      // Sets up an infinite loop.
                      while (true)
                         log.debug( "CacheManager Scanning For Expired Objects...");
                         // Get the set of all keys that are in cache.  These are the unique
                         // identifiers
                         Set keySet      = null;
                         Iterator keys   = null;
                         Object key      = null;
                         Cacheable value = null;
                         synchronized ( cacheHashMap )
                            keySet = cacheHashMap.keySet();
                            // An iterator is used to move through the Keyset //
                            synchronized( keySet )
                               keys = keySet.iterator();
                            // Sets up a loop that will iterate through each key in the KeySet
                            while(keys.hasNext())
                               // Get the individual key. We need to hold on to this key
                               // in case it needs to be removed
                               synchronized ( keys )
                                  key = keys.next();
                               // Get the cacheable object associated with the key inside the cache
                               value = (Cacheable)cacheHashMap.get(key);
                               log.debug( "CacheManager: " + value.getIdentifier() + " in Cache... expiry?");
                               // Is the cacheable object expired?
                               if (value.isExpired())
                                  //Yes it's expired! Remove it from the cache
                                  cacheHashMap.remove(key);
                                  cacheHashMap.notifyAll();
                                  log.info( "CacheManager Removed " + key.toString() );
                             ***** A LRU (least-recently used) or
                                                  LFU (least-frequently used) *****
                             ******* would best be inserted here              *****
                         // Puts the thread to sleep. Don't need to check it continuously
                         Thread.sleep( this.milliSecondSleepTime);
                   catch (Exception e)
                      e.printStackTrace();
                   return;
                } // End run method
             }); // End class definition and close new thread definition
             // Sets the thread's priority to the minimum value.
             threadCleanerUpper.setPriority( Thread.MIN_PRIORITY );
             // Starts the thread.
             threadCleanerUpper.start();
          catch(Exception e)
             System.out.println( "CacheManager.Static Block: " + e);
       } // End static block
       // default constructor
       public CacheManager()
       * Used to add an object to the Cache
       * @param object the object to be added to the cache
       public static void putCache(Cacheable object)
          Logger log = Logger.getLogger(CacheManager.class);
          // Remember if the HashMap previously contains a mapping for the key, the old value
          // will be replaced.  This is valid functioning.
          if ( object == null ) {
             log.debug("object to be cached is null. Caching was not attempted");
             return;
          if ( object.getIdentifier() == null ) {
             log.debug("object to be cached has a null key. Caching was not attempted");
             return;
          else
             synchronized ( cacheHashMap ) {
                cacheHashMap.put(object.getIdentifier(), object);
                log.debug( object.getIdentifier() + " cached");
       * Used to get an object from the cache
       * @param object the object to be retrieved from the cache
       * @return the cached object
       public static Cacheable getCache(Object identifier)
          Logger log = Logger.getLogger(CacheManager.class);
          if (identifier == null ) {
             log.debug( "Cache key was null" );
             return null;
          log.debug("Looking for " + identifier.toString() );
          Cacheable object = null;
          synchronized ( cacheHashMap )  {
             object = ( Cacheable )cacheHashMap.get(identifier);
          if (object == null) {
             log.debug( "object not found in cache");
             return null;
          if (object.isExpired())
             log.debug( "object in cache was expired");
             synchronized ( cacheHashMap )  {
                cacheHashMap.remove(identifier);
             return null;
          else
             log.debug( object.getIdentifier() + " found");
             object.incrementCacheHits(); // track the performance
             return object;
       * Used to clear all objects from the cache
       public static void emptyCache()
          Logger log = Logger.getLogger(CacheManager.class);
          synchronized ( cacheHashMap )  {
             cacheHashMap.clear();
          log.debug( "Cache cleared");
       * Used to remove a particular object from the cache
       * @param identifier the object to be removed from the cache
       public static void removeEntry(Object identifier)
          Logger log = Logger.getLogger(CacheManager.class);
          if (identifier == null ) {
             log.debug( "Cache key was null" );
             return;
          synchronized ( cacheHashMap )  {
             cacheHashMap.remove(identifier);
          log.debug( identifier + " removed");
       * Used to get a count of cached objects
       * @return number of objects in the cache
       public static int getCount()
          synchronized ( cacheHashMap )  {
             return cacheHashMap.size();
       * Used to get a set of the entries in the cache
       * @param Set a set of the objects in the cache
       public static Set getEntrySet()
          synchronized ( cacheHashMap )  {
             return cacheHashMap.entrySet();
       * Used to get a html page on the status of the cache
       public static String getStatus()
          Set keySet = null;
          Iterator keys = null;
          synchronized (cacheHashMap) {
             keySet = cacheHashMap.keySet();
             keys = keySet.iterator();
          String status = new String();
          status += ( "<html><head>");
          status += ( "<meta http-equiv=\"Cache-Control\" content=\"no-cache\" />");
          status += ( "<meta http-equiv=\"Pragma\" content=\"no-cache\" />");
          status += ( "<meta http-equiv=\"Expires\" content=\"0\" /> ");
          status += ( "<meta http-equiv=\"refresh\" content=\"10\" /> ");
          status += ( "</head><body>" );
          status += ( "<p><h4>Cache Status " + (new java.util.Date()).toString() + "</h4>" );
          status += ( "<br>Page automagically refreshed every 10 seconds<br>" );
          status += ( getCount() + " object(s) cached" );
          status += ( "<p>Cache contains: " );
          while(keys.hasNext())
             Object key = keys.next();
             // Get the cacheable object associated with the key inside the cache
             Cacheable object = null;
             synchronized ( cacheHashMap )  {
                object = (Cacheable)cacheHashMap.get(key);
             status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i>"  );
             status += ( "<br>���<b>Class�of:</b><i>" + object.toString() + "</i>");
             status += ( "<br>���<b> Expires at:</b><i>" + object.getExpireDate() + "</i>");
             status += ( "<br>���<b> Cache Hits:</b><i>" + object.getCacheHits().toString() + "</i>");
             status += ( "<br>���<b> Object Size:</b><i>" + object.getByteCount(object).toString() + "</i>");
             int bytesServed = object.getCacheHits().intValue() * object.getByteCount(object).intValue();
             double eff = 0.0;
             // handle divide by 0
             if ( bytesServed > 0 ) {
                eff = ( bytesServed - object.getByteCount(object).intValue() ) / bytesServed;
             status += ( "<br>���<b> Cache Efficiency:</b><i>" + eff + "</i><br><br>");
          status += ( "</body></html>" );
          return status;
       * Used to get a html page on the status of the cache
       public static String flushCache()
          Set keySet = null;
          Iterator keys = null;
          synchronized ( cacheHashMap )  {
             keySet = cacheHashMap.keySet();
             keys   = keySet.iterator();
          String status = new String();
          status += ( "<html><head>");
          status += ( "<meta http-equiv=\"Cache-Control\" content=\"no-cache\" />");
          status += ( "<meta http-equiv=\"Pragma\" content=\"no-cache\" />");
          status += ( "<meta http-equiv=\"Expires\" content=\"0\" /> ");
          status += ( "</head><body>" );
          status += ( "<p><h4>Cache status before cache reset " + (new java.util.Date()).toString() + "</h4>" );
          status += ( "<p>Cache size: " + getCount() + " object(s) cached" );
          status += ( "<p>Cache contains: " );
          while(keys.hasNext())
             Object key = keys.next();
             // Get the cacheable object associated with the key inside the cache
             Cacheable object = null;
             synchronized ( cacheHashMap )  {
                object = (Cacheable)cacheHashMap.get(key);
             status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i>  <b>Class of:</b><i>" + object.toString() );
             status += ( "</i><b> Expires at:</b>" + object.getExpireDate() + "</i>");
          CacheManager.emptyCache();
          status += ( "<p><h4>Cache status after cache reset " + (new java.util.Date()).toString() + "</h4>" );
          status += ( "<p>Cache size: " + CacheManager.getCount() + " object(s) cached" );
          status += ( "<p>Cache contains: " );
          Set newKeySet = null;
          Iterator newKeys = null;
          synchronized ( cacheHashMap )  {
             newKeySet = cacheHashMap.keySet();
             newKeys   = newKeySet.iterator();
          // this really never gets executed
          while(newKeys.hasNext())
             Object key = newKeys.next();
             // Get the cacheable object associated with the key inside the cache
             Cacheable object = null;
             synchronized ( cacheHashMap )  {
                object = (Cacheable)cacheHashMap.get(key);
             status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i>  <b>Class of:</b><i>" + object.toString() );
             status += ( "</i><b> Expires at:</b>" + object.getExpireDate() + "</i>");
          status += ( "</body></html>" );
          return status;

  • Java.util.zip

    Hi,
    I'm using java.util.zip package and I want to remove the directory
    structure from the zipped files. How to make a ZipEntry without having the directory path of the original file in the zipped file.
    Thanks in Advance
    Carlos

    Carlos
    What you need to do is create a ZipEntry for that file without the directory structure on it.
    The sample snippet below will archive a directory and all it's subdirectories, creating a zip file with the base name, inside a specified storage location. All the files in the zip are created relative to the base dir.
    Hope it helps,
    Neil
    :o)
      static final int BUFFER = 2048;
      public void zip() throws Exception
            File dirToArchive = new File("C:\Test\ZipMe");
            File storagePlace = new File("C:\Zips");
         ArrayList allFilesToZip = new ArrayList();
         this.getFiles(allFilesToZip, dirToArchive);
         String storeName = this.storagePlace.getAbsolutePath()+File.separator+dirToArchive.getName()+".zip";
         FileOutputStream dest = new FileOutputStream(storeName);
         ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
         byte data[] = new byte[BUFFER];
         BufferedInputStream origin = null;
         for (Iterator itr = allFilesToZip.iterator(); itr.hasNext();)
           File current = (File)itr.next();
           System.out.println("Adding : "+current.getName());
           if (current.isFile()) // skip dirs, don't need them
             FileInputStream fi = new FileInputStream(current);
             origin = new BufferedInputStream(fi, BUFFER);
             String newEntryName = current.getAbsolutePath();
                // cut off the front of the file's absolute path the same
                // number of characters as our parent archive directory has
                // plus one for the file seperator
                // This leaves us with a 'relative' path name for the entry
                // I've left the code here for a little clarity on what's going on
                // but you'll want to put the calculation in a local variable
                // outside the loop as it doesn't change
                newEntryName = newEntryName.substring(this.dirToArchive.getAbsolutePath().length()+1);
             ZipEntry entry = new ZipEntry(newEntryName);
             out.putNextEntry(entry);
             int count;
             while((count = origin.read(data, 0, BUFFER)) != -1)
                out.write(data, 0, count);
             origin.close();
         out.close();
       private void getFiles(ArrayList inHere, File dir)
          File[] files = dir.listFiles();
          for (int i=0; i<files.length; i++)
            File current = files;
         inHere.add(current);
         if (current.isDirectory())
              getFiles(inHere, current); // recurse

  • Exception in thread "main" java.util.NoSuchElementException

    Hello there,
    I need to store resultset values in arrays.
    Following is my code:
    (Note : The function uses the jdbc connection with mysql that is return from other function.)
    public static void getResultSetInArray(Connection con) throws Exception
    Map list = new HashMap();
    Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = stmt.executeQuery("show columns from launchcomm.events");
    while(rs.next())
    list.put(rs.getString("Field"),rs.getString("Type"));
    rs.close();
    con.close();
    System.out.println("List = " + list + "\n");
    Iterator iter = null;
    iter = list.keySet().iterator();
    System.out.println("iter = " + iter);
    String field;
    String type;
    int i=1;
    System.out.println("list size = " + list.size());
    while(iter.hasNext() != false)
    System.out.println("iter.hasNext() = " + iter.hasNext() +"......" +(i++));
    System.out.println("iter.next() = " + iter.next());
    field = (String)iter.next();
    type = (String)list.get(iter.next());
    Following is my output with error:
    List = {folder_name=varchar(50), is_repeat=tinyint(1), footer=text, thankyou_email=text, box_header_bg_color=varchar(25), organization_id=int(11), attendee_delete_right=tinyint(1), show_ticket_remaining=tinyint(1), order_confirmation_email=text, save_for_later=tinyint(1), start_register=tinyint(4), id=int(11), logo=varchar(100), publish=tinyint(1), end_unregister=datetime, owner_id=int(11), confirmation_email=text, audience_id=int(11), event_color_code=varchar(30), showcalendar=tinyint(1), registration_enddate=datetime, directory_name=varchar(20), eventstatus_id=int(11), contact_id=int(11), password_protect=tinyint(1), include_header=tinyint(1), thankyou_page=text, header=text, is_hotel_capacity=tinyint(1), want_close=tinyint(1), travel_housing_request=tinyint(1), box_header_text_color=varchar(25), default_location_id=int(11), end_reg_modification=datetime, user_id=int(11), passkey_eventcode=varchar(255), page_size=int(11), passkey_password=varchar(255), event_capacity=int(11), box_text_color=varchar(25), updated_on=datetime, link_color=varchar(25), ends_on=datetime, hotel_capacity=int(11), template_id=int(11), allow_overlap_session=tinyint(1), starts_on=datetime, reg_another_button=varchar(50), passkey_partnerid=int(11), personalized_url=tinyint(1), hide_start_date=tinyint(1), hide_end_date=tinyint(1), include_footer=tinyint(1), text_color=varchar(25), allow_another_registrant=tinyint(1), passkey_eventid=int(11), resize=tinyint(1), default_closetemplate=tinyint(1), dateformat=text, personalize_agenda=tinyint(1), cssfile_id=int(11), passkey_information=tinyint(1), confirmation_page=text, activate_waitlist=tinyint(1), box_border_color=varchar(25), google_analytics_code=text, show_iframe_design=tinyint(1), confirmation_mail_format=tinyint(1), url=varchar(100), bg_color=varchar(25), package_id=int(11), name=varchar(200), password=varchar(50), capacity=int(11), modify_registration=tinyint(1), is_event_capacity=tinyint(1), include_css=tinyint(1), passkey_username=varchar(255), created_on=datetime, promote_url=varchar(100), page_views=int(11), box_bg_color=varchar(25), title_text_color=varchar(25), registration_open_text=text, require_login=tinyint(1), closetemplate_description=text, registration_startdate=datetime, domain=varchar(200), timezone_id=varchar(100), description=text, tag=varchar(255), allow_unregister=tinyint(1), order_confirmation_page=text, css=text, showmap=tinyint(1)}
    iter = java.util.HashMap$KeyIterator@18a47e0
    list size = 95
    iter.hasNext() = true......1
    iter.next() = folder_name
    iter.hasNext() = true......2
    iter.next() = footer
    iter.hasNext() = true......3
    iter.next() = box_header_bg_color
    iter.hasNext() = true......4
    iter.next() = attendee_delete_right
    iter.hasNext() = true......5
    iter.next() = order_confirmation_email
    iter.hasNext() = true......6
    iter.next() = start_register
    iter.hasNext() = true......7
    iter.next() = logo
    iter.hasNext() = true......8
    iter.next() = end_unregister
    iter.hasNext() = true......9
    iter.next() = confirmation_email
    iter.hasNext() = true......10
    iter.next() = event_color_code
    iter.hasNext() = true......11
    iter.next() = registration_enddate
    iter.hasNext() = true......12
    iter.next() = eventstatus_id
    iter.hasNext() = true......13
    iter.next() = password_protect
    iter.hasNext() = true......14
    iter.next() = thankyou_page
    iter.hasNext() = true......15
    iter.next() = is_hotel_capacity
    iter.hasNext() = true......16
    iter.next() = travel_housing_request
    iter.hasNext() = true......17
    iter.next() = default_location_id
    iter.hasNext() = true......18
    iter.next() = user_id
    iter.hasNext() = true......19
    iter.next() = page_size
    iter.hasNext() = true......20
    iter.next() = event_capacity
    iter.hasNext() = true......21
    iter.next() = updated_on
    iter.hasNext() = true......22
    iter.next() = ends_on
    iter.hasNext() = true......23
    iter.next() = template_id
    iter.hasNext() = true......24
    iter.next() = starts_on
    iter.hasNext() = true......25
    iter.next() = passkey_partnerid
    iter.hasNext() = true......26
    iter.next() = hide_start_date
    iter.hasNext() = true......27
    iter.next() = include_footer
    iter.hasNext() = true......28
    iter.next() = allow_another_registrant
    iter.hasNext() = true......29
    iter.next() = resize
    iter.hasNext() = true......30
    iter.next() = dateformat
    iter.hasNext() = true......31
    iter.next() = cssfile_id
    iter.hasNext() = true......32
    iter.next() = confirmation_page
    iter.hasNext() = true......33
    iter.next() = box_border_color
    iter.hasNext() = true......34
    iter.next() = show_iframe_design
    iter.hasNext() = true......35
    iter.next() = url
    iter.hasNext() = true......36
    iter.next() = package_id
    iter.hasNext() = true......37
    iter.next() = password
    iter.hasNext() = true......38
    iter.next() = modify_registration
    iter.hasNext() = true......39
    iter.next() = include_css
    iter.hasNext() = true......40
    iter.next() = created_on
    iter.hasNext() = true......41
    iter.next() = page_views
    iter.hasNext() = true......42
    iter.next() = title_text_color
    iter.hasNext() = true......43
    iter.next() = require_login
    iter.hasNext() = true......44
    iter.next() = registration_startdate
    iter.hasNext() = true......45
    iter.next() = timezone_id
    iter.hasNext() = true......46
    iter.next() = tag
    iter.hasNext() = true......47
    iter.next() = order_confirmation_page
    iter.hasNext() = true......48
    iter.next() = showmap
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:844)
    at java.util.HashMap$KeyIterator.next(HashMap.java:877)
    at GetDataTypeFromDB.getResultSetInArray(GetDataTypeFromDB.java:57)
    at GetDataTypeFromDB.main(GetDataTypeFromDB.java:16)
    I am unable to fine the reason for the exception.
    Please help me to solve my problem.
    Regards,
    Thevoice
    Edited by: TheVoice on May 14, 2008 12:01 AM

    TheVoice wrote:
    while(iter.hasNext() != false)
    System.out.println("iter.hasNext() = " + iter.hasNext() +"......" +(i++));
    System.out.println("iter.next() = " + iter.next());
    field = (String)iter.next();
    type = (String)list.get(iter.next());
    }Your major problem is that iter.next() advances one place every time you call it, so in every iteration of that loop, you advance three steps. The first step is guaranteed to be okay, because you checked it with iter.hasNext(), but the other two are not. In addition, you are in effect "skipping" the printing of two out of every three items.
    To print out every item, you probably want to do something like this (call it only one and store it in a variable):
    while(iter.hasNext())
        String field = (String)iter.next();
        System.out.println("iter.hasNext() = " + iter.hasNext() +"......" +(i++));
        System.out.println("iter.next() = " + field);
        String type = (String)list.get(field);
    }For additional clarity, I would recommend using Generics, Map.entrySet(), and the for-each loop:
    public static void getResultSetInArray(Connection con) throws Exception
        Map<String,String> list = new HashMap<String,String>();
        Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = stmt.executeQuery("show columns from launchcomm.events");
        while(rs.next())
            list.put(rs.getString("Field"),rs.getString("Type"));
        rs.close();
        con.close();
        for (Map.Entry<String,String> e : list.entrySet())
            String field = e.getKey();
            String type = e.getValue();
            // do stuff with them
    }Edited by: spoon_ on May 14, 2008 7:34 PM

  • NullpointerException in java.util.Hashtable.access$100 ???

    Hi folks.
    I am trying to reconstruct a Hashtable using my own way of serialization/deserialization via Java Reflection. It works fine with most classes, but a reconstructed hashtable is seriously screwed up. After reconstruction, it is passed as an argument to a class that uses the putAll-Method, which causes a NullpointerException.
    The root in the stack trace is java.util.Hashtable.access$100 at line 90 in java.util.Hashtable. Unfortunately, if you check the source of hashtable, you will only find the class header on this line.
    Is it correct, that javac creates access-methods for inner classes? What are they used for?
    Any idea what could cause this?

    The exception happens whenever I try methods like toString, putAll or hashCode on the hashtable. The code of the deserialization is just a bit to complex to post here.
    I have been able to track the problem down to the internal creation of creation of an iterator by the hashtable.
    Here is the stack trace:
    Exception in thread "main" java.lang.NullPointerException
    at java.util.Hashtable.access$100(Hashtable.java:90)
    at java.util.Hashtable$EntrySet.iterator(Hashtable.java:592)
    at java.util.Collections$SynchronizedCollection.iterator(Collections.java:1096)
    at java.util.Hashtable.hashCode(Hashtable.java:728)
    at java.util.Hashtable.get(Hashtable.java:315)
    at mypackage.serializer.XMLSerializer.buildXML(XMLSerializer.java:205)
    at mypackage.serializer.XMLSerializer.buildXML(XMLSerializer.java:178)
    at mypackage.serializer.XMLSerializer.main(XMLSerializer.java:66)

  • Puzzled by the redefinition of the methods in java.util.Set

    Hi all,
    I don't understand why those methods in java.util.Set redefined since their counterparts have alrealdy been defined in java.util.Collection and java.util.Set extends java.util.Collection. I agree to redefine boolean add(Object o) because its contract has been modified, but what about the rest like
    size() and iterator() ?
    Thanks.

    Hi all,
    I don't understand why those methods in
    in java.util.Set redefined since their counterparts
    have alrealdy been defined in java.util.Collection
    and java.util.Set extends java.util.Collection. I
    agree to redefine boolean add(Object o) because its
    contract has been modified, but what about the rest
    like
    size() and iterator() ?Completeness's sake?
    ~Cheers

  • Need node-level access in java.util.LinkedList... possible?

    Hi, I require access to the nodes not the elements, in a java.util.LinkedList. Is this possible, or will I have to write my own implementation.
    Thanks
    Grape

    I do need full control over the nodes because I am linking them together to form an n-dimensional circularly-linked lattice. After thinking about it, it became clear it would be much easier to write my own nodes and special type of iterator along with an Axis enum type than it would be to muck around trying to weave together prefab lists even if I did have access to the nodes. Anyways, the feat has been accomplished :) Thanks for your reply.

  • EntrySet has private access in java.util.Hashtable

    Hi friends,
    While i try to retrieve the data from the hashtable through a JSP page, i'm getting the error saying "E:\Tomcat 5.0\work\Catalina\localhost\dd\org\apache\jsp\disp_jsp.java:55: entrySet has private access in java.util.Hashtable
    Iterator i = h.entrySet.iterator();
    For your reference the code goes like this,
    <% Hashtable h = (Hashtable) session.getAttribute("hash");
    Iterator i = h.entrySet.iterator();
    while(i.hasNext())
    %>
    <tr><td>
    <% String st = i.next().toString();
    String k[] = st.split("=");     
    out.println(k[0]); %>
    </td><td><%
    out.println(k[1]); %></td></tr><% } %>
    can anyone tell me how to get rid of this error quickly please.. Thanks in advance...
    Regards,
    Prakash.

    Iterator i = h.entrySet.iterator();Iterator i = h.entrySet().iterator();

  • Error in Parser.fx file "incompatible types found   : java.util.Properties"

    Hi,
    In parser file "Parser.fx",
    public-read def PROPERTIES_PARSER = StreamParser {
    override public function parse(input : java.io.InputStream) : RecordSet {
    var props = javafx.util.Properties {};
    props.load(input);
    input.close();
    MemoryRecordSet {
    records: [
    MapRecord {
    fields: props
    due to under line portion an error is appearing:
    "incompatible types
    found : javafx.util.Properties
    required: java.util.Map
    fields: props".
    Please suggest some solution.
    Thanks in advance.
    regards,
    Choudhary Nafees Ahmed
    Edited by: ChoudharyNafees on Jul 5, 2010 3:48 AM

    Parser.fx
    package org.netbeans.javafx.datasrc;
    import javafx.data.pull.PullParser;
    import javafx.data.pull.Event;
    import org.netbeans.javafx.datasrc.MemoryRecordSet;
    public-read def PROPERTIES_PARSER = StreamParser {
        override public function parse(input : java.io.InputStream) : RecordSet {
            var props =java.util.Properties{};
            props.load(input);
            input.close();
            MemoryRecordSet {
                records: [
                    MapRecord {
                        fields: props
    public-read def LINE_PARSER_FIELD_LINE = ".line";
    public-read def LINE_PARSER = StreamParser {
        override public function parse(input : java.io.Reader) : RecordSet {
            var line : String;
            var result : Record [] = [];
            line = readLine(input);
            // BEWARE  ("" == null) is true
            while (line != null or "".equals(line)) {
                var map = new java.util.HashMap();
                map.put(LINE_PARSER_FIELD_LINE, line);
                var record = MapRecord {
                    fields: map
                insert record into result;
                line = readLine(input);
            MemoryRecordSet {
                records: result
    function readLine(in : java.io.Reader) : String {
        var str = new java.lang.StringBuilder;
        while (true) {
            var c = in.read();
            if (c == -1) {
                return if (str.length() == 0) then null else str.toString();
            } else if (c == 0x0D) {
                c = in.read();
                if (c == 0x0A or c == -1) {
                    return str.toString();
                str.append(0x0D);
            } else if (c == 0x0A) {
                return str.toString();
            str.append(c as Character);
        str.toString()
    public-read def JSON_PARSER = StreamParser {
        function toSequence(list : java.util.List) : Record [] {
            var result : Record [] = [];
            var ii = list.iterator();
            while (ii.hasNext()) {
                var r = ii.next() as Record;
                insert r into result;
            result
        override public function parse(input : java.io.InputStream) : RecordSet {
            var topLevel : Object;
            def parser = PullParser {
                documentType: PullParser.JSON
                input: input
                var mapStack = new java.util.Stack();
                var currentMap : java.util.Map;
                var recordsStack = new java.util.Stack();
                var currentRecords : java.util.List;
                var lastEvent: Event;
                onEvent: function(event: Event) {
                    if (event.type == PullParser.TEXT) {
                        currentMap.put(event.name, event.text)
                    } else if (event.type == PullParser.INTEGER) {
                        currentMap.put(event.name, event.integerValue)
                    } else if (event.type == PullParser.NULL) {
                        currentMap.put(event.name, null)
                    } else if (event.type == PullParser.START_ELEMENT) {
                        if (lastEvent.type == PullParser.START_ARRAY_ELEMENT) return;
                        var oldMap = currentMap;
                        var temp = new java.util.HashMap();
                        temp.put(new Object(), null);
                        currentMap = temp;
                        currentMap.clear();
                        mapStack.push(currentMap);
                        if (topLevel == null) topLevel = currentMap;
                        if (oldMap != null) {
                            var mr = MapRecord {
                                fields: currentMap
                            if (event.name == "" and lastEvent.type == PullParser.START_VALUE) {
                                oldMap.put(lastEvent.name, mr)
                            } else {
                                oldMap.put(event.name, mr)
                    } else if (event.type == PullParser.START_ARRAY_ELEMENT) {
                        var temp = new java.util.HashMap();
                        temp.put(new Object(), null);
                        currentMap = temp;
                        currentMap.clear();
                        mapStack.push(currentMap);
                        var mr = MapRecord {
                            fields: currentMap
                        currentRecords.add(mr);
                    } else if (event.type == PullParser.END_ELEMENT) {
                        mapStack.pop();
                        if (not mapStack.empty()) {
                            currentMap = mapStack.peek() as java.util.HashMap;
                        } else {
                            currentMap = null;
                    } else if (event.type == PullParser.END_ARRAY_ELEMENT) {
                        if (lastEvent.type == PullParser.END_ELEMENT) return;
                        mapStack.pop();
                        if (not mapStack.empty()) {
                            currentMap = mapStack.peek() as java.util.HashMap;
                        } else {
                            currentMap = null;
                    } else if (event.type == PullParser.START_ARRAY) {
                        currentRecords = new java.util.ArrayList();
                        recordsStack.push(currentRecords);
                        if (topLevel == null) topLevel = currentRecords;
                    } else if (event.type == PullParser.END_ARRAY) {
                        var set = MemoryRecordSet {
                            records: toSequence(currentRecords)
                        currentMap.put(event.name, set);
                        recordsStack.pop();
                        if (not recordsStack.empty()) {
                            currentRecords = recordsStack.peek() as java.util.List;
                        } else {
                            currentRecords = null;
                    lastEvent = event;
            parser.parse();
            if (topLevel instanceof java.util.Map) {
                var mr = MapRecord {
                    fields: topLevel as java.util.Map
                MemoryRecordSet {
                   records: [mr]
            } else {
                // List
                var rs = MemoryRecordSet {
                    records: toSequence(topLevel as java.util.List)
                rs
            parser.parse();
            var mr = MapRecord {
                fields: topLevel as java.util.Map
            MemoryRecordSet {
               records: [mr]

  • Synchronized and java.util.ConcurrentModificationException

    Hi,
    I keep getting a java.util.ConcurrentModificationException when running the following code:
    ArrayList tObjects = ...
    synchronized (tObjects) {
    Iterator tObjectsIterator = tObjects.iterator();
    while (tObjectsIterator.hasNext()) {
    Object tObject = tObjectsIterator.next(); -----> Exception
    I run synchronized on tObjects so I can't understand why (and how) I get the Exception, can anyone help?
    Thanks,
    Iggy

    thanks for the help, I still have some difficulties:
    I have a (static) class ObjectsHolder which holds an ArrayList tObjects, I have various methods that access the ArrayList and return one/some elements.
    I would like to synchrinize on the ArrayList tObjects in ObjectsHolder, but the holder returns the ArrayList itself I am unsure whether the access to the ArrayList will be synchronized even in the calling method.
    A.

Maybe you are looking for

  • LR 5.4 and Win 8.1 Update 1 - LR wont launch

    I've been running a trial version of LR5.4 while waiting for the boxed version to come.  There are still 21 days left on the trial. Under Windows 8.1 LR worked every time, however since applying Update 1, LR only launches once.  The second and subesq

  • Open a PDF file using PDF reader

    Hi All, How to open a dynamique adresse of pdf files with adobe reader and not with the browser using URLLoader Thanks, Amine

  • Can't Open Library In iTunes

    I have not been able to open up my library in iTunes. I tried to reinstall it, I did it successfully, it is the most updated version. I just can't open the window to see my songs. This is getting frustrating. Can anyone help?

  • Error Setting up Xcelcius 2008 trial

    Hi, I have downloaded a trial version of Xcelsius 2008 from: http://www.sdn.sap.com/irj/uac/library-bi#section11 http://downloads.businessobjects.com/akdlm/xcelsius/Xcelsius_Engage_30day_trial.zip When the setup is run the following error occurs: u20

  • How to Fill in Forms on Ipad w/Adobe Ideas

    I read an Apple post (Apple - iPad in Business - Profiles - Dr. Jonathan Ferencz) about a prosthodontist who uses AI w/Ipads for his patient files. According to the post, the combination enables patients to fill in their intake forms on the Ipad I in