Problem with StringTokenizer

Hi! ..
I am trying to read this line from a CSV file::
sl-vpn1-stk,4,204.215.135.77,159.55.0.0,255.255.0.0,10,192.168.170.49
But i am not getting the success, and getting this error::
Just read this line:: sl-vpn1-stk,4,204.215.135.77,159.55.0.0,255.255.0.0,10,192.168.170.49
Token at 0 :: 4
Token at 0 :: 159.55.0.0
Token at 0 :: 10
java.util.NoSuchElementException
Any solution to the problem?? .. Please reply back soon.

The code id::
lineAllRouter = bf.readLine();
                    System.out.println("Just read this line:: "+lineAllRouter.toString());
                    while (lineAllRouter != null){
               String [] inputString= new String[11];
                    StringTokenizer st = new StringTokenizer(lineAllRouter, ",");
                    int numberOfTokens = st.countTokens();
                    System.out.println("Total Tokens ::"+numberOfTokens);
                    int count = 0;
                    while (st.hasMoreTokens()){
                         String token = st.nextToken();
                         inputString[count] = st.nextToken();
                         System.out.println("Token at "+count+" :: "+inputString[count]);
                    }

Similar Messages

  • Possible problem with StringTokenizer?

    Hi all
    I am having a problem with StringTokenizer and I would like your comments.
    This is a simple class to put the class path folders into an array:
    import java.io.*;
    import java.util.*;
    class TestThis1   {
       public static void main( String plist[] ) {
          String value = System.getProperty( "java.class.path" );
          System.out.println( "\n" );
          System.out.println( value );
          System.out.println( "\n" );
          StringTokenizer st = new StringTokenizer( value, ";" );
          String valueArray[] = new String[ st.countTokens() ];
          System.out.println( "folders in class path: " + st.countTokens() + "\n" );
          int i = 0;
          import java.io.*;
    import java.util.*;
    class TestThis1   {
       public static void main( String plist[] ) {
          String value = System.getProperty( "java.class.path" );
          System.out.println( "\n" );
          System.out.println( value );
          System.out.println( "\n" );
          StringTokenizer st = new StringTokenizer( value, ";" );
          String valueArray[] = new String[ st.countTokens() ];
          System.out.println( "folders in class path: " + st.countTokens() + "\n" );
          int i = 0;
          while( st.hasMoreTokens() ) {
             System.out.println( st.nextToken() );
             valueArray[i++] = st.nextToken();
             System.out.println( st.nextToken() );
             valueArray[i++] = st.nextToken();
    Output:
    D:\java\Viewer_JPro\ckv7\classes\;D:\j2sdk1.4.0\Coroutine for Java 2002\Coroutin
    e\Coroutine4Java.jar;D:\j2sdk1.4.0\Coroutine for Java 2002\JavaDDE\JavaDde.jar;D
    :\j2sdk1.4.0\Coroutine for Java 2002\Java2COM\Java2COM.jar;D:\j2sdk1.4.0\Corouti
    ne for Java 2002\JPrint\JPrint.jar;X:\JTOpen\lib\jt400.jar;X:\Java\wdt400tb.jar;
    D:\j2sdk1.4.0\jre\lib\rt.jar;D:\j2sdk1.4.0\lib\dt.jar;D:\j2sdk1.4.0\lib\tools.ja
    r;D:\j2sdk1.4.0\jre\lib\ext\Coroutine4Java.jar;D:\j2sdk1.4.0\jre\lib\ext\dnsns.j
    ar;D:\j2sdk1.4.0\jre\lib\ext\jai_codec.jar;D:\j2sdk1.4.0\jre\lib\ext\jai_core.ja
    r;D:\j2sdk1.4.0\jre\lib\ext\ldapsec.jar;D:\j2sdk1.4.0\jre\lib\ext\localedata.jar
    ;D:\j2sdk1.4.0\jre\lib\ext\mlibwrapper_jai.jar;D:\j2sdk1.4.0\jre\lib\ext\sunjce_
    provider.jar;D:\j2sdk1.4.0\jre\lib
    folders in class path: 19
    D:\java\Viewer_JPro\ckv7\classes\
    D:\j2sdk1.4.0\Coroutine for Java 2002\JavaDDE\JavaDde.jar
    D:\j2sdk1.4.0\Coroutine for Java 2002\JPrint\JPrint.jar
    X:\Java\wdt400tb.jar
    D:\j2sdk1.4.0\lib\dt.jar
    D:\j2sdk1.4.0\jre\lib\ext\Coroutine4Java.jar
    D:\j2sdk1.4.0\jre\lib\ext\jai_codec.jar
    D:\j2sdk1.4.0\jre\lib\ext\ldapsec.jar
    D:\j2sdk1.4.0\jre\lib\ext\mlibwrapper_jai.jar
    D:\j2sdk1.4.0\jre\lib
    Exception in thread "main" java.util.NoSuchElementException
            at java.util.StringTokenizer.nextToken(StringTokenizer.java:232)
            at com.accuchekinc.util.TestThis1.main(TestThis1.java:25)There are 19 folders in the classpath. However the nextToken() method is skipping some of them.
    Further st.hasMoreTokens() should prevent the loop from overrunning the list of tokens but doesn't.
    Does anyone have any ideas? What did I do wrong?
    Thanks all
    Bill

    while( st.hasMoreTokens() ) {
    System.out.println( st.nextToken() );
    valueArray[i++] = st.nextToken();
    }It looks like you're calling nextToken() twice each
    time through the while loop, but only checking to see
    if it exists once. This would be better:
    while(st.hasMoreTokens()) {
    String tok = st.nextToken();
    System.out.println(tok);
    valueArray[i++] = tok;
    Duhh............ Thanks! It was a long day.
    That makes senses. It is not like say String.length() which returns a set value. Ask and learn.

  • Problem with stringtokenizer on event handling

    First of all I apologise if its not the proper area.
    I have built a typical gui with netbeans builder.When I double-click a button to switch to source and edit its actionPerformed function the first thing I do is to declare a StringTokenizer variable.I am tottaly sure that I have imported java.util package.So I ask for your help.Whats the deal and I cannot do this declaration?
    thanks in advance!
    EDIT:
    My code
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
       StingTokenizer stok=new StringTokenizer("kjvfw jqwejoiqe ieie9");
    }       Edited by: ultimate_aektzis on Dec 23, 2008 7:14 PM
    Edited by: ultimate_aektzis on Dec 23, 2008 7:16 PM

    Spell StringTokenizer correctly.
    (and it will help if you post the exact error message in the future.)

  • Deliminator problem with StringTokenizer

    String str = "xxx-----xxx-----xxx-----xx-x-----xxx-----xxx";
    StringTokenizer st = new StringTokenizer(str, "-----");
    I am expecting 6 tokens, but get 7 tokens. Why does it treat "-" as
    a deliminator when I set the deliminator to "-----". Any fix for this? Thanks.....

    I am expecting 6 tokens, but get 7 tokens. Why does it
    treat "-" as
    a deliminatorBecause it is supposed to
    when I set the deliminator to "-----".String tokenizer doesn't use Strings as delimiters, it uses characters.
    Any fix for this? Thanks.....Fix for what, everything works like it is supposed to.
    If you want to split apart a String using another String, then you must use regular expressions..
    If you want to use Regular Expressions, you need to be using Java 1.4
    String str = "xxx-----xxx-----xxx-----xx-x-----xxx-----xxx";
    String[] tokens = str.split(-----);tokens will be {"xxx", "xxx", "xxx", "xx-x", "xxx", "xxx"}

  • Help: Problems with StringTokenizer

    Hello.
    I try to use the StringTokenizer class for divide a String into tokens, but I want to use a String like "," (including the double quotation marks), but the StringTokenizer not behaves like I expected, it thinks that the quotation marks and the comma are independent separators.
    I construct my StringTokenizer object in this way
    StringTokenizer st = new StringTokenizer( stringvariable, "\",\"");
    There is another possibility to StringTokenizer behaves like I expect?
    There is another class to help me?
    Thanks

    StringTokenizer st = new StringTokenizer(
    stringvariable, "\",\"");
    Try to change it to:StiringTokenizer st = new StringTokenizer(str, "\",");

  • StringTokenizer class problem with strings in double quotes

    Hello Technocrats,
    I have a problem with tokenizing following string enclosed in (). (abc," India, Asia", computer engineer). My separator is ",", thus StringTokenizer class gives me 4 tokens namely abc, "India, Asia" and computer engineer. But I require that String in double quotes should be a single token. How to achieve this using StringTokenizer class? Or is there any other way?
    Thanks in advance.

    Try
    String[] str="abc,\" India, Asia\",computer engineer".split(",",1);
              for(String s: str)
                   System.out.println(s);
              }Thanks.

  • Problem with Java assignment using StringTokenizer

    I am having trouble with a Java assignment. The objective is to take a user-defined sentence, split each word up, and put each word on a line. Then the program extracts the vowels and prints them to the end of the word in the order they appeared. The program, when properly done, looks like this:
    Enter a line of text: Early in the morning 'bout the break of day
    rlEay
    ni
    the
    mrnngoi
    'btou
    the
    brkea
    fo
    day
    I can't figure out how to take the vowels and put them at the end of the word. So far my code looks like this:
    import java.io.*;
    import java.util.*;
    class WordPlay
         public static void main (String[] args) throws IOException
              // ========================= //
              // Declaration of variables. //
              // ========================= //
              int               count;
              BufferedReader     keyboard;
              String               oneWord;
              String               sentence;
              String               spaces;
              String               vowels;
              StringTokenizer     words;
              // ================================== //
              // Introduction and user orientation. //
              // ================================== //
              System.out.print ("Enter a line of text: ");
              // ============================ //
              // Initialization of variables. //
              // ============================ //
              keyboard           = new BufferedReader (new InputStreamReader(System.in));
              sentence           = keyboard.readLine();
              spaces               = " ";
              words               = new StringTokenizer(sentence,spaces);
              // ================= //
              // Logic statements. //
              // ================= //
              while (words.countTokens() > 0)
                   oneWord          = words.nextToken();
                   vowels          = "A,a,E,e,I,i,O,o,U,u,Y,y";
                   count          = 0;
                   System.out.println(" " + oneWord);
    I know that I need to use a StringTokenizer method to break each word's characters up and extract the vowels, but I don't know the right way to do this. My instructor stated that the program uses 2 while statements and an if statement, in that order. Problem is that I don't know how to proceed from here. Can anyone point me in the right direction?
    Let me know if you want anything clarified. I apologize for the verbose code; my instructor doesn't let us take any shortcuts.

    Hey, thanks for replying, but I'm still confused about one thing.
    If I'm not mistaken, the program when executed takes each word that I separated with StringTokenizer and prints the consonants and then moves on. How can I get Java to store the vowels only for the amount of time needed to concatenate them to the end of the word? I would think a while loop would solve the problem, but as my code is set up, the sentence is tokenized to only words. How do I properly break down the words into characters? I would think that another StringTokenizer could do this, but it seems to me that one StringTokenizer will override the other one, yet I need each word separated as well.
    Can you offer any advice on that?

  • Problem with threads running javaw

    Hi,
    Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
    troy.

    troy,
    Try and post a minimum code sample of your app which
    does not work.
    When using javaw, make sure you redirect the standard
    error and standard output streams to file.
    Graeme.Hi Graeme,
    I dont understand what you mean by redirection to file? some of my code below.
    The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
    public class Server{
    ServerSocket aServerSocket;
    Socket dianosticsSocket;
    Socket nPortExpress;
    ClientListener aClientListener;
    LinkedList queue = new LinkedList();
    int port = 0;
    int clientPort = 0;
    String clientName = null;
    boolean serverAlive = true;
    * Server constructor generates a server
    * Socket and then starts a client threads.
    * @param aPort      socket port of local machine.
    public Server(int aPort, String aClientName, int aClientPort){
    port = aPort;
    clientName = aClientName;
    clientPort = aClientPort;
    try{
    // create a new thread
    aServerSocket = new ServerSocket(port) ;
    // connect to the nPortExpress
    aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
    // aClientListener.setDaemon(true);
    aClientListener.start();
    // start a dianostic port
    DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
    // System.out.println("Server is running on port " + port + "...");
    // System.out.println("Connect to nPort");
    catch(Exception e)
    // System.out.println("ERROR: Server port " + port + " not available");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
    serverAlive = false;
    System.exit(1);
    while(serverAlive&&aClientListener.hostSocket.isConnected()){
    try{
    // connect the client
    Socket aClient = aServerSocket.accept();
    //System.out.println("open client connection");
    //System.out.println("client local: "+ aClient.getLocalAddress().toString());
    // System.out.println("client localport: "+ aClient.getLocalPort());
    // System.out.println("client : "+ aClient.getInetAddress().toString());
    // System.out.println("client port: "+ aClient.getLocalPort());
    // make a new client thread
    ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
    // start thread
    clientThread.start();
    catch(Exception e)
    //System.out.println("ERROR: Client connection failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
    }// end while
    } // end constructor Server
    void serverExit(){
         JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
         System.exit(1);
    }// end class Server
    *** connect to another server
    public class ClientListener extends Thread{
    InetAddress hostName;
    int hostPort;
    Socket hostSocket;
    BufferedReader in;
    PrintWriter out;
    boolean loggedIn;
    LinkedList queue;      // reference to Server queue
    Server serverRef; // reference to main server
    * ClientListener connects to the host server.
    * @param aHostName is the name of the host eg server name or IP address.
    * @param aHostPort is a port number of the host.
    * @param aLoginName is the users login name.
    public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer)      // reference to Server queue)
    hostName = aHostName;
    hostPort = aHostPort;
    queue = aQueue;
    serverRef = aServer;      
    // connect to the server
    try{
    hostSocket = new Socket(hostName, hostPort);
    catch(IOException e){
    //System.out.println("ERROR: Connection Host Failed");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);     
    System.exit(0);
    } // end constructor ClientListener
    ** multi client connection server
    ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
    queue = aQueue;
    addToQueue(this);
    client = aSocket;
    clientRef = aClientListener;
    aDiagnostic = diagnostics;
    } // end constructor ClientWorker
    * run method is the main loop of the server program
    * in change of handle new client connection as well
    * as handle all messages and errors.
    public void run(){
    boolean alive = true;
    String aSubString = "";
    in = null;
    out = null;
    loginName = "";
    loggedIn = false;
    while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
    if(aDiagnostic){
    out.println("WELCOME to diagnostics");
    broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    out.println("WELCOME to Troy's Server");
    broadCastDia("Connect : client "+client.getInetAddress().toString());
         out.flush();
    String line;
    while(((line = in.readLine())!= null)){
    StringTokenizer aStringToken = new StringTokenizer(line, " ");
    if(!aDiagnostic){
    broadCastDia(line);
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    else{
    if(line.equals("GETIPS"))
    getIPs();
    else{
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    } // end while
    catch(Exception e){
    // System.out.println("ERROR:Client Connection reset");
                             JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);     
    try{
    if(aDiagnostic){
    broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    broadCastDia("Disconnect : client "+client.getInetAddress().toString());
         out.flush();
    // close the buffers and connection;
    in.close();
    out.close();
    client.close();
    // System.out.println("out");
    // remove from list
    removeThreadQueue(this);
    alive = false;
    catch(Exception e){
    // System.out.println("ERROR: Client Connection reset failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);     
    }// end while
    } // end method run
    * method run - Generates io stream for communicating with the server and
    * starts the client gui. Run also parses the input commands from the server.
    public void run(){
    boolean alive = true;
    try{
    // begin to life the gui
    // aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
    // aGuiClient.show();
    in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
    while (alive && hostSocket.isConnected()){
    String line;
    while(((line = in.readLine())!= null)){
    System.out.println(line);
    broadCast(line);
    } // end while
    } // end while
    catch(Exception e){
    //     System.out.println("ERRORa Connection to host reset");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
    try{
    hostSocket.close();
         }catch(Exception a){
         JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
    alive = false;
    System.exit(1);
    } // end method run

  • I have a little problem with input in my program...(System.in, BufferedRead

    I'm coding a program that takes a input like this :
    Sample Input
    1 11 5
    2 6 7
    3 13 9
    12 7 16
    14 3 25
    19 18 22
    23 13 29
    24 4 28
    So I wrote a code like this :
    public static void main(String[] args) throws Exception{
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              String input = null;
                   while((input = br.readLine()) != null) {
                   StringTokenizer st = new StringTokenizer(input);
                   int leftX = Integer.parseInt(st.nextToken());
                   int height = Integer.parseInt(st .nextToken());
                   int rightX = Integer.parseInt(st.nextToken());
    .... rest of the code....
    But unlike I expected, the program did not pass the while loop.
    When I observed in debugging mode, when "br.readLine()" has no more strings to read,
    the whole program just becomes idle doing nothing, and it does not proceed further.
    Is there any problem with my code there? I've been trying to figure it out for hours... Please help!!!

    myunghajang wrote:
    Why doesn't it work in a way I intended? BufferedReader returns null if there is no more string to read, and what's the problem?
    It's so frustrating...The computer doesn't have a mind reading input, how is your program supposed to know you have finished typing the input?
    If you put the data in a file and redirect it into your program on the command line it will work (because the file knows where its end is)
    Your program could instead assume that a blank line is you end of input.

  • Problem with focus border and ListCellRenderer in custom listbox

    I have a bug in some code that I adapted from another posting on this board -- basically what I've done is I have a class that implements a custom "key/value" mapping listbox in which each list item/cell is actually a JPanel consisting of 3 JLabels: the first label is the "key", the second is a fixed "==>" mapping string, and the 3rd is the value to which "key" is mapped.
    The code works fine as long as the list cell doesn't have the focus. When it does, it draws a border rectangle to indicate focus, but if the listbox needs to scroll horizontally to display all the text, part of the text gets cut off (i.e. "sometex..." where "sometext" should be displayed).
    The ListCellRenderer creates a Gridlayout to lay out the 3 labels in the cell's JPanel.
    What can I do to remedy this situation? I'm not sure what I'd need to do in terms of setting the size of the panel so that all the text gets displayed OK within the listbox. Or if there's something else I can do to fix this. The code and a main() to run the code are provided below. To reproduce the problem, click the Add Left and Add Right buttons to add a "mapping" -- when it doesn't have focus, everything displays fine, but when you give it focus, note the text on the right label gets cut off.
    //======================================================================
    // Begin Source Listing
    //======================================================================
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.Vector;
    import java.util.Enumeration;
    public class TwoColumnListbox extends JPanel
    private JList m_list;
    private JScrollPane m_Pane;
    public TwoColumnListbox(Collection c)
         DataMapListModel model = new DataMapListModel();
         if (c != null)
         Iterator it = c.iterator();
         while (it.hasNext())
         model.addElement(it.next());
         m_list = new JList(model);
         ListBoxRenderer renderer= new ListBoxRenderer();
              m_list.setCellRenderer(renderer);
              setLayout(new BorderLayout());
              m_list.setVisibleRowCount(4);
              m_Pane = new JScrollPane(m_list);
              add(m_Pane, BorderLayout.NORTH);
    public JList getList()
    return m_list;
    public JScrollPane getScrollPane()
    return m_Pane;
    public static void main(String s[])
              JFrame frame = new JFrame("TwoColumnListbox");
              frame.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {System.exit(0);}
    final DataMappings dm = new DataMappings();
    final TwoColumnListbox lb = new TwoColumnListbox(dm.getMappings());
              final DataMap map = new DataMap();
              JButton leftAddBtn = new JButton("Add Left");
              leftAddBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setSource("JButton1");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton leftRemoveBtn = new JButton("Remove Left");
              leftRemoveBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setSource("");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton rightAddBtn = new JButton("Add Right");
    rightAddBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setDestination("/getQuote/symbol[]");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton rightRemoveBtn = new JButton("Remove Right");
    rightRemoveBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setDestination("");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JPanel leftPanel = new JPanel(new BorderLayout());
              leftPanel.add(leftAddBtn, BorderLayout.NORTH);
              leftPanel.add(leftRemoveBtn, BorderLayout.SOUTH);
    JPanel rightPanel = new JPanel(new BorderLayout());
              rightPanel.add(rightAddBtn, BorderLayout.NORTH);
              rightPanel.add(rightRemoveBtn, BorderLayout.SOUTH);
    frame.getContentPane().add(leftPanel, BorderLayout.WEST);
              frame.getContentPane().add(lb,BorderLayout.CENTER);
    frame.getContentPane().add(rightPanel, BorderLayout.EAST);
              frame.pack();
              frame.setVisible(true);
         class ListBoxRenderer extends JPanel implements ListCellRenderer
              private JLabel left;
              private JLabel arrow;
              private JLabel right;
              private Color clrForeground = UIManager.getColor("List.foreground");
    private Color clrBackground = UIManager.getColor("List.background");
    private Color clrSelectionForeground = UIManager.getColor("List.selectionForeground");
    private Color clrSelectionBackground = UIManager.getColor("List.selection.Background");
              public ListBoxRenderer()
                   setLayout(new GridLayout(1, 2, 10, 0));
                   //setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
                   left = new JLabel("");
                   left.setForeground(clrForeground);               
                   arrow = new JLabel("");
                   arrow.setHorizontalAlignment(SwingConstants.CENTER);
                   arrow.setForeground(clrForeground);
                   right = new JLabel("");
                   right.setHorizontalAlignment(SwingConstants.RIGHT);
                   right.setForeground(clrForeground);
                   add(left);
                   add(arrow);
                   add(right);
              public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean isSelected, boolean cellHasFocus)
                   if (isSelected)
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                        left.setForeground(clrSelectionForeground);
                        arrow.setForeground(clrSelectionForeground);
                        right.setForeground(clrSelectionForeground);
                   else
                        setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   left.setForeground(clrForeground);
                        arrow.setForeground(clrForeground);
                        right.setForeground(clrForeground);               
                   // draw focus rectangle if control has focus. Problem with focus
    // and cut off text!!
                   if (cellHasFocus)
                   // FIXME: for Windows LAF I'm not getting the correct thing here for some reason.
                   // Looks OK on Metal though.
                   setBorder(BorderFactory.createLineBorder(UIManager.getColor("focusCellHighlightBorder")));
                   else
                   setBorder(BorderFactory.createEmptyBorder());               
    DataMap map = (DataMap) value;
                   String displaySource = map.getSource();
                   String displayDest = map.getDestination();
                   left.setText(displaySource);
                   arrow.setText("=>to<=");
                   right.setText(displayDest);
                   return this;
    /** Interface for macro editor UI
    * @version 1.0
    class DataMappings
    private Collection mappings;
    public DataMappings()
    setMappings(new Vector(0));
    public DataMappings(Collection maps)
    setMappings(maps);
    /** gets mapping value of a specified source object
    * @param src -- the "key" or source object, what is mapped.
    * @return what the source object is mapped to
    * @version 1.0
    public Object getValue(String src)
    if (src != null)
    Iterator it = mappings.iterator();
    while (it.hasNext());
    DataMap thisMap = (DataMap) it.next();
    if (thisMap.getSource().equals(src))
    return thisMap.getDestination();
    return null;
    /** sets mapping value of a specified source object
    * @param src -- the "key" or source object, what is mapped.
    * @param what the source object is to be mapped to
    * @version 1.0
    public void setValue(String src, String dest)
    if (src != null)
    // see if the value is in there first.
    Iterator it = mappings.iterator();
    while (it.hasNext())
    DataMap thisMap = (DataMap) it.next();
    if (thisMap.getSource().equals(src))
    thisMap.setDestination(dest);
    return;
    // not in the collection, add it
    mappings.add(new DataMap(src, dest));
    /** gets collection of mappings
    * @return a collection of all mappings in this object.
    * @version 1.0
    public Collection getMappings()
    return mappings;
    /** sets collection of mappings
    * @param maps a collection of src to destination mappings.
    * @version 1.0
    public void setMappings(Collection maps)
    mappings = maps;
    /** adds a DataMap
    * @param map a DataMap to add to the mappings
    * @version 1.0
    public void add(DataMap map)
    if (map != null)
    mappings.add(map);
    class DataMap
    public DataMap() {}
    public DataMap(String source, String destination)
    m_source = source;
    m_destination = destination;
    public String getSource()
    return m_source;
    public void setSource(String s)
    m_source = s;
    public String getDestination()
    return m_destination;
    public void setDestination(String s)
    m_destination = s;
    protected String m_source = null;
    protected String m_destination = null;
    /** list model for datamaps that provides ways
    * to determine whether a source is already mapped or
    * a destination is already mapped.
    class DataMapListModel extends DefaultListModel
    public DataMapListModel()
    super();          
    /** determines whether a source is already mapped
    * @param src -- the source property of a datamapping
    * @return true if the source is in the list, false if not
    public boolean containsSource(Object src)
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    if (dm.getSource().equals(src))
    return true;
    return false;
    /** determines whether a destination is already mapped
    * @param dest -- the destination property of a datamapping
    * @return true if the destination is in the list, false if not
    public boolean containsDest(Object dest)
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    if (dm.getDestination().equals(dest))
    return true;
    return false;
    public DataMappings getDataMaps()
    DataMappings maps = new DataMappings();
    // add all the datamaps in the model
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    maps.add(dm);
    return maps;
    //======================================================================
    // End of Source Listing
    //======================================================================

    I did not read the program, but the chopping looks like a layout problem.
    I think it's heavy to use a panel + 3 components in a gridlayout for each cell. look at this sample where i draw the Cell myself,
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Jlist3 extends JFrame 
         Vector      v  = new Vector();
         JList       jc = new JList(v);
         JScrollPane js = new JScrollPane(jc);
    public Jlist3()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         for (int j=0; j < 70; j++)     v.add(""+j*1000+"a  d"+j);
           setBounds(1,1,400,310);
         getContentPane().add(js);
         js.setPreferredSize(new Dimension(230,259));
         jc.setSelectedIndex(1);
         jc.setCellRenderer(new MyCellRenderer());
         getContentPane().setLayout(new FlowLayout());
         setVisible(true);
    public class MyCellRenderer extends JLabel implements ListCellRenderer
         String  txt;
         int     idx;
         boolean sel;
    public Component getListCellRendererComponent(JList list,
                             Object  value,           // value to display
                             int     index,           // cell index
                             boolean isSelected,      // is the cell selected
                             boolean cellHasFocus)    // the list and the cell have the focus
         idx = index;
         txt = value.toString();
         sel = isSelected;
         setText(txt);
         return(this);
    public void paintComponent(Graphics g)
         if (idx%2 == 1) g.setColor(Color.white);
              else        g.setColor(Color.lightGray);
         if (sel)        g.setColor(Color.blue);
         g.fillRect(0,0,getWidth(),getHeight());
         StringTokenizer st = new StringTokenizer(txt.trim()," ");
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),1,14);
         g.setColor(Color.red);
         g.drawString("===>",70,14);
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),110,14);
    public static void main (String[] args) 
         new Jlist3();
    Noah
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Jlist3 extends JFrame
         Vector v = new Vector();
         JList jc = new JList(v);
         JScrollPane js = new JScrollPane(jc);
    public Jlist3()
         addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         for (int j=0; j < 70; j++)     v.add(""+j*1000+"a d"+j);
         setBounds(1,1,400,310);
         getContentPane().add(js);
         js.setPreferredSize(new Dimension(230,259));
         jc.setSelectedIndex(1);
         jc.setCellRenderer(new MyCellRenderer());
         getContentPane().setLayout(new FlowLayout());
         setVisible(true);
    public class MyCellRenderer extends JLabel implements ListCellRenderer
         String txt;
         int idx;
         boolean sel;
    public Component getListCellRendererComponent(JList list,
                             Object value, // value to display
                             int index, // cell index
                             boolean isSelected, // is the cell selected
                             boolean cellHasFocus) // the list and the cell have the focus
         idx = index;
         txt = value.toString();
         sel = isSelected;
         setText(txt);
         return(this);
    public void paintComponent(Graphics g)
         if (idx%2 == 1) g.setColor(Color.white);
              else g.setColor(Color.lightGray);
         if (sel) g.setColor(Color.blue);
         g.fillRect(0,0,getWidth(),getHeight());
         StringTokenizer st = new StringTokenizer(txt.trim()," ");
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),1,14);
         g.setColor(Color.red);
         g.drawString("===>",70,14);
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),110,14);
    public static void main (String[] args)
         new Jlist3();
    }

  • Problems with SwingWorker and classes in my new job, ;), can you help me?

    Hi all, ;)
    First of all, sorry about my poor English.
    I have a problem with Swing and Threads, I hope you help me (because I'm in the firsts two weeks in my new job)
    I have two classes:
    Form1: Its a JPanel class with JProgressBar and JLabel inside.
    FormularioApplet: (the main) Its a JPanel class with a form1 inside.
    I have to download a file from a server and show the progress of the download in the JProgressBar. To make it I do this:
    In Form1 I make a Thread that update the progress bar and gets the fole from the server.
    In FormularioApplet (the main) I call to the method getDownloadedFile from Form1 to get the File.
    THE PROBLEM:
    The execution of FormularioApplet finishes before the Thread of Form1 (with download the file) download the file. Then, when I call in FormularioApplet the variable with the file an Exception: Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException is generated.
    First main begins his execution, then call to Form1 (a thread) then continues his execution and when the execution is finished ends the execution os Form1 and his thread.
    How can I do for main class call the function and the Thread download his file after main class assign the file of return method?
    How can I pass information froma class include an a main class. Form1 can't send to main (because main class made a Form1 f1 = new Form1()) any information from his end of the execution. I think if Form1 can say to main class that he finishes is job, then main class can gets the file.
    I put in bold the important lines.
    Note: My level of JAVA, you can see, is not elevated.
    THANKS A LOT
    Form1 class:
    package es.cambrabcn.signer.gui;
    import java.awt.HeadlessException;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import javax.swing.SwingUtilities;
    public class Form1 extends javax.swing.JPanel {
        //Variables relacionadas con la clase original DownloadProgressBar
        private InputStream file;
        private int totalCicles;
        private int totalFiles;
        private int currentProgress;
        private SwingWorker worker;
        private ByteArrayOutputStream byteArray;
        private boolean done;
        /** Creates new form prueba */
        public Form1() {
            initComponents();
            this.byteArray = new ByteArrayOutputStream();
            progressBar.setStringPainted(true);
            //this.totalFiles = totalFiles;
            currentProgress = 0;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" C�digo Generado ">                         
        private void initComponents() {
            label1 = new javax.swing.JLabel();
            progressBar = new javax.swing.JProgressBar();
            statusLabel = new javax.swing.JLabel();
            setBackground(new java.awt.Color(255, 255, 255));
            setMaximumSize(new java.awt.Dimension(300, 150));
            setMinimumSize(new java.awt.Dimension(300, 150));
            setPreferredSize(new java.awt.Dimension(300, 150));
            label1.setFont(new java.awt.Font("Arial", 1, 18));
            label1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            label1.setText("Barra de progreso");
            statusLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            statusLabel.setText("Cargando");
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, statusLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, progressBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, label1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(statusLabel)
                    .addContainerGap(73, Short.MAX_VALUE))
        }// </editor-fold>                       
        // Declaraci�n de variables - no modificar                    
        private javax.swing.JLabel label1;
        private javax.swing.JProgressBar progressBar;
        private javax.swing.JLabel statusLabel;
        // Fin de declaraci�n de variables                  
        public byte[] getDownloadedFile(String documentToSign){
             //Variables locales
             byte puente[] = null;
             try{
                //Leemos el documento a firmar
                StringTokenizer st = new StringTokenizer(documentToSign, ";");
                Vector<URL> fileURL = new Vector<URL>();
                HttpSender sender = new HttpSender(null);
                //Introducimos la lista de URLs de archivos a bajar en el objeto Vector
                for(; st.hasMoreTokens(); fileURL.add(new URL(st.nextToken())));
                //Para cada URL descargaremos un archivo
                for(int i = 0; i < fileURL.size(); i++) {
                    file = sender.getMethod((URL)fileURL.get(i));
                    if(file == null) {
                        Thread.sleep(1000L);
                        throw new RuntimeException("Error descarregant el document a signar.");
                    System.out.println("Form1 Dentro de getDownloadFile, Antes de startDownload()");
                    //Fijamos el valor del n�mero de ciclos que se har�n seg�n el tama�o del fichero
                    this.totalCicles = sender.returnCurrentContentLength() / 1024;
                    this.progressBar.setMaximum(totalCicles);
                    //Modificamos el texto del JLabel seg�n el n�mero de fichero que estemos descargando
                    this.statusLabel.setText((new StringBuilder("Descarregant document ")).append(i + 1).append(" de ").append(fileURL.size()).toString());
                    statusLabel.setAlignmentX(0.5F);
                    *//Iniciamos la descarga del fichero, este m�todo llama internamente a un Thread*
                    *this.startDownload();*
                    *System.out.println("Form1 Dentro de getDownloadFile, Despu�s de startDownload()");*
                    *//if (pane.showProgressDialog() == -1) {*
                    *while (!this.isDone()){*
                        *System.out.println("No est� acabada la descarga");*
                        *if (this.isDone()){*
                            *System.out.println("Thread ACABADO --> Enviamos a puente el archivo");*
                            *puente = this.byteArray.toByteArray();*
                            *System.out.println("Form1 getDownloadFile() tama�o puente: " + puente.length);*
                        *else{*
                            *Thread.sleep(5000L);*
    *//                        throw new RuntimeException("Proc�s de desc�rrega del document a signar cancel�lat.");*
            catch (HeadlessException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("UI: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (MalformedURLException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (HttpSenderException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (InterruptedException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            //System.out.println("Form1 getDownloadFile() tama�o puente: " + puente.length);
            return puente;
        public void updateStatus(final int i){
            Runnable doSetProgressBarValue = new Runnable() {
                public void run() {
                    progressBar.setValue(i);
            SwingUtilities.invokeLater(doSetProgressBarValue);
        public void startDownload() {
            System.out.println("Form1 Inicio startDownload()");
            System.out.println("Form1 Dentro de startDownload, antes de definir la subclase SwingWorker");
            System.out.println(done);
            worker = new SwingWorker() {
                public Object construct() {
                    System.out.println("Form1 Dentro de startDownload, dentro de construct(), Antes de entrar en doWork()");
                    return doWork();
                public void finished() {
                    System.out.println("Form1 Dentro de startDownload, dentro de finished(), Antes de asignar done = true");
                    System.out.println(done);
                    done = true;
                    System.out.println("Form1 Dentro de startDownload, dentro de finished(), Despu�s de asignar done = true");
                    System.out.println(done);
                    statusLabel.setText("Completado, tama�o del archivo: " + (byteArray.size() / 1024) + "KB");
            System.out.println("Form1 Dentro de startDownload, antes de worker.start()");
            worker.start();
            System.out.println("Form1 Dentro de startDownload, antes de salir de startDownload");
            System.out.println(done);
            System.out.println("Form1 Dentro de startDownload, despu�s de worker.start()");
         * M�todo doWork()
         * Este m�todo descarga por partes el archivo que es necesario descargar, adem�s de actualizar
         * la barra de carga del proceso de carga de la GUI.
        public Object doWork() {
            System.out.println("Form1 doWork() this.byteArray.size(): " + this.byteArray.size());
            try {
                byte buffer[] = new byte[1024];
                for(int c = 0; (c = this.file.read(buffer)) > 0;) {
                    this.currentProgress++;
                    updateStatus(this.currentProgress);
                    this.byteArray.write(buffer, 0, c);
                this.byteArray.flush();
                this.file.close();
                this.currentProgress = totalCicles;
                updateStatus(this.currentProgress);
            } catch(IOException e) {
                e.printStackTrace();
            System.out.println("Form1 doWork() FINAL this.byteArray.size(): " + this.byteArray.size());
            //done = true;
            System.out.println("AHORA DONE = TRUE");
            return "Done";
        public boolean isDone() {
            return this.done;
    FormularioApplet class (main)
    package es.cambrabcn.signer.gui;
    import java.awt.Color;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.URL;
    import java.security.Security;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import javax.swing.SwingUtilities;
    import netscape.javascript.JSObject;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import sun.security.provider.Sun;
    import be.cardon.cryptoapi.provider.CryptoAPIProvider;
    public class FormularioApplet extends java.applet.Applet {
        //Variables globales
        int paso = 0;
        private static final String JS_ONLOAD = "onLoad";
        private static final String JS_ONLOADERROR = "onLoadError";
        private static final int SIGNATURE_PDF = 1;
        private static final int SIGNATURE_XML = 2;
        //private String signButtonValue;
        private int signatureType;
        private String documentToSign;
        private String pdfSignatureField;
        private Vector<String> outputFilename;
        private Color appletBackground = new Color(255, 255, 255);
        private Vector<byte[]> ftbsigned;
         * Initializes the applet FormularioApplet
        public void init(){
            try {
                SwingUtilities.invokeLater(new Runnable() {
                //SwingUtilities.invokeAndWait(new Runnable() {
                //java.awt.EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        try{
                            readParameters();
                            initComponents();
                        catch(FileNotFoundException e){
                            javascript(JS_ONLOADERROR, new String[] {
                                (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                            e.printStackTrace();                       
                        catch(IOException e) {
                            javascript(JS_ONLOADERROR, new String[] {
                                (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                            e.printStackTrace();
            catch (Exception e) {
                javascript(JS_ONLOADERROR, new String[] {
                    (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                e.printStackTrace();
            javascript(JS_ONLOAD, null);
        /** This method is called from within the init() method to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" C�digo Generado ">
        private void initComponents() {
            this.setSize(350, 450);
            appletPanel = new javax.swing.JPanel();
            jPanel1 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JLabel();
            jPanel2 = new javax.swing.JPanel();
            label = new javax.swing.JLabel();
            jPanel3 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            setLayout(new java.awt.BorderLayout());
            appletPanel.setBackground(new java.awt.Color(255, 255, 255));
            appletPanel.setMaximumSize(new java.awt.Dimension(350, 430));
            appletPanel.setMinimumSize(new java.awt.Dimension(350, 430));
            appletPanel.setPreferredSize(new java.awt.Dimension(350, 430));
            jPanel1.setBackground(new java.awt.Color(255, 255, 255));
            jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            jTextField1.setFont(new java.awt.Font("Arial", 1, 18));
            jTextField1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jTextField1.setText("SIGNATURA ELECTRONICA");
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel2.setBackground(new java.awt.Color(255, 255, 255));
            jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            label.setIcon(new javax.swing.ImageIcon("C:\\java\\workspaces\\cambrabcn\\firmasElectronicas\\logo.gif"));
            org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label)
                    .addContainerGap(229, Short.MAX_VALUE))
            jPanel3.setBackground(new java.awt.Color(255, 255, 255));
            jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            //this.jButton1.setVisible(false);
            //this.jButton2.setVisible(false);
            jButton1.setText("Seg\u00fcent");
            jButton1.setAlignmentX(0.5F);
            //Cargamos el primer formulario en el JPanel2
            loadFirstForm();
            //Modificamos el texto del bot�n y el contador de pasos.
            //this.jButton1.setText("Siguiente");
            //this.jButton1.setVisible(true);
            //this.jButton2.setVisible(true);
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jButton2.setText("Cancel\u00b7lar");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
            jPanel3.setLayout(jPanel3Layout);
            jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 94, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 112, Short.MAX_VALUE)
                    .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton2)
                        .add(jButton1))
                    .addContainerGap())
            org.jdesktop.layout.GroupLayout appletPanelLayout = new org.jdesktop.layout.GroupLayout(appletPanel);
            appletPanel.setLayout(appletPanelLayout);
            appletPanelLayout.setHorizontalGroup(
                appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, appletPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .add(appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
            appletPanelLayout.setVerticalGroup(
                appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, appletPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            add(appletPanel, java.awt.BorderLayout.CENTER);
        }// </editor-fold>
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            this.destroy();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            changeForms(this.paso);
        // Declaraci�n de variables - no modificar
        private javax.swing.JPanel appletPanel;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JPanel jPanel3;
        private javax.swing.JLabel jTextField1;
        private javax.swing.JLabel label;
        // Fin de declaraci�n de variables
         * M�todo readParameters
         * M�todo que inicializa los valores de los par�metros internos, recibidos por par�metro.
        private void readParameters() throws FileNotFoundException, IOException {
             ???????????????? deleted for the forum
            addSecurityProviders();
         * M�tode loadFirstForm
         * Aquest m�tode carrega a jPanel2 el formulari que informa sobre la c�rrega dels arxius
        private void loadFirstForm(){
            //Form1 f1 = new Form1(stream, i + 1, fileURL.size(), sender.returnCurrentContentLength(), appletBackground);
            //Form1 f1 = new Form1(fileURL.size(), sender.returnCurrentContentLength());
            Form1 f1 = new Form1();
            //Lo dimensionamos y posicionamos
            f1.setSize(310, 150);
            f1.setLocation(10, 110);
            //A�adimos el formulario al JPanel que lo contendr�
            this.jPanel2.add(f1);
            //Validem i repintem el JPanel
            jPanel2.validate();
            jPanel2.repaint();
            //Descarreguem l'arxiu a signar
            *System.out.println("FormularioApplet Dentro de loadFirstForm(), antes de llamar a getDownloadFile()");*
            *byte obj[] = f1.getDownloadedFile(this.documentToSign);*
            if (obj == null){
                System.out.println("Lo que devuelve f1.getDownloadedFile(this.documentToSign) es NULL");
            else{
                System.out.println("Lo que devuelve f1.getDownloadedFile(this.documentToSign) NO es NULL");
                System.out.println("obj: " + obj.length);
            this.ftbsigned.add(obj);
            System.out.println("FormularioApplet Dentro de loadFirstForm(), despu�s de llamar a getDownloadFile()");
            //Indicamos que el primer paso ya se ha efectuado
            this.paso++;
         * M�tode changeForms
         * Aquest m�tode carrega a jPanel2 un formulari concret segons el valor de la variable global "paso"
        private void changeForms(int paso){
            /*A cada paso se cargar� en el JPanel y formulario diferente
             * Paso previo: Se realiza en la inicializaci�n, carga el formulario, descarga el archivo y muestra la barra de carga.
             * Case 1: Se carga el formulario de selecci�n de tipo de firma.
             * Case 2: Se carga el formulario de datos de la persona que firma.
            this.paso = paso;
            switch(paso){
                case 1:
                    //Creamos un objeto de formulario (seleccion de tipo de firma)
                    Form2 f2 = new Form2();
                    //Lo dimensionamos y posicionamos
                    f2.setSize(310, 185);
                    f2.setLocation(10, 110);
                    //Quitamos el formulario 1 y a�adimos el formulario 2 al JPanel
                    this.jPanel2.remove(1);
                    this.jPanel2.add(f2);
                    //Validem i repintem el JPanel
                    jPanel2.validate();
                    jPanel2.repaint();
                    //Modificamos el contador de pasos.
                    this.paso++;
                    break;
                case 2:
                    //Creamos un objeto de formulario (seleccion de tipo de firma)
                    Form3 f3 = new Form3();
                    //Lo dimensionamos y posicionamos
                    f3.setSize(310, 175);
                    f3.setLocation(15, 130);
                    //Quitamos el formulario 1 y a�adimos el formulario 3 al JPanel
                    this.jPanel2.remove(1);
                    this.jPanel2.add(f3);
                    //Validem i repintem el JPanel
                    jPanel2.validate();
                    jPanel2.repaint();
                    //Modificamos el texto del bot�n y el contador de pasos.
                    this.jButton1.setText("Finalizar");
                    this.paso++;
                    break;
                default:
                    //Finalizar el Applet
                    //C�digo que se encargue de guardar el archivo en el disco duro del usuario
                    break;
        private void addSecurityProviders() throws FileNotFoundException, IOException {
            Security.addProvider(new CryptoAPIProvider());
            if (signatureType == SIGNATURE_PDF) {
                Security.addProvider(new BouncyCastleProvider());
            else {
                Security.addProvider(new Sun());
        private File createOutputFile(String filename, int index) {
            return new File((String)outputFilename.get(index));
        protected Object javascript(String function, String args[]) throws RuntimeException {
            //Remove
            if (true) return null;
            try {
                Vector<String> list = new Vector<String>();
                if(args != null) {
                    for(int i = 0; i < args.length; i++) {
                        list.addElement(args);
    if(list.size() > 0) {
    Object objs[] = new Object[list.size()];
    list.copyInto(objs);
    return JSObject.getWindow(this).call(function, objs);
    } catch(UnsatisfiedLinkError e) {
    e.printStackTrace();
    throw new RuntimeException((new StringBuilder()).append(e).append("\nFunci�: ").append(function).toString());
    } catch(Throwable e) {
    e.printStackTrace();
    throw new RuntimeException((new StringBuilder()).append(e).append("\nFunci�: ").append(function).toString());
    return JSObject.getWindow(this).call(function, new Object[0]);
    Edited by: Kefalegereta on Oct 31, 2007 3:54 AM
    Edited by: Kefalegereta on Oct 31, 2007 4:00 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Look at iOS Troubleshooting Wi-Fi networks and connections  http://support.apple.com/kb/TS1398
    iPad: Issues connecting to Wi-Fi networks  http://support.apple.com/kb/ts3304
    iOS: Recommended settings for Wi-Fi routers and access points  http://support.apple.com/kb/HT4199
    Additional things to try.
    Try this first. Turn Off your iPad. Then turn Off (disconnect power cord) the wireless router & then back On. Now boot your iPad. Hopefully it will see the WiFi.
    Go to Settings>Wi-Fi and turn Off. Then while at Settings>Wi-Fi, turn back On and chose a Network.
    Change the channel on your wireless router. Instructions at http://macintoshhowto.com/advanced/how-to-get-a-good-range-on-your-wireless-netw ork.html
    Another thing to try - Go into your router security settings and change from WEP to WPA with AES.
    How to Quickly Fix iPad 3 Wi-Fi Reception Problems
    http://osxdaily.com/2012/03/21/fix-new-ipad-3-wi-fi-reception-problems/
    If none of the above suggestions work, look at this link.
    iPad Wi-Fi Problems: Comprehensive List of Fixes
    http://appletoolbox.com/2010/04/ipad-wi-fi-problems-comprehensive-list-of-fixes/
    Fix iPad Wifi Connection and Signal Issues  http://www.youtube.com/watch?v=uwWtIG5jUxE
    ~~~~~~~~~~~~~~~
    If any of the above solutions work, please post back what solved your problem. It will help others with the same problem.
     Cheers, Tom

  • Having Problem with JSP In Netscape!HELP!!!

    HI to all! I�m having problem with the jsp that i have :( If i use the Internet explorer it works but at Netscape... it doesn�t work :( The value of "PTE" is null... I need help !!!Please! I think the HTML IS NOT HELPING ...
    the code is :
    <html>
    <head>
    <!--tp001_transferencias_oic_POR.jsp-->
    <title>BBVA - Transfer&ecirc;ncias - Transfer&ecirc;ncias OIC</title>
    <LINK rel=STYLESHEET type='text/css' href="estilos/tablas.css">
    <!--script language="javascript" src "js/dynlayer.js"></script-->
    <script language="Javascript" src="js/banner.js"></script>
    <script language="Javascript" src="js/tp_oic.js"></script>
    <script language="Javascript" src="js/utilidades.js"></script>
    <script language="javascript" src="js/limpar.js"></script>
    <script language="javascript" src="js/tiempo.js"></script>
    </HEAD>
    <body marginheight="0" marginwidth="0" leftmargin="0" topmargin="0" class="pag-contenido" onLoad="controlSesion();">
    <%@ include file ="includecbtf.jsp" %>
    <% String s = (String)datos.get("dt");
    java.util.StringTokenizer str = new java.util.StringTokenizer(s, "-");
    String anoServer = str.nextToken() ;
    String mesServer = str.nextToken() ;
    String diaServer = str.nextToken() ;
    %>
    <!--1�form-->
    <form method="post" name="captura" action="<%=urls.get("action")%>">
    <center> <!--1�center-->
    <br>
    <!--1�table-->
    <table border="0" cellpadding="0" cellspacing="0" width="500"> <!--table das transf e nome-->
    <tr>
    <td colspan="3"><img src="images/linea.gif" border="0"></td>
    </tr>
    <tr>
    <td width="250"><img src="images/traspasos.gif" border="0"></td>
    <td width="82"><img src="images/titular.gif" border="0"></td>
    <td width="169" class="fondotitular"><font class="texttitular"><%=datos.get("usuario")%></font></td>
    </tr>
    <tr>
    <td colspan="3"><img src="images/linea.gif" border="0"></td>
    </tr>
    </table> <!--Fim do 1� table-->
    <br><br>
    </center> <!--Fim do 1� Center-->
    <center> <!--2� Center-->
    <!--Conteudo do table 2-->
    <table cellpadding="3" cellspacing="1" border="0" align="center" width="500"> <!--table referente a mensagem-->
    <tr>
    <td class="cabeceratitulo" colspan="2"><p class="titulotabla">Nota : As Transfer&ecirc;ncias para outras Institui&ccedil;&otilde;es de Cr&eacute;dito decorrem de acordo com os hor&aacute;rios da Compensa&ccedil;&atilde;o Interbanc&aacute;ria, n&atilde;o se responsabilizando o BBVA pela sua realiza&ccedil;&atilde;o fora das regras em uso.</p></td>
    </tr>
    <tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
    </table> <!--fim do table2-->
    </center> <!--Fim do 2� Center-->
    <center> <!-- Inicio 3� Center-->
    <!--Conteudo da table Combo-->
    <!--Table3-->
    <table cellpadding="3" cellspacing="1" border="0" align="center" width="500">
    <tr>
    <td class="cabeceratitulo" colspan="2"><p class="titulotabla">Transfer&ecirc;ncia Conta a Conta para outras Institui&ccedil;&ocirc;es de Cr&eacute;dito</p></td>
    </tr>
    <tr>
    <td class="formgrisosc" width="100">
    <p class="dato">Conta Ordenante:  </p></td>
    <td class="formgrisosc" width="300">
         <%
    java.util.Vector v = (java.util.Vector)(datos.get("ListaCuentas"));
    java.util.Hashtable elem;
    java.util.Enumeration e = v.elements();
    %>
    <!--1� Select-->
    <select name="conta" size="1" class="formgrisosc">
    <%
    while (e.hasMoreElements()){
    elem = (com.ibm.dse.base.Hashtable)(e.nextElement());
    String cuenta = ((String)elem.get("s_banco")).trim() + "-"+((String)elem.get("s_oficina")).trim()+((String)elem.get("s_dcontrol")).trim()+((String)elem.get("s_num_cuenta")).trim();
    out.println("<option value=\"" + ((String)elem.get("s_tipo")) + "$" + ((String)elem.get("s_clave_asunto")) + "\">" + cuenta + "</option>");
    %>
    </select> <!--Fim do 1� Select-->
    </td>
    </tr>
    <tr>
    <td class="formgriscla" width="100"><p class="dato">Data de Processamento:</p></td>
    <td class="formgriscla">
    <input type="text" name="dia" size="2"class="formgriscla" value="<%=diaServer %>" maxlength="2" class="formgriscla"> / 
    <input type="text" name="mes" size="2"class="formgriscla" value="<%=mesServer %>" maxlength="2" class="formgriscla"> / 
    <input type="text" name="ano" size="4"class="formgriscla" value="<%=anoServer %>" maxlength="4" class="formgriscla"></td>
    <input type="hidden" name="dact" size="2"class="formgriscla" value="<%=diaServer %>" maxlength="2" class="formgriscla">
    <input type="hidden" name="mact" size="2"class="formgriscla" value="<%=mesServer %>" maxlength="2" class="formgriscla">
    <input type="hidden" name="aact" size="4"class="formgriscla" value="<%=anoServer %>" maxlength="4" class="formgriscla"></td>
    </tr>
    <tr>
    <td class="formgrisosc" width="100"><p class="dato">Moeda: </p></td>
    <td class="formgrisosc"><p class="dato">
    <!--Select 2�Ver este bem-->
    <select name="Moeda" size="1" class="formgrisosc">
    <option value="PTE" selected>Escudos</option>      
    <option value="EUR">Euros</option>
    </select> </p>
    </td>
    </tr>
    <tr>
    <td class="formgriscla" width="100"><p class="dato">Import&acirc;ncia:</p></td>
    <td class="formgriscla"><input type="text" name="importancia" size="20" maxlength="15" class="formgriscla"></td>
    </tr>
    <tr>
    <td class="formgrisosc" width="100"><p class="dato">Ref&ecirc;rencia:</p></td>
    <td class="formgrisosc"><input type="text" name="ref" size="15" maxlength="10" class="formgrisosc"></td>
    </tr>
    <tr>
    <td class="formgriscla" width="100"><p class="dato">NIB Benefici&aacute;rio:</p></td>
    <td class="formgriscla"><input type="text" name="nibBeneficiario" size="30" maxlength="21" class="formgriscla"></td>
    </tr>
    <tr>
    <td class="formgrisosc" width="100"><p class="dato">Descri&ccedil;&atilde;o p/ Conta D&eacute;bito:</p></td>
    <td class="formgrisosc"><input type="text" name="debito" size="45" maxlength="45" class="formgrisosc"></td>
    </tr>
    <tr>
    <td class="formgriscla" width="100"><p class="dato">Descri&ccedil;&atilde;o p/ Conta Cr&eacute;dito:</p></td>
    <td class="formgriscla"><input type="text" name="credito" size="45" maxlength="45" class="formgriscla"></td>
    </tr>
    <tr>
    <td class="cabecera" colspan="2"><img src="images/1x1.gif" width=1 height=3 border="0"></td>
    </tr>
    </table> <!--Fim do table 3-->
    </center> <!--Fim do 3�center-->
    <center> <!--Inicio do 4� Center-->
    <!--Inicio da table 4�-->
    <table border="0" cellspacing="2" cellpadding="0">
    <tr>
    <td valign="top"><img src="images/limpar.gif" border="0" alt="Apagar"></td>
    <td valign="top"><img src="images/continuar.gif" border="0" alt="Continuar"></td>
    </tr>
    </table> <!--Fim do 4� Table-->
    </form> <!--Fim do FORM-->
    </center> <!--Fim do 4� Center-->
    </body> <!--Fim do BODY-->
    </html> <!--Fim do Html-->
    Thanks pepole!

    thanks people! when i try to validate the action "PTE" he gaves me (if i put a ALERT...) null.
    the js code is : (Moeda is coin )
    //testa amount
    // var ent = (f.amount.value);
    var tamanho = f.amount.value.length;
    var valor = f.amount.value;
    decimals = 2; // Apenas pode ter duas casas decimais?
    if (((tamanho == 0) || (valor == 0)) && ok)
    alert ("A import�ncia tem de ser maior que zero.");
    f.amount.focus();
    f.amount.select();
    ok = false;
    else
         alert(f.Moeda.value);
    if((f.Moeda.value=="PTE") && ok)
    for (j = 0; j < tamanho; j++)
    xx = valor.charAt(j);     
         if ((!(xx.match(numeroER)) && ok))
    alert ("O Campo Import�ncia deve ser num�rico inteiro.");     
         f.amount.focus();
         f.amount.select();
         ok = false;
              //if para limitar valor dos Escudos      
         if (ok)
         if (eval(valor) > 1000000)
         alert ("The field amount must be maxium 1 000 000 Pte.");     
         f.amount.focus();
         f.amount.select();
         ok = false;
    else
         if (ok)
              //function checkDecimals(f.amount, f.importancia.value) {
              if (isNaN(valor)) {
                   alert("O Campo Import�ncia deve ser num�rico e como separador decimal, o ponto.");
                   f.amount.select();
                   f.amount.focus();
                   ok = false;
              else {
                   timeshundred = parseFloat(valor * Math.pow(10, decimals));
                   integervalue = parseInt(parseFloat(valor) * Math.pow(10, decimals));
                   if (timeshundred != integervalue)
                   alert ("Apenas pode ter " + decimals + " casas decimais. Por favor tente outra vez.");
                   f.amount.select();
                   f.amount.focus();
                   ok = false;
              if (ok)
              {  //if to limit the value of the  Euros
         if(eval(valor) > 4988)
    alert ("The field amount must be maxium 4988 Eur.");     
         f.amount.focus();
         f.amount.select();
         ok = false;
    }//end of amount

  • WLS 7.0 sp2 - Servlet Problems with SOAP messages

              I'm using Weblogic 7.0 SP2 and trying to create a Servlet to receive SOAP wrapped
              XML messages. I'm getting the following error. Is this a problem with WLS7.0sp2's
              support of JAXM? The System.out.println's indicate I have successfully received
              the incoming SOAP request and then successfully formatted the SOAP response, but
              upon returning saving the response it appears to blow up. Does anyone have any
              suggestions?
              I need to do the following in a servlet:
              - receive an incoming SOAP request with an embedded XML message
              - perform some processing
              - return a SOAP response with an embedded XML message
              Should I be using JAXM? Or can I do this same task easily with JAX-RPC?
              <Feb 24, 2004 4:10:42 PM AST> <Error> <HTTP> <101017> <[ServletContext(id=260434
              7,name=isd.war,context-path=)] Root cause of ServletException
              java.lang.Error: NYI
              at weblogic.webservice.core.soap.SOAPMessageImpl.saveRequired(SOAPMessag
              eImpl.java:360)
              at javax.xml.messaging.JAXMServlet.doPost(Unknown Source)
              at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
              at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
              at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run
              (ServletStubImpl.java:1058)
              at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
              pl.java:401)
              at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
              pl.java:306)
              at weblogic.servlet.internal.WebAppServletContext$ServletInvocationActio
              n.run(WebAppServletContext.java:5445)
              at weblogic.security.service.SecurityServiceManager.runAs(SecurityServic
              eManager.java:780)
              at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
              rvletContext.java:3105)
              at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
              pl.java:2588)
              at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:213)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:189)
              >
              I've stripped the code down so that all it does is verifies the incoming SOAP/XML
              request and creates a hard-coded response... be gentle... I'm a novice at this
              import javax.xml.soap.*;
              import javax.servlet.*;
              import javax.servlet.http.*;
              // import javax.xml.transform.*;
              import java.util.*;
              import java.io.*;
              public class RegisterServlet extends HttpServlet
              static MessageFactory fac = null;
              static
              try
              fac = MessageFactory.newInstance();
              catch (Exception ex)
              ex.printStackTrace();
              public void init(ServletConfig servletConfig) throws ServletException
              super.init(servletConfig);
              public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
              IOException
              try
              System.out.println("** Note: doPost() Entering req = " + req);
              // Get all the headers from the HTTP request
              MimeHeaders headers = getHeaders(req);
              // Get the body of the HTTP request
              InputStream is = req.getInputStream();
              // Now internalize the contents of a HTTP request
              // and create a SOAPMessage
              SOAPMessage msg = fac.createMessage(headers, is);
              System.out.println("** Note: doPost() Step A");
              SOAPMessage reply = null;
              reply = onMessage(msg);
              System.out.println("** Note: doPost() Step B reply = " + reply);
              if (reply != null)
              * Need to call saveChanges because we're
              * going to use the MimeHeaders to set HTTP
              * response information. These MimeHeaders
              * are generated as part of the save.
              if (reply.saveRequired())
              System.out.println("** Note: doPost() Step C reply.saveRequired()");
              reply.saveChanges();
              resp.setStatus(HttpServletResponse.SC_OK);
              putHeaders(reply.getMimeHeaders(), resp);
              // Write out the message on the response stream
              OutputStream os = resp.getOutputStream();
              System.out.println("** Note: doPost() Step D os = " + os);
              reply.writeTo(os);
              os.flush();
              else
              resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
              catch (Exception ex)
              throw new ServletException("** Error: SAAJ POST failed: " + ex.getMessage());
              static MimeHeaders getHeaders(HttpServletRequest req)
              Enumeration enum = req.getHeaderNames();
              MimeHeaders headers = new MimeHeaders();
              while (enum.hasMoreElements())
              String headerName = (String)enum.nextElement();
              String headerValue = req.getHeader(headerName);
              StringTokenizer values =
              new StringTokenizer(headerValue, ",");
              while (values.hasMoreTokens())
              headers.addHeader(headerName,
              values.nextToken().trim());
              return headers;
              static void putHeaders(MimeHeaders headers, HttpServletResponse res)
              Iterator it = headers.getAllHeaders();
              while (it.hasNext())
              MimeHeader header = (MimeHeader)it.next();
              String[] values = headers.getHeader(header.getName());
              if (values.length == 1)
              res.setHeader(header.getName(),
              header.getValue());
              else
              StringBuffer concat = new StringBuffer();
              int i = 0;
              while (i < values.length)
              if (i != 0)
              concat.append(',');
              concat.append(values[i++]);
              res.setHeader(header.getName(), concat.toString());
              // This is the application code for handling the message.
              public SOAPMessage onMessage(SOAPMessage message)
              SOAPMessage replymsg = null;
              try
              System.out.println("** Note: OnMessage() Entering msg = " + message);
              //Extract the ComputerPart element from request message and add to reply SOAP
              message.
              SOAPEnvelope reqse = message.getSOAPPart().getEnvelope();
              SOAPBody reqsb = reqse.getBody();
              //System.out.println("** Note: OnMessage() Step B");
              System.out.println("** Note: OnMessage () Step A Soap Request Message Body = "
              + reqsb);
              //Create a reply mesage from the msgFactory of JAXMServlet
              System.out.println("** Note: OnMessage () Step B");
              replymsg = fac.createMessage();
              SOAPPart sp = replymsg.getSOAPPart();
              SOAPEnvelope se = sp.getEnvelope();
              SOAPBody sb = se.getBody();
              System.out.println("** Note: OnMessage () Step C Soap Reply Before Message Body
              = " + sb);
              se.getBody().addBodyElement(se.createName("RegisterResponse")).addChildElement(se.createName("ErrorCode")).addTextNode("000");
              System.out.println("** Note: OnMessage () Step D Soap Reply After Message Body
              = " + sb);
              replymsg.saveChanges();
              System.out.println("** Note: OnMessage() Exiting replymsg = " + (replymsg));
              catch (Exception ex)
              ex.printStackTrace();
              return replymsg;
              

    Michael,
    I got the same error on WLS8.1/Win2K professional and apache FOP (old version).
    After digging into the WLS code and FOP(old version). i found the conflict happens
    on
    the "org.xml.sax.parser" system property. In WLS code, they hard coded like the
    following when startup weblogic server:
    System.setProperty("org.xml.sax.parser", "weblogic.xml.jaxp.RegistryParser");
    But the FOP code try to use the "org.xml.sax.parser" system property to find the
    sax parser then conlict happens.
    Here is the response from BEA support :
    "I consulted with our developers regarding the question of whether we can change
    the hard-coded value for the java system property: org.xml.sax.parser by using
    a configuration parameter and I found that unfortunately there is no specific
    setting to change the value. As you had mentioned in your note the org.xml.sax.parser
    system property can be changed programmatically in your application code."
    I solve my problem by using newer apache FOP (it never use the system property:org.xml.sax.parser
    any more) and XML Registy for WLS8.1.
    Good luck.
    David Liu
    Point2 Technologies Inc.
    "p_michael" <[email protected]> wrote:
    >
    Help.
    When we migrated from WLS 6.1 to WLS 7.0 SP2 when encountered a problem
    with XML
    parsing that did not previously exist.
    We get the error "weblogic.xml.jaxp.RegistryParser is not a SAX driver".
    What does this mean? And, what should we do about it.
    p_michael

  • Urgent!!!! please help!!! problems with visual j++ and jbuilder

    Hi,
    I have been worried about this problem since a long time. I couldn't get any help figuring out the problem. I am using microsoft visual j++ 6.0
    I have tried putting the rt.jar file in the class path but its getting me out of the compilation errors and not this runtime error.
    I faced this problem with many codes.
    When i used the jbuilder as one of the users suggested, i am getting this compilation errors,
    "FloatingAgent.java": Error #: 704 : cannot access directory vrml at line 4, column 4
    "FloatingAgent.java": Error #: 704 : cannot access directory vrml\node at line 5, column 4
    "FloatingAgent.java": Error #: 704 : cannot access directory vrml\field at line 6, column 4
    "FloatingAgent.java": Error #: 300 : class Script not found in class FloatingAgent at line 9, column 39
    Please somebody help.
    Jagadish.
    // an agent is floating randomly.
    import java.util.*;
    import vrml.*;
    import vrml.node.*;
    import vrml.field.*;
    import java.io.*;
    public class FloatingAgent extends Script{
    SFVec3f setAgentPosition;
    SFRotation setAgentRosition;
         static int count=0;
         float agentPosition[] = new float[3];
         float agentRosition[] = new float[4];
         float rotangle = 0.0f;
         float aRad= (float) (Math.PI/180);
    //Random randomNumGenerator = new Random();
    public void initialize(){
    // get the reference of the event-out 'setAgentPosition'.
    setAgentPosition =
    (SFVec3f)getEventOut("setAgentPosition");
              setAgentRosition =
    (SFRotation)getEventOut("setAgentRosition");
    // initialize the agent position.
    agentPosition[0] = 0.0f;
    agentPosition[1] = 0.0f;
    agentPosition[2] = 0.0f;
         agentRosition[0] = 0.0f;
    agentRosition[1] = 0.0f;
    agentRosition[2] = 1.0f;
         agentRosition[3] = 0.0f;
    public void processEvent(Event e){
    if(e.getName().equals("interval") == true){
    moveAgent();
    // generate random float value ranging between -0.1 to 0.1.
    /*float generateRandomFloat(){
    return(randomNumGenerator.nextFloat() * 0.2f - 0.1f);
    // move the agent randomly.
    void moveAgent()
    agentPosition = reader();
    // agentPosition[0] += generateRandomFloat() ;
    // agentPosition[1] += generateRandomFloat();
    //agentPosition[2] += generateRandomFloat();
         rotangle += 2.0f;
         agentRosition[3] = rotangle * aRad;
    // move the agent to the new position.
    setAgentPosition.setValue(agentPosition);
         setAgentRosition.setValue(agentRosition);
    }//move agent
    static float[] reader()
         float p1[] = new float[3];
         try{
         FileReader fr = new FileReader("data.txt");
         BufferedReader br = new BufferedReader(fr);
         String s;
    int count1=0;
    count++;     
         try{  
         while((s=br.readLine())!=null)
    count1++;
              StringTokenizer st = new StringTokenizer(s);
              if(count1==count)
              int i=0;
              while(st.hasMoreTokens())
              p1[i++]=Float.parseFloat(st.nextToken());
              }//if
              }//end of stringTokenizer while.
         fr.close();                
         catch(IOException f)
              System.out.println("file cannot be opened");
         }//try
         catch(FileNotFoundException e)
         System.out.println("file doesn't exist");
         } //try
         return p1;
    }//reader

    Didn't we hear this from you yesterday? Sounds too familiar. If so, we told you you're using a MICROSOFT product (Visual J++), which is OLD, and not up to the SUN's java specification. We suggested that you dump Visual J++ and go with something like JBuilder, Forte, Visual Cafe, etc.
    This is a SUN site in support of SUN's java - not Microsoft's outdated and non-existent (anymore) version.

  • Spotify and facebook problem with the date

    Hi, everyone.My spotify account have a problem with the date. I changed the date on facebook and nothing happens with that, the spotify account has a wrong date, is not the same as facebook account

    Hi ,
    By default , RFC accept date format of SQL date (yyyy-mm-dd) . If you are using a date picker from WD, it directly set the date in SQL date format. Incase if you are trying to pass date to RFC in some other way you have to convert that into SQL date format before passing.
    if you are passing String date of format dd-mm-yyyy , you try this method to convert that to SQL date and pass to your RFC.
    public java.sql.Date sqlDateConvert( String date)  {
        //@@begin sqlDateConvert()
         java.sql.Date dateObj=null;
         try{     
              StringTokenizer tempStringTokenizer = new StringTokenizer(""+date,"-");          int dd=Integer.parseInt(tempStringTokenizer.nextToken().trim());
                                    int mm=Integer.parseInt(tempStringTokenizer.nextToken().trim());
              mm=mm-1;
              int yyyy=Integer.parseInt(tempStringTokenizer.nextToken().trim());
              Calendar cal =Calendar.getInstance();   
              cal.set(yyyy,mm,dd);                         
              dateObj = new java.sql.Date( cal.getTime().getTime());
         }catch(Exception e)
              return dateObj;
    Hope this will help you.

Maybe you are looking for

  • I get a blue screen on Windows 7 startup via bootcamp (Lion OS)

    My Windows 7 works fine via VMWare Fusion, however since having upgrading to Lion: 1. Get a blue screen hardware issue starting up directly in Windows which appears just after the Windows startup animation. Using the windows repair doesn't seem to do

  • User-exits or BAdI for transaction VL10B

    Hello everybody, I have to modify an outbound order during its creation from a purchase order in transaction VL10B. The modification is to update the serial numbers and the batch. As the process is in background it is quite difficult to debug the pro

  • Upgrading from 10.4.11 to 10.5 Finder wont launch

    I updated my G5 from 10.4.11 to 10.5 using the default install on the 10.5 dvd. Trying to restart gets all the way to bkground pattern & applications visible in the dock & the clock working but it never gets all the way to launching the desktop. Just

  • Passing multiple single values to a Planning Sequence

    Hi All,       We are using BEx Analyzer for  planning. We  are passing multiple single values for a single variable , to a IP-planning sequence.  Planning sequence is only taking the last value passed and ignoring the rest. Multiple variable values a

  • XPAAJ Java API question

    Hi, I am currently struggling with this task: I have created a PDF using livecycle, what i want todo is in java convert the generated PDF to an image, i cannot use the livecycle server, as it will have to generate on a client machine, that at the tim