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 java.util.Set;
 
 
 
This class implements low level transport on http transport using suns UrlConnection implementation.

Author(s):
s2877, s3595
Version:
$Id: HTTPTransport.java 10965 2013-08-22 11:23:48Z dschwarz $
 
 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();
 
     private HashMap<StringStringredirectCache = new HashMap<StringString>();
     
     {
         = 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(.cookiePolicyClass);
        =CookiePolicy.getDefaultSpec();
    }

    
logs the proxy settings at the given level.
    public void logProxyInfo(LogLevel level) {
        StringBuffer result = new StringBuffer();
        String proxyHost = System.getProperty("http.proxyHost");
        if(proxyHost!=null) {
            result.append("http proxy is: "+proxyHost);
            String proxyPort = System.getProperty("http.proxyPort");
            if(proxyPort!=null) {
                result.append(":"+proxyPort);
            }
            .log(level,result.toString());
        } else {
            .log(level,"no http proxy used");
        }
        result = new StringBuffer();
        proxyHost = System.getProperty("https.proxyHost");
        if(proxyHost!=null) {
            result.append("https proxy is: "+proxyHost);
            String proxyPort = System.getProperty("https.proxyPort");
            if(proxyPort!=null) {
                result.append(":"+proxyPort);
            }
            .log(level,result.toString());
        } else {
            .log(level,"no https proxy used");
        }
        String nonProxyHosts = System.getProperty("http.nonProxyHosts");
        if(nonProxyHosts!=null) {
            .log(level,"no proxy used for: "+nonProxyHosts);
        }
    }

    
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);
        }
    }
    /* (non-Javadoc)
     * @see at.spardat.xma.boot.transport.Transport#getRedirection(at.spardat.xma.boot.transport.XMA_URI)
     */
    @Override
    public XMA_URI getRedirection(XMA_URI resource) {
        String resourceHostApp = resource.getHostApp();
        String translated = .get(resourceHostApp);
        if (translated != null) {
            String newUrl = resource.toString().replace(resourceHostApptranslated);
            try {
                return new XMA_URI(newUrl);
            } catch (MalformedURLException e) {
                .info("Can't translate URL: " + newUrl + ": " + e.toString());
            }
        }
        return null;
    }
    
    private Object callRedirectAware(XMA_URI resourceRedirectCallback callbackthrows CommunicationException {
        Set<URLredirectLoopPreventionSet = new HashSet<URL>();
        
        URL url = resource.getHTTP_URI();
        String initialResourceHostApp = resource.getHostApp();
        
        do {
            XMA_URI redirectedResource = getRedirection(resource);
            if (redirectedResource != null) {
                url = redirectedResource.getHTTP_URI();
                .log(."Using redirect cache: " + resource + " -> " + redirectedResource);
            }
            redirectLoopPreventionSet.add(url);
            try {
                return callback.call(url);
            } catch (RedirectException re) {
                .log(.re.getMessage());
                try {
                    url = new URL(re.getLocation());
                    String resourceHostApp = resource.getHostApp();
                    resource = new XMA_URI(url);
                    
                    String newHostApp = resource.getHostApp();
                    
                    if (!resourceHostApp.equals(newHostApp)) {
                        .put(resourceHostAppnewHostApp);
                        // be aware of multiple redirects
                        .put(initialResourceHostAppnewHostApp);
                        .log(."Adding redirect cache: " + resourceHostApp + " -> " + newHostApp);
                    }
                } catch (MalformedURLException e) {
                    throw new ServerException("Illegal HTTP redirect location: " + re.getLocation(), rere.getReturnCode());
                }
            }
        } while (!redirectLoopPreventionSet.contains(url) && redirectLoopPreventionSet.size() < 5);
        throw new ServerException("HTTP redirect loop detected at " + url);        
    }
    
    public Result getResourceImpl(final IRtXMASessionClient sessionXMA_URI resourcefinal long modifiedSincefinal String etagthrows CommunicationException {
        RedirectCallback callback = new RedirectCallback() {
            public Object call(URL urlthrows CommunicationException {
                return getResourceImpl(sessionurlmodifiedSinceetag);
            }
        };
        
        return (ResultcallRedirectAware(resourcecallback);
    }
    
    private Result getResourceImpl(IRtXMASessionClient sessionURL urllong modifiedSinceString etagthrows CommunicationException {
        /* locals ---------------------------------- */
            Result result = new Result();
            int    code   = 0;
            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==. || code==.) {
                String location = conn.getHeaderField(.);
                throw new RedirectException("redirect received from " + url.toString() + " to " + locationcodelocation);
            } 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 (RedirectException re) {
            throw re;
        } 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;
    }
    public byte[] callServerEvent(final IRtXMASessionClient session,final XMA_URI eventHandler,final byte[] inputthrows CommunicationException {
        return callServerEvent(sessioneventHandlerinputfalse);
    }
    /* (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[] inputfinal boolean handleRedirectthrows 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,inputhandleRedirect);
                    } 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,inputhandleRedirect);
        }
    }
    private byte[] callServerEventImpl(final IRtXMASessionClient sessionXMA_URI eventHandlerfinal byte[] inputboolean handleRedirectthrows CommunicationException {
        if (handleRedirect) {
            RedirectCallback callback = new RedirectCallback() {
                public Object call(URL urlthrows CommunicationException {
                    return callServerEventImpl(sessionurlinputtrue);
                }
            };
            return (byte[]) callRedirectAware(eventHandlercallback);
        } else {
            return callServerEventImpl(sessioneventHandler.getHTTP_URI(), inputfalse);
        }
    }
    
    private byte[] callServerEventImpl(IRtXMASessionClient sessionURL urlbyte[] inputboolean handleRedirectthrows CommunicationException {
        OutputStream serverIn;
        int code = 0;
        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();
            
            // if requested, we allow redirect also on POST requests, therewith violating RFC 2616 section 10.3!
            if (handleRedirect && code==. || code==.) {
                String location = conn.getHeaderField(.);
                throw new RedirectException("redirect received from " + url.toString() + " to " + locationcodelocation);
            }
            
            buffer = this.readOutput(conn);
            readCookies(session,url,conn);
            return buffer;
        } catch (RedirectException re) {
            throw re;
        } 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
java.io.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<byte[]> bufferList = null;
                final int defLen = 1024*8;
                int lastLength = 0;
                bufferList = new ArrayList<byte[]>();
                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;
    }

    
Return the httpState for the session. To support multiple sessions override this method.
		return ;  
	}

Returns all cookies which are stored for the given url.

Deprecated:
Use getCookies(URL url, IRtXMASessionClient session) instead.
    public Cookie[] getCookies(URL url) {
    	return getCookies(urlnull);
    }

Returns all cookies which are stored for the given url and session.
    public Cookie[] getCookies(URL urlIRtXMASessionClient session) {
        Cookie[] cookies = getHttpState(session).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,session);
        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]);
                                getHttpState(session).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