C++ key iteration

Hi,
I realise you're still finalising the documentation and various areas may be a little sparse at the moment. With this in mind I was wondering if you could help me out the manipulation of some of your classes.
I want to iterate over all the keys in a given cache. I found these two functions.
virtual Set::View keySet      (           )      const [pure virtual]
virtual Set::Handle keySet      (           )      [pure virtual]
The documentation seems to be the same for both, so I'm unsure which one to use.
Secondly once I use one of these methods, whats the correct way of iterating over a View/Handle in order to return the keys. Assume all my keys are strings.
Thanks
Rich

Thanks again Mark. Sadly I'm not familiar with the java side of things, I'm coming to this new and from a c++ point of view.
It's difficult to see how the various classes fit together (but I am learning :)).
As I want all of the items stored in a cache I'm trying to use the AllFilter (which I assume returns all the results?)
However when I use it an exception is thrown. I think it causes a problem on the server as an exception is thrown there also.
Here's the code;
     Filter::View          vAll = AllFilter::create();
Set::View vSetResult2 = hCache->entrySet(vAll);
Maybe I'm missing something ...
Here's the exception on the server;
2008-10-17 11:26:21.809 Oracle Coherence GE 3.4/397 (Pre-release) <D5> (thread=P
roxy:ProxyService:TcpAcceptorWorker:0, member=1): An exception occurred while pr
ocessing a QueryRequest for Service=Proxy:ProxyService:TcpAcceptor: (Wrapped: Fa
iled request execution for DistributedCache service on Member(Id=1, Timestamp=20
08-10-17 10:20:56.025, Address=10.1.45.224:8088, MachineId=9952, Location=site:e
uro.net.intra,machine:LONW00051451,process:76788, Role=CoherenceServer)) java.la
ng.NullPointerException
at com.tangosol.util.filter.ArrayFilter.calculateFilters(ArrayFilter.jav
a:87)
at com.tangosol.util.filter.AllFilter.applyIndex(AllFilter.java:100)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.g
rid.DistributedCache$Storage.query(DistributedCache.CDB:28)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.g
rid.DistributedCache.onQueryRequest(DistributedCache.CDB:23)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.g
rid.DistributedCache$QueryRequest.run(DistributedCache.CDB:1)
at com.tangosol.coherence.component.net.message.requestMessage.Distribut
edCacheRequest.onReceived(DistributedCacheRequest.CDB:12)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.G
rid.onMessage(Grid.CDB:9)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.G
rid.onNotify(Grid.CDB:130)
at com.tangosol.coherence.component.util.daemon.queueProcessor.service.g
rid.DistributedCache.onNotify(DistributedCache.CDB:3)
at com.tangosol.coherence.component.util.Daemon.run(Daemon.CDB:37)
at java.lang.Thread.run(Unknown Source)

Similar Messages

  • Key iteration via cursor

    Hi all,
    While looking at the documentation, I have been unable to find a way to iterate over the keys of a database without loading the values. Did I miss something or is this not possible? If not possible, are there any plans to change this?
    The reason I ask is that BDB JE is used as the default back-end for Voldemort (http://project-voldemort.com/) and for certain admin functions, it's useful to be able to work out which nodes have which keys. It would be nice to be able to do this without loading the values.
    Best,
    Ismael

    Ismael, no it is not possible with JE today. It will be possible in a future release, but only if ReadUncommitted is used.
    --mark                                                                                                                                                                                                                                                                           

  • Problem in enc/dec with DSA-Elgamal (keys generated using GNUPG utility)

    Hi all
    Facing the problem in encryption/decryption using DSA-Elgamal (keys generated using GNUPG utility)
    Steps followed
    Generated a key pair using DSA and Elgamal (default) form GNUPG utility (size 1024)
    Placed generated keys pubring.gpg & secring.gpg in the source directory where the code is executing but am getting the error
    D:\test>c:\jdk\bin\java BouncyCastlePGPTest
    Creating a temp file...
    Temp file created at
    D:\test\pgp
    Reading the temp file to make sure that the bits were written
    the message I want to encrypt
    Get Public Key
    Key Strength = 1024
    Algorithm = 17
    mohankumar (start) <[email protected]>
    Key Count = 1
    In Ecrypt File
    creating comData...
    comData created...
    using PGPEncryptedDataGenerator...
    111...
    java.lang.IllegalArgumentException: passed in key not an encryption key!f
    D:\test>
    but the same code works fine if we try to encrypt using RSA generated keys
    D:\test>c:\jdk\bin\java BouncyCastlePGPTest
    Creating a temp file...
    Temp file created at
    D:\test\pgp
    Reading the temp file to make sure that the bits were written
    the message I want to encrypt
    Get Public Key
    Key Strength = 1024
    Algorithm = 1
    sriganesh (sriganesh) <[email protected]>
    Key Count = 1
    In Ecrypt File
    creating comData...
    comData created...
    using PGPEncryptedDataGenerator...
    used PGPEncryptedDataGenerator...
    wrote bOut to byte array...
    Reading the encrypted file
    -----BEGIN PGP MESSAGE-----
    Version: BCPG v1.31
    hIwD7qqzP41CKpUBBACOnQE265ud3AuJ8zGx9TjUFyeSwZH+PZJhjGLBTkI7gKdh
    /hIF1u/sCzubw+9Mt8dbS0V2uHiqQgkCHAYIQKoVmiN65s8sUsIS0q3cTtBudUnd
    xIEiyegtvB8LEpzldU/XrSglh8h6MdhhcPql46BG+0vs6p/bUAOygNv5e/DGzck2
    1wNvc2/u2ffBgEP4qfrJUcF9OlvVAm03aB0S6gP8cH4LVdo5K9Bwu3d71qNKsryP
    mML16rkA
    =lfxf
    -----END PGP MESSAGE-----
    Decrypted Data= the message I want to encrypt
    no message integrity check
    Code As follows
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.security.NoSuchProviderException;
    import java.security.SecureRandom;
    import java.security.Security;
    import org.bouncycastle.bcpg.ArmoredOutputStream;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
    import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
    import org.bouncycastle.openpgp.PGPException;
    import org.bouncycastle.openpgp.PGPLiteralData;
    import org.bouncycastle.openpgp.PGPPublicKey;
    import org.bouncycastle.openpgp.PGPPublicKeyRing;
    import org.bouncycastle.openpgp.PGPUtil;
    import org.bouncycastle.openpgp.*;
    import java.util.Iterator;
    public class BouncyCastlePGPTest {
    private static PGPPrivateKey findSecretKey(
                                                      InputStream keyIn,
                                                      long keyID,
                                                      char[] pass)
                                                      throws IOException, PGPException, NoSuchProviderException {
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
    if (pgpSecKey == null) {
    return null;
    return pgpSecKey.extractPrivateKey(pass, "BC");
    private static void decryptFile(InputStream in, InputStream keyIn, char[] passwd) throws Exception
    in = PGPUtil.getDecoderStream(in);
    try {
    PGPObjectFactory pgpF = new PGPObjectFactory(in);
    PGPEncryptedDataList enc;
    Object o = pgpF.nextObject();
    // the first object might be a PGP marker packet.
    if (o instanceof PGPEncryptedDataList)
    enc = (PGPEncryptedDataList)o;
    else
    enc = (PGPEncryptedDataList)pgpF.nextObject();
    // find the secret key
    Iterator it = enc.getEncryptedDataObjects();
    PGPPrivateKey sKey = null;
    PGPPublicKeyEncryptedData pbe = null;
    while (sKey == null && it.hasNext())
    pbe = (PGPPublicKeyEncryptedData)it.next();
    sKey = findSecretKey(keyIn, pbe.getKeyID(), passwd);
    if (sKey == null)
    throw new IllegalArgumentException("secret key for message not found.");
    InputStream clear = pbe.getDataStream(sKey, "BC");
    PGPObjectFactory plainFact = new PGPObjectFactory(clear);
    Object message = plainFact.nextObject();
    if (message instanceof PGPCompressedData)
    PGPCompressedData cData = (PGPCompressedData)message;
    PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());
    message = pgpFact.nextObject();
    if (message instanceof PGPLiteralData)
    PGPLiteralData ld = (PGPLiteralData)message;
    FileOutputStream fOut = new FileOutputStream(ld.getFileName());
    InputStream unc = ld.getInputStream();
    int ch;
    System.out.print("\n\n\nDecrypted Data= ");
    while ((ch = unc.read()) >= 0)
                             System.out.print(""+(char)ch);
    fOut.write(ch);
    System.out.println("\n\n\n");
    else if (message instanceof PGPOnePassSignatureList)
    throw new PGPException("encrypted message contains a signed message - not literal data.");
    else
    throw new PGPException("message is not a simple encrypted file - type unknown.");
    if (pbe.isIntegrityProtected())
    if (!pbe.verify())
    System.err.println("message failed integrity check");
    } else
    System.err.println("message integrity check passed");
    else
    System.err.println("no message integrity check");
    catch (PGPException e) {
    System.err.println(e);
    if (e.getUnderlyingException() != null) {
    e.getUnderlyingException().printStackTrace();
         public static void main(String[] args) {
              // the keyring that holds the public key we're encrypting with
              String publicKeyFilePath = "D:\\test\\pubring.gpg"; //D:\\test\\pubring.pkr;
              // init the security provider
              Security.addProvider(new BouncyCastleProvider());
              try {
                   System.out.println("Creating a temp file...");
                   // create a file and write the string to it
                   File outputfile = new File("pgp");//File.createTempFile("pgp", null);
                   FileWriter writer = new FileWriter(outputfile);
                   writer.write("the message I want to encrypt".toCharArray());
                   writer.close();
                   System.out.println("Temp file created at ");
                   System.out.println(outputfile.getAbsolutePath());
                   System.out.println("Reading the temp file to make sure that the bits were written\n----------------------------");
                   BufferedReader isr = new BufferedReader(new FileReader(outputfile));
                   String line = "";
                   while ((line = isr.readLine()) != null) {
                        System.out.println(line + "\n");
                   // read the key
                   FileInputStream     in = new FileInputStream(publicKeyFilePath);
                   PGPPublicKey key = readPublicKey(in);
                   // find out a little about the keys in the public key ring
                   System.out.println("Key Strength = " + key.getBitStrength());
                   System.out.println("Algorithm = " + key.getAlgorithm());
                   int count = 0;
                   for (java.util.Iterator iterator = key.getUserIDs(); iterator.hasNext();) {
                        count++;
                        System.out.println((String)iterator.next());
                   System.out.println("Key Count = " + count);
                   // create an armored ascii file
                   FileOutputStream out = new FileOutputStream(outputfile.getAbsolutePath() + ".asc");
                   // encrypt the file
                   encryptFile(outputfile.getAbsolutePath(), out, key);
                   System.out.println("Reading the encrypted file\n----------------------------");
                   BufferedReader isr2 = new BufferedReader(new FileReader(new File(outputfile.getAbsolutePath() + ".asc")));
                   String line2 = "";
                   while ((line2 = isr2.readLine()) != null) {
                        System.out.println(line2);
    //FileInputStream in = new FileInputStream(args[1]);
              FileInputStream in2 = new FileInputStream("d:\\test\\pgp.asc");
         FileInputStream keyIn = new FileInputStream("d:\\test\\secring.gpg");
         decryptFile(in2, keyIn, "test123".toCharArray());
              } catch (PGPException e) {
                   System.out.println(e.toString());
                   System.out.println(e.getUnderlyingException().toString());
              } catch (Exception e) {
                   System.out.println(e.toString());
         private static PGPPublicKey readPublicKey(InputStream in) throws IOException {
              System.out.println("Get Public Key");
              try {
                   PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in);
                   Iterator itr = pgpPub.getPublicKeys();
                   PGPPublicKey pk = null;
                   return pgpPub.getPublicKey();
              } catch (IOException io) {
                   System.out.println("readPublicKey() threw an IOException");
                   System.out.println(io.toString());
                   throw io;
         private static void encryptFile(String fileName, OutputStream out, PGPPublicKey encKey)
    //     throws IOException, NoSuchProviderException, PGPException
              try {
    System.out.println("In Ecrypt File");
              out = new ArmoredOutputStream(out);
              ByteArrayOutputStream bOut = new ByteArrayOutputStream();
              System.out.println("creating comData...");
              // get the data from the original file
              PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
              PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
              comData.close();
              System.out.println("comData created...");
              System.out.println("using PGPEncryptedDataGenerator...");
              // object that encrypts the data
              PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");
              cPk.addMethod(encKey);
              System.out.println("used PGPEncryptedDataGenerator...");
              // take the outputstream of the original file and turn it into a byte array
              byte[] bytes = bOut.toByteArray();
              System.out.println("wrote bOut to byte array...");
              // write the plain text bytes to the armored outputstream
              OutputStream cOut = cPk.open(out, bytes.length);
              cOut.write(bytes);
              // cOut.close();
              cPk.close();
              out.close();
              } catch (IOException ex) {
                   System.out.println("IOException\t" +ex.toString());
              } catch (NoSuchProviderException ex1) {
                   System.out.println("NoSuchProviderException\t" +ex1.toString());
              } catch (PGPException ex2) {
                   System.out.println("PGPException\t" +ex2.toString());
    }

    First - you're responding to a year-old message. I doubt the OP is still around.
    Second - DSA is a Digital Signature Algorithm. The error tells you exactly what the problem is - DSA is not an encryption algorithm, and can't be used as one.
    Grant

  • (quick question)adding key value pairs to hashtable

    I know I can create a hashtable and add key value pairs to it with
    Hashtable numbers = new Hashtable();
    numbers.put("one", new Integer(1));
    numbers.put("two", new Integer(2));
    numbers.put("three", new Integer(3));
    But this is somewhat annoying when I want to add alot of elements. Is there a way to add the elements when I initialize the table. Perhaps something like
    Hashtable numbers =
    new HashTable("one",new Integer(1),"two",new Integer(2) )

    If you don't see such a ctor in the javadocs, then there's no easy way to do it.
    You'll just have to create two Collections of key, value pairs and add them in programmatically yourself:
    import java.util.*;
    public class MapLoader
        public static void main(String [] args)
            if ((args.length > 0) && (args.length % 2 == 0))
                List keys = new ArrayList();
                List values = new ArrayList();
                for (int i = 0; i < args.length; )
                    keys.add(args[i++]);
                    values.add(args[i++]);
                MapLoader mapLoader = new MapLoader();
                System.out.println(mapLoader.loadMap(keys, values));
        public Map loadMap(final Collection keys, final Collection values)
            if (keys.size() != values.size())
                throw new IllegalArgumentException("Must have a key for every value and visa versa");
            Map result = new HashMap(keys.size());
            Iterator keysIter = keys.iterator();
            Iterator valuesIter = values.iterator();
            while (keysIter.hasNext() && valuesIter.hasNext())
                result.put(keysIter.next(), valuesIter.next());
            return result;
    }MOD

  • Get a Hashtable key given a value

    hi,
    can anyone tell me how I get a the key of Hashtable value given the value. I cant see anything in the api, and having been trying to figure this out for hours.
    Hashtable numbers = new Hashtable();
    numbers.put("one", new Integer(1));
    numbers.put("two", new Integer(2));
    numbers.put("three", new Integer(3));
    if say I had value Integer 2, how can I find the key of this if I didn't know the key.

    I prefer HashMaps. You have to look for it yourself.import java.util.*;
    public class Test3 {
      public static void main(String[] args) {
        String[] data = {"Zero","One","Two","Three","Four","Five","Six"};
        HashMap hm = new HashMap();
        for (int i=0; i<data.length; i++) hm.put(data, new Integer(i));
    Random rand = new Random();
    Set keys = hm.keySet();
    for (int i=0; i<10; i++) {
    Integer value = new Integer(rand.nextInt(data.length));
    System.out.println("Looking for "+value);
    for (Iterator iter=keys.iterator(); iter.hasNext();) {
    Object key = iter.next();
    if (value.equals(hm.get(key))) {
    System.out.println(" Found key '"+key+"' with value '"+value+"'");
    }You might think about a reverse hashmap or else letting us know what you are trying to do.

  • Key existence test

    Hi,
         I'd like to be able to test for existence of a key and, unlike NamedCache.containsKey() that seems to only test against cached keys, I'd like to know whether or not the key exists in the underlying database. Clearly, it would be quite expensive to use NamedCache.get() for such tests especially if, as it is in my case, most of the tests would be positive. Doing so will most likely result in cache thrashing and excessive load on the database.
         What is the best way to implement the deep key existence test?
         I'd like to believe there is a reason NamedCache.containsKey() is implemented this way (even though I have no clue what the reason might be). Ideally, NamedCache.containsKey() method should delegate to the cache loader if the key is not present in the map. The CacheLoader interface would have to be extended to support two new methods: one to test against keys and another to test against values.
         Thanks
         Andrew

    Hi Andrew,
         in this case, I suggest you simply put a unique constraint on the login name field (if it is not the primary key anyway), and try to insert it, when the data is filled in, and handle the resulting error if it is already taken.
         Any prevalidation is not a fully reliable check instead of a unique constraint, as another user can commit the registering transaction which takes the requested login name after your validation but before your commit. In this case you would end up with two or more identical login names if you don't have a unique constraint or the primary key on the login name.
         If you really want to find out that a user name is taken without trying to write the user name, then I suggest that you go to the DB with JDBC directly (if it is accepted by your architecture).
         If you don't have DB connectivity on the tier where you put your business logic, then make a read-through cache with automatic eviction (to allow for a stubborn user). The CacheLoader instance of the read-through cache should be something like the following:
                  package test;
             import java.sql.Connection;
             import java.sql.PreparedStatement;
             import java.sql.ResultSet;
             import java.sql.SQLException;
             import java.util.Collection;
             import java.util.HashMap;
             import java.util.Iterator;
             import java.util.Map;
             import com.tangosol.net.cache.CacheLoader;
             public class IdentityCheckCacheLoader implements CacheLoader {
                 private static final String TABLENAME = "user_table";
                 private static final String LOGINNAME_COLUMN = "login_name";
                 private static final String CHECK_STATEMENT =
                     "SELECT 1 FROM "+TABLENAME+" WHERE "+LOGINNAME_COLUMN+"=?";
                     // if there is a unique index on the login_name column, then this is sort of optimal
                 private Connection getConnection() throws SQLException {
                     Connection conn = null;
                     // put your JDBC connection acquiring code here
                     // (you should probably use a connection pool, as there can be multiple threads
                     //  operating on the cache loader at the same time)
                     return conn;
                 private PreparedStatement prepare(Connection conn) throws SQLException {
                     return conn.prepareStatement(CHECK_STATEMENT);
                 public Object load(Object key) {
                     try {
                         Connection conn = getConnection();
                         PreparedStatement stat = null;
                         if (conn != null) {
                             try {
                                 stat = prepare(conn);
                                 return doGetById(stat, key);
                             } finally {
                                 if (stat != null) {
                                     try {
                                         stat.close();
                                     } catch (SQLException e) {
                                         // ignore close problem
                                 try {
                                     conn.close();
                                 } catch (SQLException e) {
                                     // ignore close problem
                     } catch (Exception e) {
                         // log error here
                     return null;
                 private Object doGetById(PreparedStatement stat, Object key) throws SQLException {
                     stat.setString(1, (String) key); // key is the login name
                     ResultSet rs = stat.executeQuery();
                     try {
                         return rs.next()?Boolean.TRUE:Boolean.FALSE;
                     } finally {
                         rs.close();
                 public Map loadAll(Collection keys) {
                     // naive implementation, could be optimized to be a minimal number of selects
                     Map result = new HashMap();
                     try {
                         final Connection conn = getConnection();
                         PreparedStatement stat = null;
                         if (conn != null) {
                             try {
                                 stat = prepare(conn);
                                 Iterator iter = keys.iterator();
                                 while (iter.hasNext()) {
                                     Object key = iter.next();
                                     result.put(key, doGetById(stat, key));
                             } finally {
                                 if (stat != null) {
                                     try {
                                         stat.close();
                                     } catch (SQLException e) {
                                         // ignore close problem
                                 try {
                                     conn.close();
                                 } catch (SQLException e) {
                                     // ignore close problem
                     } catch (Exception e) {
                         // log error here
                     return result;
                       You should refer to this class into your cache configuration (see this url for a config example: http://wiki.tangosol.com/display/COH32UG/Read-Through%2C+Write-Through%2C+Refresh-Ahead+and+Write-Behind+Caching )
         Note that this will cache the information that the login name is already used. Therefore you should also configure an automatic eviction policy so that this cache does not grow to an unlimited size.
         Of course, this is only my 2 cents.
         BR,
         Robert Varga

  • Get textbox values from ADF table

    Hi,
    I have af:table with input Textbox as a single column in which user can enter values.
    I have applied valuechangelistener for textbox using which I can get values entered by user.
    Say I have multiple rows. When valuechangelistener is called, I get only current entered value. Whereas I need all the values entered by user in all the textboxes.
    How I can implement this?

    HI try this:
    1) make binding of your table
    2)make rowSelection="multiple" on table
    3)select multiple rows for which you want data using ctrl.
    4)add below code in method of backing bean on actionlistener of some button say save or edit
    UIXTable table = getSearchResultsTable();
    //getting iterator to iterate over selected row keys
    Iterator selection = table.getSelectedRowKeys().iterator();
    while (selection.hasNext()) {
    Object rowKey = selection.next();
    //setting the rowKey to table one by one
    table.setRowKey(rowKey);
    String strRow=(String) table.getRowData();
    //then you can add this in list or whatever you want
    }

  • Unable to schedule a report to email and print

    I have been working on a task to both print and email a report to recipients whose email addresses are obtained at runtime.  So far I am able to email the report as a PDF attachment, however, I am not able to get the report to print.  I have three thoughts as to why the report is not printing.
    1. The printer is in a subdomain under the domain where InfoView and the Enterprise server reside.
    2. It is not possible to schedule a report for both an SMTP and print destination simultaneously.
    3. The format is causing an issue in printing - the SDK API states "Printer is a report format specific destination and can only be used when the report object is a Crystal Report."
    I have looked at the scheduled report in InfoView and can see that the print settings I am passing are correctly set for the scheduled instance.  Does anyone know if there is a problem with trying to schedule printing and email at the same time, or if the report format must be .rpt?
    Below is my code. Thank you for your time.
    String query = "Select SI_ID, SI_NAME, SI_PROCESSINFO, SI_SCHEDULEINFO, SI_SCHEDULE_STATUS From CI_INFOOBJECTS Where SI_ID=" + reportId;
            IInfoObjects results = null;
            ISchedulingInfo schedulingInfo = null;
            try {       
               results = iStore.query(query);           
            } catch( SDKException sdke ){
               logger.error(sdke);
            if( !results.isEmpty() ){
                // get the actual report object from collection and set scheduling information
                IInfoObject report = (IInfoObject)results.get(0);
                schedulingInfo = report.getSchedulingInfo();
                schedulingInfo.setType(CeScheduleType.ONCE);
                schedulingInfo.setRightNow(true);
                schedulingInfo.setRetriesAllowed(3);           
                try {
                    Set<String> keys = destinations.keySet();
                    Iterator i = keys.iterator();
                    while( i.hasNext() ){
                        String dest = (String) i.next();
                        if(dest.equals(CrystalDestinations.EMAIL)){
                            // get the destination object and set it to SMTP plugin
                            List emailAddress = destinations.get(CrystalDestinations.EMAIL);
                            IDestination destinationObject = schedulingInfo.getDestination();
                            destinationObject.setName("CrystalEnterprise.SMTP");    
                            IDestinationPlugin smtpPlugin = (IDestinationPlugin) iStore.query("SELECT * FROM CI_SYSTEMOBJECTS WHERE SI_PARENTID = 29 AND SI_NAME='CrystalEnterprise.SMTP'").get(0);
                            ISMTPOptions smtpOptions = (ISMTPOptions) smtpPlugin.getScheduleOptions();
                            smtpOptions.setDomainName( emailDomain );
                            smtpOptions.setServerName( smtpHost );
                            smtpOptions.setSMTPUserName( smtpUser );
                            smtpOptions.setSMTPPassword( smtpPass );
                            smtpOptions.setSubject( "Email for report " + report.getTitle() );
                            smtpOptions.setMessage( "This is the message body" );
                            smtpOptions.setSenderAddress( smtpUser + "@cdrh.fda.gov" );
                            smtpOptions.setSMTPAuthenticationType( ISMTPOptions.CeSMTPAuthentication.LOGIN );
                            for(int j = 0; j < emailAddress.size(); j++ ){
                                smtpOptions.getToAddresses().add( emailAddress.get(j) );
                            destinationObject.setFromPlugin( smtpPlugin );                                                                               
    } else if ( dest.equals(CrystalDestinations.PRINT) ){
                            List printers = destinations.get( CrystalDestinations.PRINT );                   
                            IReportPrinterOptions printerOptions = ((IReport)report).getReportPrinterOptions();
                            printerOptions.setCopies(1);
                            printerOptions.setEnabled(false);
                            printerOptions.setPrinterName( (String)printers.get(0) );                   
                            printerOptions.setPageLayout(IReportPrinterOptions.CeReportLayout.USE_SPECIFIED_PRINTER_SETTING);
                    List reportPrompts = ((IReport)report).getReportParameters();
                    for(int j = 0; j < reportPrompts.size(); j++){
                        IReportParameter prompt = (IReportParameter) reportPrompts.get(j);                   
                        if(prompt.getParameterName().equals(mdrParamName)){
                          IReportParameterSingleValue v = prompt.getCurrentValues().addSingleValue();
                          v.setValue(reportParameters.get(mdrParamName));
                        } else if(prompt.getParameterName().equals(addressParamName)){
                            IReportParameterSingleValue v = prompt.getCurrentValues().addSingleValue();
                            v.setValue(reportParameters.get(addressParamName)); 
                    IReportFormatOptions format = ( (IReport) report).getReportFormatOptions();
                    format.setFormat(IReportFormatOptions.CeReportFormat.PDF);
                    iStore.schedule( results );

    Hi Jason,
    Based on your code, I could not tell if you were scheduling a Crystal Report or a WebI document.
    Regardless, what I would suggest is you try scheduling the report/document on InfoView.
    Once you schedule it on InfoView, you can retrieve the instance on Query Builder (or through code) and compare the properties that are being set through InfoView and the one you set through your code.
    This should indicate if you are missing some properies or have set some properties incorrectly.
    Hope this helps.
    Regards,
    Dan

  • Cannot sort child rows in multilevel tree table

    Hi,
    I originally hijacked a two-year-old forum thread that was vaguely similar to my issue, but a kind forum moderator split my post away
    (and deleted my other hijack post asking this same question)
    so that my inquiry might be viewable on its own.
    Hopefully someone can pay attention to my issue instead of getting it confused with those other old forum threads.
    So, here we go ...
    Is sorting in a treeTable at a particular level possible? Just want to let you I have tried the following approaches to do this. But it dis not work for me.
    I have tree table with 2 levels. I am trying to sort the child rows based on its column say "Display Sequence".
    User can type in number in this column which contains input text. On value change event of the this field, all the
    child rows in the level 2 need to be sorted. This needs to be done without committing the data. On commit it works,
    because it sorts based on order by clause. I want the child rows to be sorted on value change event. Following
    various approaches I tried.
    TreeModel tModel = (TreeModel)treeTable.getValue();
    SortCriterion sortCriterion = new SortCriterion("DisplaySequence",true);
    List<SortCriterion> sortCriteriaList = new ArrayList<SortCriterion>();
    sortCriteriaList.add(sortCriterion);
    tModel.setSortCriteria(sortCriteriaList);
    The above code does not work, As "DisplaySequence" is not available in the parent view object.
    Here is approach no 2
    JUCtrlHierBinding treeTableBinding = null;
    JUCtrlHierNodeBinding nodeBinding = null;
    JUCtrlHierNodeBinding parentNodeBinding = null;
    JUCtrlHierTypeBinding nodeHierTypeBinding = null;
    Key rowKey;
    Object dispSeqObj;
    Number displaySequence = null;
    Map<Key,Number> keyValueMap = null;
    Set<Key> emptyValueKeySet = null;
    Map<Key,Number> sortedKeyValueMap = null;
    DCIteratorBinding target = null;
    Iterator iter = null;
    int rowIndex = 1;
    RowSetIterator rsi = null;
    Row currentRow = null;
    Row row = null;
    RowKeySet selectedRowKey = lookupTreeTable.getSelectedRowKeys();
    Iterator rksIterator = selectedRowKey.iterator();
    if (rksIterator.hasNext()) {
    List key = (List)rksIterator.next();
    System.out.println("key :"+key);
    treeTableBinding = (JUCtrlHierBinding) ((CollectionModel)lookupTreeTable.getValue()).getWrappedData();
    nodeBinding = treeTableBinding.findNodeByKeyPath(key);
    parentNodeBinding = nodeBinding.getParent();
    //rsi = nodeBinding.getParentRowSetIterator();
    rsi = parentNodeBinding.getChildIteratorBinding().getRowSetIterator();
    keyValueMap = new LinkedHashMap<Key,Number>();
    emptyValueKeySet = new LinkedHashSet<Key>();
    // Gets the DisplaySequence by iterating through the child rows
    while(rsi.hasNext()) {
    if(rowIndex==1)
    row = rsi.first();
    else
    row = rsi.next();
    rowKey = row.getKey();
    dispSeqObj = row.getAttribute("DisplaySequence");
    if(dispSeqObj!=null && dispSeqObj instanceof Number) {
    displaySequence = (Number)dispSeqObj;
    keyValueMap.put(rowKey, displaySequence);
    }else {
    emptyValueKeySet.add(rowKey);
    rowIndex++;
    rowIndex = 0;
    // Sort the numbers using comparator
    DisplaySequenceComparator dispSeqComparator = new DisplaySequenceComparator(keyValueMap);
    sortedKeyValueMap = new TreeMap<Key,Number>(dispSeqComparator);
    sortedKeyValueMap.putAll(keyValueMap);
    rsi.reset();
    nodeHierTypeBinding = nodeBinding.getHierTypeBinding();
    System.out.println("nodeHierTypeBinding :"+nodeHierTypeBinding);
    String expr = nodeHierTypeBinding.getTargetIterator();
    if (expr != null) {
    Object val = nodeBinding.getBindingContainer().evaluateParameter(expr, false);
    if (val instanceof DCIteratorBinding) {
    target = ((DCIteratorBinding)val);
    ViewObject targetVo = target.getViewObject();
    System.out.println("targetVo :"+targetVo);
    targetVo.setAssociationConsistent(true);
    //ri = target.findRowsByKeyValues(new Key[]{rowData.getRowKey()});
    rsi = parentNodeBinding.getChildIteratorBinding().getRowSetIterator();
    //rsi = nodeBinding.getParentRowSetIterator();
    // Rearrange the tree rows by inserting at respective index based on sorting.
    ViewObject vo = nodeBinding.getViewObject();
    iter = sortedKeyValueMap.keySet().iterator();
    while(iter.hasNext()) {
    currentRow = rsi.getRow((Key)iter.next());
    rsi.setCurrentRow(currentRow);
    rsi.setCurrentRowAtRangeIndex(rowIndex);
    //rsi.insertRowAtRangeIndex(rowIndex, currentRow);
    rowIndex++;
    iter = emptyValueKeySet.iterator();
    while(iter.hasNext()) {
    currentRow = rsi.getRow((Key)iter.next());
    rsi.setCurrentRow(currentRow);
    rsi.setCurrentRowAtRangeIndex(rowIndex);
    //rsi.insertRowAtRangeIndex(rowIndex, currentRow);
    rowIndex++;
    rsi.closeRowSetIterator();
    AdfFacesContext.getCurrentInstance().addPartialTarget(treeTable);
    private class DisplaySequenceComparator implements Comparator {
    Map<Key,oracle.jbo.domain.Number> dispSeqMap = null;
    public DisplaySequenceComparator(Map<Key,oracle.jbo.domain.Number> dispSeqMap) {
    this.dispSeqMap = dispSeqMap;
    public int compare(Object a, Object b) {
    Key key1 = (Key)a;
    Key key2 = (Key)b;
    oracle.jbo.domain.Number value1 = dispSeqMap.get(key1);
    oracle.jbo.domain.Number value2 = dispSeqMap.get(key2);
    if(value1.getValue() > value2.getValue()) {
    return 1;
    } else if(value1.getValue() == value2.getValue()) {
    return 0;
    } else {
    return -1;
    In the above code I tried to perform sorting of DisplaySequence values using comparator, then tried to rearrange
    nodes or rows based on sort resurts. But rsi.insertRowAtRangeIndex(rowIndex, currentRow) give
    DeadViewException...unable to find view reference. While setting current row also does not work.
    Approach 3.
    DCIteratorBinding iter1 =
    bindings.findIteratorBinding("childIterator");
    iter1.executeQuery();
    SortCriteria sc = new SortCriteriaImpl("DisplaySequence",false);
    SortCriteria [] scArray = new SortCriteria[1];
    scArray[0] = sc;
    iter1.applySortCriteria(scArray);
    Any help in Sorting Child nodes ADF treeTable is appreciated. Thanks in Advance.
    Abhishek

    Hi Frank,
    Thanks for your reply. I have tried similar approach for sorting tree table child rows based on user specified number and it works. But there is a limitation for this. This sorting works only for read only/transient view object. For updatable view object after sorting, data cannot be saved or updated, as it cannot find the rowid. Here is what I tried
    In the ParentViewImpl class,
    1. overrode the method createViewLinkAccessorRS, so that this method is forcefully executed.
    @Override
    protected ViewRowSetImpl createViewLinkAccessorRS(AssociationDefImpl associationDefImpl,
    oracle.jbo.server.ViewObjectImpl viewObjectImpl,
    Row row,
    Object[] object) {
    ViewRowSetImpl viewRowSetImpl = super.createViewLinkAccessorRS(associationDefImpl, viewObjectImpl, row, object);
    return viewRowSetImpl;
    2. Added the following method, which will be invoked on valueChange of DisplaySequence in child row. Expose this method through client interface. This method accept a parameter i.e. parent row key of the child row.
    public void sortChildRecords(Key parentKey) {
    ViewObject viewObject = null;
    String type = null;
    if(parentKey==null) {
    Row [] row = this.findByKey(parentKey, 1);
    RowSet rowSet = (RowSet)row[0].getAttribute("ChildVO");
    viewObject = rowSet.getViewObject();
    viewObject.setSortBy("DisplaySequence asc");
    }else {
    Row row = getCurrentRow();
    RowSet rowSet = (RowSet)row.getAttribute("ChildVO");
    viewObject = rowSet.getViewObject();
    viewObject.setSortBy("DisplaySequence asc");
    this.setQueryMode(ViewObject.QUERY_MODE_SCAN_DATABASE_TABLES |
    ViewObject.QUERY_MODE_SCAN_ENTITY_ROWS);
    this.executeQuery();
    For custom sort, lets say all the numbers should be display first in ascending order, and null or empty values to be display at the end need to override the getRowComparator method in the ChildViewImpl class,
    Here is the code for the same
    @Override
    public Comparator getRowComparator() {
    SortCriteria sortCriteria = new SortCriteriaImpl("DisplaySequence",false);
    SortCriteria [] sortCriterias = new SortCriteria[1];
    sortCriterias[0] = sortCriteria;
    return new DisplaySequenceComparator(sortCriterias);
    private class DisplaySequenceComparator extends RowComparator {
    public DisplaySequenceComparator(SortCriteria [] sortCriterias) {
    super(sortCriterias);
    public int compareRows(Row row1, Row row2) {
    Object dispSeqObj1;
    Object dispSeqObj2;
    Number dispSeq1 = null;
    Number dispSeq2 = null;
    boolean compareRow1 = true;
    boolean compareRow2 = true;
    if(row1!=null) {
    dispSeqObj1 = row1.getAttribute("DisplaySequence");
    if(dispSeqObj1!=null && dispSeqObj1 instanceof Number) {
    dispSeq1 = (Number)dispSeqObj1;
    }else {
    compareRow1 = false;
    if(row2!=null) {
    dispSeqObj2 = row2.getAttribute("DisplaySequence");
    if(dispSeqObj2!=null && dispSeqObj2 instanceof Number) {
    dispSeq2 = (Number)dispSeqObj2;
    }else {
    compareRow2 = false;
    if(compareRow1 && compareRow2) {
    if(dispSeq1.getValue() > dispSeq2.getValue()) {
    return 1;
    } else if(dispSeq1.getValue() == dispSeq2.getValue()) {
    return 0;
    } else {
    return -1;
    if(!compareRow1 && compareRow2)
    return 1;
    if(compareRow1 && !compareRow2)
    return -1;
    return 0;
    The above solution works properly, and sorts the child tree rows. But while saving the changes, update fails. I also came to know that in-memory sorting is applicable to read-only/transient view objects from some blogs and also mentiond in this link http://docs.oracle.com/cd/E24382_01/web.1112/e16182/bcadvvo.htm
    Is there any way that updatable view objects can be sorted and saved as well?
    Thanks,
    Abhishek
    Edited by: 930857 on May 2, 2012 7:12 AM

  • Java.nio select() method return 0 in my client application

    Hello,
    I'm developing a simple chat application who echo messages
    But my client application loop because the select() method return 0
    This is my code
    // SERVER
    package test;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    public class Server {
         private int port = 5001;
         public void work() {               
              try {
                   ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                   serverSocketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(port);               
                   serverSocketChannel.socket().bind(isa);
                   Selector selector = Selector.open();
                   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                   System.out.println("Listing on "+port);
                   while(selector.select()>0) {
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isAcceptable()) {
                                  ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel();                              
                                  SocketChannel channel = keyChannel.accept();
                                  channel.configureBlocking(false);                              
                                  channel.register(selector, SelectionKey.OP_READ );
                             } else if (key.isReadable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel );
                                  Help.write(m.toUpperCase(), keyChannel );
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         public static void main(String[] args) {
              Server s = new Server();
              s.work();
    // CLIENT
    package test;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {               
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);               
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
                   while(true) {
                        selector.select();
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  if (keyChannel.isConnectionPending()) {
                                       System.out.println("Connected "+keyChannel.finishConnect());                                                                           
                             } else if (key.isReadable()) {                                                                                                                                                           
                                  SocketChannel keyChannel = (SocketChannel) key.channel();                                             
                                  String m = Help.read(keyChannel);
                                  display(m);                                                                                                                                                                                                                   
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {               
                   public void run() {                                                                                
                        try {                         
                             Help.write(m, socketChannel);
                        } catch (IOException e) {               
                             e.printStackTrace();
              t.start();                    
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);     
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();
    // HELPER CLASS
    package test;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    public class Help {
         private static Charset charset = Charset.forName("us-ascii");
         private static CharsetEncoder enc = charset.newEncoder();
         private static CharsetDecoder dec = charset.newDecoder();
         private static void log(String m) {
              System.out.println(m);
         public static String read(SocketChannel channel) throws IOException {
              log("*** start READ");                              
              int n;
              ByteBuffer buffer = ByteBuffer.allocate(1024);
              while((n = channel.read(buffer)) > 0) {
                   System.out.println("     adding "+n+" bytes");
              log("  BUFFER REMPLI : "+buffer);
              buffer.flip();               
              CharBuffer cb = dec.decode(buffer);          
              log("  CHARBUFFER : "+cb);
              String m = cb.toString();
              log("  MESSAGE : "+m);          
              log("*** end READ");
              //buffer.clear();
              return m;                    
         public static void write(String m, SocketChannel channel) throws IOException {          
              log("xxx start WRITE");          
              CharBuffer cb = CharBuffer.wrap(m);
              log("  CHARBUFFER : "+cb);          
              ByteBuffer  buffer = enc.encode(cb);
              log("  BUFFER ALLOUE REMPLI : "+buffer);
              int n;
              while(buffer.hasRemaining()) {
                   n = channel.write(buffer);                         
              System.out.println("  REMAINING : "+buffer.hasRemaining());
              log("xxx end WRITE");

    Here's the fix for that old problem. Change the work method to do the following
    - don't register interest in things that can't happen
    - when you connect register based on whether the connection is complete or pending.
    - add the OP_READ interest once the connection is complete.
    This doesn't fix all the other problems this code will have,
    eg.
    - what happens if a write is incomplete?
    - why does my code loop if I add OP_WRITE interest?
    - why does my interestOps or register method block?
    For code that answers all those questions see my obese post Taming the NIO Circus
    Here's the fixed up Client code
    // CLIENT
    package test
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   int interest = 0;
                   if(socketChannel.isConnected())interest = SelectionKey.OP_READ;
                   else if(socketChannel.isConnectionPending())interest = SelectionKey.OP_CONNECT;
                   socketChannel.register(selector, interest);
                   while(true)
                        int nn = selector.select();
                        System.out.println("nn="+nn);
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();)
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  System.out.println("Connected "+keyChannel.finishConnect());
                                  key.interestOps(SelectionKey.OP_READ);
                             if (key.isReadable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel);
                                  display(m);
              } catch (IOException e) {
                   e.printStackTrace();
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {
                   public void run() {
                        try {
                             Help.write(m, socketChannel);
                        } catch (IOException e) {
                             e.printStackTrace();
              t.start();
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();

  • Performance problem creating rows on viewobject

    Hi,
    When a user pushes a button in my Oracle ADF 11.1.1.3.0 GUI,
    he triggers a method in my backing bean.
    This method is called insertNewForecastTable, that takes a (Tree)Map called forecastMap as input. (see below)
    ( The key of this map is a Timestamp,
    the value of this map is an object ForecastEntry.
    A ForecastEntry consists out of 10 ForecastParts, and each Forecastpart contains 4 long values. )
    private void insertNewForecastTable(Map forecastMap) {
    DCBindingContainer bc = (DCBindingContainer)getBindings();
    DCIteratorBinding ForecastIter = bc.findIteratorBinding("ForecastViewIterator");
    DCDataControl dc = ForecastIter.getDataControl();
    ApplicationModule am = (ApplicationModule)dc.getDataProvider();
    ViewObject forecastVO = am.findViewObject("ForecastView");
    Set keys = forecastMap.keySet();
    Iterator keyIter = keys.iterator();
    RowSetIterator it = ForecastIter.getRowSetIterator();
    while (keyIter.hasNext()) {
    Long timestamp = (Long)keyIter.next();
    Timestamp ts = new Timestamp(timestamp);
    Row r = it.createRow();
    r.setAttribute(0, ts);
    ForecastEntry forecastentry = (ForecastEntry)forecastMap.get(timestamp);
    int j = 1;
    for (int i=0;i<10;i++) {
    ForecastPart forecastPart = forecastentry.getForecastPart(i);
    r.setAttribute(j,forecastPart.getHistory());
    j++;
    r.setAttribute(j,forecastPart.getForecast());
    j++;
    r.setAttribute(j,forecastPart.getTrend());
    j++;
    r.setAttribute(j,forecastPart.getLimit());
    j++;
    forecastVO.insertRow(r);
    am.getTransaction().commit();
    Configuration.releaseRootApplicationModule(am,true);
    Problem is : for 3360 entries in this table or viewobject, it takes 10 minutes (!!!) to complete this code.
    Bottleneck is the for-loop and the forecastVO.insertRow(r);
    Both timings are rising from 15 msec in the beginning to 500 msec at the end.
    Anyone has some ideas how to improve my performance ?
    Am I doing something wrong trying to create and insert 3360 rows in this table ?
    Thanks.

    Ok,
    My binding is back ok, so the nullpointer is gone.
    But the speed of processing 1000+ inserts into a table is still very poor.
    This is my code at the moment :
      +private void insertNewForecastTable(Map forecastMap) {+
        +DCBindingContainer bc = (DCBindingContainer)getBindings();+
        +DCIteratorBinding ForecastIter = bc.findIteratorBinding("ForecastViewIterator");+
        +DCDataControl dc  = ForecastIter.getDataControl();+
        +ApplicationModule am = (ApplicationModule)dc.getDataProvider();+
        +ViewObject forecastVO = am.findViewObject("ForecastView");+ 
        +RowSetIterator it = ForecastIter.getRowSetIterator();+
        +Set keys = forecastMap.keySet();+        
        +Iterator keyIter = keys.iterator();+
        +List nameList = new ArrayList();+
        +nameList.add("Timestamp");+
        +for (int i=1 ; i<=10; i ++) {+
          +String H = "H"+i;+
          +String F = "F"+i;+
          +String T = "T"+i;+
          +String L = "L"+i;+
          +nameList.add(H);+
          +nameList.add(F);+
          +nameList.add(T);+
          +nameList.add(L);+
        +}+
        +long time_begin = System.currentTimeMillis();+
        +int counter = 0;+
        +// for each timestamp+
        +while (keyIter.hasNext()) {+
          +// Get the timestamp.+
           +Long timestamp = (Long)keyIter.next();+
           +// convert long to timestamp+
           +Timestamp ts = new Timestamp(timestamp);+
           +// create new row in table+
           +Row r = it.createRow();+
          +List valueList = new ArrayList();+
          +valueList.add(ts);+
          +ForecastEntry forecastentry = (ForecastEntry)forecastMap.get(timestamp);+
          +for (int i=0;i<10;i++) {+
              +ForecastPart forecastPart = forecastentry.getForecastPart(i);+
              +valueList.add(forecastPart.getHistory());+
              +valueList.add(forecastPart.getForecast());+
              +valueList.add(forecastPart.getTrend());+
              +valueList.add(forecastPart.getLimit());+
          +}+
          +r.setAttributeValues(nameList, valueList);+
          +forecastVO.insertRow(r);+
          +counter++;+
          +if (counter % 100 == 0) {+
            +am.getTransaction().commit();+
            +System.out.println("Committing rows " + (counter-100) + " to " + counter );+
          +}+
        +}+
        +long time_end = System.currentTimeMillis();+
        +// commit+
        +am.getTransaction().commit();+
       +// Configuration.releaseRootApplicationModule(am,true);+
        +System.out.println("Total time to insert all rows : " + (time_end-time_begin ));+
      +}+It takes up to 500 seconds to insert 3000 rows !
    I also changed the update batch value from 100 to 5, but no difference.
    I'm now also committing every 100 rows.
    And at the end, I get a nullpointer exception at RowDataManager.getRowIndex(RowDataManager.java:191)
    All help welcome.

  • Show another page in the same page

    Hello
    I have the following case :
    Trinidad Page it includes A trinidad table of urls and in the same page i have an iframe .when the user select a row from the table :
    - the screen is submitted and display the selected URL in the iframe.
    What is the best way to do that.
    Regards

    Hi, The following assumes that you are using 'single' as the selection strategy for the table.
    try the following:
    1. declare a global variable iframeSource with getter and setter methods.
    2. set the autoSubmit property of the table to true
    3. add a selectionListener method to the table; and in that write the following code
    RowKeySet keys = table.getSelectedRowKeys();
    Iterator iterator = keys.iterator();
    while(iterator.hasNext()){
    Your-RowObject-Containing-URL urlobject =(Your-RowObject-Containing-URL) iterator.next(); // may be the object is simple string in your case.
    iframeSource=urlobject.getURL();
    4. wrap your iframe in a trinidad's panelGroupLayout or any other container component to make use of PPR :
    &lt;tr:panelGroupLayout partialTriggers="table-id" &gt;
    &lt;iframe src="#{your-backing-bean.iframeSource}" .... .... .... /&gt;
    &lt;/tr:panelGroupLayout&gt;
    With that, when ever a row is clicked in the table the content of the iframe gets updated with the content from the selected url.
    Edited by: saasira on Feb 19, 2009 5:25 AM

  • I can't seem to Print out the Object I made in this Map. Any ideas?

    Well here's my problem I'm trying to print out the Key's and Value's associated in the following MutliMap.
    The code formating seems to screw up < and >. My datastructure is a Multi Map, the Key is a String Object and
    the Value associated with that String Key is an ArrayList of an object of type Message I defined below.
    Map<String,List<Message>> = new HashMap<String,List<Message>>();
    Here's my code for where I try to Print everything (in the function print() ) .
    The Print just either prints out the KEY and no value, if I take out my ((Message)value) cast, it will print the Message class, like
    43343@Message because I'm assuming its wondering how to Print something that is an object I defined.
    Thats why I defined my own print function and I also override the toString() function but both don't work it seems.
    package parser;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.io.*;
    //this class should store all the Messages or "Events" and
    //you can access them based on their Serial key.
    public class MessageDB
         //database to hold the information
         //     holds the Alerts/messages
         Map<String, List<Message>> AlertMap;
         //Constructor
         MessageDB()
              AlertMap = new HashMap<String, List<Message>>();
         //print, outputs the contents of the hashMap
         public void print()
            //want to print out the Key and all the Messages
              //associated with that key
              Set keys = AlertMap.keySet();          // The set of keys in the map.
              Iterator keyIter = keys.iterator();
              System.out.println("The map contains the following associations:");
              while (keyIter.hasNext()) {
                    Object key = keyIter.next();  // Get the next key.
                    Object value = AlertMap.get(key);  // Get the value for that key.
                    System.out.println( "Serial (key): " + key + "\n");
                    System.out.println("value: " + ((Message)value).toString() + "\n");
                    //((Message)value).print();
         //overloaded print to print to user screen.
         public  void print(PrintWriter out)
              //want to print out the Key and all the Messages
              //associated with that key
              Set keys = AlertMap.keySet();          // The set of keys in the map.
              Iterator keyIter = keys.iterator();
              out.println("The map contains the following associations:");
              out.flush();
              while (keyIter.hasNext()) {
                    Object key = keyIter.next();  // Get the next key.
                    Object value = AlertMap.get(key);  // Get the value for that key.
                   //out.flush();
                   /* out.println( "   (" + key + "," + value + ")" );
                   out.flush();*/
                   // out.println("------------------\n");
                   out.println("EntityID: " + key + "\n"
                                 + "Message: " + value + "\n");
                   //out.println("------------------\n");
                   out.flush();
         void add(Message msg)
              //getting the position of the List by EntityID if avaiable
              List<Message> AlertList = AlertMap.get(msg.Serial);
              //checking to see if there is a unique Key already in the Map.
              if (AlertList == null)
                   //if there isnt a key in the map, add a new key, and a new List mapping
                   //to the key EntityID;
                     AlertList = new ArrayList<Message>();
                     AlertMap.put(msg.Serial, AlertList);
                     AlertList.add(msg);
              else
              //adding message to List
                   AlertList.add(msg);
    }Here's my message class:
    package parser;
    //this class will hold the Event/Message
    import java.util.List;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.ArrayList;
    import java.util.Set;
    import java.util.Iterator;
    public class Message {
         String Identifer;
         String Serial;
         String Node;
         String NodeAlias;
         String Manager;
         String Agent;
         String AlertGroup;
         String AlertKey;
         String Severity;
         String Summary;
         String StateChange;
         String FirstOccurance;
         String LastOccurance;
         String InternalLast;
         String EventId;
         String LocalNodeAlias;
         Message()
               Identifer = "";
               Serial = "";
               Node = "";
               NodeAlias = "";
               Manager = "";
               Agent = "";
               AlertGroup = "";
               AlertKey = "";
               Severity = "";
               Summary = "";
               StateChange = "";
               FirstOccurance = "";
               LastOccurance = "";
               InternalLast = "";
               EventId = "";
               LocalNodeAlias = "";
         void print()
              System.out.println("Identifer: " + this.Identifer + '\n'
                        + "Serial: " + this.Serial + '\n'
                        + "Node: " + this.Node + '\n'
                        + "NodeAlias: " + this.NodeAlias + '\n'
                        + "Manager: "  + this.Manager + '\n'
                        + "Agent: " + this.Agent + '\n'
                        + "AlertGroup: " + this.AlertGroup + '\n'
                        + "AlertKey: " + this.AlertKey + '\n'
                        + "Severity: " + this.Severity + '\n'
                        + "Summary: " + this.Summary + '\n'
                        + "StateChange: " + this.StateChange + '\n'
                        + "FirstOccurance: " + this.FirstOccurance + '\n'
                        + "LastOccurance: " +      this.LastOccurance + '\n'
                        + "InternalLast: " + this.InternalLast + '\n'
                        + "EventId: " + this.EventId + '\n'
                        + "LocalNodeAlias: " + this.LocalNodeAlias + '\n');
         public String toString()
              return ("Identifer: " + this.Identifer + '\n'
                        + "Serial: " + this.Serial + '\n'
                        + "Node: " + this.Node + '\n'
                        + "NodeAlias: " + this.NodeAlias + '\n'
                        + "Manager: "  + this.Manager + '\n'
                        + "Agent: " + this.Agent + '\n'
                        + "AlertGroup: " + this.AlertGroup + '\n'
                        + "AlertKey: " + this.AlertKey + '\n'
                        + "Severity: " + this.Severity + '\n'
                        + "Summary: " + this.Summary + '\n'
                        + "StateChange: " + this.StateChange + '\n'
                        + "FirstOccurance: " + this.FirstOccurance + '\n'
                        + "LastOccurance: " +      this.LastOccurance + '\n'
                        + "InternalLast: " + this.InternalLast + '\n'
                        + "EventId: " + this.EventId + '\n'
                        + "LocalNodeAlias: " + this.LocalNodeAlias + '\n');
    }I'm correctly populating my Messages sent to me from the client, I tested it and it works but iterating over them once the messages are inserted into the map is my issue.
    I'm not getting an error, just no output for the values
    here's how I'm adding the Messages to the MessageDB
    //This string is coming from a client
    String str = in.readLine();
    // creating a scanner to parse
    Scanner scanner = new Scanner(str);
    Scanner scannerPop = new Scanner(str);
    //Creating a new message to hold information
    Message msg = new Message();
    //place Scanner object here:
    MessageParser.printTokens(scanner);
    MessageParser.populateMessage(scannerPop, msg);
    System.out.println("-------PRINTING MESSAGE------\n");
    msg.print();
    System.out.println("----------END PRINT----------\n");
    System.out.println("-------Accessing data from Map----\n");
    MessageDB testDB = new MessageDB();
    testDB.add(msg);
    testDB.print();I know this code is ugly, I should make accessor and modifer functions for my Message class but for now I'm just trying to see if I this method is even going to work then I'm going to go about making it more protected.
    Also here is my output:
    that long mess is the incoming string from the client, and im parsing it up into tokens and assigning my message object certain values.
    Address of server: 0.0.0.0/0.0.0.0
    Server is bound to port: 2222
    Echo :UPDATE: "GATEWAY:@barneyfifedisconnectedMon Jun 11 16:46:12
    2007",446,"barneyfife","","ConnectionWatch","","Gateway","GATEWAY:",0,"A
    GATEWAY process  running on barneyfife has disconnected as username
    gateway",06/11/07 16:50:12,06/11/07 16:46:12,06/11/07 16:46:12,06/11/07 16:46:12,0,1,1,0,0,"",65534,0,0,0,"",0,0,0,"","",0,0,"",0,"",0,0,"","","","","","","","",0,
    0,"","","NCOMS",446,""
    Token [0]UPDATE: "GATEWAY:@barneyfifedisconnectedMon Jun 11 16:46:12 2007"
    Token [1]446
    Token [2]"barneyfife"
    Token [3]""
    Token [4]"ConnectionWatch"
    Token [5]""
    Token [6]"Gateway"
    Token [7]"GATEWAY:"
    Token [8]0
    Token [9]"A GATEWAY process  running on barneyfife has disconnected as username gateway"
    Token [10]06/11/07 16:50:12
    Token [11]06/11/07 16:46:12
    Token [12]06/11/07 16:46:12
    Token [13]06/11/07 16:46:12
    Token [14]0
    Token [15]1
    Token [16]1
    Token [17]0
    Token [18]0
    Token [19]""
    Token [20]65534
    Token [21]0
    Token [22]0
    Token [23]0
    Token [24]""
    Token [25]0
    Token [26]0
    Token [27]0
    Token [28]""
    Token [29]""
    Token [30]0
    Token [31]0
    Token [32]""
    Token [33]0
    Token [34]""
    Token [35]0
    Token [36]0
    Token [37]""
    Token [38]""
    Token [39]""
    Token [40]""
    Token [41]""
    Token [42]""
    Token [43]""
    Token [44]""
    Token [45]0
    Token [46]0
    Token [47]""
    Token [48]""
    Token [49]"NCOMS"
    Token [50]446
    Token [51]""
    Entering populate mssage inside case 0
    case 0: UPDATE: "GATEWAY:@barneyfifedisconnectedMon Jun 11 16:46:12 2007"
    case 1: 446
    case 2: "barneyfife"
    case 3: ""
    case 4: "ConnectionWatch"
    case 5: ""
    case 6: "Gateway"
    case 7: "GATEWAY:"
    case 8: 0
    case 9: "A GATEWAY process  running on barneyfife has disconnected as username gateway"
    case 10: 06/11/07 16:50:12
    case 11: 06/11/07 16:46:12
    case 12: 06/11/07 16:46:12
    case 13: 06/11/07 16:46:12
    DEFAULT: 0
    DEFAULT: 1
    DEFAULT: 1
    DEFAULT: 0
    DEFAULT: 0
    DEFAULT: ""
    DEFAULT: 65534
    DEFAULT: 0
    DEFAULT: 0
    DEFAULT: 0
    case 24: ""
    DEFAULT: 0
    DEFAULT: 0
    DEFAULT: 0
    DEFAULT: ""
    DEFAULT: ""
    DEFAULT: 0
    DEFAULT: 0
    DEFAULT: ""
    DEFAULT: 0
    DEFAULT: ""
    DEFAULT: 0
    DEFAULT: 0
    case 37: ""
    DEFAULT: ""
    DEFAULT: ""
    DEFAULT: ""
    DEFAULT: ""
    DEFAULT: ""
    DEFAULT: ""
    DEFAULT: ""
    DEFAULT: 0
    DEFAULT: 0
    DEFAULT: ""
    DEFAULT: ""
    DEFAULT: "NCOMS"
    DEFAULT: 446
    DEFAULT: ""
    -------PRINTING MESSAGE------
    Identifer: UPDATE: "GATEWAY:@barneyfifedisconnectedMon Jun 11 16:46:12 2007"
    Serial: 446
    Node: "barneyfife"
    NodeAlias: ""
    Manager: "ConnectionWatch"
    Agent: ""
    AlertGroup: "Gateway"
    AlertKey: "GATEWAY:"
    Severity: 0
    Summary: "A GATEWAY process  running on barneyfife has disconnected as username gateway"
    StateChange: 06/11/07 16:50:12
    FirstOccurance: 06/11/07 16:46:12
    LastOccurance: 06/11/07 16:46:12
    InternalLast: 06/11/07 16:46:12
    EventId: ""
    LocalNodeAlias: ""
    ----------END PRINT----------
    -------Accessing data from Map----
    The map contains the following associations:
    Serial (key): 446As you see it is printing the correct Serial, but it seems like it isn't even entering into the printing the value associated with that key.
    NOTE: if you need more code I can supply my parsing functions as well.
    Thanks!
    Message was edited by:
    lokie
    NOTE: the code formating screws up the < >
    it should be HashMap<String,List<Message>>();
    Message was edited by:
    lokie
    Message was edited by:
    lokie
    Message was edited by:
    lokie

    Thanks Good Idea :)
    Heres a small version of the same problem:
    MainTest
    package ds;
    public class MainTest {
         public static void main(String []args)
              //create a new message object, assign it some values.
              //note: Serial is the key to the map.
              Message m1 = new Message();
              m1.Identifer = "Test Message";
              m1.Serial = "222";
              m1.Agent = "AgentTest";
              m1.Identifer = "IdentiferTest";
              //test to see if it assigned right.
              m1.print();
              //insert into a map
              MessageDB dbTest = new MessageDB();
              dbTest.add(m1);
              //print key/values
              dbTest.print();
    }Here is the 2 classes that I use, Message and MessageDB.
    The problem is in the MesesageDB i'm getting the following error:
    Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to ds.Message
         at ds.MessageDB.print(MessageDB.java:43)
         at ds.MainTest.main(MainTest.java:28)
    package ds;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.io.*;
    //this class should store all the Messages or "Events" and
    //you can access them based on their Serial key.
    public class MessageDB
         //database to hold the information
         //     holds the Alerts/messages
         Map<String, List<Message>> AlertMap;
         //Constructor
         MessageDB()
              AlertMap = new HashMap<String, List<Message>>();
         //print, outputs the contents of the hashMap
         public void print()
            //want to print out the Key and all the Messages
              //associated with that key
              Set keys = AlertMap.keySet();          // The set of keys in the map.
              Iterator keyIter = keys.iterator();
              System.out.println("The map contains the following associations:");
              while (keyIter.hasNext()) {
                    Object key = keyIter.next();  // Get the next key.
                    Object value = AlertMap.get(key);  // Get the value for that key.
                    System.out.println( "Serial (key): " + key + "\n");
                    System.out.println("value: " + ((Message)value) + "\n");
                    //((Message)value).print();
         ///adds a message (value) to the map, along with the key.
         void add(Message msg)
              //getting the position of the List by EntityID if avaiable
              List<Message> AlertList = AlertMap.get(msg.Serial);
              //checking to see if there is a unique Key already in the Map.
              if (AlertList == null)
                   //if there isnt a key in the map, add a new key, and a new List mapping
                   //to the key EntityID;
                     AlertList = new ArrayList<Message>();
                     AlertMap.put(msg.Serial, AlertList);
                     AlertList.add(msg);
              else
              //adding message to List
                   AlertList.add(msg);
    }Here is the message class you'll need to use to compile:
    package ds;
         public class Message {
              String Identifer;
              String Serial;
              String Node;
              String NodeAlias;
              String Manager;
              String Agent;
              Message()
                    Identifer = "";
                    Serial = "";
                    Node = "";
                    NodeAlias = "";
                    Manager = "";
                    Agent = "";
              void print()
                   System.out.println("Identifer: " + this.Identifer + '\n'
                             + "Serial: " + this.Serial + '\n'
                             + "Node: " + this.Node + '\n'
                             + "NodeAlias: " + this.NodeAlias + '\n'
                             + "Manager: "  + this.Manager + '\n'
                             + "Agent: " + this.Agent + '\n');
              public String toString()
                   return ("Identifer: " + this.Identifer + '\n'
                             + "Serial: " + this.Serial + '\n'
                             + "Node: " + this.Node + '\n'
                             + "NodeAlias: " + this.NodeAlias + '\n'
                             + "Manager: "  + this.Manager + '\n'
                             + "Agent: " + this.Agent + '\n');
         }It doesn't like this line as I suspected:
    System.out.println("value: " + ((Message)value) + "\n");

  • How can I use a Selector in a thread safe way?

    Hello,
    I'm using a server socket with a java.nio.channels.Selector contemporarily by 3 different threads (this number may change in the future).
    From the javadoc: Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not.
    Following this advise, I wrote code in this way:
             List keys = new LinkedList(); //private key list for each thread
             while (true) {
              keys.clear();
              synchronized(selector) {
                  int num = selector.select();
                  if (num == 0)
                   continue;
                  Set selectedKeys = selector.selectedKeys();
                  //I expected this code to produce disjoint key sets on each thread...
                  keys.addAll(selectedKeys);
                  selectedKeys.clear();
              Iterator it = keys.iterator();
              while (it.hasNext()) {
                  SelectionKey key = (SelectionKey) it.next();
                  if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                   Socket s = serverSocket.accept();
                   SocketChannel sc = s.getChannel();
                   sc.configureBlocking( false );
                   sc.register( selector, SelectionKey.OP_READ );
                  } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
    //.....Unfortunately synchronizing on the selector didn't have the effect I expected. When another thread select()s, it sees the same key list as the other thread that select()ed previously. When control arrives to serverSocket.accept(), one thread goes ahead and the other two catch an IllegalBlockingModeException.
    I'm not willing to handle this exception, the right thing to do is giving disjoint key sets to each thread. How can I achieve this goal?
    Thanks in advance

    A single thread won't be enough cause after reading data from the socket I do some processing on it that may take long.So despatch that processing to a separate thread.
    Most of this processing is I/O boundI/O bound on the socket? or something else? If it's I/O bound on the socket that's even more of a reason to use a single thread.
    Anyway I think I'll use a single thread with the selector, put incoming data in a queue and let other 2 or 3 threads read from it.Precisely. Ditto outbound data.
    Thanks for your replies. But I'm still curious: why is a selector thread safe if it can't be used with multiple threads because of it's semantics?It can, but there are synchronization issues to overcome (with Selector.wakeup()), and generally the cost of solving these is much higher than the cost of a single-threaded selector solution with worker threads for the application processing.

  • Is there a way to overload the Map's toString() function?

    Hello everyone. I was wondering if its possible to overload the toString() function of the Map datastructure supplied by java.
    I looked it up and it says:
    public class HashMapextends AbstractMapSo I looked up AbstractMap and it says:
    public abstract class AbstractMapextends Objectimplements MapAnd I found a toString() function in the AbstractMap saying:
    toString
    public String toString() Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object). This implementation creates an empty string buffer, appends a left brace, and iterates over the map's entrySet view, appending the string representation of each map.entry in turn. After appending each entry except the last, the string ", " is appended. Finally a right brace is appended. A string is obtained from the stringbuffer, and returned.
    here: http://java.sun.com/j2se/1.3/docs/a...ml#toString()So I did the following:
    package parse;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.io.*;
    //this class should store all the Messages or "Events" and
    //you can access them based on their EntityID key.
    public class MessageDB extends HashMap
         //database to hold the information
         //     holds the Alerts/messages
         public static Map<Integer, List<String>> AlertMap;
         //Constructor
         MessageDB()
              AlertMap = new HashMap<Integer, List<String>>();
         public String toString()
              return ( )//not sure what to put here...
         //print, outputs the contents of the hashMap
         public static void print()
            //want to print out the Key and all the Messages
              //associated with that key
              Set keys = AlertMap.keySet();          // The set of keys in the map.
              Iterator keyIter = keys.iterator();
              System.out.println("The map contains the following associations:");
              while (keyIter.hasNext()) {
                    Object key = keyIter.next();  // Get the next key.
                    Object value = AlertMap.get(key);  // Get the value for that key.
                    System.out.println( "EntityID: " + key + "\n"
                                  + "Message: " + value + "\n" );
         //overloaded print to print to user screen.
         public static void print(PrintWriter out)
              //want to print out the Key and all the Messages
              //associated with that key
              Set keys = AlertMap.keySet();          // The set of keys in the map.
              Iterator keyIter = keys.iterator();
              out.println("The map contains the following associations:");
              out.flush();
              while (keyIter.hasNext()) {
                    Object key = keyIter.next();  // Get the next key.
                    Object value = AlertMap.get(key);  // Get the value for that key.
                   //out.flush();
                   /* out.println( "   (" + key + "," + value + ")" );
                   out.flush();*/
                   // out.println("------------------\n");
                   out.println("EntityID: " + key + "\n"
                                  + "Message: " + value + "\n");
                   //out.println("------------------\n");
                   out.flush();
         void add(Message msg)
              //getting the position of the List by EntityID if avaiable
              List<String> Alert = AlertMap.get(msg.entityID);
              //checking to see if there is a unique Key already in the Map.
              if (Alert == null)
                   //if there isnt a key in the map, add a new key, and a new List mapping
                   //to the key EntityID;
                     Alert = new ArrayList<String>();
                     AlertMap.put(msg.entityID, Alert);
                     Alert.add(msg.message);
              else
              //adding message to List
                   Alert.add(msg.message);
    }Right now the output is like this:
    The map contains the following associations:
    EntityID: 99999
                      Message: [a test ]
    EntityID: 800
                    Message: [this is a test , again a test ]
    EntityID: 801
                    Message: [again a test ]
    EntityID: 111
                    Message: [a test again yes , a test once again ]You see how its automatically doing [message1, message2,...,message x]
    By me calling this line of code:
    out.println("EntityID: " + key + "\n"
                                  + "Message: " + value + "\n");Because I found out it implicity calls the toString() method when concatinating it to a string.
    What I would like it to display would be:
    EntityID: 800
    Message:
    This is a test
    This is a test again
    any ideas would be great!
    Or is there a way to just iterate over the messages, rather than doing it my way?
    Message was edited by:
    lokie

    Hi,
    When you do a String concatenation in java, calls are implicitly done to #toString().
    Means, you are doing this:
    while (keyIter.hasNext()) {
                    Object key = keyIter.next();  /
                    Object value = AlertMap.get(key); 
                    System.out.println( "EntityID: " + key.toString()+ "\n"
                                  + "Message: " + value.toString() + "\n" );
    }The "[ [/b]... [b], ... , ... ]" you can see in your output is created by the implicit call to List#toString() method.
    You can Override it in an anonymous class by doing:
    if (Alert == null)
                   //if there isnt a key in the map, add a new key, and a new List mapping
                   //to the key EntityID;
                     Alert = new ArrayList<String>(){
                              @Override
                               public String toString(){
                                StringBuilder sb = new StringBuilder();
                       for(String s: this){
                        sb.append(s);
                        sb.append("\n");
                               return sb.toString();
                             };PS:
    toString() is usually used for debbuging only...

Maybe you are looking for

  • Ipod Classic not playing sunched content

    Please can someone assist me. I am having enless problems synching content to my iPod Classic.  I had the same problem on a previous iPod and bought a new one thinking the device was broken.  Now the same thing is happening on this device. The music

  • Goods Receipt check box on Purchase Order

    Hi All, I am creating a NB Purchase order (non-account assigned). Immediately on entering the Material, in the Line Item 'Delivery' tab, "Goods Receipt" is automatically checked and this option is disabled. Does anyone know the configuration that def

  • WD External Hard Drive - Not Enough USB Power?

    Hello, I have a Western Digital External Hard Drive that I've had for about 5 years. It plugs in/loads through the USB port. However, it hasn't worked when I plug it in to my MAC anymore. The red light comes on like it is getting power, but the blue

  • How to save Pdf form localy without internet

    How to save Pdf form localy without internet? I thought in the beginning about advanced user rights and pure saving them on adobe reader but i saw legal notes about 500 user who can legaly save it localy and answer to me (bu they can`t answer to my c

  • How to request a replacement phone

    Does anyone know how to request a replacement phone without calling Apple if my phone customer service has ended? I still have a warranty on my phone, I just need to figure out how to request it without having to call. Help?