HTTPS Tunneling in OC4J

Has anyone got HTTPS tunneling working in OC4J when there is a "HTTP 1.1 proxy server" (to get through firewall) that requires Basic authentication between the client and OC4J? I can get this working fine with HTTP, but I need HTTPS. I'm using oc4j version 1.0.2.2.1. When I tried to use https:ormi://host:443/appname without a http proxy server between the client and the server things work great. When I have a http proxy server, I get a similar exception:
javax.naming.NamingException: Error reading application-client descriptor: Error communicating with server: Lookup error: java.lang.NegativeArraySizeException; nested exception is:
java.lang.NegativeArraySizeException; nested exception is:
javax.naming.NamingException: Lookup error: java.lang.NegativeArraySizeException; nested exception is:
java.lang.NegativeArraySizeException
at com.evermind.server.ApplicationClientInitialContextFactory.getInitialContext(ApplicationClientInitialContextFactory.java:184)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:665)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246)
at javax.naming.InitialContext.init(InitialContext.java:222)
at javax.naming.InitialContext.<init>(InitialContext.java:198)
at com.platts.dmz.DMZTestingClient.<init>(DMZTestingClient.java:48)
at com.platts.dmz.DMZTestingClient.main(DMZTestingClient.java:374)
Thanks
Frank

What is proxying the request to OC4J?
Can you tell what proxy server are you using ?
regards
Debu Panda
Oracle

Similar Messages

  • HTTPS mode for OC4J - Very Urgent

    Hi,
    I am trying to implement HTTPS mode with OC4J for our internal application. The Server Configuration and how I tried to implement is detailed below.
    The Server Configuration :
    Operating System     :     Linux 7.1
    Java Development Kit     :     j2sdk1.3 with j2sse 1.0.3
    Web Server          :     Oracle9iAS Containers for J2EE (OC4J) OC4J build# 020712.1645.
    The command for generating the CSR (for test certificate from Entrust)
    1. keytool -genkey -keyalg "RSA" -keystore keystore -storepass 123456 -keysize 512
    2. keytool -certreq -keyalg "RSA" -file gisl-dev -keystore keystore
    I had generated a CSR from the server and submitted the CSR online for a test certificate. On submission freecert.entrust.com had issued the web server certificate and the CA certificate successfully.
    After this I tryed to import the Web Server Certificate with this command:
    3. keytool -keystore -keyalg "RSA" -import -trustcacerts -file gisl-dev.cer
    I am getting an error:
    keytool error: java.security.cert.CertificateException: Unsupported encoding
    Is there anyway to come out of this problem, I think I can use Apache Server and tunnel the request for OC4J through Apache. But the sad thing is that I don't know how do it.
    Please help me out to solve this problem

    1/ try to add a LF to your reply certicate. (there is a bug on keytool import)
    2/ Also you need to check if your CA provider certicate is known on cacerts file. If not you need to import it.
    Hope this help

  • Http tunnelling not working with virtual host

    Hi,
    We have recently migrated our application from OC4J server to the Weblogic 11g server. There is one EJB client module which connects using t3 protocol. We are trying to use Http Tunneling for it. The server setup consists of two machines (machine1.global.com and machine2.global.com) in clustered mode. A virtual host cbs.global.com is configured to load balance across the above 2 two machine. Also Apache HTTP Server plugin is used for handling the web tier.
    For enabling tunneling, we have checked the 'Enable HTTP Tunneling' check box in the server. Also in the Httpd.conf file, we have added a block for
    <Location /HTTPClnt>
    SetHandler weblogic-handler
    </Location>
    If we give the initial context url as http://machine1.global.com:7005 or http://machine2.global.com, then it is working fine. But when we give the virtual host names - http://cbs.global.com or http://cbs.global.com:7005, it is not working. This application needs to be accessed outside the company network, so we cannot directly give the machine names and have to make it work using virtual host.
    Please advise whether any other settings need to be done for enabling the tunnelling for virtual hosts.
    Highly appreciate your help in this regard.
    Best Regards,
    Jaison
    Edited by: user13152776 on Aug 29, 2011 7:00 PM

    Thanks Peter for the reply.
    We are having multiple managed servers configured to multiple ports - 7003, 7005, 7007, etc. Please find below the mod_wl_ohs.conf file
    # NOTE : This is a template to configure mod_weblogic.
    LoadModule weblogic_module "${ORACLE_HOME}/ohs/modules/mod_wl_ohs.so"
    # This empty block is needed to save mod_wl related configuration from EM to this file when changes are made at the Base Virtual Host Level
    <IfModule weblogic_module>
    # WebLogicHost <WEBLOGIC_HOST>
    # WebLogicPort <WEBLOGIC_PORT>
    # Debug ON
    # WLLogFile /app/oracle/middleware/user_projects/domains/base_domain/ClusterLogs/weblogic.log
    # MatchExpression *.jsp
    # Dev Cluster Configuration - Port 7003
    <Location />
    SetHandler weblogic-handler
    WebLogicCluster nooslux050d.gl.2wglobal.com:7003,nooslux051d.gl.2wglobal.com:7003
    Debug ON
    WLLogFile /app/oracle/middleware/user_projects/domains/base_domain/ClusterLogs/devcluster.log
    MatchExpression *
    </Location>
    <Location /intApp>
    SetHandler weblogic-handler
    WebLogicCluster nooslux050d.gl.2wglobal.com:7003,nooslux051d.gl.2wglobal.com:7003
    Debug ON
    WLLogFile /app/oracle/middleware/user_projects/domains/base_domain/ClusterLogs/devcluster.log
    MatchExpression *
    </Location>
    # Ocean Cluster Configuration - Port 7005
    <Location /CQS>
    SetHandler weblogic-handler
    WebLogicCluster nooslux050d.gl.2wglobal.com:7005,nooslux051d.gl.2wglobal.com:7005
    Debug ON
    WLLogFile /app/oracle/middleware/user_projects/domains/base_domain/ClusterLogs/oceancluster.log
    MatchExpression *
    </Location>
    # Websi Cluster Configuration - Port 7007
    <Location /si>
    SetHandler weblogic-handler
    WebLogicCluster nooslux050d.gl.2wglobal.com:7007,nooslux051d.gl.2wglobal.com:7007
    Debug ON
    WLLogFile /app/oracle/middleware/user_projects/domains/base_domain/ClusterLogs/websicluster.log
    MatchExpression *
    </Location>
    </IfModule>
    Best Regards,
    Jaison

  • Http tunneling (t3 over http) doesn't work!!  (examples too)

    Hi,
    I'm trying to get http tunneling (t3 connection over http protocol) to work. I
    ran some examples included with Weblogic that try establishing that connection
    (PingTest, HelloApplet, SimpleT3Client), as well as my own test program, and they
    all give an error similar to this :
    Couldn't get a reference to server. Exception :
    javax.naming.CommunicationException. Root exception is java.net.ConnectException:
    No server found at HTTP://<IP>:<port>
    at weblogic.rjvm.RJVMFinder.findOrCreate(RJVMFinder.java:161) at weblogic.rjvm.ServerURL.findOrCreateRJVM(ServerURL.java:200)
    at weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialContextFactoryDelegate.java,
    Compiled Code) at weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialContextFactoryDelegate.java:148)
    at weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:123)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:671) at
    javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:242) at javax.naming.InitialContext.init(InitialContext.java:218)
    at javax.naming.InitialContext.<init>(InitialContext.java:194)
    (I replaced the actual Ip and port with <IP> and <port>).
    Now, the server is started and working at that ip and port - it services web http
    requests correctly, etc. Regular T3 connection (not over http) also works with
    it.
    Does anyone know the reason for this problem and/or how to fix it?
    Thanks, Leonid Portnoy

    It appears that one has to use the "Java Plugin" for this mode to work. The
    question is does the version of plugin need to be "in sync" with the JVM
    version on the server. ?.
    /rk
    "Adomas Svirskas" <[email protected]> wrote in message
    news:[email protected]...
    >
    It seems that the solution is to have these two lines in the
    properties file:
    weblogic.httpd.enable=true
    weblogic.httpd.tunnelingenabled=true
    Now it works.
    Thanks,
    Adomas
    "Adomas Svirskas" <[email protected]> wrote:
    Hi Leonid,
    Have you found a solution for this? I have these problems too.
    Thanks,
    Adomas
    "Leonid Portnoy" <[email protected]> wrote:
    Hi,
    I'm trying to get http tunneling (t3 connection over http protocol)to
    work. I
    ran some examples included with Weblogic that try establishing thatconnection
    (PingTest, HelloApplet, SimpleT3Client), as well as my own test program,
    and they
    all give an error similar to this :
    Couldn't get a reference to server. Exception :
    javax.naming.CommunicationException. Root exception is
    java.net.ConnectException:
    No server found at HTTP://<IP>:<port>
    at weblogic.rjvm.RJVMFinder.findOrCreate(RJVMFinder.java:161) atweblogic.rjvm.ServerURL.findOrCreateRJVM(ServerURL.java:200)
    atweblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialCon
    textFactoryDelegate.java,
    Compiled Code) atweblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialCon
    textFactoryDelegate.java:148)
    atweblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFact
    ory.java:123)
    atjavax.naming.spi.NamingManager.getInitialContext(NamingManager.java:671)
    at
    javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:242)
    at javax.naming.InitialContext.init(InitialContext.java:218)
    at javax.naming.InitialContext.<init>(InitialContext.java:194)
    (I replaced the actual Ip and port with <IP> and <port>).
    Now, the server is started and working at that ip and port - it services
    web http
    requests correctly, etc. Regular T3 connection (not over http) alsoworks
    with
    it.
    Does anyone know the reason for this problem and/or how to fix it?
    Thanks, Leonid Portnoy

  • Help needed in HTTP Tunneling - urgent

    Hi all,
    I urgently need a working code sample of a client which sends requests to a server that redirects the request to an RMI server via RMI servlet.
    Does any of you familiar of such a code sample?
    Thanks

    I'm sorry, but HTTP Tunneling is not working for me. I must have done something wrong.
    Let me describe my configuration:
    I have a server behind NAT router which connected to apache2 and tomcat 4.1 web servers. The apache2 and tomcat are not connected between them.
    I deployed war file on tomcat which contains the servlet for the HTTP Tunneling which its code is:
    public class RmiHttpTunnelerServlet extends HttpServlet
        public void init(ServletConfig config) throws ServletException
            super.init(config);
            System.out.println("Simplified RMI Servlet Handler loaded successfully.");
        public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
            try
                String queryString = req.getQueryString();
                String command, param;
                int delim = queryString.indexOf("=");
                if (delim == -1)
                    command = queryString;
                    param = "";
                else
                    command = queryString.substring(0, delim);
                    param = queryString.substring(delim + 1);
                if (command.equalsIgnoreCase("forward"))
                    try
                        ServletForwardCommand.execute(req, res, param);
                    catch (ServletClientException e)
                        returnClientError(res, "client error : " + e.getMessage( ));
                        e.printStackTrace();
                    catch (ServletServerException e)
                        returnServerError(res, "internal server error : " + e.getMessage());
                        e.printStackTrace();
                else
                    returnClientError(res, "invalid command: " + command);
            catch (Exception e)
                returnServerError(res, "internal error: " + e.getMessage());
                e.printStackTrace();
        public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
            returnClientError(res, "GET Operation not supported: Can only forward POST requests.");
        public void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
            returnClientError(res, "PUT Operation not supported: Can only forward POST requests.");
        public String getServletInfo()
            return "Simplified RMI Call Forwarding Servlet Servlet.<br>\n ";
        private static void returnClientError(HttpServletResponse res, String message) throws IOException
            res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                          "<HTML><HEAD><TITLE>Java RMI Client Error < / TITLE > < / HEAD > < BODY > " +
                          "<H1>Java RMI Client Error</H1>" + message + "</BODY></HTML>");
            System.err.println(HttpServletResponse.SC_BAD_REQUEST + "Java RMI Client Error" + message);
        private static void returnServerError(HttpServletResponse res,
                                              String message) throws IOException
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                          "<HTML><HEAD>< TITLE > Java RMI Server Error < / TITLE > < / HEAD > < BODY > " +
                          "<H1>Java RMI Server Error < / H1 > " + message + " < / BODY > < / HTML > ");
            System.err.println(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + "Java RMI Server Error : " + message);
        }There is also a utility class:
    public class ServletForwardCommand {
        public static void execute(HttpServletRequest request, HttpServletResponse response, String stringifiedPort)
            throws ServletClientException, ServletServerException, IOException {
            int port = convertStringToPort(stringifiedPort);
            Socket connectionToLocalServer = null;
            try {
                connectionToLocalServer = connectToLocalServer(port);
                forwardRequest(request, connectionToLocalServer);
                forwardResponse(response, connectionToLocalServer);
            } finally {
                if (null != connectionToLocalServer) {
                    connectionToLocalServer.close();
        private static int convertStringToPort(String stringfiedPort) throws ServletClientException {
            int returnValue;
            try {
                returnValue = Integer.parseInt(stringfiedPort);
            } catch (NumberFormatException e) {
                throw new ServletClientException("invalid port number: " + stringfiedPort);
            if (returnValue <= 0 || returnValue > 0xFFFF) {
                throw new ServletClientException("invalid port: " + returnValue);
            if (returnValue < 1024) {
                throw new ServletClientException("permission denied for port: " + returnValue);
            return returnValue;
        private static Socket connectToLocalServer(int port) throws ServletServerException {
            Socket returnValue;
            try {
                returnValue = new Socket(InetAddress.getLocalHost(), port);
            } catch (IOException e) {
                throw new ServletServerException("could not connect to " + "local port");
            return returnValue;
        private static void forwardRequest(HttpServletRequest request, Socket connectionToLocalServer)
            throws IOException, ServletClientException, ServletServerException {
            byte buffer[];
            DataInputStream clientIn = new DataInputStream(request.getInputStream());
            buffer = new byte[request.getContentLength()];
            try {
                clientIn.readFully(buffer);
            } catch (EOFException e) {
                throw new ServletClientException("unexpected EOF " + "reading request body");
            } catch (IOException e) {
                throw new ServletClientException("error reading request" + " body");
            DataOutputStream socketOut = null;
            // send to local server in HTTP
            try {
                socketOut = new DataOutputStream(connectionToLocalServer.getOutputStream());
                socketOut.writeBytes("POST / HTTP/1.0\r\n");
                socketOut.writeBytes("Content-length: " + request.getContentLength() + "\r\n\r\n");
                socketOut.write(buffer);
                socketOut.flush();
            } catch (IOException e) {
                throw new ServletServerException("error writing to server");
        private static void forwardResponse(HttpServletResponse response, Socket connectionToLocalServer)
            throws IOException, ServletClientException, ServletServerException {
            byte[] buffer;
            DataInputStream socketIn;
            try {
                socketIn = new DataInputStream(connectionToLocalServer.getInputStream());
            } catch (IOException e) {
                throw new ServletServerException("error reading from " + "server");
            String key = "Content-length:".toLowerCase();
            boolean contentLengthFound = false;
            String line;
            int responseContentLength = -1;
            do {
                try {
                    line = socketIn.readLine();
                } catch (IOException e) {
                    throw new ServletServerException("error reading from server");
                if (line == null) {
                    throw new ServletServerException("unexpected EOF reading server response");
                if (line.toLowerCase().startsWith(key)) {
                    responseContentLength = Integer.parseInt(line.substring(key.length()).trim());
                    contentLengthFound = true;
            while ((line.length() != 0) &&
                (line.charAt(0) != '\r') && (line.charAt(0) != '\n'));
            if (!contentLengthFound || responseContentLength < 0)
                throw new ServletServerException("missing or invalid content length in server response");
            buffer = new byte[responseContentLength];
            try {
                socketIn.readFully(buffer);
            } catch (EOFException e) {
                throw new ServletServerException("unexpected EOF reading server response");
            } catch (IOException e) {
                throw new ServletServerException("error reading from server");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/octet-stream");
            response.setContentLength(buffer.length);
            try {
                OutputStream out = response.getOutputStream();
                out.write(buffer);
                out.flush();
            } catch (IOException e) {
                throw new ServletServerException("error writing response");
    }I checked also with packets monitoring tool, I couldn't see any http transportation.
    Any help will be appreciated.

  • Dont think RMi is HTTP tunneling through proxy firewall

    Hi Guys,
    Does anyone know how to monitor if RMI is using the option toHTTP tunnel through a proxy ???
    Many of clients sit behind firewalls/proxies that enable HTTP only. I thought RMI would, as a default, use HTTP tunneling POST, RESPONSe methods to get through, but it does not.
    Would that case be insted of using Naming.lokup("RMIServer"); that i should use
    Registry reg = LocateRegistry.getResgistry(serverAddress, serverPort);
    reg.lookup("RMIServer");
    Any help would be greatly appreciated.

    RMI doesn't have an option like that. Sockets do, and you get it for any socket including RMI by setting socksProxyHost and socksProxyPort.
    The RMI HTTP tunnelling thing happens when there is an HTTP server at the server side. which redirects the request to an RMI server via rmi-cgi.cgi or the RMI servlet. It's automatic, as a fallback, and you can enforce its use via a system property which you can find in the Javadoc Guide to Features/Remote Method Invocation/Useful java.rmi system properties.

  • HTTP tunneling is disabled in weblogic 9.2

    I have restarted my weblogic server on last saturday, after that i am getting the following exception continuously.
    ####<Jun 5, 2010 11:27:44 PM MEST> <Info> <ServletContext-/bea_wls_internal> <aberdeen> <IAEABEADMP> <[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <> <1275773264990> <000000> <HTTPCl
    ntLogin: Login rejected with code: 'Failed', reason: java.net.ProtocolException: HTTP tunneling is disabled
    at weblogic.rjvm.http.HTTPServerJVMConnection.acceptJVMConnection(HTTPServerJVMConnection.java:88)
    at weblogic.rjvm.http.TunnelLoginServlet.service(TunnelLoginServlet.java:80)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3244)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2010)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1916)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
    In my weblogic server, i am not changed any configuration file, and i can see the HTTP tunneling flag is false (default value).
    Can any one tell why the reason for getting this exception.
    Since i have not changed any configiguration file and i am restarting the server every saturday, this is the first time i got this error.
    Please help to identify the possible reason for this error.?
    Oracle forums suggest that for resolving this just enable the HTTP tunneling flag in weblogic console.

    Thanks for you response manish.
    Once again i have gone throught the log file. Transactions are rollbacked but the cache is not cleaned. i contacted some of friends who is working in weblogic, even thought they are not able to find the solution.
    some guys are saying clean or flush ejb cache is container task. but the container not cleaning the ejb cache.
    Please any body give some solution for me it is very ugent.

  • Use of servlet http tunneling for client server communication

    Hello I am having a problem connecting a simple client applet to a server application. I can connect the two directly using sockets. However, when I try to connect the two via a servlet the input stream cannot be accessed. The application is purely for demonstration. Here is some of the source code
    A servlet for http tunneling
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class SocketServlet extends HttpServlet
         ServletInputStream servletinput;
         ServletOutputStream servletoutput;
         Socket socket;
         DataOutputStream dataoutput;
         DataInputStream datainput;     
         public SocketServlet()
    public void init(ServletConfig servletconfig) throws ServletException
    super.init(servletconfig);
    log("Socket servlet initialized.");
         public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
    try
    servletinput = request.getInputStream();
    socket = new Socket( InetAddress.getByName( "127.0.0.1" ), 5000 );
    dataoutput = new DataOutputStream( socket.getOutputStream() );
    try
                        byte[] inbytes = new byte[1024];
                        servletinput.read( inbytes );
                        String inmessage = new String( inbytes );                    
                        dataoutput.writeBytes( inmessage );
    catch(IOException ioex)
    dataoutput.flush();
    datainput = new DataInputStream( socket.getInputStream() );
    servletoutput = response.getOutputStream();
    try
    byte[] outbytes = new byte[1024];
    datainput.read( outbytes );
    servletoutput.write( outbytes );
    catch(IOException ioex)
    servletoutput.flush();
    servletoutput.close();
    catch(Exception ex)
    // Server.java
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Server extends JFrame {
    private JTextField enter;
    private JTextArea display;
    DataOutputStream output;
    DataInputStream input;
    public Server()
    super( "Server" );
    Container c = getContentPane();
         enter = new JTextField();
         enter.setEnabled( false );
         c.add( enter, BorderLayout.SOUTH );
    display = new JTextArea();
    c.add( new JScrollPane( display ),
    BorderLayout.CENTER );
    setSize( 300, 150 );
    show();
    public void runServer()
    ServerSocket server;
    Socket connection;
    int counter = 1;
    try {
    // Step 1: Create a ServerSocket.
    server = new ServerSocket( 5000, 100 );
    while ( true ) {
    // Step 2: Wait for a connection.
    display.setText( "Waiting for connection\n" );
    connection = server.accept();
    display.append( "Connection " + counter +
    " received from: " +
    connection.getInetAddress().getHostName() );
    // Step 3: Get input and output streams.
    output = new DataOutputStream(
    connection.getOutputStream() );
    input = new DataInputStream(
    connection.getInputStream() );
    display.append( "\nGot I/O streams\n" );
    // Step 4: Process connection.
    String message =
    "SERVER>>> Connection successful";
    output.writeBytes( message );
    enter.setEnabled( true );
                   display.append( "\nConnected\n" );
    do {
    try {
                        byte[] mess = new byte[1024];
    input.read( mess );
    display.append( "\n" + message );
    display.setCaretPosition(
    display.getText().length() );
                   catch (IOException ioex )
    } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
    // Step 5: Close connection.
    display.append( "\nUser terminated connection" );
    enter.setEnabled( false );
    output.close();
    input.close();
    connection.close();
    ++counter;
    catch ( EOFException eof ) {
    System.out.println( "Client terminated connection" );
    catch ( IOException io ) {
    io.printStackTrace();
    private void sendData( String s )
    try {
    output.writeBytes( "SERVER>>> " + s );
    display.append( "\nSERVER>>>" + s );
    catch ( IOException cnfex ) {
    display.append(
    "\nError writing object" );
    public static void main( String args[] )
    Server app = new Server();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    app.runServer();
    // Fig. 21.4: Client.java
    // Set up a Client that will read information sent
    // from a Server and display the information.
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.util.zip.*;
    public class Client extends Applet implements ActionListener {
    private TextField enter;
    private TextArea display;
    DataOutputStream output;
    DataInputStream input;
    private Button button, button2;
    URLConnection connection;
    private byte[] bytes1, bytes2;
    private String message, message2;
    public void init()
    setLayout( new BorderLayout() );
    enter = new TextField( " Enter text here " );
    enter.setEnabled( false );
    enter.addActionListener( this );
    add( enter, BorderLayout.NORTH );
    display = new TextArea( 4, 30 );
         display.setEditable( false );
    add( display, BorderLayout.CENTER );
         button = new Button( "Connect" );
         button.addActionListener( this );
         add( button, BorderLayout.SOUTH );
    public void runClient()
    Socket client;
    try {
    // Step 1: Create a Socket to make connection.
    display.setText( "Attempting connection\n" );
              URL currentpage = getCodeBase();
              String protocol = currentpage.getProtocol();
              String host = currentpage.getHost();
              int port = 8100;
              String urlsuffix = "/servlet/SocketServlet";
              URL dataurl = new URL( "http://localhost:8100/servlet/SocketServlet" );
              connection = dataurl.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/octet-stream");
              connection.setUseCaches( false );
              display.append( "\nConnected to: " + host );          
    // Step 2: Get the output streams.
    output = new DataOutputStream(
    connection.getOutputStream() );
              display.append( "\n got output stream\n" );
              // Step 3 get input connection
              try
              display.append( "\nAttempting to connect to input stream\n" );
                   input = new DataInputStream( connection.getInputStream() );
                   bytes1 = new byte[1024];
                   input.readFully( bytes1 );
                   display.append( "\nGot input stream\n" );
                   message = new String( bytes1 );
                   display.append( "\n" + message + "\n" );          
              catch ( IOException ioex )
              // Step 3: Process connection.
              enter.setEnabled( true );
              do {
              try {
    bytes2 = new byte[1024];
              input.readFully( bytes2 );
              message2 = new String( bytes2 );
              display.append( "\n" + message2 );
              display.setCaretPosition(
              display.getText().length() );
              catch ( IOException ioex ) {
              display.append(
              "\nUnknown object type received" );
              } while ( !message.equals( "SERVER>>> TERMINATE" ) );
    // Step 4: Close connection.
    display.append( "Closing connection.\n" );
    output.close();
    input.close();
         catch (MalformedURLException mfe )
    catch ( EOFException eof ) {
    System.out.println( "Server terminated connection" );
    catch ( IOException e ) {
    e.printStackTrace();
    private void sendData( String s )
    try {
    message = s;
    output.writeBytes( "CLIENT>>> " + s );
    display.append( "\nCLIENT>>>" + s );
    catch ( IOException cnfex ) {
    display.append(
    "\nError writing object" );
    public void actionPerformed( ActionEvent e )
         if ( e.getActionCommand() == "Connect" )
              runClient();
         else
              sendData( e.getActionCommand() );
    public static void main(String args[])
    Frame f = new Frame("Chat Client");
         Client c = new Client();
         c.init();
         f.add("Center", c);
         f.setSize(300, 150);
         f.show();
    the connection appears to fail at client step 3, any help is super, thanks
    Aidan

    Hi,
    In your client you are trying to open OutputStream even though you are not using it.
    So there are two solutions here.
    1. If you dont need OutputStream your code shoud look like this
    try {
    // Step 1: Create a Socket to make connection.
    display.setText( "Attempting connection\n" );
    URL currentpage = getCodeBase();
    String protocol = currentpage.getProtocol();
    String host = currentpage.getHost();
    int port = 8100;
    String urlsuffix = "/servlet/SocketServlet";
    URL dataurl = new URL( "http://localhost:8100/servlet/SocketServlet" );
    connection = dataurl.openConnection();
    //connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/octet-stream");
    connection.setUseCaches( false );
    display.append( "\nConnected to: " + host );
    // Step 2: Get the output streams.
    //output = new DataOutputStream(
    //connection.getOutputStream() );
    //display.append( "\n got output stream\n" );
    display.append( "\n Not interested in output stream\n" );
    //Step 3 Inpustream related
    // Step 4: Close connection.
    display.append( "Closing connection.\n" );
    //output.close();
    input.close();
    1. If you need OutputStream, close your OutputStream before even trying to get InputStream, your code should like this
    try {
    // Step 1: Create a Socket to make connection.
    display.setText( "Attempting connection\n" );
    URL currentpage = getCodeBase();
    String protocol = currentpage.getProtocol();
    String host = currentpage.getHost();
    int port = 8100;
    String urlsuffix = "/servlet/SocketServlet";
    URL dataurl = new URL( "http://localhost:8100/servlet/SocketServlet" );
    connection = dataurl.openConnection();
    //connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/octet-stream");
    connection.setUseCaches( false );
    display.append( "\nConnected to: " + host );
    // Step 2: Get the output streams.
    output = new DataOutputStream(
    connection.getOutputStream() );
    display.append( "\n got output stream\n" );
    //I'll do whateve I've to do with outputstream
    //done with output stream closing
    output.close();
    //Step 3 Inpustream related
    // Step 4: Close connection.
    display.append( "Closing connection.\n" );
    //output.close();
    input.close();
    hope this works
    all the best,
    Raj

  • How to initialize the Http Tunnel Connection

    hi all,
    I am developing an application in which i have to get the images from the server.At first i have used the Apache Tomcat it was working fine in my localSystem.
    when the same application when getting the images from the server it was getting the following exception in the RunTime,Error in HTTP Tunnel initializing
    what does it mean,is this a problem in the network.Can anybody give me the way to initialize the Server or the midlet to get the image.
    When the same URL in the Browser it was displaying the image.Can anybody please give me the solution in this aspect
    thanks in advance
    lakshman

    hi ,
    The above preferences about the network will work fine when you are working with the localhost.When the same application dealing with the network connection like http://mywebsite/.... it was not giving wny response.
    I don't know the reason for that, if you know please share with me.but the application will work fine in mobile. I tested that application with the ASP file in my website with the 6630.
    if you have any doubts feel free to post here
    lakshman

  • 10g: HTTP Server and OC4J on different servers?

    Can anyone assist with configuring HTTP Server and OC4J on different servers?
    I installed AS 10g on both; our application runs fine on one server, with the HTTP Server and OC4J both on the same box.
    I need to also test this with the HTTP Server on a separate box.
    I added this to mod_ocj4.conf:
    Oc4jMount /indox-qa1
    instance://cvodev2:oas_dev2.cvodev2.int.sys.com:indox-qa1
    Oc4jMount /indox-qa1/*
    instance://cvodev2:oas_dev2.cvodev2.int.sys.com:indox-qa1
    But when I try to access something like http://cvodev4/indox-qa1 I get this in the logs:
    [Wed Jul 06 16:54:10 2005] [warn] [client 10.1.1.231] [ecid: 1120683250:192.152.136.127:1248:1544:1,0] MOD_OC4J_0184: Failed to find an oc4j process for destination: instance://cvodev2.int.camsys.com:oas_dev2.cvodev2.int.camsys.com:indor-qa1
    [Wed Jul 06 16:54:10 2005] [error] [client 10.1.1.231] [ecid: 1120683250:192.152.136.127:1248:1544:1,0] MOD_OC4J_0145: There is no oc4j process (for destination: instance://cvodev2.int.camsys.com:oas_dev2.cvodev2.int.camsys.com:indor-qa1) available to service request.
    [Wed Jul 06 16:54:10 2005] [error] [client 10.1.1.231] [ecid: 1120683250:192.152.136.127:1248:1544:1,0] MOD_OC4J_0119: Failed to get an oc4j process for destination: instance://cvodev2.int.camsys.com:oas_dev2.cvodev2.int.camsys.com:indor-qa1
    [Wed Jul 06 16:54:10 2005] [error] [client 10.1.1.231] [ecid: 1120683250:192.152.136.127:1248:1544:1,0] MOD_OC4J_0013: Failed to call destination: instance://cvodev2.int.camsys.com:oas_dev2.cvodev2.int.camsys.com:indor-qa1's service() to service the request.
    I did some ethernet sniffing and it doesn't look to me like the OHS box is even trying to contact the OC4J box.
    Is there more configuration I need to do beyond this?
    Thanks,
    dwh

    hi user11159690
    Maybe this can help:
    "Oracle® HTTP Server Administrator's Guide 10g Release 3 (10.1.3) B25211-02"
    "7.32 mod_oc4j"
    http://download.oracle.com/docs/cd/B25221_04/web.1013/b25211/confmods.htm#i1025739
    Maybe more specifically "Oc4jMount":
    http://download.oracle.com/docs/cd/B25221_04/web.1013/b25211/confmods.htm#CIHJBGFB
    (tip : You can use "Your Control Panel" to make your name visible in forum posts.)
    success
    Jan Vervecken

  • HTTP-Tunneling through Apache Plug-in

    Hello,
    has anybody experience with HTTP-Tunneling of requests to a WLS
    4.5.1SP13 through an Apache-Webserver?
    I'm not able to configure the apache plug-in from weblogic to act as a
    reverse proxy for requests coming from a
    Java Client Application.
    Any Hints available?
    Remo

    "Jong Lee" <[email protected]> wrote in message
    news:3a4a9efa$[email protected]..
    >
    Remo Schnidrig <[email protected]> wrote:
    Hello Jong,
    HTTP tunneling will append ".tun" to your request.
    For apache, you can use "MatchExpression" to proxy the mime type.
    i.e: add the following line to your httpd.conf
    MatchExpression *.tunThat is functioning. Thank you very much.
    Another question:
    What about HTTPS-Tunneling through an Apache-Server?
    How can I get everything through?
    Thank you
    Remo
    We don't support https from the bridge to the server yet.
    JongWhat about using HTTPS-Tunneling between our Java client and the WLS
    Stronghold plug-in and HTTP-Tunneling between the plug-in and the WLS?
    If this is possible, how do I have to setup the stronghold?
    Remo

  • HTTP Tunneling and Load Balancing with Weblogic Server 6.1

    We use T3 for Java client to application server communication (Weblogic Server
    6.1) and keep the session open for the life of the client. We many customers
    using this with load balancers and all works fine. We have just started to use
    BEA's HTTP tunneling and I have a question concerning how this will work with
    load balancers. Since the single T3 connection has been replaced with a series
    of stateless HTTP connections, does the BEA tunneling code put session information
    in the HTTP header? If so, what information does it place in the header. If
    it does we should be able to use that to make sure that the load balancer always
    sends HTTP requests with that session to the same application server.
    Thanks!
    Rick

    Rick,
    You may want to look at the Alteon and F5 configuration we have on edocs.
    Take a look at the following URLs for a possible solution
    http://edocs.bea.com/wls/docs61/cluster/alteon.html#591902
    http://edocs.bea.com/wls/docs61/cluster/bigip.html#591902
    Chuck Nelson
    DRE
    BEA Technical Support

  • [Fwd: JMS publishing via http-tunneling]

    "Jeffrey S. Hair" wrote:
    Does anyone know of way to speed up WL JMS publishing via http-tunneling?
    We have a server that is publishing messages to JMS rather frequently (1/200 millisecs). We then
    have several applications and applets subscribed for this topic. The applications work great and get
    all of the messages quite fast (using t3 protocol).
    However, the applet, running on the other side of a firewall, and connected to the server over a 28k
    modem, receives the updates rather slowly since the messages need tunneled through http. In fact, so
    many updates are being published that the applet continually falls behind. If we stopped the updates
    or slowed down the updates, the applet would eventually catch up and reflect the latest message.
    The sessions in the applet were created using AUTO_ACKNOWLEDGE. I've since changed them to use
    CLIENT_ACKNOWLEDGE and allow for 15 seconds of messages to be processed before acknowledging. This
    improved the speed but the applet still falls behind to some degree. When the publishing slows down,
    the applet now at least catches up.
    As a side note, does anyone know of a way to view the contents of the JMS queue?
    Thanx,
    jsh
    Jeffrey S. Hair
    Sr. System Architect, FNX Limited[email.eml]

    Which web server are you using?
    Both iWS6.0 SP2 or iWS Fast-track 4.1 works with iMQ.
    But earler versions of iWS6.0 do not and we have no
    control of that.

  • HTTP tunneling T3 when using WebStart - java.security.AccessControlException: access denied

    Hi !
    WLS version: 5.1 with SP10
    Server OS: NT4
    Client distr.: Java WebStart
    Client OS: Windows 2000
    I get the following exception when I try to create a T3 connection
    (tunnelled through HTTP) to my WLS server:
    java.security.AccessControlException: access denied
    (java.util.PropertyPermission proxyHost read)
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
    at java.lang.System.getProperty(Unknown Source)
    at weblogic.net.http.HttpClient.resetProperties(HttpClient.java:62)
    at weblogic.net.http.HttpClient.openServer(HttpClient.java:186)
    at weblogic.net.http.HttpClient.<init>(HttpClient.java:85)
    at weblogic.net.http.HttpClient.New(HttpClient.java:117)
    at weblogic.net.http.HttpURLConnection.connect(HttpURLConnection.java:97)
    at
    weblogic.net.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1
    44)
    at weblogic.socket.JVMSocketHTTPClient.sendMsg(JVMSocketHTTPClient.java:260)
    at weblogic.socket.JVMAbbrevSocket.sendOutMsg(JVMAbbrevSocket.java:348)
    at weblogic.socket.JVMAbbrevSocket.sendMsg(JVMAbbrevSocket.java:237)
    at weblogic.rjvm.ConnectionManager.sendMsg(ConnectionManager.java:420)
    at weblogic.rjvm.RJVMImpl.send(RJVMImpl.java:564)
    at
    weblogic.rjvm.MsgAbbrevOutputStream.flushAndSendRaw(MsgAbbrevOutputStream.ja
    va:155)
    at
    weblogic.rjvm.MsgAbbrevOutputStream.flushAndSend(MsgAbbrevOutputStream.java:
    163)
    at
    weblogic.rjvm.MsgAbbrevOutputStream.sendRecv(MsgAbbrevOutputStream.java:186)
    at
    weblogic.rmi.internal.BasicOutgoingRequest.sendRecv(BasicOutgoingRequest.jav
    a:23)
    at
    weblogic.rmi.extensions.AbstractRequest.sendReceive(AbstractRequest.java:73)
    at
    com.unitor.message.server.UserInformationServiceBeanHomeImpl_WLStub.create(U
    serInformationServiceBeanHomeImpl_WLStub.java:151)
    at
    com.unitor.message.server.UserInformationServiceBeanHomeImpl_ServiceStub.cre
    ate(UserInformationServiceBeanHomeImpl_ServiceStub.java:121)
    at
    com.unitor.message.beans.gui.MessageLogic.getUserInformationService(MessageL
    ogic.java:230)
    at
    com.unitor.message.beans.gui.MessageLogic.addUserInformation(MessageLogic.ja
    va:186)
    at com.unitor.message.beans.gui.MessageLogic.<init>(MessageLogic.java:104)
    at
    com.unitor.message.beans.gui.MessageApplication.internalStartApplication(Mes
    sageApplication.java:64)
    at
    com.unitor.ifs.util.gui.UnitorApplication.startApplication(UnitorApplication
    .java:167)
    at
    com.unitor.ifs.util.gui.DesktopApplication$ApplicationLoader.run(DesktopAppl
    ication.java:676)
    at
    com.unitor.ifs.util.gui.DesktopApplication.startApplication(DesktopApplicati
    on.java:303)
    at
    com.unitor.ifs.util.gui.UnitorDesktopAppStarter$SwingEventCall.run(UnitorDes
    ktopAppStarter.java:294)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    The strange thing is that I can connect to my server if I run the client on
    NT4 !!!
    I solved the problem by modifying my local java.policy file with the
    following settings:
    // Test with HTTP tunnelling. 18.10.2001
    [email protected]
    permission java.util.PropertyPermission "proxyHost", "read";
    permission java.util.PropertyPermission "proxyPort", "read";
    permission java.util.PropertyPermission "http.proxyHost", "read";
    permission java.util.PropertyPermission "http.proxyPort", "read";
    permission java.net.SocketPermission "*","connect,resolve";
    // Test with HTTP tunnelling. 18.10.2001
    [email protected]
    Have someone else experienced the same or similar problems ?
    How can I make sure that the client gets access to read the properties
    http.proxyHost, http.proxyPort, proxyHost and proxyPort without telling the
    users of the client application to modify their java.policy files ?
    Any leads will be greatly appreciated !
    Regards
    Sten Richard

    This is in reply to the first post. I don't know what happened after.
    Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission sun.arch.data.model read)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
         at java.lang.System.getProperty(Unknown Source)
         at org.eclipse.swt.internal.Library.loadLibrary(Library.java:167)
         at org.eclipse.swt.internal.Library.loadLibrary(Library.java:151)
         at org.eclipse.swt.internal.C.<clinit>(C.java:21)
    If you read the above trace from bottom to top, it shows none of you classes, only classes from that Eclipse library, which seems to loadLibrary() a native DLL. In order to do this, it needs to call System.getProperty( "sun.arch.data.model" ). This call is not allowed from un unsigned applet. So I guess you need to sign the applet and this problem will go away. Many other problems may follow. Just read very very carefully all the related documentation, which I did not.

  • Here is example code for HTTPS Tunneling through proxy(400 Lines of code

    Here is the source for Https Tunneling that I have gotten working. It is based on Pua Yeow Cheong's JavaWorld Tip 111. Thanks to David Lord for providing the final breakthrough that I needed.
    I have posted it here for anyone who wishes to use it. If you find any bugs, or write any improvements, please tack them onto the end of this thread.
    I have been trying to tackle this problem for quite some time, so I hope this helps a few of you out there.
    Lots of Luck,
    nightmask.
    <----- Begin Copy and Paste -------->
    import java.net.*;
    import java.io.*;
    import java.security.*;
    import sun.misc.BASE64Encoder;
    import javax.net.*;
    import javax.net.ssl.*;
    *  This example is based on JavaWorld Tip 111. Thanks to Pua Yeow Cheong for writing it.
    *  It tunnels through a proxy using the Https protocol.
    *  Thanks go to David Lord in the java forums for figuring out the main problem with Tip 111
    *  PLEASE NOTE: You need to have the JSSE 1.0.2 jars installed for this to work
    *  Downloads contents of a URL, using Proxy Tunneling and Basic Authentication
    public class URLReader {
         *  The main program for the URLReader class
        public static void main(String[] args) throws Exception {
            //set up strings for use in app. Change these to your own settings
            String proxyPassword = "password";
            String proxyUsername = "username";
            String proxyHost = "myproxy.com";
            String proxyPort = "3128";
            String connectionURL = "https://www.verisign.com";
            //set up system properties to indicate we are using a proxy
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort);
            System.setProperty("proxyHost", proxyHost);
            System.setProperty("proxyPort", proxyPort);
            System.setProperty("proxySet", "true");
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            System.setProperty("http.proxySet", "true");
            //set up handler for jsse
            System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
            java.security.Provider prov = new com.sun.net.ssl.internal.ssl.Provider();
            Security.addProvider(prov);
            //create the connection
            URL myURL = new URL(connectionURL);
            URLConnection myConnection = myURL.openConnection();
            if (myConnection instanceof com.sun.net.ssl.HttpsURLConnection) {
                ((com.sun.net.ssl.HttpsURLConnection) myConnection).setSSLSocketFactory(new SSLTunnelSocketFactory(System.getProperty("proxyHost"), System.getProperty("proxyPort")));
            myConnection.setDoInput(true);
            myConnection.setDoOutput(true);
            BufferedReader in;
            try {
                System.err.println("opening Input stream1");
                in = new BufferedReader(
                        new InputStreamReader(
                        myConnection.getInputStream()));
                String inputLine;
                System.err.println("Input stream is Open1");
                while ((inputLine = in.readLine()) != null) {
                    System.err.println(inputLine);
                in.close();
                System.err.println("Input stream is Closed1");
            } catch (Exception e) {
                e.printStackTrace(System.err);
                String tmp = e.getMessage().toLowerCase().trim();
                System.err.println("tmp *" + tmp + "*");
                if (tmp.indexOf("http") > -1) {
                    //http error message to be parsed
                    tmp = tmp.substring(tmp.indexOf("http")).trim();
                    System.err.println("tmp *" + tmp + "*");
                    tmp = tmp.substring(8).trim();
                    System.err.println("tmp *" + tmp + "*");
                    if (tmp.startsWith("407")) {
                        //proxy authentication required
                        myURL = new URL(connectionURL);
                        myConnection = myURL.openConnection();
                        if (myConnection instanceof com.sun.net.ssl.HttpsURLConnection) {
                            ((com.sun.net.ssl.HttpsURLConnection) myConnection).setSSLSocketFactory(new SSLTunnelSocketFactory(System.getProperty("proxyHost"), System.getProperty("proxyPort"), proxyUsername, proxyPassword));
                        myConnection.setDoInput(true);
                        myConnection.setDoOutput(true);
                        try {
                            System.err.println("opening Input stream 2");
                            in = new BufferedReader(
                                    new InputStreamReader(
                                    myConnection.getInputStream()));
                            String inputLine;
                            System.err.println("Input stream is Open 2");
                            while ((inputLine = in.readLine()) != null) {
                                System.out.println(inputLine);
                            in.close();
                            System.err.println("Input stream is closed 2");
                        } catch (Exception ex) {
                            System.err.println(ex.getMessage());
                            ex.printStackTrace(System.err);
    *  SSLSocket used to tunnel through a proxy
    class SSLTunnelSocketFactory extends SSLSocketFactory {
        private String tunnelHost;
        private int tunnelPort;
        private SSLSocketFactory dfactory;
        private String tunnelPassword;
        private String tunnelUserName;
        private boolean socketConnected = false;
        private int falsecount = 0;
         *  Constructor for the SSLTunnelSocketFactory object
         *@param  proxyHost  The url of the proxy host
         *@param  proxyPort  the port of the proxy
        public SSLTunnelSocketFactory(String proxyHost, String proxyPort) {
            System.err.println("creating Socket Factory");
            tunnelHost = proxyHost;
            tunnelPort = Integer.parseInt(proxyPort);
            dfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
         *  Constructor for the SSLTunnelSocketFactory object
         *@param  proxyHost      The url of the proxy host
         *@param  proxyPort      the port of the proxy
         *@param  proxyUserName  username for authenticating with the proxy
         *@param  proxyPassword  password for authenticating with the proxy
        public SSLTunnelSocketFactory(String proxyHost, String proxyPort, String proxyUserName, String proxyPassword) {
            System.err.println("creating Socket Factory with password/username");
            tunnelHost = proxyHost;
            tunnelPort = Integer.parseInt(proxyPort);
            tunnelUserName = proxyUserName;
            tunnelPassword = proxyPassword;
            dfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
         *  Sets the proxyUserName attribute of the SSLTunnelSocketFactory object
         *@param  proxyUserName  The new proxyUserName value
        public void setProxyUserName(String proxyUserName) {
            tunnelUserName = proxyUserName;
         *  Sets the proxyPassword attribute of the SSLTunnelSocketFactory object
         *@param  proxyPassword  The new proxyPassword value
        public void setProxyPassword(String proxyPassword) {
            tunnelPassword = proxyPassword;
         *  Gets the supportedCipherSuites attribute of the SSLTunnelSocketFactory
         *  object
         *@return    The supportedCipherSuites value
        public String[] getSupportedCipherSuites() {
            return dfactory.getSupportedCipherSuites();
         *  Gets the defaultCipherSuites attribute of the SSLTunnelSocketFactory
         *  object
         *@return    The defaultCipherSuites value
        public String[] getDefaultCipherSuites() {
            return dfactory.getDefaultCipherSuites();
         *  Gets the socketConnected attribute of the SSLTunnelSocketFactory object
         *@return    The socketConnected value
        public synchronized boolean getSocketConnected() {
            return socketConnected;
         *  Creates a new SSL Tunneled Socket
         *@param  s                         Ignored
         *@param  host                      destination host
         *@param  port                      destination port
         *@param  autoClose                 wether to close the socket automaticly
         *@return                           proxy tunneled socket
         *@exception  IOException           raised by an IO error
         *@exception  UnknownHostException  raised when the host is unknown
        public Socket createSocket(Socket s, String host, int port, boolean autoClose)
                 throws IOException, UnknownHostException {
            Socket tunnel = new Socket(tunnelHost, tunnelPort);
            doTunnelHandshake(tunnel, host, port);
            SSLSocket result = (SSLSocket) dfactory.createSocket(tunnel, host, port, autoClose);
            result.addHandshakeCompletedListener(
                new HandshakeCompletedListener() {
                    public void handshakeCompleted(HandshakeCompletedEvent event) {
                        System.out.println("Handshake Finished!");
                        System.out.println("\t CipherSuite :" + event.getCipherSuite());
                        System.out.println("\t SessionId: " + event.getSession());
                        System.out.println("\t PeerHost: " + event.getSession().getPeerHost());
                        setSocketConnected(true);
            // thanks to David Lord in the java forums for figuring out this line is the problem
            // result.startHandshake(); //this line is the bug which stops Tip111 from working correctly
            return result;
         *  Creates a new SSL Tunneled Socket
         *@param  host                      destination host
         *@param  port                      destination port
         *@return                           tunneled SSL Socket
         *@exception  IOException           raised by IO error
         *@exception  UnknownHostException  raised when the host is unknown
        public Socket createSocket(String host, int port)
                 throws IOException, UnknownHostException {
            return createSocket(null, host, port, true);
         *  Creates a new SSL Tunneled Socket
         *@param  host                      Destination Host
         *@param  port                      Destination Port
         *@param  clientHost                Ignored
         *@param  clientPort                Ignored
         *@return                           SSL Tunneled Socket
         *@exception  IOException           Raised when IO error occurs
         *@exception  UnknownHostException  Raised when the destination host is
         *      unknown
        public Socket createSocket(String host, int port, InetAddress clientHost,
                int clientPort)
                 throws IOException, UnknownHostException {
            return createSocket(null, host, port, true);
         *  Creates a new SSL Tunneled Socket
         *@param  host             destination host
         *@param  port             destination port
         *@return                  tunneled SSL Socket
         *@exception  IOException  raised when IO error occurs
        public Socket createSocket(InetAddress host, int port)
                 throws IOException {
            return createSocket(null, host.getHostName(), port, true);
         *  Creates a new SSL Tunneled Socket
         *@param  address          destination host
         *@param  port             destination port
         *@param  clientAddress    ignored
         *@param  clientPort       ignored
         *@return                  tunneled SSL Socket
         *@exception  IOException  raised when IO exception occurs
        public Socket createSocket(InetAddress address, int port,
                InetAddress clientAddress, int clientPort)
                 throws IOException {
            return createSocket(null, address.getHostName(), port, true);
         *  Sets the socketConnected attribute of the SSLTunnelSocketFactory object
         *@param  b  The new socketConnected value
        private synchronized void setSocketConnected(boolean b) {
            socketConnected = b;
         *  Description of the Method
         *@param  tunnel           tunnel socket
         *@param  host             destination host
         *@param  port             destination port
         *@exception  IOException  raised when an IO error occurs
        private void doTunnelHandshake(Socket tunnel, String host, int port) throws IOException {
            OutputStream out = tunnel.getOutputStream();
            //generate connection string
            String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n"
                     + "User-Agent: "
                     + sun.net.www.protocol.http.HttpURLConnection.userAgent;
            if (tunnelUserName != null && tunnelPassword != null) {
                //add basic authentication header for the proxy
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                String encodedPassword = enc.encode((tunnelUserName + ":" + tunnelPassword).getBytes());
                msg = msg + "\nProxy-Authorization: Basic " + encodedPassword;
            msg = msg + "\nContent-Length: 0";
            msg = msg + "\nPragma: no-cache";
            msg = msg + "\r\n\r\n";
            System.err.println(msg);
            byte b[];
            try {
                //we really do want ASCII7 as the http protocol doesnt change with locale
                b = msg.getBytes("ASCII7");
            } catch (UnsupportedEncodingException ignored) {
                //If ASCII7 isn't there, something is seriously wrong!
                b = msg.getBytes();
            out.write(b);
            out.flush();
            byte reply[] = new byte[200];
            int replyLen = 0;
            int newlinesSeen = 0;
            boolean headerDone = false;
            InputStream in = tunnel.getInputStream();
            boolean error = false;
            while (newlinesSeen < 2) {
                int i = in.read();
                if (i < 0) {
                    throw new IOException("Unexpected EOF from Proxy");
                if (i == '\n') {
                    headerDone = true;
                    ++newlinesSeen;
                } else
                        if (i != '\r') {
                    newlinesSeen = 0;
                    if (!headerDone && replyLen < reply.length) {
                        reply[replyLen++] = (byte) i;
            //convert byte array to string
            String replyStr;
            try {
                replyStr = new String(reply, 0, replyLen, "ASCII7");
            } catch (UnsupportedEncodingException ignored) {
                replyStr = new String(reply, 0, replyLen);
            //we check for connection established because our proxy returns http/1.1 instead of 1.0
            if (replyStr.toLowerCase().indexOf("200 connection established") == -1) {
                System.err.println(replyStr);
                throw new IOException("Unable to tunnel through " + tunnelHost + ":" + tunnelPort + ". Proxy returns\"" + replyStr + "\"");
            //tunneling hanshake was successful
    }<----- End Copy and Paste -------->

    BTW, if you are using an implementation in which
    the http/https implementation recognises
    the java.net.Authenticator properly, you can use
    that framework to do basic/digest authentication.
    I think Sun's JDK 1.4 supports both basic
    and digest for both proxies and the actual end
    site you connect via http/https, but I haven't
    tested it to be sure. I know it works
    with http/basic at the end host.
    Today's Ob hack:
    import java.net.*;
    import java.io.*;
    class MyAuth extends Authenticator {
        protected PasswordAuthentication getPasswordAuthentication() {
            System.out.println("The realm '" + getRequestingPrompt() +
                "' at '" + getRequestingHost() + ":" + getRequestingPort() +
                "'\n" + "using " + getRequestingProtocol() + " is requesting " +
                getRequestingScheme().toUpperCase() + " authentication.");
            System.out.println("");
            System.out.println("What should we send them?  Let's send them ...");
            System.out.println("");
            return new PasswordAuthentication("username", "password".toCharArray());    }  
    public class MyURL {
        public static void main(String[] args) throws Exception {
            // set to the authenticator you want to use.
            Authenticator.setDefault(new myAuth());
            URL url =
                new URL("http://www.some.com/something_protected/index.htm");
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    url.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            in.close();

Maybe you are looking for

  • Using time capsule to backup pc

    Can I backup my Windows 7 machine to the Time Capsule?

  • How to update content of a file on server using a Java Applet?

    Hi, I'm new to Java, and I have a task now to overwrite a text file on a server using an applet. I have written a piece of code which compiles but doesn't work. Can you please take a look at the code or give me another way to do it? Thanks. Code: imp

  • DMS Server Specs

    Can anybody provide a doc with the correct server specs? I'm looking for the actual C210 server. Specifically, is it an M1 or M2? What amount of memory is installed in the DMM and SnS? What CPU? Heat? Power? Dimensions? Etc. Last document I saw on co

  • What are the new [bond_interfaces] in initscripts?

    Is this for explicitly naming certain devices as discussed in this thread: http://bbs.archlinux.org/viewtopic.php?t=8676&start=15 ? If it - why the complex initscripts?  wireless_tools and net-tools both provide tools for naming interfaces.  As the r

  • I cleaned my Macbook pro too much and I think it's damaged.

    How do I get rid of streak marks that are really bothering me?