Overriding Socket Implementation

Few threads were already opened for this question, but I found none with the answer.
How do I overide default Socket implementation?
I want:
- to be responsible of the creation of every new Socket (or SocketImpl)
to be able to provide my own Socket implementation.
I want my socket implementation:
- to be built above the default socket implementation.
- to provide getInputStream() and getOutputStream() methods
that return a FilterInputStream and FilterOutputStream
which would refer to the Socket's input and output streams.
I see Socket.setSocketImplFactory() allow to set the default SocketImplFactory,
but I don't know how to get the default one nor how to build default SocketImpl.
Thanks for your help.

ejp wrote:
OK:
public class MySocket extends Socket
public MySocket(String host, int port) throws IOException
super(host, port);
// etc for the other constructors you need
public InputStream getInputStream() throws IOException
// your code, which at some point needs to call super.getInputStream();
// etc for getOutputStream()
}No need to override anything else, write delegators, etc. Just override exactly and only the methods you need to change.
Ok for this one, that's exactly what I've done for now for clients side sockets.
So that's done and dusted. This does not indeed set MySocket as the default socket for the entire JVM but believe me you don't want to do that. Consider what it would do to all URLs, and all SSL sockets. Break them. It would even break DNS lookups if they happened to be implemented via TCP.Well... hmm... sorry but, I don't belive you, at least not yet.
That's exactly what I want, URL (http, https) SSL, DNS, and I also want LDAP.
But I totally agree how dangerous it is, and how it could just break anything that uses Sockets.
So, how do I do that?
I see in the source (1.4.2_16) there are at least 2 implementations:
- PlainSocketImpl must be the default one
- SocksSocketImpl must be one that allows to use some socks server
What now if want to tunnel through an http server?
Can't I write my HttpTunnelSocketImpl?
If it makes sense to write a SocksSocketImpl,
it should make sense to write a HttpTunnelSocketImpl, no?
In case HttpTunnelSocketImpl already exists, then suppose I have my home made
non standard proxy/firewalls and want to pass through them.
So the only remaining problem is at the server side: how do I accept such a socket? Easy:
// Add a nullary constructor to MySocket
public MySocket(){}
// Define MyServerSocket
public class MyServerSocket extends ServerSocket
public MyServerSocket(int port) throws IOException
super(port);
// etc for the other constructors you need
// Accept method. Returns a MySocket object.
public Socket accept() throws IOException
Socket socket = new MySocket();
super.implAccept(socket);
return socket;
In the source for 1.4.2_16 the accept method is as follows:
    public Socket accept() throws IOException {
        if (isClosed())
            throw new SocketException("Socket is closed");
        if (!isBound())
            throw new SocketException("Socket is not bound yet");
        Socket s = new Socket((SocketImpl) null);
        implAccept(s);
        return s;
    }Shouldn't I copy the controls about closed and unbound sockets?
Please tell me Mr Sun is not going to blame me if I copy these 4 lines of code.

Similar Messages

  • Socket implementation in MIDP1.0

    Hi,
    Is socket implementation optional in MIDP1.0? If it optional, which OEMs implement sockets in their phones? I looked over Sprint API and they support StreamConnection and DatagramConnection, which is a part of socket connection. Although SocketConnection is not supported directly in SprintAPI, but StreamConnection and DatagramConnection should work fine (can anybody confirm that?). I'm really interested to know if socket is a OEM issue or a Sprint issue.
    If I can't use socket connection, I need to use HTTP. HTTP has some latency issues. What are some of the major issues that can cause latency using HTTP?
    Thank you.

    You might also be intrested in JHTTP Tunnel: http://www.jcraft.com/jhttptunnel/
    My only test device is a MIDP2, GPRS Socket capable device. But it almost as usable as socket mode.

  • Does the socket implementation suport only 2 simultaneous connections?

    Hi all,
    I implemented this server the traditional way:
    public void run() {
       while(state.isRunning()) {
          try {
             System.out.println("listening...");
             sourceSock = ssock.accept();
             System.out.println("new incoming connection");
             sourceSock.setSoTimeout(config.getHttpTimeout());
             new Thread(new ProxyHttpConnectionWorker(sourceSock, config)).start();
          } catch (IOException _ex) {
             config.out.trace(_ex.getMessage());
    }It seems ok to me. I implemented it several times in a lot of situations.
    However, this time I noted that after two simultaneous socket connections are opened (via accept()), all other connections I try to make from a client are blocking until one of the first two sockets close().
    I mean, it seems to be blocking the incoming connections in the accept() method, because the string "listening..." was printed, but the string "new incoming connection" is only printed when one of the two initial sockets close()
    Why is this happening? Is this correct?
    I implemented it with J2SE 1.3.1 in a windows NT 4 workstation machine.
    Is this an Operating System problem? A TCP/IP problem? Is the problem in the java socket implementation? Is there any flaw in my code?
    Thank you all in advance,
    Filipe Fedalto

    Hi, Chuck
    It could also be the case.
    Actually, I am implementing a proxy server. All the major work is done and were it not this accept() problem it would be functioning very well.
    The server is running in my machine and I am testing it by issuing 4 simultaneous HTTP requests from Internet Explorer 5.5 from my own machine itself. So, you see, this could be the problem, according to what you've just said.
    I try to open the 4 browser connections simultaneously, but the servers' accept() method only seems to receive 2 of them at a time.
    What do you think about it?
    Just in case, I will try and test it using Netscape. Let's see if the number of simultaneous connections change...
    Notwithstanding, why do the browsers limit the number of concurrent connections? I might think that this is because it is better to open a single page or two faster than trying to open 5 or 6 pages slowly... is this the point?
    Thank you very much!
    Filipe Fedalto

  • Socket implementation

    Hi
    I have a class that extends Socket. How can I instruct my JRE to use this Socket implementation than the default one? I want something that doesn't affect the applications that use the Sockets.

    I have a class that extends Socket. How can I
    instruct my JRE to use this Socket implementation
    than the default one? I want something that doesn't
    affect the applications that use the Sockets.I question the need for this also.
    However see the setSocketImplFactory() method.

  • NIO Socket implementation - delay between select and get data from socket

    Hi all,
    I have implemented a internal CallAPI for RPC over a socket connection. It works fine but if there are more than five clients and some load I have the phenomena that the READ selector returns a SelectorKey but I did not get any data from the socket.
    My implementation is based on NIO has following components:
    + Accept-Thread
    Thread handles new clients.
    + Read-Thread
    Thread handles the data from the socket for the registered client. Each request is handled in an own Process-Thread. A Thread-Pool implementation is used for processing.
    + Process-Thread
    The Process-Thread reads the data from the socket and starts the processing of the logical request.
    In my tests I get the notification of data at the socket. The Process-Thread want to read the data for the socket, but no data are available. In some situations if have to read about 20 times and more to get the data. Between each read attempt I have inserted a sleep in the Process-Thread if no data was available. This have improved the problem, but it already exists. I tested the problem with several systems and jvm's but it seams that it is independent from the system.
    What can I to do improve the situation?
    I already include the read implementation from the grizzly-Framework. But it doesn't improve the situation.
    Socket - Init
         protected void openSocket( String host, int port ) throws IOException
              serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking( false );
              serverSocket = serverChannel.socket();
              serverSocket.setReuseAddress( true );
              this.serverhost = host;
              this.serverport = port;
              this.srvAcceptSelector = Selector.open();
              this.srvReadSelector = Selector.open();
              InetSocketAddress isa = null;
              if ( serverhost != null )
                   isa = new InetSocketAddress( this.serverhost, this.serverport );
              else
                   isa = new InetSocketAddress( this.serverport );
              serverSocket.bind( isa, 50 );
              serverChannel.register( this.srvAcceptSelector, SelectionKey.OP_ACCEPT );
         }New Client � Init
         // New Client
         if ( key.isAcceptable())
              keyCountConnect++;
              ServerSocketChannel actChannel =
                   (ServerSocketChannel) key.channel();
              // Socket akteptieren
              SocketChannel actSocket = actChannel.accept();
              if ( actSocket != null )
                   actSocket.finishConnect();
                   actSocket.configureBlocking( false );
                   actSocket.socket().setTcpNoDelay( true );
                   this.registerSocketList.add( actSocket );
                   this.srvReadSelector.wakeup();
         }Read Data from Socket
        protected int readDatafromSocket( ByteArrayOutputStream socketdata )
             throws IOException
             int readedChars = 0;
            int count = -1;
            Selector readSelector = null;
            SelectionKey tmpKey = null;
            if ( sc.isOpen())
                  ByteBuffer inputbuffer = null;
                 try
                      inputbuffer = bufferpool.getBuffer();
                      while (( count = sc.read( inputbuffer )) > 0 )
                           readedChars += count;
                          inputbuffer.flip();
                           byte[] tmparray=new byte[inputbuffer.remaining()];
                           inputbuffer.get( tmparray );
                           socketdata.write( tmparray );
                          inputbuffer.clear();
                      if ( count < 0 )
                           this.closeSocket();
                           if( readedChars == 0 )
                                readedChars = -1;
                           if ( log.isDebug())
                                  log.debug( "Socket is closed! " );
                      else if ( readedChars == 0 )
                           if ( log.isDebug())
                                  log.debug( "Reread with TmpSelector" );
                           // Glassfish/Grizzly-Implementation
                         readSelector = SelectorFactory.getSelector();
                         if ( readSelector == null )
                              return 0;
                          count = 1;
                          tmpKey = this.sc.register( readSelector, SelectionKey.OP_READ );
                         tmpKey.interestOps(
                              tmpKey.interestOps() | SelectionKey.OP_READ );
                         int code = readSelector.select( 500 );
                         tmpKey.interestOps(
                             tmpKey.interestOps() & ( ~SelectionKey.OP_READ ));
                         if ( code == 0 )
                             return 0;
                             // Return on the main Selector and try again.
                           while (( count = sc.read( inputbuffer )) > 0 )
                                readedChars += count;
                               inputbuffer.flip();
                                byte[] tmparray=new byte[inputbuffer.remaining()];
                                inputbuffer.get( tmparray );
                                socketdata.write( tmparray );
                               inputbuffer.clear();
                           if ( count < 0 )
                                this.closeSocket();
                                if( readedChars == 0 )
                                     readedChars =-1;
                           else if ( count == 0 )
                                  // No data
                 finally
                      if ( inputbuffer != null )
                           bufferpool.releaseBuffer( inputbuffer );
                           inputbuffer = null;
                      // Glassfish-Implementierung
                    if ( tmpKey != null )
                        tmpKey.cancel();
                    if ( readSelector != null)
                        // Bug 6403933
                         try
                            readSelector.selectNow();
                         catch (IOException ex)
                        SelectorFactory.returnSelector( readSelector );
            return readedChars;
        }Thanks for your time.

    I've commented on that blog before. It is rubbish:
    - what does 'overloading the main Selector' actually mean? if anything?
    - 'Although this not clearly stated inside the NIO API documentation': The API documentation doesn't say anything about which Selector you should register channels with. Why would it? Register it with any Selector you like ...
    - 'the cost of maintaining multiple Selectors can reduce scalability instead of improving it' Exactly. So what is the point again?
    - 'wrapping a ByteBuffer inside a ByteBufferInputStream:' Code is rubbish and redundant. java.nio.channels.Channels has methods for this.
    There is no a priori advantage to using multiple Selectors and threads unless you have multiple CPUs. And even then not much, as non-blocking reads and writes don't consume significant amounts of CPU. It's the processing of the data once you've got it that takes the CPU, and that should be done in a separate thread.
    So I would re-evaluate your strategy. I suspect you're getting the channel registered with more than one Selector at a time. Implement it the simple way first then see if you really have a problem with 'overloading the main Selector' ...

  • J2EE Connection Architecture - Client Socket implementation

    I have a requirement to use a Socket connect to a quote vendor and ask for a quote(s) then receieve the response. The request looks like SQL except for the stream level info like lengths etc.. I wonder if anyone has implemented something like this as a JAC (J2C) application and could provide a sample? In a managed JAC environment the Application Server would provide a pooling mechanism; thus, the connection would remain active and be able to service many requests..

    This may be a forum bug, but your post has appeared in the JBI forum, not the Connector forum. I suspect your chances of getting an answer to your query would be better in the appropriate Connector forum.

  • Overriding default implementation of TrustManager class

    The IBM JSSE provider's default TrustManager implementation doesn't allow anonymous cipher suites.
    http://www-128.ibm.com/developerworks/library/j-ibmsecurity.html?ca=drs-j4304
    I want to override it, so that anonymous cipher suites can be allowed.
    Does anyone know how to do this.
    Thanks,
    JVR

    A custom renderer needs to extend the abstract class
    javax.faces.Renderer and supply five methods. Four of
    them (encodeXXX and decode) make perfect sense, but
    the fifth one (getClientId) isn't in the same league.
    Wouldn't most renderers want to use the standard
    mechanism?
    Thanks for the feedback.
    This issue is already on the Expert Group's radar as an issue to be addressed. I would not be at all surprised if we end up with a standard base class for Renderers that includes a default implementation for things like getClientId().
    Craig

  • Custom Socket Implementation

    How can we Implement Custom Socket Connection in a JDBC Connection to Sybase SQL Anywhere...??

    For what purpose do you intend to use such a feature?
    If you are asking this because you are looking at the JConnect options for SSL based encryption then it should be noted that those are not supported by SAP SQL Anywhere currently.  There is a JDBC driver specific to SQL Anywhere that can be used for strongly (TLS) encrypted communication client/server.

  • Socket communication failure between Java applet and C++ application

    I have a java applet that connects to a C++ application via Java's ServerSocket and Socket objects. THe C++ application is using the Winsock 2 API. The applet and application are running on an NT workstation (SP 6) and using IE (5.5) For a very simple C++ test applications the communictions work fine. Once more code gets added to the C++ application the portion of the socket that C++ listens to seems to close. Upon performing a recv call the return value is a zero. Microsoft insists this is a sign the Java side has shut down the socket. The Java applet can still receive messages from the C++ app but C++ cannot receive responses from the Java side. Java throws no exceptions and an explicit check of the socket shows no errors. Again, what puzzles me is that it works for simple C++ applications. Are there any known conflicts between Java and C++ in this regard?
    I have inlcuded the basic java code segments below.
    / run Method.
      * This method is called by the Thread.start() method. This
      * method is required for the implementation of the Runnable interface
      * This method sets up the server side socket communication and
      * contiuously loops looking for requests from a external
      * socket.
      * @author Chris Duke
      public void run(){
         // create socket connections
         boolean success = false;
         try {
             cServerSocket = new ServerSocket(cPortID);
             System.out.println("Waiting for client to connect...");
             cClientSocket = cServerSocket.accept();
             System.out.println("Client connected");
             // Create a stream to read from the client
             cInStream = new BufferedReader(new InputStreamReader(
               cClientSocket.getInputStream()));
             // Create a stream to write to the client       
             cOutStream = new PrintWriter(
               cClientSocket.getOutputStream(), true);
             success = true;
         }catch (IOException e) {
             System.out.println("CommSocket:Run - Socket Exception(1) " + e);
             success = false;
         // if the socket was successfully created, keep the thread running
         while (success){
             try{
                // check socket to see if it is still available for reading
                if (cInStream != null && cInStream.ready()){
                    // check for an incoming message
                    String message = ReceiveMessage();
                    // Send message to listeners
                    Event(message);
                if (cInStream == null){
                    success = false;
                    System.out.println("CommSocket:Run - shutdown");
             }catch (IOException e){
                System.out.println("CommSocket:Run - Socket not ready exception");
                break;
    // SendMessage method -
      *  Sends a text message to a connected listener through port specified by portID
      * @author Chris Duke
      * @param  String message - This will be the message sent out through the server
      * socket's port specified by portID.
       public void SendMessage(String message){
          cOutStream.println(message);
          if (cOutStream.checkError() == true)
            System.out.println("SendMessage : Flush = Error");
          else{
            System.out.println("SendMessage : Flush - No Error");
       }

    a very simple C++ test applications the communictions work fine. Once more code gets added to the C++ application the portion of the socket that C++ listens to seems to close.
    This quite strongly implicates the extra code in the C++ App. The firstly thing I would try would be telnet. Try connecting to both versions of the C++ Application and manually reproducing a proper exchange.
    a recv call the return value is a zero. Microsoft insists this is a sign the Java side has shut down the socket.
    A correct implementation of recv should return the number of bytes received, or -1 for an error. A zero return indicates no bytes received not a socket closed/error. This sounds like FUD to me.
    Are there any known conflicts between Java and C++ in this regard?
    I can see no obvious faults, though the code is incomplete, I don't think it's an sockets implementation issue, at either end, it sounds more likely to be a protocol/handshaking bug in the C++ App.

  • Using sockets with java from PL/SQL in Oracle 8.1.7 DBA

    Hey all,
    I've been struggling for a couple of weeks now with a problem. I wrote a framework around a toolkit which makes socket connections to another server. I am attempting to use the framework from within a PL/SQL script, which is calling the framework class files which have been loaded into Oracle 8.1.7 database. The problem seems to be if I grant all permissions, or socket permissions for all hosts/ports, or even the ones I know about are being used, I get a hang when trying to connect. The funny thing is, using the toolkit, if I invoke their classes directly within code written from Oracle's code editor, it will work.
    I suspect there is
    a) Some hidden permission issue
    b) A bug in the sockets implementation Oracle is using for their JVM.
    Can anyone offer insight to this problem?
    Thanks,
    Dave Blake
    [email protected]

    Hello,
    I'm trying to investigate the same thing.
    I want to make a soap-client with PL/SQL with 8i 8.1.6.0.0
    Did you succeed some additional information ??
    I tried to run the following example:
    http://www.oracle.com/technology/tech/webservices/htdocs/samples/dbwebservice/DBWebServices_PLSQL.html
    but it only works with 9i.
    With 8i the errors encountered were : XMLTYPE undefined
    Perhaps if we find the definition of XMLTYPE and we process it to 8i we'll be able to run the example ??
    thank's

  • Send html page (with images) using sockets

    I am trying to implement http and am coding this using sockets. So it is a simple client-server set up where the browser queries my server for a webpage and it should be shown. The html itself is fine, but I can't get any of the images to show up! All of my messages give me a status "200 OK" for the images, so I cant understand what my problem is!
    Also, is the status and header lines supposed to be shown in the browser? I didnt think so but it keeps showing up when I query a webpage.
    Please help!
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class WebServer
         public static void main(String argv[]) throws Exception
              // Set the port number.
              int port = 8888;
              // Establish the listen socket.
              ServerSocket ssocket = new ServerSocket(port);
              // Establish client socket
              Socket csocket = null;
              // Process HTTP service requests in an infinite loop.
              while (true)
                   // Listen for a TCP connection request.
                   // (note: this blocks until connection is made)
                   csocket = ssocket.accept();     
                   // Construct an object to process the HTTP request message.
                   HttpRequest request = new HttpRequest(csocket);
                   // Create a new thread to process the request.
                   Thread thread = new Thread(request);
                   // Start the thread.
                   thread.start();
    final class HttpRequest implements Runnable
         final static String CRLF = "\r\n";
         Socket socket;
         // Constructor
         public HttpRequest(Socket socket) throws Exception
              this.socket = socket;
         // Implement the run() method of the Runnable interface.
         public void run()
              try
                   processRequest();
              catch (Exception e)
                   System.out.println(e);
         private static void sendBytes(FileInputStream fis, OutputStream os)
         throws Exception
            // Construct a 1K buffer to hold bytes on their way to the socket.
            byte[] buffer = new byte[1024];
            int bytes = 0;
           // Copy requested file into the socket's output stream.
           while((bytes = fis.read(buffer)) != -1 ) {
              os.write(buffer, 0, bytes);
              os.flush();
         private static String contentType(String fileName)
              fileName = fileName.toLowerCase();
              if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
                   return "text/html";
              if(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") ) {
                   return "image/jpeg";
              if(fileName.endsWith(".gif")) {
                   return "image/gif";
              return "application/octet-stream";
         private void processRequest() throws Exception
              // Get a reference to the socket's input and output streams.
              InputStream is = socket.getInputStream();
              DataOutputStream os = new DataOutputStream(socket.getOutputStream());
              // Set up input stream filters.
              InputStreamReader ir = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(ir);
              // Get the request line of the HTTP request message.
              String requestLine = br.readLine();
              // Display the request line.
              System.out.println();
              System.out.println(requestLine);
              // Get and display the header lines.
              String headerLine = null;
              while ((headerLine = br.readLine()).length() != 0)
                   System.out.println(headerLine);
              // Extract the filename from the request line.
              StringTokenizer tokens = new StringTokenizer(requestLine);
              tokens.nextToken();  // skip over the method, which should be "GET"
              String fileName = tokens.nextToken();
              // Prepend a "." so that file request is within the current directory.
              fileName = "C:\\CSM\\Networking\\Project1" + fileName;
              // Open the requested file.
              FileInputStream fis = null;
              boolean fileExists = true;
              try {
                   fis = new FileInputStream(fileName);
              } catch (FileNotFoundException e) {
              fileExists = false;
              // Construct the response message.
              String statusLine = null;
              String contentTypeLine = null;
              String entityBody = null;
              if (fileExists) {
              statusLine = "200 OK" + CRLF;
              contentTypeLine = "Content-type: " +
                   contentType( fileName ) + CRLF
                   + "Content-length: " + fis.available() + CRLF;
              else {
              statusLine = "404 Not Found" + CRLF;
              contentTypeLine = "Content-type: text/html" + CRLF;
              entityBody = "<HTML>" +
                   "<HEAD><TITLE>Not Found</TITLE></HEAD>" +
                   "<BODY>Not Found</BODY></HTML>";
              // Send the status line.
              os.writeBytes(statusLine);
              System.out.println(statusLine);
              // Send the content type line.
              os.writeBytes(contentTypeLine);
              System.out.println(contentTypeLine);
              // Send a blank line to indicate the end of the header lines.
              os.writeBytes(CRLF);
              // Send the entity body.
              if (fileExists)     
                   sendBytes(fis, os);
                   fis.close();
              // file does not exist
                     else
                   os.writeBytes(entityBody);
              // Close streams and socket.
              os.flush();
              os.close();
              br.close();
              socket.close();
    }

    ok. i figured it out. STUPID mistake. i forgot to include "HTTP/1.1" in my status line!!!

  • JTree custom implementation

    Hi All,
    I have application, which eats all the memory, when I load big structure in JTree.
    So I have modified following function
    DefaultTreeMutableNode {
    public void insert(MutableTreeNode newChild, int childIndex) {
              children = new Vector();
    As follow:
    DefaultTreeMutableNode {
    public void insert(MutableTreeNode newChild, int childIndex) {
              children = new ArrayList(1);
    As my jTree usually has single nodes. And Default constructor of Vector() creates array of 10 child nodes, for each node.
    But still it uses the same memory ???
    Is there any way to reduce memory usage by JTree nodes, so it can handle big strucutre.
    Is there any custom implemenation is avaliable.
    Thank you for your time.
    Avin Patel

    I guess ur application is a perfect candidate for a MVC implementation. In the tree there are 2 ways to do that. u can either write ur own TreeModel or u can write ur ur own TreeNode. I can help u write either of the two.
    I can give u working examples from my application in each of them. U can also make the creation of the child nodes dyanamic and on a "on-demand-basis", by creating them only on the expansion of the parent nodes, as mentioned above.
    The first way to do that is to override the implementation of the DefaultTreeModel class:
    Plz find below an implementaion of the same:
    public class GrpModuleTreeModel extends DefaultTreeModel
         TerminationPointsModel mModel = null;
         TreePanel mTreePanel;
         GrpModuleTreeModel(TerminationPointsModel model,TreePanel treePanel)
              super(null);
              mModel = model;
              mTreePanel=treePanel;
         public int getIndexOfChild(Object parent, Object child)
              if (parent.equals(mTreePanel.mParent.getParentFrame().getNEName()))
                   ArrayList rackList = new ArrayList(mModel.getRacks());
                   return rackList.indexOf(child);
              if (parent instanceof Rack)
    //               return mModel.getSubracks(parent).size();
                   ArrayList subrackList = new ArrayList(((Rack)parent).getSubracks());
                   return subrackList.indexOf(child);
              if (parent instanceof Subrack)
    //               return mModel.getModules(parent).size();
                   ArrayList moduleList = new ArrayList(((Subrack)parent).getModules());
                   return moduleList.indexOf(child);
              if (parent instanceof Module)
    //               return this.mModel.getTerminationPoints(parent).size();
                   ArrayList tpList = new ArrayList(((Module)parent).getTerminationPoints());
                   return tpList.indexOf(child);
              if (parent instanceof TerminationPointA)
    //               return this.mModel.getTerminationPoints(parent).size();
                   ArrayList tpList = new ArrayList(((TerminationPointA)parent).getTerminationPointList());
                   return tpList.indexOf(child);
              return -1;
         public boolean isLeaf(Object node)
              if (node instanceof TerminationPointA )
                   if (node instanceof NonConfigurableCrossConnection ) return true;
                   return (((TerminationPointA)node).getTerminationPointList()==null)? true: false;
    //               java.util.ArrayList list=((TerminationPointA)node).getTerminationPointList();
    //               System.out.println("Type====== "+((TerminationPointA)node).getTerminationPointType()+","+list);
    //               if (list!=null)
    //                    System.out.println("Number of nodes ========= "+list.size());
    //                    for (int i = 0; i < list.size(); i++)
    //                         System.out.println(list.get(i).getClass().getName());
    //               return true;
              if (node instanceof Rack)
                   return (((Rack)node).getSubracks()==null)? true: false;
              if (node instanceof Subrack)
                   return (((Subrack)node).getModules()==null)? true: false;
              if (node instanceof Module)
                   return (((Module)node).getTerminationPoints()==null)? true: false;
              return false;
         public Object getChild(Object parent, int index)
              if (parent.equals(mTreePanel.mParent.getParentFrame().getNEName()))
                   ArrayList rackList = new ArrayList(mModel.getRacks());
                   return (rackList!=null)? rackList.get(index):null;
              if (parent instanceof Rack)
    //               return mModel.getSubracks(parent).size();
                   ArrayList subrackList = new ArrayList(((Rack)parent).getSubracks());
                   return (subrackList!=null? subrackList.get(index):null);
              if (parent instanceof Subrack)
    //               return mModel.getModules(parent).size();
                   ArrayList moduleList = new ArrayList(((Subrack)parent).getModules());
                   return moduleList!=null? moduleList.get(index):null;
              if (parent instanceof Module)
    //               return this.mModel.getTerminationPoints(parent).size();
                   ArrayList tpList = new ArrayList(((Module)parent).getTerminationPoints());
                   return tpList!=null? tpList.get(index):null;
              if (parent instanceof TerminationPointA)
    //               return this.mModel.getTerminationPoints(parent).size();
                   ArrayList tpList = new ArrayList(((TerminationPointA)parent).getTerminationPointList());
                   return tpList.get(index);
              return null;
         public int getChildCount(Object parent)
              if (parent ==null)
                   return -1;
              if (parent.equals(mTreePanel.mParent.getParentFrame().getNEName()))
                   return mModel.getRacks()!=null ? mModel.getRacks().size() : -1;
              if (parent instanceof Rack)
    //               return mModel.getSubracks(parent).size();
                   return ((Rack)parent).getSubracks()!=null ? ((Rack)parent).getSubracks().size() : -1;
              if (parent instanceof Subrack)
    //               return mModel.getModules(parent).size();
                   return ((Subrack)parent).getModules()!= null? ((Subrack)parent).getModules().size() : -1;
              if (parent instanceof Module)
    //               return this.mModel.getTerminationPoints(parent).size();
                   return ((Module)parent).getTerminationPoints() != null ? ((Module)parent).getTerminationPoints().size(): -1;
              if (parent instanceof TerminationPointA)
    //               return this.mModel.getTerminationPoints(parent).size();
                   return ((TerminationPointA)parent).getTerminationPointList()!= null ? ((TerminationPointA)parent).getTerminationPointList().size(): -1;
              return -1;
         public Object getRoot()
              return mTreePanel.mParent.getParentFrame().getNEName();
    IF this does'nt suffice then I can tell u another way by which u can create ur own TreeNode.
    BR
    Mohit

  • IOException: Connection reset by peer: JVM_recv in socket input stream read

    hi
    I encountered a problem : a program throw out an exception:java.io.IOException: Io exception:
    Connection reset by peer: JVM_recv in socket input stream read.
    I tried my best to resolve it ,but unfortunately,i didn't know what caused the exception.
    the following is my application environment:
    I have two PC(Win2000os),one is a server which installed oracle9.2.0.2 and jdeveloper9.0.3,the another is a
    client which only intalled jdeveloper9.0.3.Two days ago,i performed a web application on my client with
    jdeveloper,and it includes some JSP and a javabean files.JSP Page finished uploading client xml file to a
    folder on server and the javabean finished loading the xml file into a xmltype column.I can make sure the
    connection is established and the javabean is OK,beacause my some jsp page can successfully use
    <jsp:usebean> tag and use the javabean's some other public interfaces,except the interface that finishs
    loading the xml file into a xmltype(clob) column.
    Then i do many tests!I changed the javabean to a java class incluse a main method beacause it is easy to
    debug.Finally i found the following code caused the exception:
    public CLOB writetoClob( CLOB clob, InputStream is )throws SQLException, IOException {
    InputStreamReader reader = new InputStreamReader( is );
    Writer writer = clob.getCharacterOutputStream( );
    char[] buffer = new char[clob.getChunkSize(  )];
    int charsRead;
    for ( charsRead = reader.read( buffer ); charsRead > -1;charsRead = reader.read( buffer ) ) {
    writer.write( buffer, 0, charsRead );
    writer.close();
    return clob;
    when it runs to writer.close(),the exception is caused!
    Then i copy the java class to the server,it runs ok!
    That is to say ,the same code,the different result!
    But when i run my web application on server with jdeveloper Embedded OC4J Server and a jsp page loaded javabean
    and run to mentioned code ,the same exception occured!
    I checked the application log in event viewer,the descriptions was:
    The data buffer created for the "AppleTalk" service in the "C:\WINNT\system32\atkctrs.dll" library is not
    aligned on an 8-byte boundary. This may cause problems for applications that are trying to read the
    performance data buffer. Contact the manufacturer of this library or service to have this problem corrected or
    to get a newer version of this library.
    I search some some resolution about this exception with web and someone sayed :
    This basically means that a network error occurred while the client was receiving data from the server. But
    what is really happening is that the server actually accepts the connection, processes the request, and sends a
    reply to the client. However, when the server closes the socket, the client believes that the connection has
    been terminated abnormally because the socket implementation sends a TCP reset segment telling the client to
    throw away the data and report an error.
    Sometimes, this problem is caused by not properly closing the input/output streams and the socket connection.
    Make sure you close the input/output streams and socket connection properly. If everything is closed properly,
    however, and the problem persists, you can work around it by adding Thread.sleep(1000) before closing the
    streams and the socket. This technique, however, is not reliable and may not work on all systems.
    In general,the following information is conclution:
    Web application runs error both on client and on server.
    If it was changed to a client java class,it only run ok on server!
    i have done anything that i can do now,i feel depressed very much!
    how can i resolve the problem!
    Any a little help will be appreciated!
    regards!
    Thanks
    Jiawei ZHAO

    How can i solve the problem.
    Thanks in advance!
    Jiawei Zhao

  • IP address lookup and Sockets

    Hi All,
    I have created a Socket using java.net.Socket(String host, int port) by passing the required host, port parameters.
    The host string is specified in the form of xxx.xxx.xxx.xxx, even though the Java
    program(client) is running on the same machine where the server socket is listening, (IP address is not specified as 'loopback address' localhost/127.0.0.1).
    Below are my queries for the above mentioned scenario.
    1) When the data is sent/received to/from the Socket, will the data
    travel across the network and return back to the same machine or it will be a direct send/receive within the same machine?
    2) Is the loopback address 'localhost/127.0.0.1' used internally by the underlying socket implementation without performing lookup of the IP address in the network?
    3) Does this behavior varies/depends on the underlying OS or the network
    protocol/configuration?
    Thanks in advance,
    Sreenivasulu

    1: it depends upon the mechanism through which the sockets between client and server are established (in ur case the client and the server is the same machine). When u specify the localhost/127.0.0.1, port where the server is listening, then i think the request should go out to the network and the OS will handle it by it self and manage the connection then the data will not travel through the whole network. Other wise when u specify that the server is listening on 192.168.0.0:9000 then the OS will go to look up server /dns it will tell him where this system in laying on the network is it in he same netwrok or out side this network and then a connection is established now the data will travel through the network, cause it will look for the system 192.168.0.0.
    2: when u will use the loopback for specific IP then the direct connection is made to the system.
    3: i can say nothing about this issus how the other OS are behaving cause i had mostly worked on Windows NT/2000
    i am in the learning process. If i am wrong plz correct me. And i am also very much interested for the replies from other users...
    thanx

  • Java 1.3.1 and Detecting Socket Closure (A Popular Question, I Know)

    Hi, all. I've been skimming the web looking at various commentary on how it is impossible to detect whether or not a Socket has closed without calling the read of Socket.getInputStream() or the write of Socket.getOutputStream(). I wrote a networking package some months ago that would spawn one Thread for each Socket so I could spare the Threads to block on the I/O, thus following this suggestion. I also understand that Java 1.4 contains various elements of the java.nio package that are supposed to take care of nonblocking I/O. I think, however, that this is entirely possible with Sockets in Java 1.3.1.
    I wrote a program that calls Socket.setSoTimeout(), setting the timeout of the socket to 1 millisecond. I then have one Thread looking at a series of open Sockets. The Thread calls the read method on each of the Sockets' InputStream objects and does one of three things based upon the result:
    If the result is a successful read, the data is handled as is appropriate.
    If the result is a -1, the Socket has been closed and is formally shut down on this side.
    If the result is an InterruptedIOException, the Socket is open but has no available data.
    The Socket is then ignored until the next pass.
    I've tested this idea on an Athalon XP 2100+ and not seen a significant use of processing power.
    Therefore, my question is as follows: what's wrong with this idea? We've looked at it and it seems to be an appropriate solution to the problem. Yet, I've seen little mention of this way to work around blocking Socket I/O in Java 1.3.1. It seems appropriate and certainly cuts back on Thread overhead... but does anyone see a catch?
    Thanks! Best of luck!

    This approach to multiplexing seems to not work under the 1.3.1 release for Windows. I have found I still get a -1 on my input stream read, instead of the InterruptedIOException. It's pretty frustrating.
    The axact same code appears to work fine on Linux . So this may be dependent on the native code layer for the sockets implementation, or we may be encountering a bug in our or Sun's code. I haven't found documentation of the expected behaviour of the SocketInputStream (the actual class returned by Socket.getInputStream) or the socket implementation in general for each platform.
    Note that in general, your approach is not really scalable for the kind of situations the Non-blocking IO package was introduced for. Your approach means that 500 sockets will have a 1/2 second intrinsic delay. You would have to start thread-pooling, etc. You can see why something like an internet audio streaming application would benefit from lower level support in the java libraries.
    Neil

Maybe you are looking for

  • Moving from ABAP to ABAP oo

    We are currently running on a 4.0 system, but are preparing for an upgrade to ERP '05. I have looked at OO and have collected a few questions. 1.     A simple ABAP report today in 4.0 looks like this : Selection-screen Start-of-selection Perform read

  • Create purchase order form idoc

    Hi everyone, I would be very grateful if someone could explain me whether it is possible to generate a purchase order directly from an incoming ORDERS05 IDOC and specially how to do it. I am receiving an ORDERS05 IDOC from an external system but I do

  • Firefox Keeps trying to load pages

    Hi I have been having problems with my firefox! its ok for the first 5 mins but then every website i have open in my tabs keeps hanging and trying to load and is still trying to load after a few hours (I did time it to see if they did load up) the si

  • Real Sum aggregation, when using Constant selection

    Hi, all! I have to infoproviders: Cube1 MATERIAL PLANT CALDAY FLAG KYF1 Flag - may be considered as attribute of MATERIAL x PLANT x CALDAY Cube2 MATERIAL PLANT CALDAY KYF2 I need to analyze next slice: FLAG MATERIAL KYF1 KYF2 Thus, I get next results

  • Map download speed on N95

    I am installing 76 megs of maps with the Nokia map downloader and it is taking for ever, in fact just 14% in 3 hours...is this normal ?? The phone is offline and connected by the USB cable with "mass storage selected" to my XP PC