Flushing & Cathicng Exceptions

Hello ABAP-Experts,
I have a problem in understanding how to catch exceptions after calling method cl_gui_cfw=>flush.
Why calling "flush": Well, otherwise if there is no FLUSH after directory_create (for example) is called, the value of rc (methods internal return code) is checked prematurely.
Here my attempt:
" Calling method directory_create
call method cl_gui_frontend_services=>directory_create
      exporting
        directory                = tmpdir
      changing
        rc                       = returncode
      exceptions
        directory_create_failed  = 1
        cntl_error               = 2
        error_no_gui             = 3
        directory_access_denied  = 4
        directory_already_exists = 5
        path_not_found           = 6
        unknown_error            = 7
        not_supported_by_gui     = 8
        wrong_parameter          = 9
        others                   = 10.
      sy-subrc = my_sy_subrc " <=== ???!
" Calling method flush
call method cl_gui_cfw=>flush
  exceptions
    cntl_system_error = 1
    cntl_error        = 2
    others            = 3.
      sy-subrc = my_sy_subrc2 " <=== ???!
Now my problem: How can I be sure to catch the execeptions of method cl_gui_frontend_services=>directory_create (1 to 10), since the flush method has its own exceptions (1 to 3)? After calling flush, I think they are overwritten by the flush exception -- checking them before the flush makes no sense, because the method is probably not executed (Automation queue).
(Background: I am writing test-programs for some frontend methods, and want to catch all possible exceptions and to write them in a internal table, so that I can see which method crashes.)
I hope my problem is clear and someone can clarify.
Thanks a lot in advance
Regards
Jasmin

Hi,
You can rely on the SUBRC after calling the directory_create because the flush is already present in it
Look at the code of the method :
>    call method handle->call_method
>     exporting
>        method  = 'CreateDirectory'
>        p1      = directory
>        p_count = 1
>        queue_only = ' '
>      importing
>        result = rc
>      exceptions
>        others = 1.
>
>    if sy-subrc <> 0.
>      raise cntl_error.
>    endif.
>
>    call method cl_gui_cfw=>flush
>      exceptions
>        cntl_system_error = 1
>        cntl_error        = 2
>        others            = 3.
>    if sy-subrc <> 0.
>      raise cntl_error.
>    endif.

Similar Messages

  • Unable to read AsynchronousSocketChannel after getting timeout exception

    i am trying to read some data on the server using a AsynchronousSocketChannel .
    I have this scenario :
    1- Call channel.read : this will print "Received"
    2- Call channel.read : this should fail due to timeout exception.
    3- Call channel.read : I am sending data in this case but I got the exception "Reading not allowed due to timeout or cancellation"
    Below is the source code
    My environment is :
    OS : Windows 7
    JDK :
    Java(TM) SE Runtime Environment (build 1.7.0-b147)
    Java HotSpot(TM) 64-Bit Server VM (build 21.0-b17, mixed mode)
    package com.qmic.asynchronous;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.AsynchronousChannelGroup;
    import java.nio.channels.AsynchronousServerSocketChannel;
    import java.nio.channels.AsynchronousSocketChannel;
    import java.nio.channels.CompletionHandler;
    import java.util.concurrent.ConcurrentLinkedQueue;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.TimeUnit;
    public class NIOChannel {
         public static void main(String[] args) {
              try{
                   MyAsynchronousTcpServer server = new MyAsynchronousTcpServer();
                   Thread serverThread = new Thread(server);
                   serverThread.start();
                   Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9001, InetAddress.getByName("127.0.0.1"), 9003);
                   socket.setSoTimeout(30000);
                   socket.setKeepAlive(true);
                   if (socket.isConnected()){
                        PrintWriter dos = new PrintWriter(socket.getOutputStream());
                        InputStream input = socket.getInputStream();
                        byte[] buffer = new byte[1024];
                        // Data of the first call
                        dos.print("ABCDEFGH");
                        dos.flush();
                        byte[] data = new byte[50];
                        socket.getInputStream().read(data);
                        // Print the result from server, written in handler of first read operation.
                        System.out.println("Result is:" + new String(data));
                        if (data.length > 0){
                             Thread.sleep(10000); // Wait for 10 Seconds so the second read on the server will fail.
                        // Data of the third call
                        dos.print("ABCDEFGH");
                        dos.flush();
              }catch(Exception ex){
                   ex.printStackTrace();
         class MyAsynchronousTcpServer implements Runnable{
              final int SERVER_PORT = 9001;
              final String SERVER_IP = "127.0.0.1";
              private int THREAD_POOL_SIZE = 10;
              private int DEFAULT_THREAD_POOL_SIZE = 2;
              ConcurrentLinkedQueue<ListenHandler> handlers = new ConcurrentLinkedQueue<ListenHandler>();
              boolean shutDown = false;
              public void run(){
                   //create asynchronous server-socket channel bound to the default group
                   try {
                        // Create the ChannelGroup(thread pool).
                        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
                        AsynchronousChannelGroup group = AsynchronousChannelGroup.withCachedThreadPool(executorService, DEFAULT_THREAD_POOL_SIZE);
                        AsynchronousServerSocketChannel asynchronousServerSocketChannel =
                             AsynchronousServerSocketChannel.open(group);
                        if (asynchronousServerSocketChannel.isOpen())
                             //bind to local address
                             asynchronousServerSocketChannel.bind(new InetSocketAddress(SERVER_IP, SERVER_PORT));
                             while(!shutDown){
                                  Future<AsynchronousSocketChannel> asynchronousSocketChannelFuture =asynchronousServerSocketChannel.accept();
                                  final AsynchronousSocketChannel channel = asynchronousSocketChannelFuture.get(); // Timeout can be specified in the get() function, thread is blocked here
                                  System.out.println("New channel created successfully");
                                  // First call, should print Result of call 1 is : 10 (size of ABCDEFGH)
                                  ByteBuffer buffer1 = ByteBuffer.allocateDirect(250);
                                  channel.read(buffer1, 5, TimeUnit.SECONDS, null, new CompletionHandler<Integer, Object>() {
                                       @Override
                                       public void completed(Integer result, Object attachment) {
                                            System.out.println("Result of call 1 is :" + result);
                                            ByteBuffer response = ByteBuffer.wrap("Received".getBytes());
                                            channel.write(response);
                                       @Override
                                       public void failed(Throwable exc, Object attachment) {
                                            exc.printStackTrace();
                                  Thread.sleep(3000);
                                  // Second read, should print error InterruptedByTimeoutException
                                  ByteBuffer buffer2 = ByteBuffer.allocateDirect(250);
                                  channel.read(buffer2, 5, TimeUnit.SECONDS, null, new CompletionHandler<Integer, Object>() {
                                       @Override
                                       public void completed(Integer result, Object attachment) {
                                            System.out.println("Result of call 2 is :" + result);
                                       @Override
                                       public void failed(Throwable exc, Object attachment) {
                                            exc.printStackTrace();
                                  Thread.sleep(9000);
                                  // Second read operation was failed, no try to read again . AN EXCEPTION IS THROWN HERE : Reading not allowed due to timeout or cancellation
                                  ByteBuffer buffer3 = ByteBuffer.allocateDirect(250);
                                  channel.read(buffer3, 5, TimeUnit.SECONDS, null, new CompletionHandler<Integer, Object>() {
                                       @Override
                                       public void completed(Integer result, Object attachment) {
                                            System.out.println("Result of call 3 is :" + result);
                                       @Override
                                       public void failed(Throwable exc, Object attachment) {
                                            exc.printStackTrace();
                        else
                             System.out.println("The asynchronous server-socket channel cannot be opened!");
                   catch (Exception ex)
                        ex.printStackTrace();
                        System.err.println(ex);
         }

    I'm having the same "Unable to read the SIM card" issue. My phone is less than two months old, the unable to read SIM card issue started about a week after I purchased the phone. That was followed by a host of erratic, sporadic issues to the phone becomes unusable and the only way to temporarily fix it is to remove the battery for a few seconds.  I've gone through the factory reset with Verizon reps where I purchased the phone from as well as with a Verizon online Chat representative. In a nutshell, I got a ticket to send the phone back to Samsung in Plano, Texas to get the phone fixed, I am going to do that today because this problem is ridiculous.

  • Under heavy load, flush attribute gives ArrayIndexOutOfBoundsException

    Hi,
    Under heavy load conditions, the jsp include directive's flush attribute which is set to true gives java.lang.ArrayIndexOutOfBoundsException
    A similar bug 6295722 had been reported earlier. But solution to this is not present. Can you please help in resolving this issue. Is this a known issue?
    The following code generates the ArrayIndexOutOfBoundsException
    <jsp:include page="<%=file%>" flush="true" />
    Exception generated is
    java.lang.ArrayIndexOutOfBoundsException: -2147483648
         at java.text.SimpleDateFormat.subFormat(SimpleDateFormat.java:1049)
         at java.text.SimpleDateFormat.format(SimpleDateFormat.java:882)
         at java.text.SimpleDateFormat.format(SimpleDateFormat.java:852)
         at java.text.DateFormat.format(DateFormat.java:316)
         at org.apache.jserv.JServUtils.encodeCookie(JServUtils.java:217)
         at org.apache.jserv.JServConnection.sendHttpHeaders(JServConnection.java:703)
         at org.apache.jserv.JServConnection$JServOutputStream.write(JServConnection.java:1969)
         at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:202)
         at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:272)
         at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:276)
         at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:122)
         at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:212)
         at java.io.PrintWriter.flush(PrintWriter.java:276)
         at oracle.jsp.runtime.OracleJspWriter.flush(OracleJspWriter.java:554)
         at oa_html._Login._jspService(_Login.java:974)
         at oracle.jsp.runtime.HttpJsp.service(HttpJsp.java:119)
         at oracle.jsp.app.JspApplication.dispatchRequest(JspApplication.java:417)
         at oracle.jsp.JspServlet.doDispatch(JspServlet.java:267)
         at oracle.jsp.JspServlet.internalService(JspServlet.java:186)
         at oracle.jsp.JspServlet.service(JspServlet.java:156)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:588)
         at org.apache.jserv.JServConnection.processRequest(JServConnection.java:456)
         at org.apache.jserv.JServConnection.run(JServConnection.java:294)
         at java.lang.Thread.run(Thread.java:619)
    Thanks,
    Shruthi

    Format objects, like SimpleDateFormat, are generally not thread-safe. This almost looks like a case where one is being used concurrently and it's causing a problem. Take gimbal2's suggestion and contact support for your app server.
    Edit:
    Just did some quick searching and came up with a link to JServUtils.java source code (not sure what version you've got or where the "real" code lives withing Apache):
    http://turbine.apache.org/turbine/turbine-2.2.0/xref/org/apache/jserv/JServUtils.html
    You can see on line 78 that a static SimpleDateFormat field exists. You can also see it being used in the encodeCookie method on lines 103 and 111 without synchronization.
    Edited by: kschneid on Dec 18, 2009 12:39 PM

  • Help on exception

    I'm getting the following exception when I call the sessionfactory.getInstance(user, pw, host, port) method:
    Join Session failed because could not find Session ID
    Anybody ever see this before? I can't connect using any of my jython or java programs. This is major problem.
    I've been running various programs that use the API for years now and this error just came up this weekend. I've asked if anything in our environment changed but haven't gotten anyone to admit that is has just yet.
    Anybody? help?

    your problem is that there is a "\n" after the 5.5 in your txt file right?
    i had this same problem. but i may not have solved it the way you are looking for.
    what i did, was when i wrote to the text file, i ended my for loop early and instead of having a "\n", i took it out for the last entry.
    something like this...
    try
    FileWriter write = new FileWriter(fileName);
    int a;
    for(a = 0; a < totalLines - 1; a++)
    {  write.write(array[a] + "\n");
    write.write(array[a]);
    write.flush();
    catch(Exception e) {}
    sorry, if this doesn't help you at all
    Andy

  • Servlet ObjectOutputStream is unable to Flush Object Out Simultaneously

              Hi,
              I faced some strange behavior with the Servlet's ObjectOutputStream. I created
              a for loop to flush out object to the calling applet. Instead of flushing the
              Object one by one, the servlet will only flush out all the object at the end of
              the loop.
              The following code illustrate the servlet in performing the flushing:
              public void doGet(HttpServletRequest request, HttpServletResponse response)throws
              ServletException, IOException{
              response.setContentType("application/octet-stream");
              ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
              try {
              for(int i=0; i<10 ; i++) {
              oos.writeObject(new String("Hello"));
              oos.flush();
              } catch(Exception e) {
              e.printStackTrace();
              How do I make sure that the servlet flush the object out one at a time.
              Thanks.
              

    I have the same problem and have checked the memory which appears to be fine.
    Any where else i could have a look.
    Any help, would be greatly appreciated.
    Regards
    Varinder
    Edited by: tonysidhu on Sep 15, 2010 1:44 PM

  • Exception while writing textdocument()

    I am trying to write the document from a JTextPane like this way in jdk1.6
    FileOutputStream fstrm = new FileOutputStream(f);
    ObjectOutput ostrm = new ObjectOutputStream(fstrm);
    ostrm.writeObject(textPane.getDocument());but im facing some exception like this
    java.io.NotSerializableException: sun.awt.image.ToolkitImage
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java
    :1509)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:14
    74)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.jav
    a:1392)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java
    :1509)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:14
    74)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.jav
    a:1392)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java
    :1509)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:14
    74)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.jav
    a:1392)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java
    :1509)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:14
    74)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.jav
    a:1392)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
            at new_page$SaveAction.actionPerformed(new_page.java:809)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
    95)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
    a:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:236)
            at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:2
    73)
            at java.awt.Component.processMouseEvent(Component.java:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
    ad.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)please help me regarding this?
    best regards
    tanvir

    thnx pravinth
    im facing some extremely undesireble problems....
    look the incidents
    1) i wrote the in jdk1.5 and it was working properly i was happy then
    2) then i set my jdk path in JCreator to jdk1.6 and from then i am facing this error.
    3)Again i reset my jdk path to jdk1.5 but the exception is not gone
    i wrote a sample demo code with OutputObjectStream it works well
    but while in my main project code it is occuring the problem
    im quite gone to hell now
    i finished my project almost 94% but for it my whole project are in great trouble i really need serious help now
    import static java.awt.Color.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import static java.awt.event.InputEvent.*;
    import static java.awt.AWTEvent.*;
    import javax.swing.plaf.metal.*;
    import java.io.*;
    import java.net.InetAddress.*;
    import java.net.*;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import javax.swing.text.*;
    import javax.swing.undo.*;
    import javax.swing.event.*;
    import javax.swing.text.rtf.*;
    import java.util.*;
    import java.awt.event.*;
    import java.beans.*;
    public class new_page extends JInternalFrame
         JLabel splashLabel;
           JWindow splashScreen;
         JDesktopPane thedesktop;     
         String unicode="";
         String keyboardinput="";
         //JTextArea jta;
         JTextPane textPane;
         JInternalFrame ami;
         public boolean enable=true;
         public int layout=0;
         public JComboBox jtx;
         public boolean dead_key=false;
         public JComboBox jtx1;
         public JComboBox jtx2;     
         final String [] getFontsSize;
         final StyledEditorKit myeditor;
         public static String myfont_name="";
         public static int myfont_size=0;
         protected UndoAction undoAction;
        protected RedoAction redoAction;
        protected SaveAction saveAction;
        protected UndoManager undo = new UndoManager();     
         private FileAction LogInAction,LogOutAction,ExitAction,helpAction;   
         private JMenu FileMenu,ReportMenu,HelpMenu;
         private JMenuItem ItemUniversalReportAction,ItemIndividualReportAction;
         new_page(JDesktopPane thedesktop)
              this.thedesktop = thedesktop;          
              JMenuBar bar = new JMenuBar();
    //////////////////       FILE MENU ITEM      ////////////////////
              FileMenu = new JMenu("File");
              FileMenu.setMnemonic('F');
              LogInAction= new FileAction("Save",null);          
              LogOutAction= new FileAction("Font",null);          
              ExitAction=new FileAction("Print",null);
              helpAction=new FileAction("Help",null);
              undoAction = new UndoAction(KeyStroke.getKeyStroke('Z',CTRL_DOWN_MASK));
              redoAction = new RedoAction(KeyStroke.getKeyStroke('Y',CTRL_DOWN_MASK));
              saveAction = new SaveAction();
              //FileMenu.add(new JMenuItem(LogInAction));
              //FileMenu.add(new JMenuItem(LogOutAction));
              //FileMenu.addSeparator();
              //FileMenu.add(new JMenuItem(ExitAction));
              //FileMenu.addSeparator();
              LogInAction.putValue(Action.SMALL_ICON,new ImageIcon(getClass().getResource("resources/save1.GIF")));
              LogOutAction.putValue(Action.SMALL_ICON,new ImageIcon(getClass().getResource("resources/font1.GIF")));
              ExitAction.putValue(Action.SMALL_ICON,new ImageIcon(getClass().getResource("resources/print1.GIF")));
              helpAction.putValue(Action.SMALL_ICON,new ImageIcon(getClass().getResource("resources/help1.GIF")));
              //LogOutAction.putValue(Action.SMALL_ICON,new ImageIcon("a.gif"));
              bar.setBackground(Color.lightGray);
              bar.add(FileMenu);          
         //     bar.add(ReportMenu);          
              //bar.add(HelpMenu);
              //setJMenuBar(bar);
              JToolBar toolBar = new JToolBar();
              JButton loginbutton = new JButton(new ImageIcon(getClass().getResource("resources/save1.GIF")));          
              loginbutton.setBorder(null);
              loginbutton.setText(null);
              loginbutton.setToolTipText("Save");
              loginbutton.addActionListener(saveAction);
              JButton logout0button = new JButton(LogOutAction);          
              logout0button.setBorder(null);
              logout0button.setText(null);
              logout0button.setToolTipText("Save");
              JButton picbutton = new JButton(new ImageIcon(getClass().getResource("resources/pic.GIF")));          
              picbutton.setBorder(null);
              picbutton.setText(null);
              picbutton.addActionListener(
                                       new ActionListener()
                                            public void actionPerformed(ActionEvent e)
                                                 try{
                                                           JFileChooser files;
                                                            files = new JFileChooser();
                                                            //ExampleFileFilter ff = new ExampleFileFilter("jpg",)
                                                            ExampleFileFilter jpgFilter = new ExampleFileFilter("jpg", "");
                                                           ExampleFileFilter gifFilter = new ExampleFileFilter("jpeg", "");
                                                           ExampleFileFilter gif1Filter = new ExampleFileFilter("gif", "");
                                                           ExampleFileFilter bothFilter = new ExampleFileFilter(new String[] {"jpg", "jpeg","gif"}, "");
                                                           files.addChoosableFileFilter(jpgFilter);
                                                           files.addChoosableFileFilter(gifFilter);
                                                           files.addChoosableFileFilter(gif1Filter);
                                                           files.setAcceptAllFileFilterUsed(false);
                                                           files.addChoosableFileFilter(bothFilter);
                                                                int result=files.showOpenDialog(null);
                                                                if(result!=JFileChooser.APPROVE_OPTION)
                                                                     if(result!=JFileChooser.CANCEL_OPTION)
                                                                     JOptionPane.showMessageDialog(null,"Error Occured");
                                                                     return;
                                                                String s=files.getSelectedFile().getPath();
                                                                File f = files.getSelectedFile();                    
                                                 SimpleAttributeSet st = new SimpleAttributeSet();
                                                 StyleConstants.setIcon(st,new ImageIcon(s));
                                                 textPane.getDocument().insertString(textPane.getCaretPosition(),"sdf",st);
                                                 }catch(Exception er)
                                                      JOptionPane.showMessageDialog(null,"File can not be loaded.");
              picbutton.setToolTipText("Picture Insert");
              JButton undobutton = new JButton(new ImageIcon(getClass().getResource("resources/undo.GIF")));          
              undobutton.setBorder(null);
              undobutton.setText(null);
              undobutton.setToolTipText("Undo");
              undobutton.addActionListener(undoAction);
              JButton redobutton = new JButton(new ImageIcon(getClass().getResource("resources/redo.GIF")));          
              redobutton.setBorder(null);
              redobutton.setText(null);
              redobutton.setToolTipText("Redo");
              redobutton.addActionListener(redoAction);
              JButton logoutbutton = new JButton(new ImageIcon(getClass().getResource("resources/bold.GIF")));
              logoutbutton.setBorder(null);
              logoutbutton.setText(null);
              logoutbutton.setToolTipText("Bold");
              logoutbutton.addActionListener(new StyledEditorKit.BoldAction());     
              JButton logout1button = new JButton(new ImageIcon(getClass().getResource("resources/italic.GIF")));
              logout1button.setBorder(null);
              logout1button.setText(null);
              logout1button.setToolTipText("Italic");
              logout1button.addActionListener(new StyledEditorKit.ItalicAction());
              JButton logout2button = new JButton(new ImageIcon(getClass().getResource("resources/underline.GIF")));
              logout2button.setBorder(null);
              logout2button.setText(null);
              logout2button.setToolTipText("UnderLine");
              logout2button.addActionListener(new StyledEditorKit.UnderlineAction());
              JButton leftbutton = new JButton(new ImageIcon(getClass().getResource("resources/left.GIF")));          
              leftbutton.setBorder(null);
              leftbutton.setText(null);
              leftbutton.setToolTipText("Left");
              leftbutton.addActionListener(new StyledEditorKit.AlignmentAction("Left",0));
              JButton centerbutton = new JButton(new ImageIcon(getClass().getResource("resources/center.GIF")));          
              centerbutton.setBorder(null);
              centerbutton.setText(null);
              centerbutton.setToolTipText("Center");
              centerbutton.addActionListener(new StyledEditorKit.AlignmentAction("Center",1));
              JButton rightbutton = new JButton(new ImageIcon(getClass().getResource("resources/right.GIF")));          
              rightbutton.setBorder(null);
              rightbutton.setText(null);
              rightbutton.setToolTipText("Right");
              rightbutton.addActionListener(new StyledEditorKit.AlignmentAction("Right",2));
              JButton colorbutton = new JButton(new ImageIcon(getClass().getResource("resources/color.GIF")));          
              colorbutton.setBorder(null);
              colorbutton.setText(null);
              colorbutton.setToolTipText("Text Color");
              colorbutton.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                              Color co = Color.BLACK;
                              co = JColorChooser.showDialog(new_page.this,"Choose a Text Color to Apply",co);
                              if(co==null)
                                   co = Color.BLACK;
                             Action fontAction = new StyledEditorKit.ForegroundAction("color",co);
                             fontAction.actionPerformed(null);
              String sss[]={"sdfasdf","sdfsdf","sdfsdf"};
              jtx = new JComboBox(sss);
              jtx.setSize(20,15);          
              jtx.setToolTipText("Keyboard Selection");
              if(static_data.Instance().instance.supported_font!=null)
              jtx1 = new JComboBox(static_data.Instance().instance.supported_font);
              else
              jtx1 = new JComboBox();
              jtx1.setSize(15,10);
              jtx1.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             JComboBox comboBox = (JComboBox)e.getSource();
                             String fontSize = comboBox.getSelectedItem().toString();
                             Action fontAction = new StyledEditorKit.FontFamilyAction("family", fontSize);
                             fontAction.actionPerformed(null);
              jtx1.setToolTipText("Font Selection");
              getFontsSize = new String[60];
              for(int i=0;i<60;i++)
                getFontsSize[i] = String.valueOf(i+1);
              jtx2 = new JComboBox(getFontsSize);
              jtx2.setSize(10,15);
              jtx2.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             JComboBox comboBox = (JComboBox)e.getSource();
                             int fontSize = Integer.parseInt( comboBox.getSelectedItem().toString() );
                             Action fontAction = new StyledEditorKit.FontSizeAction("size", fontSize);
                             fontAction.actionPerformed(null);
              jtx2.setToolTipText("Font Size Selection");
              final JCheckBox myfont = new JCheckBox(":Default Bangla OTF Font");
              myfont.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             if(myfont.isSelected())                         
                                  jtx1.setEnabled(false);
                                       Font font;                   
                                     try {
                                           font = Font.createFont(java.awt.Font.TRUETYPE_FONT, getClass().getResourceAsStream("font/SolaimanLipi.ttf"));
                                           font=font.deriveFont(Font.PLAIN,25);
                                              textPane.setFont(font);
                                              jtx2.setSelectedIndex(24);
                                     }catch(Exception ee){
                                          JOptionPane.showMessageDialog(null,"Default Can not be Set.Either File Corrupted or Lost");
                             else
                                  jtx1.setEnabled(true);
              myfont.setToolTipText("Default OTF Font Setting");
              JButton exitbutton = new JButton(ExitAction);          
              exitbutton.setBorder(null);
              exitbutton.setText(null);
              exitbutton.setToolTipText("Print");
              JButton helpbutton = new JButton(helpAction);          
              helpbutton.setBorder(null);
              helpbutton.setText(null);
              helpbutton.setToolTipText("Help");
              toolBar.add(loginbutton);
              toolBar.add(picbutton);                    
              toolBar.add(undobutton);
              toolBar.add(redobutton);
              toolBar.addSeparator();                    
              toolBar.add(logoutbutton);
              toolBar.add(logout1button);
              toolBar.add(logout2button);
              toolBar.addSeparator();                    
              toolBar.add(leftbutton);
              toolBar.add(centerbutton);
              toolBar.add(rightbutton);
              toolBar.addSeparator();
              toolBar.add(exitbutton);
              toolBar.add(helpbutton);
              toolBar.addSeparator();     
              //toolBar.addSeparator();
              //toolBar.add(MServerRunbutton);
              toolBar.setFloatable(true);
              toolBar.setRollover(true);
              //toolBar.setBorder(BorderFactory.createEtchedBorder(WHITE,LIGHT_GRAY));
              getContentPane().add(toolBar,BorderLayout.NORTH);
              JToolBar toolBar1 = new JToolBar();
              toolBar1.add(colorbutton);
              toolBar1.addSeparator();          
              toolBar1.add(myfont);
              toolBar1.add(jtx2);
              toolBar1.add(jtx1);
              toolBar1.addSeparator();          
              toolBar1.add(jtx);
              toolBar1.addSeparator();                    
              toolBar1.setOrientation(JToolBar.HORIZONTAL);
              getContentPane().add(toolBar1,BorderLayout.SOUTH);
             this.ami = this;     
             textPane = new JTextPane();//myserialeditor();
             textPane.setToolTipText("TB-Phonetic Layout(Ctrl+Alt+T)\nUnijoy Layout(Ctrl+Alt+R)\nEnglish Layout(Ctrl+Alt+Y)");
             textPane.addKeyListener(
                  new KeyAdapter()
                       public void keyPressed(KeyEvent e)                   
                            if(dead_key&&(e.getKeyCode()==KeyEvent.VK_BACK_SPACE ||e.getKeyCode()==KeyEvent.VK_DELETE))
                            dead_key=false;
                            if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_R)
                                  jtx.setSelectedIndex(1);
                                  return ;
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_T)
                                  jtx.setSelectedIndex(0);return ;
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_Y)
                                  jtx.setSelectedIndex(2);return ;
                            try{
                            if(jtx.getSelectedIndex()==1){
                            int iin=0;
                            if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_1)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09F4",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_2)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09F5",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_3)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09F6",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_4)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09F7",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_5)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09F2",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_7)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09FA",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_0)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09F8",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_E)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u0988",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_U)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u098A",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_I)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u0990",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_O)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u0994",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_A)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u098B",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_S)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u0989",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_D)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u0987",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_F)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u0986",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_G)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09CD",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_H)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09F0",textPane.getCharacterAttributes());                                                       
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_X)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u0993",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_C)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u098F",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_V)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09F1",textPane.getCharacterAttributes());                              
                             else if (e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_PERIOD)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09BC",textPane.getCharacterAttributes());                              
                             else if (e.isShiftDown() && e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_Q)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u098C",textPane.getCharacterAttributes());                              
                             else if (e.isShiftDown() && e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_W)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09E1",textPane.getCharacterAttributes());                              
                             else if (e.isShiftDown() && e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_I)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09BD",textPane.getCharacterAttributes());                              
                             else if (e.isShiftDown() && e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_Z)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09E2",textPane.getCharacterAttributes());                              
                             else if (e.isShiftDown() && e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_X)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09D7",textPane.getCharacterAttributes());                              
                             else if (e.isShiftDown() && e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_C)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09E0",textPane.getCharacterAttributes());                              
                             else if (e.isShiftDown() && e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_V)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09E3",textPane.getCharacterAttributes());                              
                             else if (e.isShiftDown() && e.isAltDown() && e.isControlDown() && e.getKeyCode()==KeyEvent.VK_B)
                                  textPane.getDocument().insertString(textPane.getDocument().getLength(),"\u09C4",textPane.getCharacterAttributes());                              
                             else iin=1;
                             if(iin==0)
                             dead_key=false;
                         }catch(Exception exp)
                              JOptionPane.showMessageDialog(null,"Typing Error");
             myeditor = new StyledEditorKit();
             textPane.setEditorKit(myeditor);
              AbstractDocument doc;
              textPane.setCaretPosition(0);
            textPane.setMargin(new Insets(5,5,5,5));
            StyledDocument styledDoc = textPane.getStyledDocument();
            if (styledDoc instanceof AbstractDocument) {
                doc = (AbstractDocument)styledDoc;
                doc.setDocumentFilter(new keyController(new_page.this));
                doc.addUndoableEditListener(new MyUndoableEditListener());
            } else {
                System.err.println("Text pane's document isn't an AbstractDocument!");
                System.exit(-1);
              JScrollPane jsp = new JScrollPane(textPane);          
              /*LineNumber list = new LineNumber(textPane);
              jsp.setRowHeaderView(list);
              numberingPanel = new NumberingPanel();
              numberingPanel.setPreferredSize(new Dimension(30,30));
              numberingPanel.setMaximumSize(new Dimension(30,30));
              numberingPanel.setMinimumSize(new Dimension(30,30));
              textPane = new JTextPane()          {
                   public void paint(Graphics g) {
                        super.paint(g);     
                        numberingPanel.repaint();
              //this.add(numberingPanel, BorderLayout.WEST);          
              getContentPane().add(jsp,BorderLayout.CENTER);
             textPane.setSelectedTextColor(Color.WHITE);
             textPane.setSelectionColor(Color.BLUE);
             addBindings();
                                           try{                                         
                                              Font font = Font.createFont(java.awt.Font.TRUETYPE_FONT, getClass().getResourceAsStream("font/SolaimanLipi.ttf"));
                                           font=font.deriveFont(Font.PLAIN,25);
                                              textPane.setFont(font);
                                              jtx2.setSelectedIndex(24);
                                              jtx1.setEnabled(false);
                                              myfont.setSelected(true);
                                              }catch(Exception e)
                                                   JOptionPane.showMessageDialog(null,"Error Occured while fixing the font");
          }//////////end of new_page(.....)
          NumberingPanel numberingPanel;
          class NumberingPanel extends JPanel {
              public void paint(Graphics g) {
                   super.paint(g);                              
                   g.setColor(Color.BLACK);
                   g.setFont(new Font("Arial",Font.PLAIN,12));
                   Element root = textPane.getDocument().getDefaultRootElement();
                  Rectangle r;
                   try {
                        r = textPane.modelToView(root.getStartOffset());
                        g.drawString(Integer.toString(1),0,(int)(r.getY()+12));                         
                   } catch (BadLocationException e1) {
                   int lines = root.getElementCount();
                   for (int i = 0; i < lines; i++) {
                        int offset = root.getElement(i).getEndOffset();
                        try {
                            r = textPane.modelToView(offset);
                             g.drawString(Integer.toString(i+2),0,(int)(r.getY()+12));
                        } catch (BadLocationException e) {
          protected class MyUndoableEditListener
                        implements UndoableEditListener {
            public void undoableEditHappened(UndoableEditEvent e) {
                //Remember the edit and update the menus.
                undo.addEdit(e.getEdit());
                undoAction.updateUndoState();
                redoAction.updateRedoState();
          class UndoAction extends AbstractAction {
            public UndoAction() {
                super("Undo");
                setEnabled(false);
            public UndoAction(KeyStroke keystroke)
                   super("Undo");
                setEnabled(false);               
                   if(keystroke!=null)
                   putValue(ACCELERATOR_KEY,keystroke);
            public void actionPerformed(ActionEvent e) {
                try {
                    undo.undo();
                } catch (CannotUndoException ex) {
                    System.out.println("Unable to undo: " + ex);
                    ex.printStackTrace();
                    Toolkit.getDefaultToolkit().beep();
                updateUndoState();
                redoAction.updateRedoState();
            protected void updateUndoState() {
                if (undo.canUndo()) {
                    setEnabled(true);
                    putValue(Action.NAME, undo.getUndoPresentationName());
                } else {
                    setEnabled(false);
                    putValue(Action.NAME, "Undo");
         class SaveAction extends AbstractAction{
         SaveAction() {
             //super(saveAction);
            public void actionPerformed(ActionEvent e) {
                 JFrame frame = new JFrame();
              FileDialog fileDialog = new FileDialog(frame);
             fileDialog.setMode(FileDialog.SAVE);
             fileDialog.show();
             String file = fileDialog.getFile();
             if (file == null) {
              return;
             String directory = fileDialog.getDirectory();
             File f = new File(directory, file);        
    int xx = JOptionPane.showInternalConfirmDialog(new_page.this,"Style Mode:  Can't able to access the file without the editor\n"+
                                                             "             All text styles and pictures will be allright\n"+
                                                             "Normal Mode: Can able to access the file without the editor with notepad or other applications\n"+
                                                             "             All text styles and pictures may be lost\n"+
                                                             "Do you want to save in Style Mode ?","Save Modes",JOptionPane.YES_NO_OPTION);
           try {
                if(xx==JOptionPane.YES_OPTION){
                  FileOutputStream fstrm = new FileOutputStream(f);
              ObjectOutputStream ostrm = new ObjectOutputStream(fstrm);
              ostrm.writeObject(textPane.getDocument());
              ostrm.flush();
                 JOptionPane.showMessageDialog(null,"Successfulyy Saved in Style Mode");
            } catch (Exception io) {
              io.printStackTrace();// should put in status panel
              JOptionPane.showMessageDialog(null,"Error Occured while saving");
              return;
         private void writeObject(ObjectOutputStream out) throws IOException {
            out.writeObject(getParent());
            out.writeObject(getName());
        class serial implements Serializable{       
             //java.io.NotSerializableException:
             //ToolkitImage
             serial()
             public void writedata(File f,JTextPane textPane)
             try{
                  *FileOutputStream fstrm = new FileOutputStream(f);*
    *               ObjectOutput ostrm = new ObjectOutputStream(fstrm);               *
    *               ostrm.writeObject(textPane.getDocument());*
    *               ostrm.flush();*
                   }catch(Exception ee)
                        ee.printStackTrace();
        class RedoAction extends AbstractAction {
            public RedoAction() {
                super("Redo");
                setEnabled(false);
            public RedoAction(KeyStroke keystroke)
                   super("Redo");
                setEnabled(false);
                   if(keystroke!=null)
                   putValue(ACCELERATOR_KEY,keystroke);
            public void actionPerformed(ActionEvent e) {
                try {
                    undo.redo();
                } catch (CannotRedoException ex) {
                    System.out.println("Unable to redo: " + ex);
                    ex.printStackTrace();
                    Toolkit.getDefaultToolkit().beep();
                updateRedoState();
                undoAction.updateUndoState();
            protected void updateRedoState() {
                if (undo.canRedo()) {
                    setEnabled(true);
                    putValue(Action.NAME, undo.getRedoPresentationName());
                } else {
                    setEnabled(false);
                    putValue(Action.NAME, "Redo");
          //Add a couple of emacs key bindings for navigation.
        protected void addBindings() {
            InputMap inputMap = textPane.getInputMap();
            //Ctrl-b to go backward one character
            KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK);
            inputMap.put(key, StyledEditorKit.copyAction);
            //Ctrl-f to go forward one character
            key = KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK);
            inputMap.put(key, StyledEditorKit.cutAction);
            //Ctrl-p to go up one line
            key = KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK);
            inputMap.put(key, StyledEditorKit.pasteAction);
            key = KeyStroke.getKeyStroke(KeyEvent.VK_HOME, Event.CTRL_MASK);
            inputMap.put(key, StyledEditorKit.beginAction);
            key = KeyStroke.getKeyStroke(KeyEvent.VK_END, Event.CTRL_MASK);
            inputMap.put(key, StyledEditorKit.endAction);
            key = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, Event.CTRL_MASK);
            inputMap.put(key, StyledEditorKit.pageUpAction);
            key = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, Event.CTRL_MASK);
            inputMap.put(key, StyledEditorKit.pageDownAction);
            key = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, Event.CTRL_MASK & Event.ALT_MASK);
            inputMap.put(key, StyledEditorKit.deletePrevCharAction);
          void save()
               //save_page t1 = new save_page(this,thedesktop,textPane,null);
          static public boolean round = true;
          void font()
               round = true;
               new font_page(this,thedesktop,textPane);
               new StyledEditorKit.FontFamilyAction("SolaimanLipi","SolaimanLipi");
               JOptionPane.showMessageDialog(null,myfont_name+" n:"+myfont_size);
       /////////////class definition for file action
       class FileAction extends AbstractAction
              private String name;
              FileAction(String name)
                   super(name);
                   this.name=name;
              FileAction(String name,KeyStroke keystroke)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Image is not saved in jpeg/bmp file but ok with png

    Hi i am unable to save the image in disk in jpeg format.
    Here is the code.
    public void saveImage(){
    //if no filechooser is there means no image file opened.
            if(fileChooser==null){
                if(errorWindow==null)
                    errorWindow=new ErrorWindow(XXX.getPrimaryStage());
                errorWindow.showErrorWindow("There is no image to save !!\n");
            else{
                fileChooser.setTitle("Save The Image");
                File saveFile=fileChooser.showSaveDialog(XXX.getPrimaryStage());
                if(saveFile!=null){
                    System.out.println("saveFile path= "+saveFile);
                    //get the extension of output image to be saved.
                    //XXX: is the main class name(say)
                    outExtension=*XXX*.getImageExtension(saveFile);
                    //if user does not give extension: set default extension as jpg
                    if(outExtension.equalsIgnoreCase(saveFile.getName())){
                        outExtension="jpg";                   
                        String newPath=(saveFile.toString())+".jpg";
                        saveFile=new File(newPath);                   
                    Task task = new Task<Void>() {
                        @Override
                        public Void call() {
                            Platform.runLater(
                                    new Runnable() {
                                        public void run() {
                                            try {
                                                //The image is inside ImageView->inside ScrollPane-> inside TabPane.
                                                Image curImage=XXX.getCurrentImage();
                                                int width=(int)curImage.getWidth();
                                                int height=(int)curImage.getHeight();                              
                                                System.out.println("cur image width= "+width+" ht= "+height);
                                                bufferedImage=new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB );
                                                //set the current image to awt Buffered Image
                                                SwingFXUtils.fromFXImage(curImage, bufferedImage);
                                                    imageTabPane=xxx.getImageTabPane();
                                                    Tab tab=imageTabPane.getSelectionModel().getSelectedItem();                                    
                                                    TabPane childTabPane=(TabPane)tab.getContent();
                                                    ScrollPane sp=(ScrollPane)childTabPane.getSelectionModel().getSelectedItem().getContent();
                                                    final ImageView imageView=(ImageView)sp.getContent();
                                                    WritableImage wim = new WritableImage(width,height);
                                                    imageView.snapshot(null, wim);
                                                    System.out.println(" snapShot width= "+wim.getWidth()+" ht="+wim.getHeight());                             
                                                    *ImageIO.write(SwingFXUtils.fromFXImage(wim,null), outExtension, saveFile);*
                                                       //<------ its not working  for png,jpeg,bmp,gif                                          
                                                    // the below lines are working only for png and gif
                                                    OutputStream out = new FileOutputStream(saveFile);                                                
                                                    ImageIO.write((RenderedImage) bufferedImage, outExtension, out);
                                                    out.flush();
                                            } catch (Exception ex) {
                                                Logger.getLogger(FileMenuController.class.getName()).log(Level.SEVERE, null, ex);
                                                //ex.printStackTrace();
                                            System.out.println("finished");
                            return null;
                    Thread th = new Thread(task);
                    th.start();
                }else{
                    System.out.println("File is not saved");
        }//saveImageNote: The above code is executed in ubuntu(10.04) using Netbeans 7.2(Javafx(2.2), java(1.7.0_11).
    When i run(from terminal) separately in a new class with an image in an Imageview( inside a Vbox) and take the snapshot
    of the imageview and write into the file using ImageIO.write(SwingFXUtils.fromFXImage(wim,null), outExtension, saveFile);
    with any extension (jpeg,png etc) it is working fine.
    Please help me.
    Any small hint is also helpful.Please feel free to comment or give suggestion.
    Edited by: 963038 on Feb 17, 2013 7:14 PM

    When i omit the line OutputStream out = new FileOutputStream(saveFile);
    and write only
    ImageIO.write((RenderedImage) bufferedImage, outExtension,saveFile);
    //out.flush();
    then saving the image even in "png" also fails.
    The following is the error code:
    Note : FileMenuController is my file where the saveImage() is wrtten.
    javax.imageio.IIOException: I/O error writing PNG file!
    finished
         at com.sun.imageio.plugins.png.PNGImageWriter.write(PNGImageWriter.java:1168)
         at javax.imageio.ImageWriter.write(ImageWriter.java:615)
         at javax.imageio.ImageIO.doWrite(ImageIO.java:1612)
         at javax.imageio.ImageIO.write(ImageIO.java:1536)
         at *newciptk.controls.menu.file.FileMenuController$1$1.run(FileMenuController.java:205)*
         at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
         at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
         at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
         at com.sun.glass.ui.gtk.GtkApplication$3$1.run(GtkApplication.java:82)
         at java.lang.Thread.run(Thread.java:722)
    Caused by: java.io.IOException: Operation not supported
         at java.io.RandomAccessFile.writeBytes(Native Method)
         at java.io.RandomAccessFile.write(RandomAccessFile.java:499)
         at javax.imageio.stream.FileImageOutputStream.write(FileImageOutputStream.java:124)
         at javax.imageio.stream.ImageOutputStreamImpl.writeInt(ImageOutputStreamImpl.java:91)
         at com.sun.imageio.plugins.png.ChunkStream.finish(PNGImageWriter.java:136)
         at com.sun.imageio.plugins.png.PNGImageWriter.write_IHDR(PNGImageWriter.java:401)
         at com.sun.imageio.plugins.png.PNGImageWriter.write(PNGImageWriter.java:1135)
         ... 9 more
    javax.imageio.IIOException: I/O error writing PNG file!
         at com.sun.imageio.plugins.png.PNGImageWriter.write(PNGImageWriter.java:1168)
         at javax.imageio.ImageWriter.write(ImageWriter.java:615)
         at javax.imageio.ImageIO.doWrite(ImageIO.java:1612)
         at javax.imageio.ImageIO.write(ImageIO.java:1536)
         at newciptk.controls.menu.file.FileMenuController$1$1.run(FileMenuController.java:205)
         at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
         at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
         at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
         at com.sun.glass.ui.gtk.GtkApplication$3$1.run(GtkApplication.java:82)
         at java.lang.Thread.run(Thread.java:722)
    Caused by: java.io.IOException: Operation not supported
         at java.io.RandomAccessFile.writeBytes(Native Method)
         at java.io.RandomAccessFile.write(RandomAccessFile.java:499)
         at javax.imageio.stream.FileImageOutputStream.write(FileImageOutputStream.java:124)
         at javax.imageio.stream.ImageOutputStreamImpl.writeInt(ImageOutputStreamImpl.java:91)
         at com.sun.imageio.plugins.png.ChunkStream.finish(PNGImageWriter.java:136)
         at com.sun.imageio.plugins.png.PNGImageWriter.write_IHDR(PNGImageWriter.java:401)
         at com.sun.imageio.plugins.png.PNGImageWriter.write(PNGImageWriter.java:1135)
         ... 9 more

  • ### in XI Payload

    Hi Experts,
    We are facing a critical issue in our productive environment.
    The output after mapping in XI has the character '#' filled up completely meaning the entire payload is filled with '#'
    We have a multicluster server environment and this might be happening in few server nodes.
    Any inputs on this would be highly appreciated.
    Regards,
    Varun.
    The issues are below.
    1. All receivers with enhanced receiver determination could not be determined and XI is processing #### values to all subscribing systems.
    2.. #### are being filled just after mapping.
    3. We are not sure if this is the case on one server node or with all server nodes.
    4. On recommendation, we recently upgraded JVM of our system to resolve this particular issue but the issue stil persists.
    Edited by: Varun on Mar 4, 2010 5:07 PM

    Hi Varun,
    Can you plesae let me know that # you are getting in the Receiver payload ? if it so then you can use java mapping for this.
    use this java code only any edit ur logic for ur req
    package com.agr.test.replacechar;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import java.util.HashMap;
    import com.sap.aii.mapping.api.AbstractTrace;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationConstants;
    import com.sap.aii.mapping.api.MappingTrace;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class ReplaceAmpersnd implements StreamTransformation {
         private Map           param = null;
                        private AbstractTrace  trace = null;
                        public void setParameter (Map param)
                             this.param = param;
                             if (param == null)
                                  this.param = new HashMap();
                             else
                                  trace =(AbstractTrace) param.get(StreamTransformationConstants.MAPPING_TRACE);
         public void execute(InputStream in, OutputStream out) {
         try {
         int read_data;
         while ((read_data = in.read())!=-1)
         if (read_data != '&')
              out.write(read_data);
         else
         out.write("".getBytes());
         out.flush();
         catch (Exception e)
              trace.addWarning("Error " + e.getMessage());
    Regards
    Abhay
    Edited by: Abahy Aggarwal on Mar 5, 2010 1:48 PM

  • Voice chat program

    After a few days work, I have completed the mian voice chat program. I know there are so many people like me that wants that. I post these program. i will complete gui work later. and there is a problem in the program. if the speaking one do not speak for a while, the listening client will hear noise. Can some one help me.
    package com.longshine.voice;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Server
    // The ServerSocket we'll use for accepting new connections
    private ServerSocket ss;
    // A mapping from sockets to DataOutputStreams. This will
    // help us avoid having to create a DataOutputStream each time
    // we want to write to a stream.
    private Hashtable outputStreams = new Hashtable();
    final int bufSize = 16384;
    //current speak_man
    private int speakman=-1;
    // Constructor and while-accept loop all in one.
    public Server( int port ) throws IOException {
    // All we have to do is listen
    listen( port );
    private void listen( int port ) throws IOException {
    // Create the ServerSocket
    ss = new ServerSocket( port );
    // Tell the world we're ready to go
    System.out.println( "Listening on "+ss );
    // Keep accepting connections forever
    while (true) {
    // Grab the next incoming connection
    Socket s = ss.accept();
    // Tell the world we've got it
    System.out.println( "Connection from "+s );
    // Create a DataOutputStream for writing data to the
    // other side
    DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
    // Save this stream so we don't need to make it again
    outputStreams.put( s, dout );
    // Create a new thread for this connection, and then forget
    // about it
    new VoiceServer( this, s );
    // Get an enumeration of all the OutputStreams, one for each client
    // connected to us
    Enumeration getOutputStreams() {
    return outputStreams.elements();
    // Send a message to all clients (utility routine)
    void sendToAll( byte[] voice ,Socket socket) {
    // We synchronize on this because another thread might be
    // calling removeConnection() and this would screw us up
    // as we tried to walk through the list
    synchronized( outputStreams ) {
    // For each client ...
    for (Enumeration e = outputStreams.keys(); e.hasMoreElements(); ) {
    // ... get the output stream ...
    Socket tmp=(Socket)e.nextElement();
    if(!tmp.equals(socket))
    try {
    DataOutputStream dout = new DataOutputStream(tmp.getOutputStream());
    // ... and send the message
    dout.write(voice,0,44096);
    dout.flush();
    } catch( IOException ie ) { System.out.println( ie ); }
    // Remove a socket, and it's corresponding output stream, from our
    // list. This is usually called by a connection thread that has
    // discovered that the connectin to the client is dead.
    void removeConnection( Socket s ) {
    // Synchronize so we don't mess up sendToAll() while it walks
    // down the list of all output streamsa
    synchronized( outputStreams ) {
    // Tell the world
    System.out.println( "Removing connection to "+s );
    // Remove it from our hashtable/list
    outputStreams.remove( s );
    // Make sure it's closed
    try {
    s.close();
    } catch( IOException ie ) {
    System.out.println( "Error closing "+s );
    ie.printStackTrace();
    // Main routine
    // Usage: java Server <port>
    static public void main( String args[] ) throws Exception {
    // Get the port # from the command line
    int port = Integer.parseInt( args[0] );
    // Create a Server object, which will automatically begin
    // accepting connections.
    new Server( port );
    package com.longshine.voice;
    import java.net.*;
    import java.io.*;
    import java.sql.*;
    import java.io.*;
    import java.net.*;
    public class VoiceServer extends Thread
    // The Server that spawned us
    private Server server;
    final int bufSize = 16384;
    // The Socket connected to our client
    private Socket socket;
    // Constructor.
    public VoiceServer( Server server, Socket socket ) {
    // Save the parameters
    this.server = server;
    this.socket = socket;
    // Start up the thread
    start();
    // This runs in a separate thread when start() is called in the
    // constructor.
    public void run() {
    try {
    // Create a DataInputStream for communication; the client
    // is using a DataOutputStream to write to us
    DataInputStream din = new DataInputStream( socket.getInputStream() );
    byte[] voice=new byte[44096];
    // Over and over, forever ...
    while (true) {
    // ... read the next message ...
    // int bytes = din.read(voice,0,44096);
    int bytes = din.read(voice);
    // ... and have the server send it to all clients
    server.sendToAll(voice,socket);
    } catch( EOFException ie ) {
    // This doesn't need an error message
    } catch( IOException ie ) {
    // This does; tell the world!
    ie.printStackTrace();
    } finally {
    // The connection is closed for one reason or another,
    // so have the server dealing with it
    server.removeConnection( socket );
    package com.longshine.voice;
    import java.io.*;
    import java.net.*;
    public class Client {
    private String host="";
    private String port="";
    private Socket socket;
    private DataOutputStream dout;
    private DataInputStream din;
    private Capture capture=null;
    private Play play=null;
    public Client(String host,String port) {
    this.host=host;
    this.port=port;
    public void init()
    try
    socket = new Socket( host, Integer.parseInt(port));
    din = new DataInputStream( socket.getInputStream() );
    dout = new DataOutputStream( socket.getOutputStream());
    capture=new Capture(dout);
    play=new Play(din);
    catch(Exception e)
    e.printStackTrace();
    public static void main(String[] args) {
    Client client = new Client("172.18.220.176","5678");
    client.init();
    if(args[0].equalsIgnoreCase("say"))
    client.capture.start();
    if(args[0].equalsIgnoreCase("hear"))
    client.play.start();
    package com.longshine.voice;
    import java.io.*;
    import java.util.Vector;
    import java.util.Enumeration;
    import javax.sound.sampled.*;
    import java.text.*;
    import java.net.*;
    public class Play implements Runnable {
    SourceDataLine line;
    Thread thread;
    String errStr=null;
    DataInputStream in=null;
    AudioInputStream audioInputStream;
    final int bufSize = 16384;
    int duration=0;
    public Play(DataInputStream in)
    this.in=in;
    public void start() {
    errStr = null;
    thread = new Thread(this);
    thread.setName("Playback");
    thread.start();
    public void stop() {
    thread = null;
    private void shutDown(String message) {
    if ((errStr = message) != null) {
    System.err.println(errStr);
    if (thread != null) {
    thread = null;
    public void createAudioInputStream() {
    if (in != null ) {
    try {
    errStr = null;
    java.io.BufferedInputStream oin = new java.io.BufferedInputStream(in);
    audioInputStream = AudioSystem.getAudioInputStream(oin);
    } catch (Exception ex) {
    ex.printStackTrace();
    } else {
    public void run() {
    // reload the file if loaded by file
    if (in != null) {
    // createAudioInputStream();
    // make sure we have something to play
    // if (audioInputStream == null) {
    // shutDown("No loaded audio to play back");
    // return;
    // reset to the beginnning of the stream
    // try {
    // audioInputStream.reset();
    // } catch (Exception e) {
    // shutDown("Unable to reset the stream\n" + e);
    // return;
    // get an AudioInputStream of the desired format for playback
    AudioFormat format = getFormat();
    audioInputStream=new AudioInputStream(in, format, AudioSystem.NOT_SPECIFIED);
    AudioInputStream playbackInputStream = AudioSystem.getAudioInputStream(format, audioInputStream);
    if (playbackInputStream == null) {
    shutDown("Unable to convert stream of format " + audioInputStream + " to format " + format);
    return;
    // define the required attributes for our line,
    // and make sure a compatible line is supported.
    DataLine.Info info = new DataLine.Info(SourceDataLine.class,
    format);
    if (!AudioSystem.isLineSupported(info)) {
    shutDown("Line matching " + info + " not supported.");
    return;
    // get and open the source data line for playback.
    try {
    line = (SourceDataLine) AudioSystem.getLine(info);
    line.open(format, bufSize);
    } catch (LineUnavailableException ex) {
    shutDown("Unable to open the line: " + ex);
    return;
    // play back the captured audio data
    int frameSizeInBytes = format.getFrameSize();
    int bufferLengthInFrames = line.getBufferSize() / 8;
    int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
    byte[] data = new byte[bufferLengthInBytes];
    int numBytesRead = 0;
    // start the source data line
    line.start();
    while (thread != null) {
    try {
    if ((numBytesRead = playbackInputStream.read(data)) == -1) {
    break;
    int numBytesRemaining = numBytesRead;
    while (numBytesRemaining > 0 ) {
    numBytesRemaining -= line.write(data, 0, numBytesRemaining);
    } catch (Exception e) {
    shutDown("Error during playback: " + e);
    break;
    // we reached the end of the stream. let the data play out, then
    // stop and close the line.
    if (thread != null) {
    line.drain();
    line.stop();
    line.close();
    line = null;
    shutDown(null);
    public AudioFormat getFormat() {
    AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
    String encString = "linear";
    float rate = Float.valueOf("44100").floatValue();
    int sampleSize = 16;
    String signedString = "signed";
    boolean bigEndian = true;
    int channels = 2;
    if (encString.equals("linear")) {
    if (signedString.equals("signed")) {
    encoding = AudioFormat.Encoding.PCM_SIGNED;
    } else {
    encoding = AudioFormat.Encoding.PCM_UNSIGNED;
    } else if (encString.equals("alaw")) {
    encoding = AudioFormat.Encoding.ALAW;
    return new AudioFormat(encoding, rate, sampleSize,
    channels, (sampleSize/8)*channels, rate, bigEndian);
    } // End class Playback
    package com.longshine.voice;
    import java.io.*;
    import java.util.Vector;
    import java.util.Enumeration;
    import javax.sound.sampled.*;
    import java.text.*;
    import java.net.*;
    public class Capture implements Runnable {
    TargetDataLine line;
    Thread thread;
    String errStr=null;
    DataOutputStream out=null;
    AudioInputStream audioInputStream;
    final int bufSize = 16384;
    int duration=0;
    public Capture(DataOutputStream out)
    this.out=out;
    public void start() {
    errStr = null;
    thread = new Thread(this);
    thread.setName("Playback");
    thread.start();
    public void stop() {
    thread = null;
    private void shutDown(String message) {
    if ((errStr = message) != null) {
    System.out.println(errStr);
    if (thread != null) {
    thread = null;
    public AudioFormat getFormat() {
    AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
    String encString = "linear";
    float rate = Float.valueOf("44100").floatValue();
    int sampleSize = 16;
    String signedString = "signed";
    boolean bigEndian = true;
    int channels = 2;
    if (encString.equals("linear")) {
    if (signedString.equals("signed")) {
    encoding = AudioFormat.Encoding.PCM_SIGNED;
    } else {
    encoding = AudioFormat.Encoding.PCM_UNSIGNED;
    } else if (encString.equals("alaw")) {
    encoding = AudioFormat.Encoding.ALAW;
    return new AudioFormat(encoding, rate, sampleSize,
    channels, (sampleSize/8)*channels, rate, bigEndian);
    public void run() {
    duration = 0;
    audioInputStream = null;
    // define the required attributes for our line,
    // and make sure a compatible line is supported.
    AudioFormat format = getFormat();
    DataLine.Info info = new DataLine.Info(TargetDataLine.class,
    format);
    if (!AudioSystem.isLineSupported(info)) {
    shutDown("Line matching " + info + " not supported.");
    return;
    // get and open the target data line for capture.
    try {
    line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format, line.getBufferSize());
    } catch (LineUnavailableException ex) {
    shutDown("Unable to open the line: " + ex);
    return;
    } catch (SecurityException ex) {
    shutDown(ex.toString());
    return;
    } catch (Exception ex) {
    shutDown(ex.toString());
    return;
    // play back the captured audio data
    int frameSizeInBytes = format.getFrameSize();
    int bufferLengthInFrames = line.getBufferSize() / 8;
    int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
    byte[] data = new byte[bufferLengthInBytes];
    int numBytesRead;
    line.start();
    try
    while (thread != null) {
    if((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
    break;
    if(data.length>0)
    out.write(data, 0, numBytesRead);
    out.flush();
    catch (Exception e)
    e.printStackTrace();
    // we reached the end of the stream. stop and close the line.
    line.stop();
    line.close();
    line = null;
    // stop and close the output stream
    try {
    out.flush();
    out.close();
    } catch (IOException ex) {
    ex.printStackTrace();
    } // End class Capture

    After a few days work, I have completed the mian voice chat program. I know there are so many people like me that wants that. I post these program. i will complete gui work later. and there is a problem in the program. if the speaking one do not speak for a while, the listening client will hear noise. Can some one help me.
    package com.longshine.voice;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Server
    // The ServerSocket we'll use for accepting new connections
    private ServerSocket ss;
    // A mapping from sockets to DataOutputStreams. This will
    // help us avoid having to create a DataOutputStream each time
    // we want to write to a stream.
    private Hashtable outputStreams = new Hashtable();
    final int bufSize = 16384;
    //current speak_man
    private int speakman=-1;
    // Constructor and while-accept loop all in one.
    public Server( int port ) throws IOException {
    // All we have to do is listen
    listen( port );
    private void listen( int port ) throws IOException {
    // Create the ServerSocket
    ss = new ServerSocket( port );
    // Tell the world we're ready to go
    System.out.println( "Listening on "+ss );
    // Keep accepting connections forever
    while (true) {
    // Grab the next incoming connection
    Socket s = ss.accept();
    // Tell the world we've got it
    System.out.println( "Connection from "+s );
    // Create a DataOutputStream for writing data to the
    // other side
    DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
    // Save this stream so we don't need to make it again
    outputStreams.put( s, dout );
    // Create a new thread for this connection, and then forget
    // about it
    new VoiceServer( this, s );
    // Get an enumeration of all the OutputStreams, one for each client
    // connected to us
    Enumeration getOutputStreams() {
    return outputStreams.elements();
    // Send a message to all clients (utility routine)
    void sendToAll( byte[] voice ,Socket socket) {
    // We synchronize on this because another thread might be
    // calling removeConnection() and this would screw us up
    // as we tried to walk through the list
    synchronized( outputStreams ) {
    // For each client ...
    for (Enumeration e = outputStreams.keys(); e.hasMoreElements(); ) {
    // ... get the output stream ...
    Socket tmp=(Socket)e.nextElement();
    if(!tmp.equals(socket))
    try {
    DataOutputStream dout = new DataOutputStream(tmp.getOutputStream());
    // ... and send the message
    dout.write(voice,0,44096);
    dout.flush();
    } catch( IOException ie ) { System.out.println( ie ); }
    // Remove a socket, and it's corresponding output stream, from our
    // list. This is usually called by a connection thread that has
    // discovered that the connectin to the client is dead.
    void removeConnection( Socket s ) {
    // Synchronize so we don't mess up sendToAll() while it walks
    // down the list of all output streamsa
    synchronized( outputStreams ) {
    // Tell the world
    System.out.println( "Removing connection to "+s );
    // Remove it from our hashtable/list
    outputStreams.remove( s );
    // Make sure it's closed
    try {
    s.close();
    } catch( IOException ie ) {
    System.out.println( "Error closing "+s );
    ie.printStackTrace();
    // Main routine
    // Usage: java Server <port>
    static public void main( String args[] ) throws Exception {
    // Get the port # from the command line
    int port = Integer.parseInt( args[0] );
    // Create a Server object, which will automatically begin
    // accepting connections.
    new Server( port );
    package com.longshine.voice;
    import java.net.*;
    import java.io.*;
    import java.sql.*;
    import java.io.*;
    import java.net.*;
    public class VoiceServer extends Thread
    // The Server that spawned us
    private Server server;
    final int bufSize = 16384;
    // The Socket connected to our client
    private Socket socket;
    // Constructor.
    public VoiceServer( Server server, Socket socket ) {
    // Save the parameters
    this.server = server;
    this.socket = socket;
    // Start up the thread
    start();
    // This runs in a separate thread when start() is called in the
    // constructor.
    public void run() {
    try {
    // Create a DataInputStream for communication; the client
    // is using a DataOutputStream to write to us
    DataInputStream din = new DataInputStream( socket.getInputStream() );
    byte[] voice=new byte[44096];
    // Over and over, forever ...
    while (true) {
    // ... read the next message ...
    // int bytes = din.read(voice,0,44096);
    int bytes = din.read(voice);
    // ... and have the server send it to all clients
    server.sendToAll(voice,socket);
    } catch( EOFException ie ) {
    // This doesn't need an error message
    } catch( IOException ie ) {
    // This does; tell the world!
    ie.printStackTrace();
    } finally {
    // The connection is closed for one reason or another,
    // so have the server dealing with it
    server.removeConnection( socket );
    package com.longshine.voice;
    import java.io.*;
    import java.net.*;
    public class Client {
    private String host="";
    private String port="";
    private Socket socket;
    private DataOutputStream dout;
    private DataInputStream din;
    private Capture capture=null;
    private Play play=null;
    public Client(String host,String port) {
    this.host=host;
    this.port=port;
    public void init()
    try
    socket = new Socket( host, Integer.parseInt(port));
    din = new DataInputStream( socket.getInputStream() );
    dout = new DataOutputStream( socket.getOutputStream());
    capture=new Capture(dout);
    play=new Play(din);
    catch(Exception e)
    e.printStackTrace();
    public static void main(String[] args) {
    Client client = new Client("172.18.220.176","5678");
    client.init();
    if(args[0].equalsIgnoreCase("say"))
    client.capture.start();
    if(args[0].equalsIgnoreCase("hear"))
    client.play.start();
    package com.longshine.voice;
    import java.io.*;
    import java.util.Vector;
    import java.util.Enumeration;
    import javax.sound.sampled.*;
    import java.text.*;
    import java.net.*;
    public class Play implements Runnable {
    SourceDataLine line;
    Thread thread;
    String errStr=null;
    DataInputStream in=null;
    AudioInputStream audioInputStream;
    final int bufSize = 16384;
    int duration=0;
    public Play(DataInputStream in)
    this.in=in;
    public void start() {
    errStr = null;
    thread = new Thread(this);
    thread.setName("Playback");
    thread.start();
    public void stop() {
    thread = null;
    private void shutDown(String message) {
    if ((errStr = message) != null) {
    System.err.println(errStr);
    if (thread != null) {
    thread = null;
    public void createAudioInputStream() {
    if (in != null ) {
    try {
    errStr = null;
    java.io.BufferedInputStream oin = new java.io.BufferedInputStream(in);
    audioInputStream = AudioSystem.getAudioInputStream(oin);
    } catch (Exception ex) {
    ex.printStackTrace();
    } else {
    public void run() {
    // reload the file if loaded by file
    if (in != null) {
    // createAudioInputStream();
    // make sure we have something to play
    // if (audioInputStream == null) {
    // shutDown("No loaded audio to play back");
    // return;
    // reset to the beginnning of the stream
    // try {
    // audioInputStream.reset();
    // } catch (Exception e) {
    // shutDown("Unable to reset the stream\n" + e);
    // return;
    // get an AudioInputStream of the desired format for playback
    AudioFormat format = getFormat();
    audioInputStream=new AudioInputStream(in, format, AudioSystem.NOT_SPECIFIED);
    AudioInputStream playbackInputStream = AudioSystem.getAudioInputStream(format, audioInputStream);
    if (playbackInputStream == null) {
    shutDown("Unable to convert stream of format " + audioInputStream + " to format " + format);
    return;
    // define the required attributes for our line,
    // and make sure a compatible line is supported.
    DataLine.Info info = new DataLine.Info(SourceDataLine.class,
    format);
    if (!AudioSystem.isLineSupported(info)) {
    shutDown("Line matching " + info + " not supported.");
    return;
    // get and open the source data line for playback.
    try {
    line = (SourceDataLine) AudioSystem.getLine(info);
    line.open(format, bufSize);
    } catch (LineUnavailableException ex) {
    shutDown("Unable to open the line: " + ex);
    return;
    // play back the captured audio data
    int frameSizeInBytes = format.getFrameSize();
    int bufferLengthInFrames = line.getBufferSize() / 8;
    int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
    byte[] data = new byte[bufferLengthInBytes];
    int numBytesRead = 0;
    // start the source data line
    line.start();
    while (thread != null) {
    try {
    if ((numBytesRead = playbackInputStream.read(data)) == -1) {
    break;
    int numBytesRemaining = numBytesRead;
    while (numBytesRemaining > 0 ) {
    numBytesRemaining -= line.write(data, 0, numBytesRemaining);
    } catch (Exception e) {
    shutDown("Error during playback: " + e);
    break;
    // we reached the end of the stream. let the data play out, then
    // stop and close the line.
    if (thread != null) {
    line.drain();
    line.stop();
    line.close();
    line = null;
    shutDown(null);
    public AudioFormat getFormat() {
    AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
    String encString = "linear";
    float rate = Float.valueOf("44100").floatValue();
    int sampleSize = 16;
    String signedString = "signed";
    boolean bigEndian = true;
    int channels = 2;
    if (encString.equals("linear")) {
    if (signedString.equals("signed")) {
    encoding = AudioFormat.Encoding.PCM_SIGNED;
    } else {
    encoding = AudioFormat.Encoding.PCM_UNSIGNED;
    } else if (encString.equals("alaw")) {
    encoding = AudioFormat.Encoding.ALAW;
    return new AudioFormat(encoding, rate, sampleSize,
    channels, (sampleSize/8)*channels, rate, bigEndian);
    } // End class Playback
    package com.longshine.voice;
    import java.io.*;
    import java.util.Vector;
    import java.util.Enumeration;
    import javax.sound.sampled.*;
    import java.text.*;
    import java.net.*;
    public class Capture implements Runnable {
    TargetDataLine line;
    Thread thread;
    String errStr=null;
    DataOutputStream out=null;
    AudioInputStream audioInputStream;
    final int bufSize = 16384;
    int duration=0;
    public Capture(DataOutputStream out)
    this.out=out;
    public void start() {
    errStr = null;
    thread = new Thread(this);
    thread.setName("Playback");
    thread.start();
    public void stop() {
    thread = null;
    private void shutDown(String message) {
    if ((errStr = message) != null) {
    System.out.println(errStr);
    if (thread != null) {
    thread = null;
    public AudioFormat getFormat() {
    AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
    String encString = "linear";
    float rate = Float.valueOf("44100").floatValue();
    int sampleSize = 16;
    String signedString = "signed";
    boolean bigEndian = true;
    int channels = 2;
    if (encString.equals("linear")) {
    if (signedString.equals("signed")) {
    encoding = AudioFormat.Encoding.PCM_SIGNED;
    } else {
    encoding = AudioFormat.Encoding.PCM_UNSIGNED;
    } else if (encString.equals("alaw")) {
    encoding = AudioFormat.Encoding.ALAW;
    return new AudioFormat(encoding, rate, sampleSize,
    channels, (sampleSize/8)*channels, rate, bigEndian);
    public void run() {
    duration = 0;
    audioInputStream = null;
    // define the required attributes for our line,
    // and make sure a compatible line is supported.
    AudioFormat format = getFormat();
    DataLine.Info info = new DataLine.Info(TargetDataLine.class,
    format);
    if (!AudioSystem.isLineSupported(info)) {
    shutDown("Line matching " + info + " not supported.");
    return;
    // get and open the target data line for capture.
    try {
    line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format, line.getBufferSize());
    } catch (LineUnavailableException ex) {
    shutDown("Unable to open the line: " + ex);
    return;
    } catch (SecurityException ex) {
    shutDown(ex.toString());
    return;
    } catch (Exception ex) {
    shutDown(ex.toString());
    return;
    // play back the captured audio data
    int frameSizeInBytes = format.getFrameSize();
    int bufferLengthInFrames = line.getBufferSize() / 8;
    int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
    byte[] data = new byte[bufferLengthInBytes];
    int numBytesRead;
    line.start();
    try
    while (thread != null) {
    if((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
    break;
    if(data.length>0)
    out.write(data, 0, numBytesRead);
    out.flush();
    catch (Exception e)
    e.printStackTrace();
    // we reached the end of the stream. stop and close the line.
    line.stop();
    line.close();
    line = null;
    // stop and close the output stream
    try {
    out.flush();
    out.close();
    } catch (IOException ex) {
    ex.printStackTrace();
    } // End class Capture

  • How to get comparable Oracle JDBC performance using Java 1.4 vs 1.1.7?

    Our application makes extensive use of JDBC to access an Oracle database. We wrote it a number of years ago using java 1.1.7 and we have been unable to move to new versions of java because of the performance degradation.
    I traced the problem to JDBC calls. I can reproduce the problem using a simple program that simply connects to the database, executes a simple query and then reads the data. The same program running under java 1.4 is about 60% slower than under java 1.1.7. The query is about 80% slower and getting the data is about 150% slower!
    The program is attached below. Note, I run the steps twice as the first time the times are much larger which I attribute to java doing some initializations. So the second set of values I think are more representative of the actual performance in our application where there are numerous accesses to the database. Specifically, I focus on step 4 which is the execute query command and step 5 which is the data retrieval step. The table being read has 4 columns with 170 tuples in it.
    Here are the timings I get when I run this on a Sparc Ultra 5 running
    SunOs 5.8 using an Oracle database running 8.1.7:
                     java 1.1.7  java 1.4
            overall:    2.1s         3.5s
            step 1:     30           200
            step 2:    886          2009
            step 3:      2             2
            step 4:      9            17
            step 5:    122           187
            step 6:      1             1
            step 1:      0             0
            step 2:    203           161
            step 3:      0             1
            step 4:      8            15   <-   87% slower
            step 5:     48           117   <-  143% slower
            step 6:      1             2I find the same poor performance from java versions 1.2 and 1.3.
    I tried using DataDirect's type 4 JDBC driver which gives a little better performance but overall it is still much slower than using java 1.1.7.
    Why do the newer versions of java have such poor performance when using JDBC?
    What can be done so that we can have performance similar to java 1.1.7
    using java 1.4?
    ========================================================================
    import java.util.*;
    import java.io.*;
    import java.sql.*;
    public class test12 {
        public static void main(String args[]) {
            try {
                    long time1 = System.currentTimeMillis();
    /* step 1 */  DriverManager.registerDriver(
                        new oracle.jdbc.driver.OracleDriver());
                    long time2 = System.currentTimeMillis();
    /* step 2 */  Connection conn = DriverManager.getConnection (
                  "jdbc:oracle:thin:@dbserver1:1521:db1","user1","passwd1");
                    long time3 = System.currentTimeMillis();
    /* step 3 */  Statement stmt = conn.createStatement();
                    long time4 = System.currentTimeMillis();
    /* step 4 */  ResultSet rs = stmt.executeQuery("select * from table1");
                    long time5 = System.currentTimeMillis();
    /* step 5 */  while( rs.next() ) {
                      int message_num = rs.getInt(1);
                      String message = rs.getString(2);
                    long time6 = System.currentTimeMillis();
    /* step 6 */  rs.close(); stmt.close();
                    long time7 = System.currentTimeMillis();
                System.out.println("step 1: " + (time2 - time1) );
                System.out.println("step 2: " + (time3 - time2) );
                System.out.println("step 3: " + (time4 - time3) );
                System.out.println("step 4: " + (time5 - time4) );
                System.out.println("step 5: " + (time6 - time5) );
                System.out.println("step 6: " + (time7 - time6) );
                System.out.flush();
            } catch ( Exception e ) {
                System.out.println( "got exception: " + e.getMessage() );
            ... repeat the same 6 steps again...
    }

    If I run my sample program with the -server option, it
    takes a lot longer (6.8s vs 3.5s).Which has to be expected, as the -server option optimizes for long running programs - so it shoudl go with my second suggestion, more below...
    I am not certain what you mean by "just let the jvm
    running". Our users issue a command (in Unix) which
    invokes one of our java programs to access or update
    data in a database. I think what you are suggesting
    would require that I rewrite our application to have a
    java program always running on the users workstation
    and to also rewrite our
    commands (over a hundred) to some how pass data and
    receive data with this new server java program. That
    does not seem a very reasonable just to move to a new
    version of java. Or are you suggesting something
    else?No I was just suggestion what you descript. But if this is not an option, then maybe you should merge your java-programs to C or another native language. Or you could try the IBM-JDK with the -faststart (or similar) option. If thew Unix you mention is AIX, then there would be the option of a resetable-vm. But I cannot say if this VM would solve your problem. Java is definitly not good for applications which only issue some unqiue commands because the hotspot-compiler can not be efficiently used there. You can only try to get 1.1.7 performance by experimenting with vm-parameters (execute java -X).

  • How to get images from sybase database

    i have been trying to fix this code and so far after 10 hours have no succes my jsp page is coded like so...
    <html>
    <head><title>JSP The Short Course - Lesson 13 </title></head>
    <body>
    <jsp:useBean id="myBean" scope="session" class="examplebean.bean2" />
    <img src= "<%=myBean.getImage(1)%>">
    </body>
    </html>
    and the bean is coded like so
    package examplebean;
    import java.sql.* ;
    import java.io.Serializable;
    public class bean2 implements java.io.Serializable {
    public bean2() {}
    public javax.servlet.http.HttpServletResponse getImage(int p){
    java.io.BufferedInputStream bufferedInputStream;
    Connection sqlca = null;
    Statement sqlStatement = null;
    ResultSet myResultSet = null;
    javax.servlet.http.HttpServletResponse response = null;
    java.io.InputStream i = null;
    int popo = 0;
    try {
    Class.forName("com.sybase.jdbc2.jdbc.SybDriver");
    String theDatabase = "jdbc:sybase:Tds:compserver:5000/syb3026";
    sqlca = DriverManager.getConnection(theDatabase,"syb3026","oohyeahh");
    sqlStatement = sqlca.createStatement();
    myResultSet = sqlStatement.executeQuery("select Product_Picture from PRODUCT_TABLE where Product_Id = " + p + " ");
    /* Construct the heading for the table */
    /* Move to next row and & its contents
    to the html output */
    response.setContentType("image/jpeg");
    while(myResultSet.next()) {
    byte[] pepe = myResultSet.getBytes("Product_Picture");
    popo = pepe.length;
    i.read(pepe,0,popo);
    bufferedInputStream = new java.io.BufferedInputStream(i);
    java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
    int start = 0;
    int length = 1024;
    byte[] buff = new byte[popo];
    int bytesRead;
    while(-1 != (bytesRead = bufferedInputStream.read(buff, 0, popo))) {
    byteArrayOutputStream.write(buff, 0, bytesRead);
    bufferedInputStream.close();
    response.setContentLength( byteArrayOutputStream.size() );
    response.getOutputStream().write( byteArrayOutputStream.toByteArray() );
    response.getOutputStream().flush();
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
    param.setQuality(1.0f,true);
    encoder.encode(img,param);
    out.close();*/
    sqlStatement.close();
    catch (SQLException e) {
    System.out.println(" Error: SQL error of: " + e.getMessage());
    catch (Exception e) {
    System.out.println(" Error: JDBC Class creation: " + e.getMessage());
    finally {
    try {
    sqlca.close();
    catch(SQLException e) {
    System.out.println(" Error: Closing connection: " + e.getMessage());
    return response;
    I KNOW THIS CODE IS NOT THE BEST WRITEN BUT I SHOULD WORK. BUT IT DOESNT I REALLY NEED HELP AND DONT HAVE ANY ASISTENCE IN COLLEGE ANY HELP WOULD BE APPRECITAED SINCERLY AS I AM LOST WITH THIS PROBLEM
    THANK YOU
    THANK YOU
    THANK YOU
    THANK YOU

    maybe not so complex
    if (RS_photo.next()){ 
    buf = RS_photo.getBytes(1);
    response.setContentType("image/"+photoname);
    OutputStream out = response.getOutputStream();
    out.write(buf);
    out.flush();
    }catch (Exception e){ 
    //throw e;
    }

  • Problem with socket and object writing

    Hi,
    I programm this client/server app, the client has a point (graphic ) , the server has a point and when the mouse is moving it moves the point and the new position is send via the socket.
    The probleme is that i don't receive the good thing.
    When i display the coord of the point before sending it's good , but when receiving from the socket the coords are always the same ...
    i don't understand .
    Well , try and tell me ...
    Thx.

    oups, the program can be usefull ...
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class server_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    server s;
    public server_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p2=new point(50,50,new Color(0,0,255));
    p1=new point(200,200,new Color(255,0,0));
    s = new server(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    s.write_point(p1);
    repaint();
    public static void main(String args[])
         server_JFrame sjf = new server_JFrame();
    sjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         sjf.setTitle("server");
    sjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class server {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public server(point p,Container c)
    p_=p;
    c_=c;
    try
    ServerSocket server = new java.net.ServerSocket(80);
    System.out.println("attente d'un client");
    java.net.Socket client = server.accept();
    System.out.println("client accept�");
    Istream_ = new ObjectInputStream(client.getInputStream());
    Ostream_ = new ObjectOutputStream(client.getOutputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) { exception.printStackTrace(); }
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class client_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    client c;
    public client_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p1=new point(50,50,new Color(0,0,255));
    p2=new point(200,200,new Color(255,0,0));
    c = new client(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    c.write_point(p1);
    repaint();
    public static void main(String args[])
         client_JFrame cjf = new client_JFrame();
    cjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         cjf.setTitle("client");
    cjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
    private int x_;
    private int y_;
    private Color c_;
    public point(int x, int y, Color c) {
    x_=x;
    y_=y;
    c_=c;
    public int get_x() { return x_ ; }
    public int get_y() { return y_ ; }
    public void set_x(int x) { x_=x ; }
    public void set_y(int y) { y_=y ; }
    public Color get_color() { return c_ ; }
    }

  • Sending data to xport doesn't work correctly

    Dear programmers,
    For my thesis I have to send data from a computer to a microcontroller trough TCP/IP. So I've written a program in java dat sends the data, but it goes wrong. This is my code:
    import java.io.*;
    import java.net.*;
    public class Connection {
         private Socket socket = null;
        private PrintWriter output = null;
        private BufferedReader input = null;
        private BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));;
         public boolean createConnection(String ip, int port) {
            boolean connect = false;
            try {
                socket = new Socket(ip, port);                                                            // Maakt socket aan naar gegeven poort en ip
                output = new PrintWriter(socket.getOutputStream(), true);                         // Output naar de server
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));     // Ontvangen gegevens van server
                connect = true;
            } catch (UnknownHostException e) {
                connect = false;
                 System.err.println("Kan geen verbinding maken naar ip-adres: " + ip);
                System.exit(1);
            } catch (IOException e) {
                 connect = false;
                System.err.println("Kan geen input/output verkrijgen van ip-adres: " + ip);
                System.exit(1);
            return connect;
         public boolean sendMessage(String message) {          
              output.println(message);
              output.println("\r\n")
              return true;
         public String receiveMessage() {
              String message = null;
              try {
                   message = input.readLine();
              } catch (IOException e) {
                   e.printStackTrace();
              if(message.equalsIgnoreCase("HTTP/1.1 0 ERROR")) {
                   message = "#ERROR#";
              return message;
         public boolean getStatus() {
              if(socket.isConnected()) {
                   return true;
              else {
                   return false;
         public void closeConnection() {
              try {
                   output.close();
                   input.close();
                   stdIn.close();
                   socket.close();
              } catch (IOException e) {
                   e.printStackTrace();
    }The first time I send something it goes correctly, but when I try to send the second data it goes wrong.
    So as example I send 100 times the number 512 to the xport.
    1st time: 512
    2nd time: 5
    3th time: 52
    4th time: 5125
    So only the first time it sends the data correctly. It's my program and not the xport because trough hyperterminal the data is sended correctly. I hope you guys can help me.

    Okay, thanks for your reaction. Now I changed my Connection.java code into:
    import java.io.*;
    import java.net.*;
    public class Connection {
         private Socket socket = null; 
        private BufferedOutputStream ostream = null;
        private BufferedInputStream istream = null;
         public boolean createConnection(String ip, int port) {
            boolean connect = false;
            try {
                socket = new Socket(ip, port);
                ostream = new BufferedOutputStream(socket.getOutputStream());
                istream = new BufferedInputStream(socket.getInputStream());
                connect = true;
            } catch (UnknownHostException e) {
                connect = false;
                 System.err.println("Kan geen verbinding maken naar ip-adres: " + ip);
                System.exit(1);
            } catch (IOException e) {
                 connect = false;
                System.err.println("Kan geen input/output verkrijgen van ip-adres: " + ip);
                System.exit(1);
            return connect;
         public boolean sendMessage(String message) {
              byte[] buffer = new byte[10];
              try {
                   buffer = message.getBytes();
                   ostream.write(buffer, 0, message.length());
                   ostream.flush();
              catch(Exception e) {
                   e.printStackTrace();
              return true;
         public String receiveMessage() {
              String message = null;
              byte[] readBuffer = new byte[40];
              try {
                   int message_int = istream.read(readBuffer, 0, 40);
                 message = new String(readBuffer, 0, message_int);
              } catch (IOException e) {
                   e.printStackTrace();
              if(message.equalsIgnoreCase("HTTP/1.1 0 ERROR")) {
                   message = "#ERROR#";
              return message;
         public boolean getStatus() {
              if(socket.isConnected()) {
                   return true;
              else {
                   return false;
         public void closeConnection() {
              try {
                   ostream.close();
                   istream.close();
                   socket.close();
              } catch (IOException e) {
                   e.printStackTrace();
    }Do you think this was the problem? Maybe it was. Let's hope so. I will let you know something when I tested it tomorrow in school.

  • Socket example using Java 5

    Last year I posted 4 programs that provided a simple client server using both stream sockets and NIO. I decided as an exercise in using Java 5 to port that code and try to use as many of the new features as possible. The following code is very long and does what all the previous example programs did. In replies do not repost the whole of this message.
    It provides a simple chat like client and server. The user can request either a stream connection or a NIO connection or provide one of their own.
    //========================== MsgSwitch.java ===========================//
    package pkwnet.msgswitch;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    import java.util.logging.Handler;
    * main class for message switch
    * command line arguments are
    * -p port number for server
    * -s run server
    * -a server ip address including port for client
    * -i idle timer in seconds
    * -n use NIO
    * -c specify connection class
    public class MsgSwitch {
        static private int errors = 0;
        static private String address = "127.0.0.1:6060";
        static private String connectionClass = "pkwnet.msgswitch.StreamConnection";
        static public void main(String [] args) {
            int port = 6060;
            int idleTime = 600;
            boolean server = false;
            boolean nio = false;
            Logger logger = Logger.getLogger("msgswitch");
            for(String arg : args) {
                if(arg.startsWith("-a")) {
                    address = arg.substring(2);
                } else if(arg.startsWith("-p")) {
                    port = argToInt(arg);
                    server = true;
                } else if(arg.startsWith("-i")) {
                    idleTime = argToInt(arg);
                } else if (arg.startsWith("-s")) {
                    server = true;
                } else if (arg.startsWith("-c")) {
                    connectionClass = arg.substring(2);
                } else if (arg.startsWith("-n")) {
                    connectionClass = "pkwnet.msgswitch.NIOConnection";
                } else {
                    String err = "unknown argument=" + arg;
                    logger.severe(err);
                    System.err.println(err);
                    errors++;
            if (errors == 0) {
                if (server) {
                    new Server().listen(port,idleTime, nio);
                } else {
                    new Client().start(address, nio);
            } else {
                fail(errors + " errors encountered", null);
        static private int argToInt(String arg) {
            int val = 0;
            try {
                val = Integer.parseInt(arg.substring(2));
            } catch (NumberFormatException e) {
                String err = "invalid argument format: " + arg;
                Logger.getLogger("msgswitch").severe(err);
                System.err.println(err);
                errors++;
            return val;
        static public void fail(String err, Throwable e) {
            String msg = "Operation terminated: " + err;
            Logger.getLogger("msgswitch").log(Level.SEVERE, msg, e);
            System.err.println(msg);
            System.exit(12);
        static public Connection getConnection() {
            Connection conn = null;
            try {
                conn = (Connection) Class.forName(connectionClass).newInstance();
            } catch (Exception e) {
                fail ("connection class error", e);
            return conn;
        static public void logCaller(Logger logger, Level level) {
            String text = "CALLED";
            if (logger.isLoggable(level)) {
                try {
                    throw new Exception("logging stack");
                } catch (Exception e) {
                    StackTraceElement [] st = e.getStackTrace();
                    if (st.length > 1) {
                        text += formatElement(st[1]);
                    if (st.length >2) {
                        text += formatElement(st[2]);
                logger.log(level, text);
        static private String formatElement(StackTraceElement ste) {
            return "\n    " + ste.getClassName() + "." + ste.getMethodName()
                + "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")";
    //================= Client.java =============================================//
    package pkwnet.msgswitch;
    * a simple Swing chat GUI using Java 5 and sockets.
    * @author PKWooster
    * @version 1.0 August 31,2005
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JMenu;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JDialog;
    import javax.swing.SwingUtilities;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import static java.awt.BorderLayout.*;
    client GUI class
    public class Client extends JFrame implements ConnectionListener {
         // swing GUI components
         private JTextField userText = new JTextField(40);
         private JTextArea sessionLog = new JTextArea(24,40);
         private JTextField statusText = new JTextField(40);
         private JPanel outPanel = new JPanel();
         private JScrollPane sessionLogScroll = new JScrollPane(sessionLog);
         private JMenuBar menuBar = new JMenuBar();
         private JMenuItem startItem = new JMenuItem("Start");
         private JMenuItem hostItem = new JMenuItem("Host");
         private JMenuItem aboutItem = new JMenuItem("About");
         private JMenuItem abortItem = new JMenuItem("Abort");
         private JMenuItem exitItem = new JMenuItem("Exit");
         private JMenu fileMenu = new JMenu("File");
         private JMenu helpMenu = new JMenu("Help");
         private Container cp;
         private String address;
        private Connection connection;
        private boolean sendReady = false;
        private boolean nio = false;
         Client() {
        public void start(String address, boolean nio) {
            this.address = address;
            this.nio = nio;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    runClient();
        private void runClient() {   
            connection = MsgSwitch.getConnection();
            connection.addConnectionListener(this);
              buildMenu();
              cp = getContentPane();
              sessionLog.setEditable(false);
              outPanel.add(new JLabel("Send: "));
              outPanel.add(userText);
              // enter on userText causes transmit
              userText.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){userTyped(evt);}
              cp.setLayout(new BorderLayout());
              cp.add(outPanel,NORTH);
              cp.add(sessionLogScroll,CENTER);
              cp.add(statusText,SOUTH);
              setStatus("Closed");
              addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    mnuExit();
              pack();
            setVisible(true);
    * attempt to send the contents of the user text field
        private void userTyped(ActionEvent evt) {
            if (sendReady) {
                String txt = evt.getActionCommand()+"\n";
                userText.setText("");
                toSessionLog("> ", txt);
                sendReady = false;
                connection.send(txt);
    * append text to the session log
         private void toSessionLog(String prefix, String txt) {
              sessionLog.append(prefix + txt);
              sessionLog.setCaretPosition(sessionLog.getDocument().getLength() ); // force last line visible
    * build the standard menu bar
         private void buildMenu()
              JMenuItem item;
              // file menu
              startItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuStart();}});
              fileMenu.add(startItem);
              hostItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuHost();}});
              fileMenu.add(hostItem);
              exitItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuExit();}});
              fileMenu.add(exitItem);
              menuBar.add(fileMenu);
              helpMenu.add(aboutItem);
              aboutItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuAbout();}});
              menuBar.add(helpMenu);
              setJMenuBar(menuBar);
    * start and stop communications from start menu
         private void mnuStart() {
            if(connection.getState() ==  Connection.State.CLOSED) {
                connection.connect(address);
            } else {
                connection.disconnect();
    *  prompt user for host in form address:port
        private void mnuHost() {
              String txt = JOptionPane.showInputDialog("Enter host address:port", connection.getAddress());
              if (txt == null)return;
            address = txt;
         private void mnuAbout() {
              JDialog dialog = new JDialog(this, "About Client");
              JTextField text = new JTextField("Simple character client");
            dialog.getContentPane().add(text);
            dialog.pack();
            dialog.setVisible(true);
         // exit menu
         private void mnuExit() {
            exit();
        private void exit() {
              connection.disconnect();
              System.exit(0);
         private void setStatus(String st) {
            statusText.setText(st);
         private void setStatus(Connection.State state) {
            switch(state) {
                case OPENED:
                    startItem.setText("Stop");
                    setStatus("Connected to "+address);
                    break;
                case CLOSED:
                    startItem.setText("Start");
                    setStatus("Disconnected");
                    break;
                case OPENING:
                    setStatus("Connecting to "+address);
                    startItem.setText("Abort");
                    break;
                case CLOSING:
                    setStatus("Disconnecting from "+address);
                    startItem.setText("Abort");
                    break;
        public void stateChanged(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
        public void dataAvailable(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    String txt = event.getData();
                    if (txt == null) {
                        txt = "$null$";
                    toSessionLog("< ", txt + "\n");   
        public void sendAllowed(final ConnectionEvent event) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setStatus(event.getState());
                    sendReady = true;
        public void accept(ConnectionEvent event) {
    //========================== Server.java ===============================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    * a simple message switch using stream based socket i/o
    * a very simple text message switching program
    * user commands start with $ and consist of blank seperated arguments
    * other lines sent by the user are forwarded
    * $on nickname targets
    *    sign on as nickname, sending to targets
    * $to targets
    *    change target list, reports current value
    * $list nicknames
    *    list status of specified nicknames
    * $list
    *    list all connected users
    * $off
    *    sign off
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class Server {
        private ConcurrentHashMap<String, User> perUser = new ConcurrentHashMap<String,User>();
        private Timer idleTimer;
        private Connection conn;
        public void listen(int port, final int idleTime, boolean nio) {
            idleTimer = new Timer();
            idleTimer.scheduleAtFixedRate(new TimerTask(){public void run(){oneSec();}},0,1000);
            conn = MsgSwitch.getConnection();
            conn.addConnectionListener(new ConnectionListener() {
                public void stateChanged(ConnectionEvent event) {
                public void dataAvailable(ConnectionEvent event) {
                public void sendAllowed(ConnectionEvent event) {
                public void accept(ConnectionEvent event) {
                    Connection uconn = event.getConnection();
                    new User(uconn, perUser, idleTime);
            conn.listen(port);
            idleTimer.cancel();
        private void oneSec() {
            Collection<User> uc = perUser.values();
            for(User u : uc) {
                u.oneSec();
    //================= User.java  ==============================================//
    package pkwnet.msgswitch;
    import java.io.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.atomic.AtomicInteger;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * defines the processing for a message switch user
    * @author PKWooster
    * @version 1.0 June 15,2004
    public class User implements ConnectionListener {
        private ConcurrentHashMap<String, User> perUser;
        private String name;
        private String address;
        private boolean signedOn = false;
        private String[] targets;
        private AtomicInteger remainingTime;
        private int idleTime;
        Connection conn;
        Logger logger;
      * construct a user, link it to its connection and put it in the perUser table
        User(Connection conn, ConcurrentHashMap<String,User>p, int idle) {
            this.conn = conn;
            logger = Logger.getLogger("msgswitch.user");
            conn.addConnectionListener(this);
            address = conn.getAddress();
            logger.info("creating user " + address);
            perUser = p;
            idleTime = idle;
            remainingTime = new AtomicInteger(idleTime);
            rename(address);
            targets = new String[0];
    * process state changes
        public void stateChanged(ConnectionEvent event) {
            if(event.getState() == Connection.State.CLOSED) {
                close(false);
    * data is available, process commands and forward other data.
        public void dataAvailable(ConnectionEvent event) {
            String msg = event.getData();
            if (msg.startsWith("$")) {
                doCommand(msg);
            } else {
                forward(msg);
            remainingTime.set(idleTime);
    * do nothing for sendAllowed events
        public void sendAllowed(ConnectionEvent event) {
    * do nothing for accept events
        public void accept(ConnectionEvent event) {
    * called once per second by the server main thread.
        public void oneSec() {
            if(idleTime != 0 && 1 > remainingTime.decrementAndGet()) {
                close(true);
    * send a message
        private void send(String msg) {
            conn.send(msg);
            remainingTime.set(idleTime);
    * forward data messages to other users
    * @param txt the message to send
        private void forward(String txt) {
            txt = name+": "+txt + "\n";
            if(0 < targets.length) {
                for(String target :targets) {
                    User user = perUser.get(target);
                    if(user != null) {
                        user.send(txt);
            } else {
                for (User user : perUser.values()) {
                    if (user != this) {
                        user.send(txt);
    * execute command messages, commands start with a $
    * and contain arguments delimited by white space.
    * @param command the command string
        private void doCommand(String command) {
            boolean good = false;
            command = command.substring(1).trim();
            if(command.length() > 0) {
                String [] args = command.split("\\s+");
                if(args[0].equals("on")) {
                    good = signOn(args);
                } else if(args[0].equals("off")) {
                    good = signOff(args);
                } else if(args[0].equals("list")) {
                    good = listUsers(args);
                } else if(args[0].equals("to")) {
                    good = setTargets(args,1);
                } else if(args[0].equals("idle")) {
                    good = setIdle(args);
                if(!good) {
                    send("invalid command=" + command + "\n");
    * sign on command
        private boolean signOn(String [] args) {
            boolean good = false;
            if(args.length >1) {
                String nm = args[1];
                logger.info("signing on as: " + nm);
                if(rename(nm)) {
                    conn.setName(name);
                    send("Signed on as " + name + "\n");
                    signedOn = true;
                    good = true;
                    setTargets(args,2);
                } else {
                    send("name="+nm+" already signed on\n");
            return good;
    * set forwarding targets
        private boolean setTargets(String [] args, int start) {
            if(start < args.length) {
                targets = new String[args.length-start];
                System.arraycopy(args, start, targets, 0, targets.length);
            String str = "to=";
            for(String target : targets) {
                str += (target + " ");
            send(str+"\n");
            return true;
    * set idle timeout
        private boolean setIdle(String[] args) {
            try {
                idleTime = new Integer(args[1]).intValue();
                remainingTime.set(idleTime);
                send("idle time set to "+idleTime+"\r\n");
                return true;
            } catch(NumberFormatException exc) {
                return false;
    * sign off
        private boolean signOff(String [] args) {
            close(true);
            return true;
    * list connected users
        private boolean listUsers(String [] args) {
            TreeSet<String> allUsers = new TreeSet<String>(perUser.keySet());
            HashSet<String> t = new HashSet<String>(Arrays.asList(targets));
            LinkedList<String> users;
            String response = "On,Target,Nickname\n";
            if(args.length < 2) {
                users = new LinkedList<String>(allUsers);
            } else {
                users = new LinkedList<String>();
                for (int i = 1; i < args.length; i++) {
                    users.add(args);
    for(String username : users) {
    if(username.equals(name)) {
    response += "*,";
    } else {
    response += (allUsers.contains(username) ? "y," : "n,");
    response += (t.contains(username) ? "y," : "n,");
    response += (username + "\n");
    send(response);
    return true;
    * rename this user, first we attempt to add the new name then we remove
    * the old one. Both names will be registered for a short while.
    * @param newname the new name for this user
    * @return true if the rename was successful
    private boolean rename(String newname) {
    boolean b = false;
    logger.info("rename name="+name+" newname="+newname);
    if (name != null && name.equals(newname)) {
    b = true;
    } else if (null == perUser.putIfAbsent(newname, this)) {
    if (name != null) {
    perUser.remove(name);
    name = newname;
    b = true;
    return b;
    * delete from perUser and close our connection
    private void close(boolean disconnect) {
    logger.info("closing user "+name);
    perUser.remove(name);
    if (disconnect) {
    conn.disconnect();
    //====================== Connection.java ===============================//
    package pkwnet.msgswitch;
    import java.util.HashSet;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    public abstract class Connection {
    public enum State {CLOSED, OPENING, OPENED, CLOSING}
    private HashSet<ConnectionListener> listeners = new HashSet<ConnectionListener>();
    private State state = State.CLOSED;
    private String host = "127.0.0.1";
    private int port = 6060;
    private String name = "unconnected";
    public Connection() {
    public abstract void listen(int port);
    public abstract void connect(String address);
    public abstract void disconnect();
    public abstract void send(String message);
    public void addConnectionListener(ConnectionListener listener) {
    listeners.add(listener);
    public void removeConnectionListener(ConnectionListener listener) {
    listeners.remove(listener);
    protected void fireDataAvailable(String data) {
    for (ConnectionListener listener : listeners) {
    listener.dataAvailable(new ConnectionEvent(this, state, data));
    private void fireStateChanged() {
    for (ConnectionListener listener : listeners) {
    listener.stateChanged(new ConnectionEvent(this, state));
    protected void fireSendAllowed() {
    for (ConnectionListener listener : listeners) {
    listener.sendAllowed(new ConnectionEvent(this, state));
    protected void fireAccept(Connection conn) {
    for (ConnectionListener listener : listeners) {
    listener.accept(new ConnectionEvent(this, conn));
    protected void setState(State state) {
    if (this.state != state) {
    this.state = state;
    fireStateChanged();
    public State getState() {
    return state;
    protected void setAddress(String address) {
              int n = address.indexOf(':');
              String pt = null;
    setName(address);
    if(n == 0) {
                   host = "127.0.0.1";
                   pt = address.substring(1);
              else if(n < 0) {
                   host = address;
                   port = 5050;
              } else {
    host = address.substring(0,n);
                   pt = address.substring(n+1);
    if (pt != null) {
    try {
    port = Integer.parseInt(pt);
    } catch (NumberFormatException e) {
    port = -1;
    public String getName() {
    return name;
    public void setName(String value) {
    name = value;
    public String getAddress() {
    return host + ":" + port;
    public String getHost() {
    return host;
    public void setPort(int value) {
    port = value;
    public int getPort() {
    return port;
    //=================== ConnectionEvent.java ================================//
    package pkwnet.msgswitch;
    public class ConnectionEvent extends java.util.EventObject {
    private final String data;
    private final Connection.State state;
    private final Connection conn;
    public ConnectionEvent(Object source, Connection.State state, String data, Connection conn) {
    super(source);
    this.state = state;
    this.data = data;
    this.conn = conn;
    public ConnectionEvent(Object source, Connection.State state, String data) {
    this(source, state, data, null);
    public ConnectionEvent(Object source, Connection.State state) {
    this(source, state, null, null);
    public ConnectionEvent(Object source, Connection conn) {
    this(source, conn.getState(), null, conn);
    public Connection.State getState() {
    return state;
    public String getData() {
    return data;
    public Connection getConnection() {
    return conn;
    //============================ ConnectionListener.java ===================//
    package pkwnet.msgswitch;
    public interface ConnectionListener extends java.util.EventListener {
    public void stateChanged(ConnectionEvent event);
    public void dataAvailable(ConnectionEvent event);
    public void sendAllowed(ConnectionEvent event);
    public void accept(ConnectionEvent event);
    //============================ StreamConnection.java ===================//
    package pkwnet.msgswitch;
    import java.net.Socket;
    import java.net.ServerSocket;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.IOException;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    * provides stream socket i/o of character strings
    * @author PKWooster
    * @version 1.0 September 1, 2005
    public class StreamConnection extends Connection {
    private Socket sock;
    private BufferedReader in;
    private BufferedWriter out;
    private Thread recvThread = null;
    private Thread sendThread = null;
    protected LinkedBlockingQueue<String> sendQ;
    Logger logger;
    public StreamConnection() {
    super();
    logger = Logger.getLogger("msgswitch.stream");
    sendQ = new LinkedBlockingQueue<String>();
    * open a socket and start i/o threads
    public void connect(String ipAddress) {
    setAddress(ipAddress);
    try {
    sock = new Socket(getHost(), getPort());
    connect(sock);
    } catch (IOException e) {
    logger.log(Level.SEVERE, "Connection failed to=" + ipAddress, e);
    private void connect(Socket sock) {
    this.sock = sock;
    String ipAddress = getAddress();
    try {
    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
    recvThread = new Thread(new Runnable() {
    public void run() {
    doRecv();
    },"Recv." + getName());
    sendThread = new Thread(new Runnable() {
    public void run() {
    doSend();
    },"Send."+getName());
    sendThread.start();
    recvThread.start();
    setState(State.OPENED);
    } catch(IOException e) {
    logger.log(Level.SEVERE, "Connection failed to="+ipAddress, e);
    public void listen(int port) {       
    StreamConnection sconn;
    setPort(port);
    try {
    ServerSocket ss = new ServerSocket(port);
    while(true) {
    Socket us = ss.accept();
    sconn = new StreamConnection();
    String ipAddress = us.getInetAddress() + ":" + us.getPort();
    sconn.setAddress(ipAddress);
    sconn.connect(us);
    fireAccept(sconn);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "listen failed", e);
    * close the socket connection
    public void disconnect() {
    logger.fine("disconnect sock=" + sock + " state="+ getState());
    if(getState() == State.OPENED) {
    setState(State.CLOSING);
    try {
    sock.shutdownOutput();
    } catch(IOException ie) {
    logger.log(Level.SEVERE, "showdown failed", ie);
    } else if(getState() != State.CLOSED) {
    try {
    sock.close();
    } catch(Exception e) {
    logger.log(Level.SEVERE, "close failed", e);
    if (sendThread.isAlive()) {
    sendThread.interrupt();
    sendQ.clear();
    setState(State.CLOSED);
    public void send(String message) {
    if (getState() == State.OPENED) {
    try {
    sendQ.put(message);
    } catch(InterruptedException e) {
    logger.log(Level.SEVERE, "sendQ put interrupted", e);
    setState(State.CLOSING);
    disconnect();
    * sets the public name of this connection
    public void setName(String name) {
    super.setName(name);
    if (sendThread != null) {
    try {
    recvThread.setName("recv." + name);
    sendThread.setName("send." + name);
    } catch(Exception e) {
    logger.log(Level.SEVERE, "nameing threads failed", e);
    * the main loop for the send thread
    private void doSend() {
    String msg;
    boolean running = true;
    while (running) {
    if (sendQ.size() == 0) {
    fireSendAllowed();
    try {
    msg = sendQ.take();
    out.write(msg);
    out.flush();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "write failed", e);
    setState(State.CLOSING);
    disconnect();
    running = false;
    * the main loop for the receive thread
    private void doRecv() {
    String inbuf;
    while (getState() == State.OPENED) {
    try {
    inbuf = in.readLine();
    } catch(Exception e) {
    if (getState() == State.OPENED) {
    logger.log(Level.SEVERE, "readline failed", e);
    inbuf = null;
    if(inbuf == null) {
    logger.fine("null received on: " + getAdd

    Here are three of them:
    NIO server
    NIO client
    Multithreaded server
    The stream based client example seems to have been deleted, probably lost in the troll wars. I also posted a new Simple multithreaded server that uses the same protocol. As the client is missing, I'll repost it.

  • Problem in using socket streams with encryption and decryption

    Hi,
    I am developing a client/server program with encryption and decryption at both end. While sending a message from client it should be encrypted and at the receiving end(server) it should be decrypted and vice versa.
    But while doing so i got a problem if i use both encryption and decryption at both ends. But If i use only encryption at one (only outputstream) and decryption at other end(only inputstream) there is no problem.
    Here is client/server pair of programs in which i am encrypting the outputstream of the socket in client side and decrypting the inputstream of the socket in server side.
    serverSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class serverSocketDemo
         public static void main(String args[])
              try
              {                    //server listening on port 2000
                   ServerSocket server=new ServerSocket(2000);
                   while (true)
                        Socket theConnection=server.accept();
                        System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                        System.out.println("Connection request from : "+theConnection.getInetAddress());
                        //Input starts from here
                        Reader in=new InputStreamReader(getNetInStream(theConnection.getInputStream()),"ASCII");
                        StringBuffer strbuf=new StringBuffer();
                        int c;
                        while (true)
                             c=in.read();
                             if(c=='\n' || c==-1)
                                  break;
                             strbuf.append((char)c);     
                        String str=strbuf.toString();
                        System.out.println("Message from Client : "+str);
                        in.close();               
                        theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static BufferedInputStream getNetInStream(InputStream in) throws Exception
              // register the provider that implements the algorithm
              Provider sunJce = new com.sun.crypto.provider.SunJCE( );
              Security.addProvider(sunJce);
              // create a key
              byte[] desKeyDataDec = "This encryption can not be decrypted".getBytes();
              DESKeySpec desKeySpecDec = new DESKeySpec(desKeyDataDec);
              SecretKeyFactory keyFactoryDec = SecretKeyFactory.getInstance("DES");
              SecretKey desKeyDec = keyFactoryDec.generateSecret(desKeySpecDec);
              // use Data Encryption Standard
              Cipher desDec = Cipher.getInstance("DES");
              desDec.init(Cipher.DECRYPT_MODE, desKeyDec);
              CipherInputStream cin = new CipherInputStream(in, desDec);
              BufferedInputStream bin=new BufferedInputStream(new GZIPInputStream(cin));
              return bin;
    clientSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class clientSocketDemo
         public static void main(String args[])
              try
                   Socket theConnection=new Socket("localhost",2000);
                   System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                   System.out.println("Connecting to : "+theConnection.getInetAddress());
                   //Output starts from here               
                   OutputStream out=getNetOutStream(theConnection.getOutputStream());
                   out.write("Please Welcome me\n".getBytes());
                   out.flush();
                   out.close();
                   theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static OutputStream getNetOutStream(OutputStream out) throws Exception
              // register the provider that implements the algorithm
              Provider sunJce = new com.sun.crypto.provider.SunJCE( );
              Security.addProvider(sunJce);
              // create a key
              byte[] desKeyDataEnc = "This encryption can not be decrypted".getBytes();
              DESKeySpec desKeySpecEnc = new DESKeySpec(desKeyDataEnc);
              SecretKeyFactory keyFactoryEnc = SecretKeyFactory.getInstance("DES");
              SecretKey desKeyEnc = keyFactoryEnc.generateSecret(desKeySpecEnc);
              // use Data Encryption Standard
              Cipher desEnc = Cipher.getInstance("DES");
              desEnc.init(Cipher.ENCRYPT_MODE, desKeyEnc);
              CipherOutputStream cout = new CipherOutputStream(out, desEnc);
              OutputStream outstream=new BufferedOutputStream(new GZIPOutputStream(cout));
              return outstream;
    Here is client/server pair in which i use both encrypting outpustream and decrypting inputstream at both ends.
    serverSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class serverSocketDemo
         private Cipher desEnc,desDec;
         serverSocketDemo()
              try
                   // register the provider that implements the algorithm
                   Provider sunJce = new com.sun.crypto.provider.SunJCE( );
                   Security.addProvider(sunJce);
                   // create a key
                   byte[] desKeyData = "This encryption can not be decrypted".getBytes();
                   DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
                   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                   SecretKey desKey = keyFactory.generateSecret(desKeySpec);
                   desEnc = Cipher.getInstance("DES");
                   desEnc.init(Cipher.ENCRYPT_MODE, desKey);
                   desDec = Cipher.getInstance("DES");
                   desDec.init(Cipher.DECRYPT_MODE, desKey);               
              catch (javax.crypto.NoSuchPaddingException e)
                   System.out.println(e);          
              catch (java.security.NoSuchAlgorithmException e)
                   System.out.println(e);          
              catch (java.security.InvalidKeyException e)
                   System.out.println(e);          
              catch(Exception e)
                   System.out.println(e);
              startProcess();
         public void startProcess()
              try
                   ServerSocket server=new ServerSocket(2000);
                   while (true)
                        final Socket theConnection=server.accept();
                        System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                        System.out.println("Connection request from : "+theConnection.getInetAddress());
                        Thread input=new Thread()
                             public void run()
                                  try
                                       //Input starts from here
                                       Reader in=new InputStreamReader(new BufferedInputStream(new CipherInputStream(theConnection.getInputStream(), desDec)),"ASCII");
                                       StringBuffer strbuf=new StringBuffer();
                                       int c;
                                       while (true)
                                            c=in.read();
                                            if(c=='\n'|| c==-1)
                                                 break;
                                            strbuf.append((char)c);     
                                       String str=strbuf.toString();
                                       System.out.println("Message from Client : "+str);
                                  catch(Exception e)
                                       System.out.println("Error caught inside input Thread : "+e);
                        input.start();
                        Thread output=new Thread()
                             public void run()
                                  try
                                       //Output starts from here
                                       OutputStream out=new BufferedOutputStream(new CipherOutputStream(theConnection.getOutputStream(), desEnc));
                                       System.out.println("it will not be printed");
                                       out.write("You are Welcome\n".getBytes());
                                       out.flush();
                                  catch(Exception e)
                                       System.out.println("Error caught inside output Thread : "+e);
                        output.start();
                        try
                             output.join();
                             input.join();
                        catch(Exception e)
                        theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static void main(String args[])
              serverSocketDemo server=new serverSocketDemo();          
    clientSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class clientSocketDemo
         private Cipher desEnc,desDec;
         clientSocketDemo()
              try
                   // register the provider that implements the algorithm
                   Provider sunJce = new com.sun.crypto.provider.SunJCE( );
                   Security.addProvider(sunJce);
                   // create a key
                   byte[] desKeyData = "This encryption can not be decrypted".getBytes();
                   DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
                   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                   SecretKey desKey = keyFactory.generateSecret(desKeySpec);
                   desEnc = Cipher.getInstance("DES");
                   desDec = Cipher.getInstance("DES");
                   desEnc.init(Cipher.ENCRYPT_MODE, desKey);
                   desDec.init(Cipher.DECRYPT_MODE, desKey);               
              catch (javax.crypto.NoSuchPaddingException e)
                   System.out.println(e);          
              catch (java.security.NoSuchAlgorithmException e)
                   System.out.println(e);          
              catch (java.security.InvalidKeyException e)
                   System.out.println(e);          
              catch(Exception e)
                   System.out.println(e);
              startProcess();
         public void startProcess()
              try
                   final Socket theConnection=new Socket("localhost",2000);
                   System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                   System.out.println("Connecting to : "+theConnection.getInetAddress());
                   Thread output=new Thread()
                        public void run()
                             try
                                  //Output starts from here               
                                  OutputStream out=new BufferedOutputStream(new CipherOutputStream(theConnection.getOutputStream(), desEnc));
                                  out.write("Please Welcome me\n".getBytes());
                                  out.flush();
                             catch(Exception e)
                                  System.out.println("Error caught inside output thread : "+e);
                   output.start();     
                   Thread input=new Thread()
                        public void run()
                             try
                                  //Input starts from here
                                  Reader in=new InputStreamReader(new BufferedInputStream(new CipherInputStream(theConnection.getInputStream(), desDec)),"ASCII");          
                                  System.out.println("it will not be printed");
                                  StringBuffer strbuf=new StringBuffer();
                                  int c;
                                  while (true)
                                       c=in.read();
                                       if(c=='\n' || c==-1)
                                            break;
                                       strbuf.append((char)c);     
                                  String str=strbuf.toString();
                                  System.out.println("Message from Server : "+str);
                             catch(Exception e)
                                  System.out.println("Error caught inside input Thread : "+e);
                   input.start();
                   try
                        output.join();
                        input.join();
                   catch(Exception e)
                   theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static void main(String args[])
              clientSocketDemo client=new clientSocketDemo();     
    **** I know that the CInput tries to read some header stuff thats why i used two threads for input and output.
    Waiting for the reply.
    Thank you.

    Do not ever post your code unless requested to. It is very annoying.
    Try testing what key is being used. Just to test this out, build a copy of your program and loop the input and outputs together. Have them print the data stream onto the screen or a text file. Compare the 1st Output and the 2nd Output and the 1st Input with the 2nd Input and then do a static test of the chipher with sample data (same data which was outputted), then do another cipher test with the ciphertext created by the first test.
    Everything should match - if it does not then follow the steps below.
    Case 1: IO Loops do not match
    Case 2: IO Loops match, but ciphertext 1st run does not match loop
    Case 3: IO Loops match, 1st ciphertext 1st run matches, but 2nd run does not
    Case 4: IO Loops match, both chiphertext runs do not match anything
    Case 5: Ciphertext runs do not match eachother when decrypted correctly (outside of the test program)
    Problems associated with the cases above:
    Case 1: Private Key is changing on either side (likely the sender - output channel)
    Case 2: Public Key is changing on either side (likely the sender - output channel)
    Case 3: Private Key changed on receiver - input channel
    Case 4: PKI failure, causing private key and public key mismatch only after a good combination was used
    Case 5: Same as Case 4

Maybe you are looking for