Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2003, 2007 s IT Solutions AT Spardat GmbH . All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: s IT Solutions AT Spardat GmbH - initial API and implementation /
 
 
 /*
  * Created on 16.05.2003
  */
 package at.spardat.xma.boot.transport;
 
 import java.io.File;
 import java.net.URL;
 import java.util.Date;
 import java.util.List;
 
 
 import  org.apache.commons.httpclient.Cookie;
 import  org.apache.commons.httpclient.HttpState;
 import  org.apache.commons.httpclient.cookie.CookiePolicy;
 import  org.apache.commons.httpclient.cookie.CookieSpec;
 import  org.apache.commons.httpclient.cookie.CookieSpecBase;
 import  org.apache.commons.httpclient.cookie.MalformedCookieException;
 
This class implements low level transport on http transport using suns UrlConnection implementation.

Author(s):
s2877, s3595
Version:
$Id: HTTPTransport.java 2647 2008-08-26 13:53:08Z webok $
 
 public class HTTPTransport extends Transport {

    
used to format if-modified-since correctly
 
     private static DateFormat httpdate_;
 
     private static Logger log_;
 
     private static HostnameVerifier hostnameVerifier;
 
     private static CookieSpec cookieSpec;
     private static HttpState httpState = new HttpState();
 
     {
         = new SimpleDateFormat"EEE, dd MMM yyyy HH:mm:ss zzz". );            //$NON-NLS-1$
        .setTimeZone(new SimpleTimeZone(0, "GMT")); //$NON-NLS-1$
     }

    
Initializes the underlaying http-protocol-provider from the given Propterties. This sets the tcp-timeouts, the proxy-settings and ssl-settings.

Parameters:
prop containing properties for http and https protocol
 
     public static void initProperties prop ){
 
          = Logger.getLogger"boot.transport.http" ); //$NON-NLS-1$
 
         // proxy properties
         String strProxyEnable   = prop.getProperty. );
         ifstrProxyEnable != null && Boolean.valueOf(strProxyEnable).booleanValue()) {
             String strProxyServer   = prop.getProperty. );
             String strProxyPort     = prop.getProperty. );
             ifstrProxyServer!=null &&  strProxyPort!=null ) {
                 System.setProperty"proxySet""true" );
                 System.setProperty"http.proxyHost"strProxyServer );
                 System.setProperty"http.proxyPort"strProxyPort  );
                 .log(."transport proxy is: {0}:{1}"new Object[] { strProxyServerstrProxyPort } );
             }
             String strSecureProxyServer   = prop.getProperty. );
             String strSecureProxyPort     = prop.getProperty. );
             if(strSecureProxyPort!=null&&strSecureProxyServer!=null) {
                 System.setProperty("https.proxyHost",strSecureProxyServer);
                 System.setProperty("https.proxyPort",strSecureProxyPort);
                 .log(."secure transport proxy is: {0}:{1}"new Object[] { strSecureProxyServerstrSecureProxyPort } );
            }
            String strProxyOverride = prop.getProperty. );
            if(strProxyOverride!=null) {
                strProxyOverride = strProxyOverride.replace(';','|'); // documented delimiter for IE
                strProxyOverride = strProxyOverride.replace(',','|'); // IE supports ',' as delimiter, too
                strProxyOverride = strProxyOverride.replace(' ','|'); // IE supports blank as delimiter, too
                strProxyOverride = strProxyOverride.replace('\t','|'); // IE supports tab as delimiter, too
                strProxyOverride = strProxyOverride.replace('\r','|'); // IE supports carriage return as delimiter, too
                strProxyOverride = strProxyOverride.replace('\n','|'); // IE supports newline as delimiter, too
                strProxyOverride = strProxyOverride.replaceAll("<local>","localhost|127.0.0.1");
                System.setProperty("http.nonProxyHosts",strProxyOverride);
                .log(."proxy not used for: {0}"strProxyOverride );
            }
        } else {
            .log(."no transport proxy is used" );
        }
        // timeout properties
        String strConnectTimeout = prop.getProperty(.);
        if(strConnectTimeout!=null) {
            System.setProperty("sun.net.client.defaultConnectTimeout",strConnectTimeout);
            .log(."http connect timeout: "+strConnectTimeout+" milliseconds");
        }
        String strReadTimeout = prop.getProperty(.);
        if(strReadTimeout!=null) {
            System.setProperty("sun.net.client.defaultReadTimeout",strReadTimeout);
            .log(."http read timeout: "+strReadTimeout+" milliseconds");
        }
        // ssl properties
        String strTrustStore = prop.getProperty(.);
        if(strTrustStore!=null) {
            .log(.,"using trusted certificates file "+strTrustStore);
            File trustFile = new File(strTrustStore);
            if(!trustFile.exists()) {
                .log(.,"trusted certificates file '"+trustFile.getAbsolutePath()+"' not found");
            }
            System.setProperty("javax.net.ssl.trustStore",strTrustStore);
        }
        // cookie handling policy
        Class cookiePolicyClass = null;
        String strCookiePolicy = prop.getProperty(.);
        if(strCookiePolicy!=null) {
            try {
               cookiePolicyClass = Class.forName(strCookiePolicy);
            } catch (ClassNotFoundException e) {
                .log(.,"configured cookiePolicy '"+strCookiePolicy+"' not found, using default");
            }
        }
        if(cookiePolicyClass==null) {
            cookiePolicyClass = CookieSpecBase.class;
        }
        .log(.,"using cookiePolicy "+cookiePolicyClass.getName());
        CookiePolicy.registerCookieSpec(CookiePolicy.DEFAULT, cookiePolicyClass);
        =CookiePolicy.getDefaultSpec();
    }

    
Constructs a HTTPTransport.
    public HTTPTransport() {
        if==null)
             = Logger.getLogger"boot.httpTransport" ); //$NON-NLS-1$
    }

    
Converts a java.util.Date to a String using the encoding specified by the HTTP-Specification. We have to wrap this task, cause we may have to change it.

see also SUN-Bug_ID: 4397096

Parameters:
date the date to be formated
Returns:
String the formated representation
    public static String httpDate(Date date) {
       return .format(date);
    }

    
Converts a long containing a date to a String using the encoding specified by the HTTP-Specification. We have to wrap this task, cause we may have to change it.

see also SUN-Bug_ID: 4397096

Parameters:
ldate the milliseconds since January 1, 1970, 00:00:00 GMT.
Returns:
String the formated representation
    public static String httpDate(long ldate ) {
       return .formatnew Date(ldate));
    }
    /* (non-Javadoc)
     * @see at.spardat.xma.transport.Transport#getResource(at.spardat.xma.transport.XMA_URI, long)
     */
    public Result getResource(final IRtXMASessionClient sessionfinal XMA_URI resourcefinal long modifiedSincefinal String etagthrows CommunicationException {
        CCLoader swtCLoader = BootRuntime.getInstance().getAppManager().getSWTClassLoader();
        if(swtCLoader!=null) {
            class Inner implements Runnable {
                Result result;
                CommunicationException exc;
                public void run() {
                    try {
                         = getResourceImpl(session,resource,modifiedSince,etag);
                    } catch(CommunicationException exc) {
                        this.=exc;
                    }
                }
            }
            Inner inner = new Inner();
            try { // call BusyIndicator.showWhile over reflection from the SWT-Classloader
                Class busyIndicatorClass = swtCLoader.loadClass("org.eclipse.swt.custom.BusyIndicator");
                Class displayClass = swtCLoader.loadClass("org.eclipse.swt.widgets.Display");
                Method method = busyIndicatorClass.getMethod("showWhile",new Class[]{displayClass,Runnable.class});
                method.invoke(null,new Object[]{null,inner});
            } catch (Exception exc) {
                throw new RuntimeException(exc);
            }
            if(inner.exc!=nullthrow inner.exc;
            return inner.result;
        } else {
            return getResourceImpl(session,resource,modifiedSince,etag);
        }
    }
    private Result getResourceImpl(IRtXMASessionClient sessionXMA_URI resourcelong modifiedSinceString etagthrows CommunicationException {
        /* locals ---------------------------------- */
            Result result = new Result();
            int    code   = 0;
            URL    url    = resource.getHTTP_URI();
            HttpURLConnection conn;
        /* locals ---------------------------------- */
        try {
            conn = (HttpURLConnectionurl.openConnection();
            if(conn instanceof HttpsURLConnection) {
                ((HttpsURLConnection)conn).setHostnameVerifier();
            }
            sendCookies(session,url,conn);
            ifetag != null ){
                conn.setRequestProperty("If-None-Match"etag); //$NON-NLS-1$
            }
            String strUrl = url.toExternalForm();
            ifurl.getQuery()==null && ( strUrl.endsWith".jar") || strUrl.endsWith".xml")) ) {
                conn.setRequestProperty(.. + "=0"); //$NON-NLS-1$
            }
            if(modifiedSince>0) {
                // see sun bugid: 4397096
                // if HTTP_Util library is used, the original method may also be used.
                // conn.setIfModifiedSince(modifiedSince);
               conn.setRequestProperty., HTTPTransport.httpDate(modifiedSince));
             }
            conn.setRequestProperty.,"*/*"); //$NON-NLS-1$
        } catch (IOException exc) {
            .log(."error loading '"+url.toString()+"' form server:"exc); //$NON-NLS-1$
            throw new ConnectException("error loading '"+url.toString()+"' form server:",exc);
        }
        try {
            code = conn.getResponseCode();
            if(code==.) {
                result.contentLength_ = 0;
                result.lastModified_  = conn.getLastModified();
                if(result.lastModified_<=0) {
                   result.lastModified_ = modifiedSince;
                }
                result.expirationDate_ = conn.getExpiration();
                result.etag_ = conn.getHeaderField. );
                if(result.etag_==null) {
                    result.etag_ = etag;
                }
                .log(."resource not modified: {0}"url.toExternalForm()); //$NON-NLS-1$
            } else if(code==.){
                result.contentLength_  = conn.getContentLength();
                result.lastModified_   = conn.getLastModified();
                result.expirationDate_ = conn.getExpiration();
                result.etag_           = conn.getHeaderField. );
                result.transformations_conn.getHeaderField(.);
                result.setBufferthis.readOutput(conn) );
                if(result.contentLength_<0) {
                    result.contentLength_=result.buffer_.length;
                }
            } else {
                if(code<500) throw new ConnectException("error loading '"+url.toString()+"' from the server:",code);
                else throw new ServerException("error loading '"+url.toString()+"' from the server:",code);
            }
            readCookies(session,url,conn);
        } catch (CommunicationException ce) {
            if(code!=0) .log(.,"http returncode: {0}",Integer.toString(code)); //$NON-NLS-1$
            .log(."error loading '"+url.toString()+"' from the server:"ce); //$NON-NLS-1$
            throw ce;
        } catch (Exception ex) {
            if(code!=0) .log(.,"http returncode: {0}",Integer.toString(code)); //$NON-NLS-1$
            .log(.,"error loading '"+url.toString()+"' from the server:"ex);             //$NON-NLS-1$
            if(code<500) throw new ConnectException("error loading '"+url.toString()+"' from the server:",ex);
            else throw new ServerException("error loading '"+url.toString()+"' from the server:",ex);
        }
        return result;
    }
    /* (non-Javadoc)
     * @see at.spardat.xma.transport.Transport#callServerEvent(at.spardat.xma.session.XMASessionClient, at.spardat.xma.transport.XMA_URI, java.io.InputStream)
     */
    public byte[] callServerEvent(final IRtXMASessionClient session,final XMA_URI eventHandler,final byte[] inputthrows CommunicationException {
        CCLoader swtCLoader = BootRuntime.getInstance().getAppManager().getSWTClassLoader();
        if(swtCLoader!=null) {
            class Inner implements Runnable {
                byte[] result;
                CommunicationException exc;
                public void run() {
                    try {
                         = callServerEventImpl(session,eventHandler,input);
                    } catch(CommunicationException exc) {
                        this.=exc;
                    }
                }
            }
            Inner inner = new Inner();
            try { // call BusyIndicator.showWhile over reflection from the SWT-Classloader
                Class busyIndicatorClass = swtCLoader.loadClass("org.eclipse.swt.custom.BusyIndicator");
                Class displayClass = swtCLoader.loadClass("org.eclipse.swt.widgets.Display");
                Method method = busyIndicatorClass.getMethod("showWhile",new Class[]{displayClass,Runnable.class});
                method.invoke(null,new Object[]{null,inner});
            } catch (Exception exc) {
                throw new RuntimeException(exc);
            }
            if(inner.exc!=nullthrow inner.exc;
            return inner.result;
        } else {
            return callServerEventImpl(session,eventHandler,input);
        }
    }
    private byte[] callServerEventImpl(IRtXMASessionClient sessionXMA_URI eventHandlerbyte[] inputthrows CommunicationException {
        OutputStream serverIn;
        int code = 0;
        URL url = eventHandler.getHTTP_URI();
        HttpURLConnection conn;
        byte[] buffer = null;
        try {
            conn = (HttpURLConnectionurl.openConnection();
            if(conn instanceof HttpsURLConnection) {
                ((HttpsURLConnection)conn).setHostnameVerifier();
            }
            conn.setDoOutput(true);
            conn.setRequestMethod("POST"); //$NON-NLS-1$
            sendCookies(session,url,conn);
            conn.setRequestProperty.,"application/octet-stream"); //$NON-NLS-1$
            conn.setRequestProperty.,"application/octet-stream"); //$NON-NLS-1$
            serverIn = conn.getOutputStream();
        } catch (IOException exc) {
            .log(.,"error calling '"+url.toString()+"' at the server:"exc); //$NON-NLS-1$
            throw new ConnectException("error calling '"+url.toString()+"' at the server:",exc);
        }
        try {
            serverIn.write(input);
            serverIn.close();
            code = conn.getResponseCode();
            buffer = this.readOutput(conn);
            readCookies(session,url,conn);
            return buffer;
        } catch (CommunicationException ce) {
            if(code!=0) .log(.,"http returncode: {0}",Integer.toString(code)); //$NON-NLS-1$
            .log(."error calling '"+url.toString()+"' at the server:"ce); //$NON-NLS-1$
            throw ce;
        } catch (Exception ex) {
            if(code!=0) .log(.,"http returncode: {0}",Integer.toString(code)); //$NON-NLS-1$
            .log(.,"error calling '"+url.toString()+"' at the server:"ex); //$NON-NLS-1$
            if(code<500) throw new ConnectException("error calling '"+url.toString()+"' at the server:",ex);
            else throw new ServerException("error calling '"+url.toString()+"' at the server:",ex);
        }
    }


    
get server output into a buffer

Parameters:
conn connection to read from
Returns:
byte[] server output
Throws:
ServerException content lenght errro
IOException for read erros
    private byte[] readOutputHttpURLConnection conn ) throws IOException {
        InputStream serverOut = null;
        byte[] buffer         = null;
        try{
            serverOut = conn.getInputStream();
            int len   = conn.getContentLength();
            int read = 0;
            int all  = 0;
            if(len>-1) {
                buffer = new byte[len];
                while(read>-1&&all<len) {
                    read = serverOut.read(bufferalllen-all );
                    if(read>-1) all+=read;
                }
                if(read<0) {
                    throw new ServerException("Server reported contentLength "+len+" but send only "+all+" bytes of data");
                }
                return buffer;
            } else {
                // if no content length was send, use default size and grow dynamically
                List bufferList = null;
                final int defLen = 1024*8;
                int lastLength = 0;
                bufferList = new ArrayList();
                for(;read>-1;all+=lastLength) {
                    buffer = new byte[defLen];
                    for(lastLength=0;read>-1&&lastLength<defLen;) {
                        read = serverOut.read(bufferlastLengthdefLen-lastLength );
                        if(read>-1) lastLength+=read;
                    }
                    bufferList.add(buffer);
                }
                byte [] result = new byte[all];
                for(int i=0;i<bufferList.size()-1;i++) {
                    System.arraycopy(bufferList.get(i),0,result,i*defLen,defLen);
                }
                System.arraycopy(bufferList.get(bufferList.size()-1),0,result,(bufferList.size()-1)*defLen,lastLength);
                return result;
            }
        } finally {
            if(serverOut!=nullserverOut.close();
        }
    }

    
Get the used port of the url. If no port is defined in the url, the default port of the protocol is returned.
    int getPort(URL url) {
        int port = url.getPort();
        if(port==-1) { port = url.getDefaultPort(); }
        return port;
    }

    
Returns all cookies which are stored for the given url.
    public Cookie[] getCookies(URL url) {
        Cookie[] cookies = .getCookies();
        if(cookies!=null&&cookies.length>0) {
            cookies = .match(url.getHost(),getPort(url),url.getPath(),"https".equals(url.getProtocol()),cookies);
        }
        return cookies;
    }

    
Takes the cookies from the httpState which match the given url and creates the corresponsing cookie-header on the given connection.
    private void sendCookies(IRtXMASessionClient sessionURL url,HttpURLConnection conn) {
        Cookie[] cookies = getCookies(url);
        if(cookies!=null&&cookies.length>0) {
            String cookieHeader = .formatCookies(cookies);
            conn.setRequestProperty(.,cookieHeader);
            if(session!=null && session.getId()==null) { // server side http session was established before client side session was created
                for(int j=0;j<cookies.length;j++) {
                    if("JSESSIONID".equals(cookies[j].getName())) {
                        session.setId(cookies[j].getName()+"="+cookies[j].getValue());
                    }
                }
            }
        }
    }

    
Parses the cookies from the given connection and stores them in httpState. Invalid cookies are ignored and logged.
    private void readCookies(IRtXMASessionClient sessionURL url,HttpURLConnection conn) {
        String headerName="";
        for(int i=1;headerName!=null;i++) {
            headerName = conn.getHeaderFieldKey(i);
            if(..equals(headerName)) {
                try {
                    Cookie[] cookies = .parse(url.getHost(),getPort(url),url.getPath(),"https".equals(url.getProtocol()),conn.getHeaderField(i));
                    if(cookies!=null) {
                        for(int j=0;j<cookies.length;j++) {
                            try {
                                .validate(url.getHost(),getPort(url),url.getPath(),"https".equals(url.getProtocol()),cookies[j]);
                                .addCookie(cookies[j]);
                                if(session!=null && "JSESSIONID".equals(cookies[j].getName())) {
                                    session.setId(cookies[j].getName()+"="+cookies[j].getValue());
                                }
                            } catch (MalformedCookieException e) {
                                .log(.,"cookie rejected: \""+.formatCookie(cookies[j])+"\". "+e.getMessage());
                            }
                        }
                    }
                } catch (MalformedCookieException e) {
                    .log(.,"Invalid cookie header: \""+conn.getHeaderField(i)+"\". "+e.getMessage());
                }
            }
        }
    }
New to GrepCode? Check out our FAQ X