src/share/jaxws_classes/com/sun/xml/internal/ws/transport/http/client/HttpClientTransport.java

changeset 0
373ffda63c9a
child 637
9c07ef4934dd
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/share/jaxws_classes/com/sun/xml/internal/ws/transport/http/client/HttpClientTransport.java	Wed Apr 27 01:27:09 2016 +0800
     1.3 @@ -0,0 +1,358 @@
     1.4 +/*
     1.5 + * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package com.sun.xml.internal.ws.transport.http.client;
    1.30 +
    1.31 +import com.sun.xml.internal.ws.api.EndpointAddress;
    1.32 +import com.sun.xml.internal.ws.api.message.Packet;
    1.33 +import com.sun.xml.internal.ws.client.BindingProviderProperties;
    1.34 +import static com.sun.xml.internal.ws.client.BindingProviderProperties.*;
    1.35 +import com.sun.xml.internal.ws.client.ClientTransportException;
    1.36 +import com.sun.xml.internal.ws.resources.ClientMessages;
    1.37 +import com.sun.xml.internal.ws.transport.Headers;
    1.38 +import com.sun.xml.internal.ws.developer.JAXWSProperties;
    1.39 +import com.sun.istack.internal.Nullable;
    1.40 +import com.sun.istack.internal.NotNull;
    1.41 +
    1.42 +import javax.net.ssl.SSLSocketFactory;
    1.43 +import javax.net.ssl.HttpsURLConnection;
    1.44 +import javax.net.ssl.HostnameVerifier;
    1.45 +import javax.net.ssl.SSLSession;
    1.46 +import javax.xml.bind.JAXBContext;
    1.47 +import javax.xml.bind.JAXBException;
    1.48 +import javax.xml.ws.WebServiceException;
    1.49 +import javax.xml.ws.handler.MessageContext;
    1.50 +import java.io.FilterInputStream;
    1.51 +import java.io.FilterOutputStream;
    1.52 +import java.io.IOException;
    1.53 +import java.io.InputStream;
    1.54 +import java.io.OutputStream;
    1.55 +import java.net.HttpURLConnection;
    1.56 +import java.util.List;
    1.57 +import java.util.Map;
    1.58 +import java.util.zip.GZIPOutputStream;
    1.59 +import java.util.zip.GZIPInputStream;
    1.60 +
    1.61 +/**
    1.62 + *
    1.63 + * @author WS Development Team
    1.64 + */
    1.65 +public class HttpClientTransport {
    1.66 +
    1.67 +    private static final byte[] THROW_AWAY_BUFFER = new byte[8192];
    1.68 +
    1.69 +    // Need to use JAXB first to register DatatypeConverter
    1.70 +    static {
    1.71 +        try {
    1.72 +            JAXBContext.newInstance().createUnmarshaller();
    1.73 +        } catch(JAXBException je) {
    1.74 +            // Nothing much can be done. Intentionally left empty
    1.75 +        }
    1.76 +    }
    1.77 +
    1.78 +    /*package*/ int statusCode;
    1.79 +    /*package*/ String statusMessage;
    1.80 +    /*package*/ int contentLength;
    1.81 +    private final Map<String, List<String>> reqHeaders;
    1.82 +    private Map<String, List<String>> respHeaders = null;
    1.83 +
    1.84 +    private OutputStream outputStream;
    1.85 +    private boolean https;
    1.86 +    private HttpURLConnection httpConnection = null;
    1.87 +    private final EndpointAddress endpoint;
    1.88 +    private final Packet context;
    1.89 +    private final Integer chunkSize;
    1.90 +
    1.91 +
    1.92 +    public HttpClientTransport(@NotNull Packet packet, @NotNull Map<String,List<String>> reqHeaders) {
    1.93 +        endpoint = packet.endpointAddress;
    1.94 +        context = packet;
    1.95 +        this.reqHeaders = reqHeaders;
    1.96 +        chunkSize = (Integer)context.invocationProperties.get(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE);
    1.97 +    }
    1.98 +
    1.99 +    /*
   1.100 +     * Prepare the stream for HTTP request
   1.101 +     */
   1.102 +    OutputStream getOutput() {
   1.103 +        try {
   1.104 +            createHttpConnection();
   1.105 +            // for "GET" request no need to get outputStream
   1.106 +            if (requiresOutputStream()) {
   1.107 +                outputStream = httpConnection.getOutputStream();
   1.108 +                if (chunkSize != null) {
   1.109 +                    outputStream = new WSChunkedOuputStream(outputStream, chunkSize);
   1.110 +                }
   1.111 +                List<String> contentEncoding = reqHeaders.get("Content-Encoding");
   1.112 +                // TODO need to find out correct encoding based on q value - RFC 2616
   1.113 +                if (contentEncoding != null && contentEncoding.get(0).contains("gzip")) {
   1.114 +                    outputStream = new GZIPOutputStream(outputStream);
   1.115 +                }
   1.116 +            }
   1.117 +            httpConnection.connect();
   1.118 +        } catch (Exception ex) {
   1.119 +            throw new ClientTransportException(
   1.120 +                ClientMessages.localizableHTTP_CLIENT_FAILED(ex),ex);
   1.121 +        }
   1.122 +
   1.123 +        return outputStream;
   1.124 +    }
   1.125 +
   1.126 +    void closeOutput() throws IOException {
   1.127 +        if (outputStream != null) {
   1.128 +            outputStream.close();
   1.129 +            outputStream = null;
   1.130 +        }
   1.131 +    }
   1.132 +
   1.133 +    /*
   1.134 +     * Get the response from HTTP connection and prepare the input stream for response
   1.135 +     */
   1.136 +    @Nullable InputStream getInput() {
   1.137 +        // response processing
   1.138 +
   1.139 +        InputStream in;
   1.140 +        try {
   1.141 +            in = readResponse();
   1.142 +            if (in != null) {
   1.143 +                String contentEncoding = httpConnection.getContentEncoding();
   1.144 +                if (contentEncoding != null && contentEncoding.contains("gzip")) {
   1.145 +                    in = new GZIPInputStream(in);
   1.146 +                }
   1.147 +            }
   1.148 +        } catch (IOException e) {
   1.149 +            throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage), e);
   1.150 +        }
   1.151 +        return in;
   1.152 +    }
   1.153 +
   1.154 +    public Map<String, List<String>> getHeaders() {
   1.155 +        if (respHeaders != null) {
   1.156 +            return respHeaders;
   1.157 +        }
   1.158 +        respHeaders = new Headers();
   1.159 +        respHeaders.putAll(httpConnection.getHeaderFields());
   1.160 +        return respHeaders;
   1.161 +    }
   1.162 +
   1.163 +    protected @Nullable InputStream readResponse() {
   1.164 +        InputStream is;
   1.165 +        try {
   1.166 +            is = httpConnection.getInputStream();
   1.167 +        } catch(IOException ioe) {
   1.168 +            is = httpConnection.getErrorStream();
   1.169 +        }
   1.170 +        if (is == null) {
   1.171 +            return is;
   1.172 +        }
   1.173 +        // Since StreamMessage doesn't read </s:Body></s:Envelope>, there
   1.174 +        // are some bytes left in the InputStream. This confuses JDK and may
   1.175 +        // not reuse underlying sockets. Hopefully JDK fixes it in its code !
   1.176 +        final InputStream temp = is;
   1.177 +        return new FilterInputStream(temp) {
   1.178 +            // Workaround for "SJSXP XMLStreamReader.next() closes stream".
   1.179 +            // So it doesn't read from the closed stream
   1.180 +            boolean closed;
   1.181 +            @Override
   1.182 +            public void close() throws IOException {
   1.183 +                if (!closed) {
   1.184 +                    closed = true;
   1.185 +                    while(temp.read(THROW_AWAY_BUFFER) != -1);
   1.186 +                    super.close();
   1.187 +                }
   1.188 +            }
   1.189 +        };
   1.190 +    }
   1.191 +
   1.192 +    protected void readResponseCodeAndMessage() {
   1.193 +        try {
   1.194 +            statusCode = httpConnection.getResponseCode();
   1.195 +            statusMessage = httpConnection.getResponseMessage();
   1.196 +            contentLength = httpConnection.getContentLength();
   1.197 +        } catch(IOException ioe) {
   1.198 +            throw new WebServiceException(ioe);
   1.199 +        }
   1.200 +    }
   1.201 +
   1.202 +    protected HttpURLConnection openConnection(Packet packet) {
   1.203 +        // default do nothing
   1.204 +        return null;
   1.205 +    }
   1.206 +
   1.207 +    protected boolean checkHTTPS(HttpURLConnection connection) {
   1.208 +        if (connection instanceof HttpsURLConnection) {
   1.209 +
   1.210 +            // TODO The above property needs to be removed in future version as the semantics of this property are not preoperly defined.
   1.211 +            // One should use JAXWSProperties.HOSTNAME_VERIFIER to control the behavior
   1.212 +
   1.213 +            // does the client want client hostname verification by the service
   1.214 +            String verificationProperty =
   1.215 +                (String) context.invocationProperties.get(HOSTNAME_VERIFICATION_PROPERTY);
   1.216 +            if (verificationProperty != null) {
   1.217 +                if (verificationProperty.equalsIgnoreCase("true")) {
   1.218 +                    ((HttpsURLConnection) connection).setHostnameVerifier(new HttpClientVerifier());
   1.219 +                }
   1.220 +            }
   1.221 +
   1.222 +            // Set application's HostNameVerifier for this connection
   1.223 +            HostnameVerifier verifier =
   1.224 +                (HostnameVerifier) context.invocationProperties.get(JAXWSProperties.HOSTNAME_VERIFIER);
   1.225 +            if (verifier != null) {
   1.226 +                ((HttpsURLConnection) connection).setHostnameVerifier(verifier);
   1.227 +            }
   1.228 +
   1.229 +            // Set application's SocketFactory for this connection
   1.230 +            SSLSocketFactory sslSocketFactory =
   1.231 +                (SSLSocketFactory) context.invocationProperties.get(JAXWSProperties.SSL_SOCKET_FACTORY);
   1.232 +            if (sslSocketFactory != null) {
   1.233 +                ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
   1.234 +            }
   1.235 +
   1.236 +            return true;
   1.237 +        }
   1.238 +        return false;
   1.239 +    }
   1.240 +
   1.241 +    private void createHttpConnection() throws IOException {
   1.242 +        httpConnection = openConnection(context);
   1.243 +
   1.244 +        if (httpConnection == null)
   1.245 +                httpConnection = (HttpURLConnection) endpoint.openConnection();
   1.246 +
   1.247 +        String scheme = endpoint.getURI().getScheme();
   1.248 +        if (scheme.equals("https")) {
   1.249 +            https = true;
   1.250 +        }
   1.251 +        if (checkHTTPS(httpConnection))
   1.252 +                https = true;
   1.253 +
   1.254 +        // allow interaction with the web page - user may have to supply
   1.255 +        // username, password id web page is accessed from web browser
   1.256 +        httpConnection.setAllowUserInteraction(true);
   1.257 +
   1.258 +        // enable input, output streams
   1.259 +        httpConnection.setDoOutput(true);
   1.260 +        httpConnection.setDoInput(true);
   1.261 +
   1.262 +        String requestMethod = (String) context.invocationProperties.get(MessageContext.HTTP_REQUEST_METHOD);
   1.263 +        String method = (requestMethod != null) ? requestMethod : "POST";
   1.264 +        httpConnection.setRequestMethod(method);
   1.265 +
   1.266 +        //this code or something similiar needs t be moved elsewhere for error checking
   1.267 +        /*if (context.invocationProperties.get(BindingProviderProperties.BINDING_ID_PROPERTY).equals(HTTPBinding.HTTP_BINDING)){
   1.268 +            method = (requestMethod != null)?requestMethod:method;
   1.269 +        } else if
   1.270 +            (context.invocationProperties.get(BindingProviderProperties.BINDING_ID_PROPERTY).equals(SOAPBinding.SOAP12HTTP_BINDING) &&
   1.271 +            "GET".equalsIgnoreCase(requestMethod)) {
   1.272 +        }
   1.273 +       */
   1.274 +
   1.275 +        Integer reqTimeout = (Integer)context.invocationProperties.get(BindingProviderProperties.REQUEST_TIMEOUT);
   1.276 +        if (reqTimeout != null) {
   1.277 +            httpConnection.setReadTimeout(reqTimeout);
   1.278 +        }
   1.279 +
   1.280 +        Integer connectTimeout = (Integer)context.invocationProperties.get(JAXWSProperties.CONNECT_TIMEOUT);
   1.281 +        if (connectTimeout != null) {
   1.282 +            httpConnection.setConnectTimeout(connectTimeout);
   1.283 +        }
   1.284 +
   1.285 +        Integer chunkSize = (Integer)context.invocationProperties.get(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE);
   1.286 +        if (chunkSize != null) {
   1.287 +            httpConnection.setChunkedStreamingMode(chunkSize);
   1.288 +        }
   1.289 +
   1.290 +        // set the properties on HttpURLConnection
   1.291 +        for (Map.Entry<String, List<String>> entry : reqHeaders.entrySet()) {
   1.292 +            if ("Content-Length".equals(entry.getKey())) continue;
   1.293 +                for(String value : entry.getValue()) {
   1.294 +                    httpConnection.addRequestProperty(entry.getKey(), value);
   1.295 +                }
   1.296 +        }
   1.297 +    }
   1.298 +
   1.299 +    boolean isSecure() {
   1.300 +        return https;
   1.301 +    }
   1.302 +
   1.303 +    protected void setStatusCode(int statusCode) {
   1.304 +        this.statusCode = statusCode;
   1.305 +    }
   1.306 +
   1.307 +    private boolean requiresOutputStream() {
   1.308 +        return !(httpConnection.getRequestMethod().equalsIgnoreCase("GET") ||
   1.309 +                httpConnection.getRequestMethod().equalsIgnoreCase("HEAD") ||
   1.310 +                httpConnection.getRequestMethod().equalsIgnoreCase("DELETE"));
   1.311 +    }
   1.312 +
   1.313 +    @Nullable String getContentType() {
   1.314 +        return httpConnection.getContentType();
   1.315 +    }
   1.316 +
   1.317 +    public int getContentLength() {
   1.318 +        return httpConnection.getContentLength();
   1.319 +    }
   1.320 +
   1.321 +    // overide default SSL HttpClientVerifier to always return true
   1.322 +    // effectively overiding Hostname client verification when using SSL
   1.323 +    private static class HttpClientVerifier implements HostnameVerifier {
   1.324 +        public boolean verify(String s, SSLSession sslSession) {
   1.325 +            return true;
   1.326 +        }
   1.327 +    }
   1.328 +
   1.329 +    private static class LocalhostHttpClientVerifier implements HostnameVerifier {
   1.330 +        public boolean verify(String s, SSLSession sslSession) {
   1.331 +            return "localhost".equalsIgnoreCase(s) || "127.0.0.1".equals(s);
   1.332 +        }
   1.333 +    }
   1.334 +
   1.335 +    /**
   1.336 +     * HttpURLConnection.getOuputStream() returns sun.net.www.http.ChunkedOuputStream in chunked
   1.337 +     * streaming mode. If you call ChunkedOuputStream.write(byte[20MB], int, int), then the whole data
   1.338 +     * is kept in memory. This wraps the ChunkedOuputStream so that it writes only small
   1.339 +     * chunks.
   1.340 +     */
   1.341 +    private static final class WSChunkedOuputStream extends FilterOutputStream {
   1.342 +        final int chunkSize;
   1.343 +
   1.344 +        WSChunkedOuputStream(OutputStream actual, int chunkSize) {
   1.345 +            super(actual);
   1.346 +            this.chunkSize = chunkSize;
   1.347 +        }
   1.348 +
   1.349 +        @Override
   1.350 +        public void write(byte b[], int off, int len) throws IOException {
   1.351 +            while(len > 0) {
   1.352 +                int sent = (len > chunkSize) ? chunkSize : len;
   1.353 +                out.write(b, off, sent);        // don't use super.write() as it writes byte-by-byte
   1.354 +                len -= sent;
   1.355 +                off += sent;
   1.356 +            }
   1.357 +        }
   1.358 +
   1.359 +    }
   1.360 +
   1.361 +}

mercurial