A strange behaviour throwing Threads via anonymous class technique

Hi friends!
I've noted a strange behaviour executing the next code:
public class ResolAnonimes
     private int value;
     public ResolAnonimes(int value)
          this.value = value;
     public ResolAnonimes myMethod(int nThreads)
          final ResolAnonimes a = this;
          int nThreadsFor = nThreads - 1;
          for( int i=0; i < nThreadsFor; i++)
               new Thread(){
                    public void run()
                            System.out.println(Thread.currentThread().getName() + " has begun processing");
                                 doSomethingWith(a);
                            System.out.println(Thread.currentThread().getName() + " has finished processing");
               }.start();
               this.value++;
          }//for loop
          return a;
     public static void doSomethingWith(ResolAnonimes a)
          System.out.println(a.value);
     public static void main(String Args[])
          ResolAnonimes first = new ResolAnonimes(1);
          ResolAnonimes result = first.myMethod(5);
}When I execute it, that's the output I get:
Thread-0 has begun processing
2
Thread-0 has finished processing
Thread-0 has begun processing
3
Thread-0 has finished processing
Thread-0 has begun processing
4
Thread-0 has finished processing
Thread-0 has begun processing
5
Thread-0 has finished processingWhere's the "1" printed? It doesn't appear! It seems it has thrown only 4 threads, not 5.
Am I doing anything wrong? Is it a bug?
Can you help me, please?
Thank you in advance.

Oh I'm sorry. I was changing the code because of privacy rerasons and I finally didn't type what I want.
Consider an array which all cells must be typed with the array lentgh. Moreover, the work is distributed by some threads.
I'm refering to something like this:
import java.util.Random;
import java.util.LinkedList;
public class MyArray
     private static int initialRow = 0;
     private static int lastRow = 0;
     private int[] vector;
     public MyArray(int size)
          vector = new int[size];
     public static boolean correctIndex(MyArray a )
          for(int i = 0; i< a.vector.length; i++)
               if(a.vector[i] != a.vector.length)
                    return false;
          return true;
     public String toString()
          String s ="";
          for(int i=0; i < this.vector.length; i++)
               s += this.vector[i] + " ";
          return s;
     public MyArray  operationWith(int nThreads)
          MyArray a = this;
          MyArray result = null;
          final Contenidor ctros = new Contenidor(new LinkedList());
          result = a.putTheIndexValue(nThreads, ctros);
          Thread consumerThread = new Thread( new Consumer( ctros, nThreads));
          consumerThread.start();
          try
               consumerThread.join();
          catch(InterruptedException ie){}
          return result;
     public MyArray putTheIndexValue(int nThreads, Contenidor ctros) //Este metode encara es experimental
          final MyArray a = this;
          final MyArray result = new MyArray( a.vector.length);
          final Contenidor ctrosR = ctros;
          for(int i = 0; i < result.vector.length; i++)
                    result.vector= 0;
          int incRows = a.vector.length / nThreads - 1;
          initialRow = 0;
          lastRow= incRows;
          int nFilsFor = nThreads - 1;
          Thread[] vectorFils = new Thread[nThreads];
          for( int i=0; i < nFilsFor; i++)
               /*vectorFils[i] = */ new Thread()
                                             public void run()
                                                  System.out.println(Thread.currentThread().getName() + " has begun processing");
                                                  MyArray.putTheIndexValue( a, initialRow, lastRow);
                                                  System.out.println(Thread.currentThread().getName() + " has finished processing");
                                                  String s = Thread.currentThread().getName();
                                                  ctrosR.put(s);                         
               vectorFils[i]*/.start();
               initialRow = initialRow + 1;
               lastRow = initialRow + incRows;
          new Thread()
               public void run()
                    System.out.println(Thread.currentThread().getName() + " has begun processing");
                    MyArray.putTheIndexValue( a, initialRow, a.vector.length - 1);
                    System.out.println(Thread.currentThread().getName() + " has finished processing");
                    String s = Thread.currentThread().getName();
                    ctrosR.put(s);                         
               vectorFils[i]*/.start();
          return result;
     public static void putTheIndexValue( MyArray a, int initialRow, int lastRow)
          for(int i = initialRow; i <= lastRow; i++)
               a.vector[i] = a.vector.length;
public class Interface
     public static void main(String Args[])
          int nThreads = 2;
          int arraySize = 5;
          MyArray ma = new MyArray(arraySize);
          MyArray result = ma.operationWith(nThreads);
          if(MyArray.correctIndex(result))
               System.out.println("The operation has been done correctly");
          else
               System.out.println("THE OPERATION HAS NOT BEEN CORRECTLY!");
          System.out.println(ma.toString());
public class Consumer implements Runnable
     private Contenidor ctros;
     private int nFils;
     public Consumer(Contenidor ctros, int nFils)
          this.ctros = ctros;
          this.nFils = nFils;
     public void run()
          System.out.println(Thread.currentThread().getName() + "is waiting the total process to be finished");
          for(int i = 0; i< nFils; i++)
                  System.out.println( Thread.currentThread() + " is waiting a thread to give me its chunk");
                  String s = ctros.get();
                  System.out.println( Thread.currentThread() + ":  " + s + " has already given me its chunk");
             System.out.println(Thread.currentThread().getName() + "says all threads have finished");
import java.util.Queue;
import java.util.LinkedList;
public class Contenidor
    private int nDadesNoves;
    private Queue contenidor;
    public Contenidor(Queue contenidor)
        this.contenidor = contenidor;
        this.nDadesNoves = 0;
    public synchronized String get()
        while(nDadesNoves < 1)
            try
                wait();
            catch(InterruptedException ie){}
        nDadesNoves--;
        notifyAll();
        return (String)contenidor.poll();
    public synchronized void put(String s)
        contenidor.offer(s);
        nDadesNoves++;
        notifyAll();
}The output I get sometimes is:
THE OPERATION HAS NOT BEEN CORRECTLY!
5 5 5 5 5And I get also sometimes that:
THE OPERATION HAS NOT BEEN CORRECTLY!
0 5 5 5 5That's what I wanted to refer last post. I think I'm doing a correct synchronization. Am I wrong?
I don't understand that behaviour.
Anyone can help me, please?
Thank you in advance.

Similar Messages

  • Strange behaviour accessing cache via TCPExtend in multithreaded client

    I have set up a test where 10 threads issue a cache.invoke against the cache service, and the EntryProcessor simply sleeps for 4 seconds. The key being used for each thread is different.
    The single cluster node which I am using for the test is configured using a Pool of 10 Proxy service threads and default settings for the distributed cache service (zero thread pool size so just use the service thread).
    I see the EPs being executed one at a time on the server as expected (because they are all being called from the single service thread) - so it takes 40 seconds for all 10 calls finish - the first finishing after 4s, the second after 8s and so on.
    I'd expect each of the client threads to finish running after the server has finished processing the invoke, but they often dont. What seems to happen is that a number of the threads end up completing the EP call at the same time.
    For example, 4 threads completed after 16 seconds instead of the 1st finishing at 4s and the second at 8s and so on.
    When the Proxy thread pool size is 1, I get my expected behaviour. However, when it is set to 10 this batching occurs so many of my client-side tasks are delayed.
    Can anyone shed any light on why this is happening?
    Many thanks,
    Simon

    Simon,
    Could you please send the complete test case (including the configuration files) to Coherence support at Oracle Metalink?
    Regards,
    Gene

  • Application freezing and recovering & Strange behaviour in Thread Dump & GC

    Hi All,
    I am facing a problem in my SWINGS application. The application is a real time data streaming application its working in TCP/IP sockets, which is reading and writing data in string format. I noticed that the data streaming getting freeze sometimes and it recovers after a few minutes. To find out why it is behaving like that i took the Thread Dump and Garbage Collection Trace of the application and found some thing strange. Find below the line taken from the Thread Dump, the third line in the log below shows that the time have jumped backwards, I don't know why that happened.
    2009-03-12 17:07:48
    Full thread dump Java HotSpot(TM) Client VM (1.6.0-b105 mixed mode, sharing):
    2009-03-12 17:07:57
    Full thread dump Java HotSpot(TM) Client VM (1.6.0-b105 mixed mode, sharing):
    *2009-03-12 17:04:08*
    Full thread dump Java HotSpot(TM) Client VM (1.6.0-b105 mixed mode, sharing):
    2009-03-12 17:04:15
    Full thread dump Java HotSpot(TM) Client VM (1.6.0-b105 mixed mode, sharing):
    2009-03-12 17:04:28
    Full thread dump Java HotSpot(TM) Client VM (1.6.0-b105 mixed mode, sharing):
    Almost during the same time in Garbage Collector log, normally the garbage collector was running multiple times a second and during that time the frequency of garbage collection reduced. please find the details below
    3682.686: [GC 28265K->25644K(41312K), 0.0009666 secs]
    3682.731: [GC 28268K->25645K(41312K), 0.0009825 secs]
    3682.817: [GC 28269K->25647K(41312K), 0.0010381 secs]
    3682.934: [GC 28271K->25649K(41312K), 0.0009364 secs]
    3682.943: [GC 28273K->25649K(41312K), 0.0008954 secs]
    3682.985: [GC 28273K->25650K(41312K), 0.0008845 secs]
    3683.037: [GC 28274K->25651K(41312K), 0.0008747 secs]
    3683.199: [GC 28275K->25651K(41312K), 0.0010448 secs]
    *3698.250: [GC 28275K->25728K(41312K), 0.0009655 secs]*
    *3720.655: [GC 28352K->25867K(41312K), 0.0010588 secs]*
    *3743.011: [GC 28491K->26000K(41312K), 0.0015047 secs]*
    *3765.935: [GC 28624K->26130K(41312K), 0.0010180 secs]*
    *3788.487: [GC 28754K->26260K(41312K), 0.0011328 secs]*
    *3810.348: [GC 28884K->26402K(41312K), 0.0010091 secs]*
    *3832.596: [GC 29026K->26523K(41312K), 0.0010373 secs]*
    *3855.048: [GC 29147K->26652K(41312K), 0.0010029 secs]*
    *3877.230: [GC 29276K->26795K(41312K), 0.0010387 secs]*
    *3899.420: [GC 29419K->26915K(41312K), 0.0009959 secs]*
    3922.146: [GC 29539K->27042K(41312K), 0.0010088 secs]
    3922.201: [GC 29666K->27043K(41312K), 0.0010297 secs]
    3922.231: [GC 29667K->27046K(41312K), 0.0008521 secs]
    3922.260: [GC 29670K->27048K(41312K), 0.0009208 secs]
    3922.269: [GC 29672K->27048K(41312K), 0.0009831 secs]
    3922.298: [GC 29672K->27049K(41312K), 0.0008867 secs]
    3922.308: [GC 29673K->27050K(41312K), 0.0009264 secs]
    can any one please explain whats happening, I am getting no clue from these
    Thanks in Advance
    Rajin Das
    Edited by: rajindas on Mar 16, 2009 6:40 PM

    Have you used any profilers to analyze the logs? It is very difficult to read it just like that.
    I use IBM Monitoring and Diagnostic Tools for Java™. I think it does support Sun and IBM JVMs. Try out and let me know how it goes.

  • Strange behaviour, threading?

    Hiya, i have written a program which is showing strange behaviour (only strange becuase i dont understand it). Effectivly its a counter of sorts, which displayed a number on a jpanel. Now when i set a loop running which looks something like this
    for(int run = 0; run < 10000; run++){
        jPanel.counterNo++;
        jPanel.repaint();
    }everything works fine and the screen repaints many times before its finished, but when this loop is initiated by a swing object, in this case a JButton, only the final value is displayed at the end of the loop, as if the jpanel is blocked from repainting until the loop is finished. Could anyone explain to me why this is happening?
    Thanks
    Dori

    You need to call this in a separate (non UI) thread to see the updates hitting the UI
    read the javadocs about Thread, Runnable, and SwingWorker

  • Are anonymous classes reentrant and multi-thread safe?

    Consider the following code. Please let me know how does this code behave wrt to reentrancy and MT. My main confusion is with the "static" keyword.
    Appreciate any inputs. Thanks in advance.
    public abstract class AnAbstract {
       public abstract int abstractFoo();
       public static AnAbstract AnAbstractImpl = new AnAbstract() {
          public int abstractFoo() {
             //do stuff here....
             return 0;
       public static void main(String [] args) {
          System.out.println(AnAbstract.AnAbstractImpl.abstractFoo());
    }

    static has nothing to do with threading.
    Nor is there anything special about anonymous classes.
    As implemented the class is safe.
    However, given that the class is going to do more than the code that you posted the actual implementation might not be safe.

  • Very strange behaviour of RGBImageFilter class

    Hi!
    I found very strange behaviour of RGBImageFilter class and problem is
    that I need to solve that problem :/ So, situation is next:
    I decided to use filtering process for collecting information about
    image. So, I extended my own class from RGBImageFilter and overwrite
    filterRGB( ... ) method ( everything is absolutely the same as in
    documentation ) and also added my own code for 'no matter what'.
    This code changes some class variable and my idea was to read those
    variables after filtering process end, but... Suddenly I realized that
    those variables, many times changed while filtering were performed
    ( I checked it ) after filtering gave the same value as in constructor!
    The only one clue and idea about what happened is that class instance
    were cloned and then executed, but thats not a functionality I was
    searching. :/ I made some example of that 'effect'.
    Image file name goes in command line.
    Please pay attention on -3 value on exit: Filtering works, count growing
    ( just uncomment setPixels() method to see it ) but, but...
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    class ToForum
         public static void main( String[] args )
              try
                   JFrame frame = new JFrame( "now i beleave in x-files!" );
                   frame.setDefaultCloseOperation( frame.DISPOSE_ON_CLOSE );
                   Toolkit kit = Toolkit.getDefaultToolkit();
                   Image origin = kit.getImage( args[0] );
                   RedBlueSwapFilter filter = new RedBlueSwapFilter();
                   Image filtered = frame.createImage( new FilteredImageSource( origin.getSource(), filter ) );
                   MediaTracker tracker = new MediaTracker( frame );
                   tracker.addImage( filtered, 1 );
                   tracker.waitForAll();
                   System.out.println( "AND WE GOT: "+filter.getCount()+" !!!" );
                   Container content = frame.getContentPane();
                   content.setLayout( new FlowLayout() );
                   JLabel label = new JLabel( new ImageIcon( filtered ) );
                   content.add( label );
                   frame.pack();
                   frame.setVisible( true );
              catch( Exception ex )
                   System.out.println( "Exception in main():\n"+ex );
    class RedBlueSwapFilter extends RGBImageFilter
         private int count=-5;
         public RedBlueSwapFilter()
              count = -3;
              canFilterIndexColorModel = true;
         // uncommenting this function will show that filterRGB method IS calling !!!
         // so, why then AFTER filtering count is still ( or again ??? ) equals to 0 ?
         public void setPixels( int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize )
              System.out.println( "on entering in setPixels count="+count );
              super.setPixels( x, y, w, h, model, pixels, off, scansize );
              System.out.println( "on exiting from setPixels count="+count );
         public int filterRGB( int x, int y, int rgb )
              count++;
              return ( (rgb&0xff00ff00) | ((rgb&0xff0000) >> 16) | ((rgb&0xff) << 16) );
         public int getCount()
              return count;

    Cliff, Hi. I'm curious because this can't work. I have no problem synching with the exchange - as long as i accept the message that the certificate of the exchange (which is not the certificate of the exchange but the certificate of dig @reighthandsideofmailadress) is not valid (expired, wrong common name etc).

  • Strange Behaviour in File class

    Hi,
    I noticed a strange behaviour. There is a file contains unicode letters in its name. I tried
    File file=new File("c:\@&#8463;&#8465;\@�&#8537;0.txt");
    file.exists() // I checked existence of file using this statement which returns false although file is exist.
    What can I do ?
    Thanks

    Hi,
    Thanks for the reply.
    I am showing the sample:
    //This is a list method
    static void list(File file) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null) {
                    for (int i = 0; i < files.length; i++) {
                        if(files.isDirectory()){
    list(files[i]);
    }else{
    System.out.println(files[i].getAbsolutePath() + " " + files[i].exists());
    System.out.println(file.getAbsolutePath() + " " + file.exists());
    if I call this method like this from main method:
    File file=new File("C:\\Documents and Settings\\Neha\\Desktop\\ttt\\@&#8463;&#8465;\\@�&#8537;0.txt");
    list(file);
    output:
    C:\Documents and Settings\Neha\Desktop\ttt\@??\@�?0.txt false [with Jre5]
    C:\Documents and Settings\Neha\Desktop\ttt\@??\@�?0.txt true [with Jre6]
    if I call like this
    File file=new File("C:\\Documents and Settings\\Neha\\Desktop\\ttt");
    list(file);
    Output:
    C:\Documents and Settings\Neha\Desktop\ttt\@??\@�?0.txt true
    C:\Documents and Settings\Neha\Desktop\ttt\@??\Chambal25.txt true
    C:\Documents and Settings\Neha\Desktop\ttt\@?? true
    C:\Documents and Settings\Neha\Desktop\ttt true

  • Where is the anonymous class in this? (lotsa code)

    When I compile ThreadPool.java, I get three classes: ThreadPool.class, ThreadPool$WorkerThread.class, and ThreadPool$1.class. I understand the first two, but I can't figure out where the anonymous class is coming from. Could it be some kind of automatically-generated wrapper class caused by the fact that all accesses to the Queue object are within synchronized blocks? Curiosity attacks!
    Thanks,
    Krum
    ThreadPool.java:
    package krum.util;
    * A thread pool with a bounded task queue and fixed number of worker threads.
    public class ThreadPool {
       protected Queue queue;
    public ThreadPool(int threads, int taskQueueSize) {
       queue = new Queue(taskQueueSize);
       /* create the worker threads */
       for(int i = 0; i < threads; ++i) {
          Thread t = new Thread(new WorkerThread());
          t.setDaemon(true);
          t.start();
    * Queues a task to be executed by this ThreadPool.  If the task queue is
    * full, the task will run in the calling thread.  (Could easily be modified
    * to throw an exception instead.)
    public void doTask(Runnable task) {
       boolean added = false;
       synchronized(queue) {
          if(!queue.isFull()) {
             queue.add(task);
             added = true;
             queue.notify();
       if(!added) task.run();
    * Tests if the task queue is empty.  Useful if you want to wait for all
    * queued tasks to complete before terminating your program.
    public boolean queueEmpty() {
       synchronized(queue) {
          return queue.isEmpty();
    private class WorkerThread implements Runnable {
    public void run() {
       Runnable task;
       while(true) {
          task = null;
          synchronized(queue) {
             try {
                if(queue.isEmpty()) queue.wait();
                else task = (Runnable)queue.getNext();
             } catch(InterruptedException e) { break; }
          if(task != null) task.run();
    } /* end inner class WorkerThread */
    } /* end class ThreadPool */Queue.java:
    package krum.util;
    * Implements a FIFO queue for storage and retrieval of objects.  This class
    * is not synchronized.
    public class Queue {
         /** circular buffer containing queued objects */
         protected Object[] queue;
         /** index of next object to be returned */
         protected int nextReturn;
         /** index in which to store next object inserted */
         protected int nextInsert;
    public Queue(int capacity) {
         queue = new Object[capacity];
         nextInsert = 0;
         nextReturn = 0;
    public boolean isEmpty() { return(queue[nextReturn] == null); }
    public boolean isFull() { return(queue[nextInsert] != null); }
    public void add(Object obj) throws QueueException {
         if(queue[nextInsert] == null) {
              queue[nextInsert] = obj;
              ++nextInsert;
              nextInsert %= queue.length;
         } else throw new QueueException();
    public Object getNext() throws QueueException {
         if(queue[nextReturn] != null) {
              Object obj = queue[nextReturn];
              queue[nextReturn] = null;
              ++nextReturn;
              nextReturn %= queue.length;
              return obj;
         } else throw new QueueException();
    } /* end class Queue */QueueException.java:
    package krum.util;
    public class QueueException extends RuntimeException { }

    I can't explain why it happens, but I've seen this
    behaviour before. I found that it was to do with an
    inner class (WorkerThread in your code) having a
    private constructor - if I made my inner class
    constructor at least package (default) access, then
    the anonymous class was no longer created.
    The generated default constructor for a class has the
    same access modifier as the class, so in your example,
    the default constructor that the compiler generates is
    private.
    I suspect the problem will go away if you either:
    1. Remove the private modifier from the WorkerThread
    class declaration.
    or:
    2. Add a no-args constructor to the WorkerThread
    class, and don't specify an access modifier.Yes, the reason is the private constructor. After decompile using JAD, the reason seems to be: if a private inner class does not explicitly have any constructor, a default no-arguments private constructor is created, and seems this default constructor can't be accessed directly (in source code, it can). So, another no-private constructor (package accessible) is created automatically (with an argument of Object's type), and the
    new WorkThread();is actually like this:
    new WorkThread(null);
    private class WorkThread implements Runnable{
       private WorkThread(){}
       WorkThread(Object obj) {
          this();
    }and I would guess it's using anonymous class tech to achieve this like:
    new WorkThread(null) {
       WorkThread(Object obj){
          this();
    }The JLS should have specified this situation.

  • Strange behaviour: two servers on the same port

    Hi!
    I hope this is the right section for this post. I need help about a strange behaviour involving a ServerSocket.
    For my thesis I need to write a program that receives data from a pre-existing DSMS client, filters them and then sends them to a pre-existing DSMS server. And here is my problem: if I try to create a ServerSocket on the same port of the DSMS server, my program throws no exception, and the servers seem running on the same port. This is a behaviour that I'd like to avoid, but I cannot understand what the problem is. Can you help me?
    The source code of the DSMS server can be found here (it's written in C++): http://infolab.stanford.edu/stream/code/stream-0.6.0.tar.gz
    The source code of my server class, instead, is this one:
    import java.io.*;
    import java.net.*;
    public class ThreadGenerator {
         private ServerSocket server;
         public void connect(String servPort, String cHost, String cPort) {
              try {
                   server = new ServerSocket(servPort);
                   System.out.println("SERVER running on port "+servPort);
              } catch (BindException e) {
                   System.out.println("Address already in use!");
              } catch (Exception e) {
                   System.err.println(e);
              try {
                   while(true){
                        Socket client = server.accept();
                        StreamThread T = new StreamThread(client, cHost, cPort);
                        T.start();
              } catch (EOFException e) {
                   System.out.println("Server closed connection!");
              } catch (Exception e) {
                   System.err.println(e);
    }I'm programming on Mac OSX Tiger, with Java 1.5.0.
    Thanks in advance for your help.

    The problem is still happening to me, I tried in this very moment. The code I'm using is the one I posted, and the second server is the one that I linked. I don't think there's anything else to add.
    If you're sure that the problem is not in my code, then it means that it is in the linked server, which partially solves the problem. But I'd like to know, if it's possibile, if there is any other way to check if the port is already in use.

  • Bug? Unable to add ActionListener using Anonymous class.

    Hi,
    I come accross one strange behaviour while adding ActionListener to RCF component.
    I am trying to add the ActionListener in the managed bean using the Anonymous.
    We can add the actionListener to a button using following methods. I am talking about the the first case. Only this case is not working. Rest other 2 cases are working properly.
    Case 1:
    class MyClass {
         RichCommmandButton btnTest = new RichCommmandButton();
         public MyClass(){
              btnTest.addActionListener(new ActionListener(){
                   public void processAction(ActionEvent event){
    Case 2:
    class MyClass implements ActionListener {
         RichCommmandButton btnTest = new RichCommmandButton();
         public void processAction(ActionEvent event){
    <af:button binding="#{myClassBean.btnTest}" actionListener="#{myClassBean.processAction}"/>
    Case 3:
    class MyClass implements ActionListener {
         RichCommmandButton btnTest = new RichCommmandButton();
         public void addActionLister(){
              //Use EL to add processAction(). Create MethodBinding
              FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory exprfactory = facesContext.getApplication().getExpressionFactory();
              MethodExpression actionListener =
    exprfactory.createMethodExpression(elContext, "#{myClassBean.processAction}", null, new Class[] { ActionEvent.class });
              btnTest.setActionListener(actionListener);
         public void processAction(ActionEvent event){
    Java has provided good way to use the Anonymous classes while adding the listeners. It should work with the RCF also.
    Some how i found the case 1 usefull, as i can have as many buttons in my screen and i can add the actionListener in one method. Also it is easy to read. I dont have to see the JSPX page to find the associated actionListener method.
    Is it a bug or i am wrong at some point?
    Any sujjestions are welcome.
    - Sujay.

    Hello Sujay,
    As I said in my previous reply, you can try with request scope. In JSF you shouldn't use the binding attribute very often. I agree that anonymous class is nice, but don't forget that you might be dealing with client state saving here so it cannot be perfectly compared with Swing that maintains everything in RAM. What I think happens with you currently is the following:
    1. Bean is created and the button instance as well. The ActionListener is added to the button;
    2. The view is rendered and while it is, the binding attribute is evaluated, resulting in the get method of your bean being called;
    3. Since the method returns something different than null, the button instance created in 1. get used in the component tree;
    4. The tree's state is saved on the client, since your class isn't a StateHolder, nor Serializable, the StateManager doesn't know how to deal with it so it gets discarded from the saved state and maybe from the component itself (would have to debug the render view phase to be sure);
    5. The postback request arrives, the tree is restored. When the handler reaches the button, it call the bean that returns the same instance that was used in the previous tree (since not request scoped), which is BAD because the remaining of the tree is not made of the same object instances, but rather new deserialized ones. The component then gets updated from the client state saved in 4, this might also be where the listener get removed (again debugging would tell you this, but I would tend more with the previous possibility). Note that with a request scoped bean you would have to add the listener during the first get method call (by checking if the component is null) or in the constructor as you're doing right now. It would be a very clean way and you could give the request bean (and thus the listener) access to the conversation scoped bean through injection which is very nice as well.
    6. The invoke application phase occurs and the listener is no longer there.
    Btw, this isn't a rich client issue, more a specification one. I'm curious if it works in a simple JSF RI application, if it does then I guess it would be a bug in Trinidad and/or rich client state handling architecture (using FacesBean).
    Regards,
    ~ Simon

  • Strange behaviour on text insert into a HTML pane

    Hi all,
    I am trying to fix a problem on inserting a span tag into an existing html page (in an EDITABLE JEditorPane).
    The behaviour:
    Assuming the cells in a table (3 rows, 2 columns) are numbered from 1 to 6, with cell one being the top left most, cell 2 top right, cell 3 middle left, etc.
    1. Inserting the text "<span></span>" in cell 4 causes during any attempt to later type into cell 5 the characters to be appended instead into cell 4, directly after the close span tag.
    2. The insertion in the first place behaves strange. If I have the caret positioned for cell 5 so that I can insert there
    (via the function void javax.swing.text.html.HTMLEditorKit.insertHTML(HTML Document doc, int offset, String html, int popDepth, int pushDepth, Tag insertTag) )
    even though the caret position is visible in cell 5, the insertion seems to take place in cell 4.
    I can sort of compensate for this by adding 1 to the offset. However, then when inserting into a line of text, for example, "the quick red fox jumped over the lazy dog"
    I insert directly before the 'j' in 'jumped', the insertion looks like this "the quick red fox j<span>..</span>umped over the lazy dog"
    So that is no solution.
    IMPORTANT! Just to prove it is not the span tag causing the trouble, if this span tag already exists in a cell on 'Load' of the html file, the strange behaviour is not observed.
    Something is going wrong here. It is me? Or is it a bug?
    Please help!!
    Here is a test app, and the test html you can use (place in current directory).
    Please test like this:
    1. run application (the html should be loaded into the pane)
    2. the span tag is programmed to automatically insert at cell 4 (by using the +1 method on the insert)
    3. another span tag was already existing in the html file, at cell 8
    4. Attempt to type into cell 5
    result: the text appears instead at cell 4
    5. Type into cell 9
    result: the text correctly is entered into cell 9
    See the difference!!
    Help!
    The test java app:
    package small.test;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.StringReader;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    import javax.swing.text.JTextComponent;
    import javax.swing.text.html.HTML;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    import javax.swing.text.html.parser.ParserDelegator;
    public class HtmlInsertTest extends JEditorPane
         public HtmlInsertTest()
         public static void main(String args[])
              JFrame frame = new JFrame("Loading/Saving Example");
              Container content = frame.getContentPane();
              frame.setSize(600, 600);
              final HtmlInsertTest editorPane = new HtmlInsertTest();
              editorPane.setEditable(true);
              JScrollPane scrollPane = new JScrollPane(editorPane);
              content.add(scrollPane, BorderLayout.CENTER);
              editorPane.setEditorKit(new HTMLEditorKit());
              JPanel panel = new JPanel();
              content.add(panel, BorderLayout.SOUTH);
              frame.setSize(600, 600);
              doLoadCommand(editorPane);
              editorPane.insertHTML("<span>inserted text</span>", 84);
              frame.setVisible(true);
         public static String getHTML()
              return
              "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"+
              "<HTML>"+     "<HEAD>"+
              "     <META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=utf-8\">"+
              "     <TITLE></TITLE>"+          
              "</HEAD>"+
              "<BODY LANG=\"en-AU\" DIR=\"LTR\">"+
              "<P STYLE=\"margin-bottom: 0cm\">This is a test xhtml document. "+
         "     </P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">"+
         "     </P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">Here is a table:</P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">"+
         "     </P>"+
         "     <p></p>"+
               "     <TABLE WIDTH=100% BORDER=1 BORDERCOLOR=\"#000000\" CELLPADDING=4 CELLSPACING=0>"+
         "          <TR VALIGN=TOP>"+
         "               <TD WIDTH=50%>"+
         "                    <P>It has</P>"+
         "               </TD>"+
         "               <TD WIDTH=50%>"+
         "                    <P>2 columns</P>"+
         "               </TD>"+
         "          </TR>"+
         "          <TR VALIGN=TOP>"+
         "               <TD WIDTH=50%><P>And 4 rows</P></TD>"+
         "               <TD WIDTH=50%><P></P></TD>"+
         "          </TR>"+
         "          <TR VALIGN=TOP>"+
         "               <TD WIDTH=50%><P></P></TD>"+
         "               <TD WIDTH=50%><P></P></TD>"+
         "          </TR>"+
         "          <TR VALIGN=TOP>"+
         "               <TD WIDTH=50%><P></P></TD>"+
         "               <TD WIDTH=50%><P><span>existing text</span></P></TD>"+
         "          </TR>"+
         "          <TR VALIGN=TOP>"+
         "               <TD WIDTH=50%><P></P></TD>"+
         "               <TD WIDTH=50%><P></P></TD>"+
         "          </TR>"+
         "     </TABLE>"+
         "     <P STYLE=\"margin-bottom: 0cm\">"+
         "     </P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">"+
         "     </P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">"+
         "     </P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">We will test the drag and drop"+
         "     functionality with this document. "+
         "     </P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">It will be loaded with the hlml editor.</P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">"+
         "     </P>"+
         "     <P STYLE=\"margin-bottom: 0cm\">"+
         "     </P>"+
         "     </BODY>"+
         "     </HTML>";
         public static void doLoadCommand(JTextComponent textComponent)
              StringReader reader = null;
              try
                   System.out.println("Loading");
                   reader = new StringReader(getHTML());
                   // Create empty HTMLDocument to read into
                   HTMLEditorKit htmlKit = new HTMLEditorKit();
                   HTMLDocument htmlDoc = (HTMLDocument)htmlKit.createDefaultDocument();
                   // Create parser (javax.swing.text.html.parser.ParserDelegator)
                   HTMLEditorKit.Parser parser = new ParserDelegator();
                   // Get parser callback from document
                   HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
                   // Load it (true means to ignore character set)
                   parser.parse(reader, callback, true);
                   // Replace document
                   textComponent.setDocument(htmlDoc);
                   System.out.println("Loaded");
              catch (Exception exception)
                   System.out.println("Load oops");
                   exception.printStackTrace();
              finally
                   if (reader != null)
                        reader.close();
         public void insertHTML(String text, int offset)
              SwingUtilities.invokeLater(new insertAction(this, text, offset));
         class insertAction implements Runnable
              String text = "";
              int offset = 0;
              JEditorPane jEditorPane1 = null;
              public insertAction(JEditorPane _jEditorPane1, String _text, int _offset)
                   jEditorPane1 = _jEditorPane1;
                   text = _text;
                   offset = _offset;
              @Override
              public void run()
                   HTMLDocument doc = (HTMLDocument)jEditorPane1.getDocument();
                   HTMLEditorKit kit = (HTMLEditorKit)jEditorPane1.getEditorKit();
                   try
                        System.out.println("reading from string reader");
                        kit.insertHTML(     doc,
                                          offset,//+1
                                          text,
                                          0,//0
                                          0,//0
                                          HTML.Tag.SPAN);
                        System.out.println(jEditorPane1.getText());
                   catch (Exception e)
                        System.out.println("error inserting html: " + e);
    }Edited by: svaens on Jul 16, 2009 6:34 PM
    fix another stuffed up attempt at a SSCCE.

    Well, I know nothing about HTML in JEditorPanes. I have never been able to figure out how insertions work.
    My comment was a warning to others. Some people (like me) avoid answering posting of this type for reasons given in the JavaRanch link. Others will answer anyway. Other might first check the other site to see if they are wasting there time, but they can only do that if a link was posted with the original question.
    The only suggestion I have is to repost the question, (since this posting is now completely off topic) making sure to then respond to this posting stating that a fresh question has been asked so you don't get a discussion going on in two places.

  • Strange behaviour BOXI R2

    Post Author: Ermakov Alexey
    CA Forum: .NET
    using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using CrystalDecisions.Enterprise;using BusinessObjects.ReportEngine;using BusinessObjects.Enterprise.Desktop;using System.IO;using System.Runtime.InteropServices;using System.Collections;namespace BusinessObjectsInteroperation{     public class BusinessObjectsInterop     {          public void GetBinaryReportByName(string NameOfTheReport, Stream StreamForDataBeWritten, BOConfigs BOCfg, OutputFormatType OutputFormat, Hashtable PromptValues)          {               EnterpriseSession enterpriseSession = null;               ReportEngines reportEngines = null;               SessionMgr sessionMgr = new SessionMgr();               try               {                    enterpriseSession = sessionMgr.Logon(BOCfg.BO_LoginName, BOCfg.BO_Password, BOCfg.BO_MachineToConnect, BOCfg.BO_LoginType);               }               catch (COMException exc)               {                    int HRESULT = exc.ErrorCode;                    switch (HRESULT)                    {                         case -2147210751:                              throw new ArgumentException(" BO_MachineToConnect");                         case -2147211005:                              throw new ArgumentException(" BO_LoginName");                         case -2147211006:                              throw new ArgumentException(" BO_Password");                         case -2147210653:                              throw new ArgumentException(" BO_LoginType");                         default:                              throw new ArgumentException("");                    }               }               InfoStore iStore = (InfoStore)enterpriseSession.GetService("InfoStore");               UserInfo userInfo = enterpriseSession.UserInfo;               if (enterpriseSession != null)               {                    if (reportEngines == null)                    {                         int iMinuteNumber = 1;                         int iLogonNumber = 1;                          string strToken = enterpriseSession.LogonTokenMgr.CreateWCAToken("", iMinuteNumber, iLogonNumber);                         reportEngines =  new ReportEngines(strToken);                    }               }                              IReportEngine reportEngine = reportEngines.getService(ReportEngineType.FC_ReportEngine);               FullClient ReportToPrint = (FullClient)getReport(iStore, NameOfTheReport, CrystalDecisions.Enterprise.InfoStore.CeKind.FullClient);               IDocumentInstance doc = null;               try               {                    doc = reportEngine.OpenDocument(ReportToPrint.ID); //ERROR Happens here               }               catch(Exception e)               {                    Console.Write(e.StackTrace);               }                              doc.Refresh();               IPrompts prompts = doc.GetPrompts();               foreach (IPrompt ip in prompts)               {                    string OnlyOneValue="";                    try                    {                         OnlyOneValue = (string)PromptValues&#91;ip.Name&#93;;                    }                    catch(IndexOutOfRangeException exc)                    {                         throw new ArgumentException(String.Format("Отчет {0} имеет необходимый параметр , который не был предоставлен.", NameOfTheReport, ip.Name), exc);                    }                    string&#91;&#93; vlArr = ; //Почему одному IPrompt надо передавать массив значений остается загадкой.                    ip.EnterValues(vlArr);               }               doc.SetPrompts();               IBinaryView docBinaryView = (IBinaryView)doc.GetView(OutputFormat);               docBinaryView.WriteContent(StreamForDataBeWritten);               doc.CloseDocument();                              reportEngine.Close();               reportEngines.Close();               iStore.Dispose();               enterpriseSession.Logoff();               enterpriseSession.Dispose();                                        }                    private InfoObject getReport(InfoStore iStore, string Name, string Kind)          {               InfoObjects list = null;               string query = String.Format(@"                SELECT                     SI_ID,                     SI_NAME,                          SI_PARENTID,                         SI_KIND,                          SI_INSTANCE,                          SI_DESCRIPTION                     FROM                         CI_INFOOBJECTS                     WHERE                          SI_KIND='{0}' AND                         SI_NAME=''", Kind, Name);                list = iStore.Query(query);               if (list.Count == 0)               {                    throw new Exception(String.Format("На сервере не существует отчета с именем {0}, его необходимо создать. Либо у вас нет на него прав.", Name));               }               if (list.Count > 1)               {                    throw new Exception(String.Format("На сервере существует более одного отчета с именем {0}, удалите неверный.", Name));               }               foreach (InfoObject obj in list)               {                    return obj;               }               return null;          }          public void ReportInPdfToHTTPResponse(string NameOfTheReport, params Par&#91;&#93; Prompts)          {               Hashtable PromptValues = new Hashtable();               foreach (Par p in Prompts)               {                    PromptValues.Add(p.Key, p.Value);               }               HttpResponse Response = HttpContext.Current.Response;               Response.Clear();               Response.ContentType = "application/pdf";               Response.AddHeader("Content-Type", "application/pdf");               Response.Expires = 0;               GetBinaryReportByName(NameOfTheReport, Response.OutputStream, new BOConfigs(), OutputFormatType.Pdf, PromptValues);               Response.Flush();               Response.End();          }          public void ReportInXlsToHTTPResponse(string NameOfTheReport, params Par&#91;&#93; Prompts)          {               Hashtable PromptValues = new Hashtable();               foreach (Par p in Prompts)               {                    PromptValues.Add(p.Key, p.Value);               }               HttpResponse Response = HttpContext.Current.Response;               Response.Clear();               Response.ContentType = "application/vnd.ms-excel";               Response.AddHeader( "Content-Type", "application/vnd.ms-excel");               Response.Expires = 0;               GetBinaryReportByName(NameOfTheReport, Response.OutputStream, new BOConfigs(), OutputFormatType.Xls, PromptValues);               Response.Flush();               Response.End();          }               }     } I have this code, but it has strange behaviour.When I restart IIS and run this function first time, I get an ArgumentOutOfRangeException in reportEngine.OpenDocument(ReportToPrint.ID);But the most strange thing is that Visual Studia shows me exception dialog and if I press Continue, then it works good.On more strange thing I get about this Code. From time to time server shows me such error:An unhandled exception of type 'BusinessObjects.ThirdParty.OOC.OB.AssertionFailed' occurred in businessobjects.enterprise.sdk.netmodule Additional information: ORBacus encountered an internal error

    Post Author: Ermakov Alexey
    CA Forum: .NET
         mscorlib.dll!System.String.LastIndexOf(char value, int startIndex) + 0x13 bytes           log4net.dll!log4net.Repository.Hierarchy.Hierarchy.UpdateParents(log4net.Repository.Hierarchy.Logger log = {log4net.Repository.Hierarchy.DefaultLoggerFactory.LoggerImpl}) + 0x1cf bytes           log4net.dll!log4net.Repository.Hierarchy.Hierarchy.GetLogger(string name = ".cctor", log4net.Repository.Hierarchy.ILoggerFactory factory = {log4net.Repository.Hierarchy.DefaultLoggerFactory}) + 0x12b bytes           log4net.dll!log4net.Repository.Hierarchy.Hierarchy.GetLogger(string name = ".cctor") + 0x46 bytes           log4net.dll!log4net.Core.LoggerManager.GetLogger(System.Reflection.Assembly repositoryAssembly = {System.Reflection.Assembly}, string name = ".cctor") + 0x94 bytes           log4net.dll!log4net.LogManager.GetLogger(System.Reflection.Assembly repositoryAssembly = {System.Reflection.Assembly}, string name = ".cctor") + 0x1b bytes           log4net.dll!log4net.LogManager.GetLogger(string name = ".cctor") + 0x1e bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Lib.Tracing.CELogger.CELogger(string name = ".cctor") + 0x20 bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Lib.Tracing.TraceManager.LoggerFactoryHelper.makeLogger(string name = ".cctor") + 0x35 bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Lib.Tracing.TraceManager.getLogger(string name = ".cctor") + 0x4a bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Infostore.Internal.AbstractSchedulableObject..cctor() + 0x23 bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Infostore.Internal.SchedulableInfoObject.SchedulableInfoObject() + 0xf bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Infostore.Internal.InfoObjects.newInfoObject(System.Object plgKey = ) + 0xbb bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Infostore.Internal.InfoObjects.continueUnpack(BusinessObjects.Enterprise.OcaFramework.Oca.InfoStore.info_wire_ob3&#91;&#93; wireObjs = {Length=0x1}) + 0x40a bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Infostore.Internal.InfoObjects.startUnpack(BusinessObjects.Enterprise.Security.Internal.ISecuritySession session = {BusinessObjects.Enterprise.Security.Internal.SecuritySession}, BusinessObjects.Enterprise.Infostore.IInfoStore infoStore = {BusinessObjects.Enterprise.Infostore.Internal.InfoStore}, BusinessObjects.Enterprise.OcaFramework.Oca.InfoStore.info_wire_ob3&#91;&#93; wireObjs = {Length=0x1}) + 0x9b bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Infostore.Internal.InfoStore.queryHelper(string query = "SELECT SI_MACHINE, SI_MACHINECHOICE from CI_INFOOBJECTS WHERE SI_ID=2762", BusinessObjects.Enterprise.Infostore.Internal.InfoObjects objs = {BusinessObjects.Enterprise.Infostore.Internal.InfoObjects}) + 0x149 bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Infostore.Internal.InfoStore.Query(string query = "SELECT SI_MACHINE, SI_MACHINECHOICE from CI_INFOOBJECTS WHERE SI_ID=2762") + 0x2f bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Ras21.RASConnection.initServerSpec(BusinessObjects.Enterprise.OcaFramework.ServerSpec serverSpec = {BusinessObjects.Enterprise.OcaFramework.ServerSpec}) + 0x30d bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Ras21.RASConnection.init(BusinessObjects.Enterprise.Ras21.IRASConnectionInitService i_initService = <undefined value>) + 0x422 bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Ras21.RASConnection.RASConnection(string i_sServerKind = "dpscacheFullClient", BusinessObjects.Enterprise.Ras21.Messages.GetConnection i_getConnection = {BusinessObjects.Enterprise.Ras21.Messages.GetConnection}, System.IO.Stream i_documentStream = <undefined value>, BusinessObjects.Enterprise.Ras21.IRASConnectionInitService i_initService = <undefined value>, BusinessObjects.Enterprise.Ras21.Serialization.IServerDeserializerFactory i_deserializerFactory = {BusinessObjects.Enterprise.Ras21.RASConnectionFactory.RASConnectionServerSerializationFactory}, BusinessObjects.Enterprise.Ras21.Serialization.IServerSerializerFactory i_serializerFactory = {BusinessObjects.Enterprise.Ras21.RASConnectionFactory.RASConnectionServerSerializationFactory}) + 0x18a bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Ras21.RASConnectionFactory.getRASConnection(string i_sServerKind = "CrystalEnterprise.FullClient", System.Globalization.CultureInfo i_locale = {System.Globalization.CultureInfo}, BusinessObjects.Enterprise.Security.Internal.ISecuritySession i_secSession = {BusinessObjects.Enterprise.Security.Internal.SecuritySession}, BusinessObjects.Enterprise.Ras21.Messages.GetConnection.DocumentId i_documentId = {BusinessObjects.Enterprise.Ras21.Messages.GetConnection.DocumentId}, System.IO.Stream i_documentStream = <undefined value>, BusinessObjects.Enterprise.Ras21.IRASConnectionInitService i_initService = <undefined value>) + 0x156 bytes           businessobjects.enterprise.sdk.netmodule!BusinessObjects.Enterprise.Ras21.RASConnectionFactory.getRASConnectionObjectId(string i_sServerKind = "CrystalEnterprise.FullClient", System.Globalization.CultureInfo i_locale = {System.Globalization.CultureInfo}, BusinessObjects.Enterprise.Security.Internal.ISecuritySession i_secSession = {BusinessObjects.Enterprise.Security.Internal.SecuritySession}, int i_nObjectId = 0xaca) + 0x108 bytes           businessobjects.reportengine.fc.dll!BusinessObjects.ReportEngine.FC.ras21.XMLviaRAS21Encode.newSession(BusinessObjects.ReportEngine.FC.ras21.RAS21SessionID i_occaSession = {BusinessObjects.ReportEngine.FC.ras21.RAS21SessionID}, string i_sLocale = "en-US", int i_nDocId = 0xaca, string s_iConnID = "1") + 0x107 bytes           businessobjects.reportengine.fc.dll!BusinessObjects.ReportEngine.FC.ras21.RAS21ReportEngineComAdapter.InitRAS21Connection(BusinessObjects.ReportEngine.FC.ras21.RAS21SessionID i_occaSession = {BusinessObjects.ReportEngine.FC.ras21.RAS21SessionID}, string i_sLocale = "", bool i_bNewDoc = false, int i_nDocId = 0xaca, string i_sConnID = "1") + 0x1d bytes           businessobjects.reportengine.fc.dll!BusinessObjects.ReportEngine.FC.ras21.RAS21ReportEngineComAdapter.openDocument(BusinessObjects.ReportEngine.Internal.Utilities.Storage.IStorageManager storageManager = {BusinessObjects.ReportEngine.Internal.Utilities.Storage.ClusterStorageManager}, string sLocale = "", int docID = 0xaca) + 0xde bytes           businessobjects.reportengine.fc.dll!BusinessObjects.ReportEngine.FC.ReportEngineImpl.OpenDocument(int docID = 0xaca) + 0x107 bytes     >     businessobjectinteroperation.dll!BusinessObjectsInteroperation.BusinessObjectsInterop.GetBinaryReportByName(string NameOfTheReport = "DO_Raport", System.IO.Stream StreamForDataBeWritten = {System.Web.HttpResponseStream}, BusinessObjectsInteroperation.BOConfigs BOCfg = {BusinessObjectsInteroperation.BOConfigs}, BusinessObjects.ReportEngine.OutputFormatType OutputFormat = Pdf, System.Collections.Hashtable PromptValues = {Count=0x3}) Line 80 + 0x22 bytes     C#

  • Strange behaviour of a Simple Servlet.Please explain

    I am experiencing a strange behaviour from this servlet.
    I have written a servlet that expects some data from the client.
    So I startup Tomcat and invoke this servlet thru the brower:
    http://localhost:8080/A_SYMBIAN_SERVLET/servlet/Recieve_Http_Data.
    The Console displays:
    Server Ready to receive Message from Symbian Application...
    How come the console is not displaying
    In Receive_Http_Data [Client] :
    at the same time at the console ? How come it is only displaying the first line?
    Shudnt the 'In Receive_Http_Data [Client] be displayed if you invoke this servlet
    thru the browser?
    Can anyone explain this strange behaviour!!!
    Attached is my servlet:
    public class Recieve_Http_Data extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    System.out.println("Server Ready to receive Message from Symbian Application...");
    BufferedReader br=null;
    /* Data Read by the Servlet*/
    String sMess="";
    // Receive data.
    DataInputStream dis = new DataInputStream(request.getInputStream());
    sMess = dis.readUTF();
    System.out.println("In Receive_Http_Data [Client] : " + sMess);
    Can some one explain this strange behaviouR!!!

    Ok,I will write an inputstream as you have mentioned in yr mail.
    Now,i will write a servlet with the code you have mentioned.
    Now how do I know that the servlet is up and running and ready to
    receive data from an application.
    OK,This is what is the actual application:
    I am supposed to receive some test data from a Mobile device
    which has the Symbian O/S.
    The application on the mobile device is in C++.
    This C++ Application connects to my Servlet and sends in request
    parameters.The application specifically specifies the name of my
    servlet and the protocol(ie method.Connect(URL,'HTTP1.1!))
    I have written this servlet on Tomcat 3.2.4 which will receive
    this request and display it on my console and return a response
    back to the symbian application.(ie the output stream of the servlet).
    So,your code will read the parameters sent in by the Symbian
    application.right?
    Could you also send in the how the outputstream from the servlet
    will be sent to the c++ application.
    An urgent reply is much appreiciated.

  • Strange behaviour whit custom JTextField and JToolTip

    Hello everyone. I hope I'm writing in the right section and sorry if I did not search for this issue but I really don't know which keywords I should use.
    I'm using NetBeans 6.1 on WinXP and JDK 1.6.0_07, I have a custom JTextField with regex validation: when you type something that don't mach regex it shows a JToolTip. This JToolTip should disappear when the text typed is finally correct, or when the textfield loses focus (see code below).
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import javax.swing.JToolTip;
    import javax.swing.Popup;
    import javax.swing.PopupFactory;
    public class MyJTextField extends javax.swing.JTextField implements FormComponent
    private static Popup popUpToolTip;
    private static PopupFactory popUpFactory = PopupFactory.getSharedInstance();
    private boolean isValidated = false;
    private String regEx = "a regex";
    public MyJTextField()
    this.addKeyListener(new java.awt.event.KeyAdapter()
    public void keyReleased(java.awt.event.KeyEvent evt)
    if(evt.getKeyCode()!=java.awt.event.KeyEvent.VK_ENTER)
    validateComponent();
    else if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER)
    if(isValidated)
    ((Component)evt.getSource()).transferFocus();
    this.addFocusListener(new java.awt.event.FocusAdapter()
    public void focusLost(java.awt.event.FocusEvent evt)
    if(popUpToolTip!=null){popUpToolTip.hide();}
    public void validateComponent()
    if(text.matches(regex))
    isValidated = true;
    if(popUpToolTip!=null){popUpToolTip.hide();}
    else
    isValidated = false;
    if(popUpToolTip!=null){popUpToolTip.hide();}
    String error = "C'&egrave; un errore nella validazione di questo campo";
    JToolTip toolTip = createToolTip();
    toolTip.setTipText(error);
    popUpToolTip = null;
    popUpToolTip = popUpFactory.getPopup(
    this,
    toolTip,
    getLocationOnScreen().x,
    getLocationOnScreen().y - this.getPreferredSize().height -1
    popUpToolTip.show();
    }(I've cut it a bit, here's only the lines that involve JToolTip use)
    I have many of them in a form, and when the first tooltip appears (on the first textfield I type in) it never disappears, while nex textfields work just fine.It seems the first tooltip appearing can't be overwritten or something similar. If I use this same component on any other NetBeans project, everithing works without issues.
    I have some other custom components working the same way (JComboBox, JXDatePicker), and they had this "not disappearing tooltip" issue since I changed this
    popUpToolTip = popUpFactory.getPopup(this, toolTip, getLocationOnScreen().x, getLocationOnScreen().y - this.getPreferredSize().height -1);
    whit this
    popUpToolTip = popUpFactory.getPopup(null, toolTip, getLocationOnScreen().x, getLocationOnScreen().y - this.getPreferredSize().height -1);
    but if I try it on the JTextField all textfield's tooltips stay stuck there, not only the first one appeared (while other components still works fine).
    This thing is really driving me crazy. Someone has an hint (or a link to another thread) which could explain this strange behaviour?
    Thanks in advance.

    BoBear2681 wrote:
    Note that an SSCCE wouldn't require you to post any proprietary code.Hmmm... well, I'll try again to reproduce the issue and post an SSCCE.
    BoBear2681 wrote:
    That probably indicates that the problem is somewhere other than where you're currently looking.Yes, I suppose so. Maybe it's some interference between all the custom components I created, or maybe something else that apparently doesn't conern at all. If I cannot reproduce it in an SSCCE and I'll figure out what's the cause of this mess I'll post it here for future knowledge.
    Many thanks for your advices. :)

  • URGENT: Strange behaviour! Help!

    Hi All.
    When I run the enclosed program I am getting some strange behaviour. For instance, when I click on the EDIT button nothing happens, but when I click on the DELETE button everything is fine!
    And I can also not run the code in edit() directly after add(). Nothing happens. PLEASE HELP ME. I am going mad because I cannot see what is wrong!
    I want to run the code associated with the buttons to update my JTable. Please tell me if there is something wrong in the code.
    As I say - it works fine when I click the DELETE button, but on the others it doesn't work.
    Please tell me if you need more information!
    HOPE TO HEAR FROM SOMEONE BEFORE I KILL MYSELF OUT OF FRUSTRATION!!!!
    C
    // The "Main" class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.JOptionPane;
    public class Team
        extends JFrame
        implements ActionListener {
      JLabel LTeamSetup = new JLabel();
      JButton Edit = new JButton();
      Font customFont1 = new Font("SansSerif", Font.BOLD, 18);
      Font customFont2 = new Font("SansSerif", Font.PLAIN, 12);
      JButton Delete = new JButton();
      JButton Close = new JButton();
      JButton Add = new JButton();
      Border border1;
      TitledBorder titledBorder1;
      TeamDataModel myModel = new TeamDataModel();
      JTable Table = new JTable(myModel);
      JScrollPane scrollPane = new JScrollPane(Table);
      public Team() {
        super("Add Team Window");
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        setSize(790, 560);
        setLocation(3,5);
        setVisible(true);
        try {
          new DBTeam();
          jbInit();
        catch (Exception e) {
          e.printStackTrace();
      public void actionPerformed(ActionEvent event) {
        if (event.getActionCommand() == "CLOSE") {
          close();
        if (event.getActionCommand() == "ADD") {
          add();
        if (event.getActionCommand() == "DELETE") {
          delete();
        if (event.getActionCommand() == "EDIT") {
          edit();
      public void close() {
        this.dispose();
      public void add() {
        new TeamAdd();
      public void delete() {
        DBTeam.numRows();
        DBTeam.rows();
        Table.tableChanged(new TableModelEvent(myModel));
        Table.repaint();
      public void edit() {
        DBTeam.numRows();
        DBTeam.rows();
        Table.tableChanged(new TableModelEvent(myModel));
        Table.repaint();
      ///////////////////////////SETUP SWING FRAME////////////////////////
      private void jbInit() throws Exception {
        border1 = BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED,Color.white,Color.white,new Color(124, 124, 124),new Color(178, 178, 178)),BorderFactory.createEmptyBorder(1,1,1,1));
        this.getContentPane().setLayout(null);
        LTeamSetup.setBounds(new Rectangle(23, 4, 203, 50));
        LTeamSetup.setEnabled(true);
        LTeamSetup.setFont(new java.awt.Font("SansSerif", 1, 36));
        LTeamSetup.setForeground(Color.black);
        LTeamSetup.setText("Team Setup");
        LTeamSetup.setBounds(new Rectangle(41, 13, 390, 50));
        Edit.setText("EDIT");
        Edit.setBounds(new Rectangle(647, 157, 94, 45));
        Edit.setActionCommand("EDIT");
        this.setResizable(false);
        this.setTitle("Team Setup");
        Delete.addActionListener(this);
        Delete.setBounds(new Rectangle(647, 214, 94, 45));
        Delete.setText("DELETE");
        Close.setText("CLOSE");
        Close.setBounds(new Rectangle(641, 480, 105, 26));
        Close.addActionListener(this);
        Add.setText("ADD");
        Add.setBounds(new Rectangle(647, 99, 94, 45));
        Add.addActionListener(this);
        scrollPane.setBounds(new Rectangle(40, 96, 567, 412));
        this.getContentPane().add(LTeamSetup, null);
        this.getContentPane().add(Delete, null);
        this.getContentPane().add(Close, null);
        this.getContentPane().add(Add, null);
        this.getContentPane().add(Edit, null);
        this.getContentPane().add(LTeamSetup, null);
        this.getContentPane().add(scrollPane, null);
        scrollPane.getViewport().add(Table, null);
        repaint();
    }

    if (event.getActionCommand() == "CLOSE") {
    if (event.getActionCommand() == "ADD") {
    if (event.getActionCommand() == "DELETE") {
    if (event.getActionCommand() == "EDIT") {And these look highly dubious, too. Shouldn't you be doing
    event.getActionCommand().equals("CLOSE")
    etc.?

Maybe you are looking for