Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * #%L
   * =====================================================
   *   _____                _     ____  _   _       _   _
   *  |_   _|_ __ _   _ ___| |_  / __ \| | | | ___ | | | |
   *    | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
   *    | | | |  | |_| \__ \ |_| | (_| |  _  |\__ \|  _  |
   *    |_| |_|   \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
   *                             \____/
  * 
  * =====================================================
  * 
  * Hochschule Hannover
  * (University of Applied Sciences and Arts, Hannover)
  * Faculty IV, Dept. of Computer Science
  * Ricklinger Stadtweg 118, 30459 Hannover, Germany
  * 
  * Email: trust@f4-i.fh-hannover.de
  * Website: http://trust.f4.hs-hannover.de/
  * 
  * This file is part of ifmapj, version 2.0.0, implemented by the Trust@HsH
  * research group at the Hochschule Hannover.
  * %%
  * Copyright (C) 2010 - 2014 Trust@HsH
  * %%
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  *      http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * #L%
  */
 package de.hshannover.f4.trust.ifmapj.channel;
 
 import java.net.URL;
 
 
 import util.Base64;
Template-method pattern for CommunicationHandler implementations. The method doRequest(java.io.InputStream) is used as template, all methods defined abstract in this class need to be implemented by a subclass.

Author(s):
aw
 
 abstract class AbstractCommunicationHandler implements CommunicationHandler {
 
 	private final SSLSocketFactory mSocketFactory;
 	private SSLSocket mSocket;
 	private final String mAuthHeaderValue;
 	private final boolean mBasicAuth;
 	private final String mPath;
 	private final URL mUrl;
 	private final int mPort;
 	private boolean mGzip;
 	private final int mInitialConnectionTimeout;
 
 			SSLSocketFactory sslSocketFactory,
 			HostnameVerifier verifierint initialConnectionTimeoutthrows InitializationException {
 
 		if (url == null) {
 			throw new NullPointerException("url is null");
 		}
 
 		if (sslSocketFactory == null) {
 			throw new NullPointerException("sslSocketFactory is null");
 		}
 
 		if (verifier == null) {
 			throw new NullPointerException("verifier is null");
 		}
 
 		try {
 			 = new URL(url);
catch (MalformedURLException e) {
			throw new InitializationException("Malformed URL ["
e.getMessage() + "]");
		}
		// fix up the path in case non is given
		 = .getPath().length() == 0 ? "/" : .getPath();
		// set the port to an appropriate value
		 = .getPort() == -1 ? .getDefaultPort() : .getPort();
		// check whether we use basicauth
		 = !(user == null || pass == null);
		// if we do, prepare the Authorization header value
		if () {
			 = "Basic " + Base64.encodeToString((user + ":" + pass).getBytes(), false);
else {
		}
		 = sslSocketFactory;
		 = verifier;
		 = initialConnectionTimeout;
	}
	/*
	 * Template method.
	 *
	 * (non-Javadoc)
	 * @see de.fhhannover.inform.trust.ifmapj.channel.CommunicationHandler#doRequest(java.io.InputStream)
	 */
	public final InputStream doRequest(InputStream httpBodythrows CommunicationException {
		InputStream reply = null;
		try {
			if (usesGzip()) {
				httpBody = compressInputStream(httpBody);
			}
			if (usesBasicAuth()) {
			}
			reply = doActualRequest(httpBody);
			if (replyIsGzipped()) {
				reply = new GZIPInputStream(reply);
			}
			return reply;
catch (IOException e) {
		}
	}
	private void writeHostLine() throws IOException {
		addHeader("Host"getUrl().getHost() + ":" + getPort());
	}
	private void writeContentTypeHeaders() throws IOException {
		addHeader("Accept-Type""application/soap+xml");
		addHeader("Content-Type""application/soap+xml");
	}
	private void writeGzipHeaders() throws IOException {
		addHeader("Accept-Encoding""gzip");
		addHeader("Content-Encoding""gzip");
	}
	private void writeAuthHeader() throws IOException {
		addHeader("Authorization"getAuthHeaderValue());
	}
	private void writeContentLengthHeader(int lengththrows IOException {
		addHeader("Content-Length""" + length);
	}
	public void setGzip(boolean gzip) {
		 = gzip;
	}
	public boolean usesGzip() {
		return ;
	}
	protected SSLSocket getSocket() throws IOException {
		if ( == null) {
			try {
catch (CommunicationException e) {
				throw new IOException(e.getMessage());
			}
		}
		return ;
	}

Before we allocate a new socket, try to delete the old one. closeTcpConnection() needs to be a nop for non-opened connections.

Returns:
Throws:
java.io.IOException
	private SSLSocket getNewSocket() throws IOException {
		String host = getUrl().getHost();
		int port = getPort();
		Socket socketConnection = new Socket();
		InetSocketAddress mapServerAddress = new InetSocketAddress(hostport);
		socketConnection.connect(mapServerAddress);
		SSLSocket ret = (SSLSocket.createSocket(socketConnectionhostporttrue);
		ret.setTcpNoDelay(true);
		// Check if all is good... Will throw IOException if we don't
		// like the other end...
			throw new IOException("Hostname Verification failed! "
"Did you set ifmapj.communication.verifypeerhost?");
		}
		return ret;
	}
	}
	private boolean usesBasicAuth() {
		return ;
	}
	private String getPath() {
		return ;
	}
	protected URL getUrl() {
		return ;
	}
	protected int getPort() {
		return ;
	}

Subclasses should set up sockets and stuff here.

	protected abstract void prepareCommunication() throws IOException;

Subclasses should create the POST requests or already write something to the server.

Parameters:
path
Throws:
java.io.IOException
	protected abstract void createPostRequest(String paththrows IOException;

Subclasses should add headers or send them to the other server already.

Parameters:
key
value
Throws:
java.io.IOException
	protected abstract void addHeader(String keyString valuethrows IOException;

Indicates that now headers will follow anymore

	protected abstract void finishHeaders() throws IOException;


Do the actual httpRequest. Return a java.io.InputStream instance representing the content of the HTTP body.

Parameters:
in
Returns:
	protected abstract InputStream doActualRequest(InputStream inthrows
Returns whether the last doActualRequest() invocation lead returned a gzip compressed stream.

Returns:
Throws:
java.io.IOException
	protected abstract boolean replyIsGzipped() throws IOException;


Do whatever has to be done for cleaning up a TCP connection.
	protected abstract void closeTcpConnectionImpl() throws IOException;
	/* (non-Javadoc)
	 * @see de.fhhannover.inform.trust.ifmapj.channel.CommunicationHandler#closeTcpConnection()
	 */
	public final void closeTcpConnection() throws CommunicationException {
		IOException tmpException = null;
		try {
catch (IOException e) {
			tmpException = e;
finally {
			try {
				if ( != null) {
				}
catch (IOException e) {
				tmpException = e;
finally {
				 = null;
			}
		}
		if (tmpException != null) {
			throw new CommunicationException(tmpException);
		}
	}

Use gzip to compress the input stream. We do copying here, but I'm not sure whether there is a way around it anyway, because we need to know the number of bytes to send out, before we can start sending them. (no chunked encoding)

Parameters:
is
Returns:
Throws:
java.io.IOException if something goes wrong while working on the java.io.InputStream instances.
		int next = -1;
		OutputStream os = new GZIPOutputStream(baos);
		while ((next = is.read()) >= 0) {
			os.write(next);
		}
		baos.close();
		os.close();
		is.close();
		return new ByteArrayInputStream(baos.toByteArray());
	}
New to GrepCode? Check out our FAQ X