All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.taskadapter.redmineapi.internal.comm.Communicators Maven / Gradle / Ivy

Go to download

Free open-source Java API for Redmine and Chiliproject bug/task management systems. This project was originally a part of Task Adapter application (http://www.taskadapter.com) and then was open-sourced.

The newest version!
package com.taskadapter.redmineapi.internal.comm;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;

import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.RedmineTransportException;

/**
 * Communicator utilities.
 */
public final class Communicators {
	private static final ContentHandler IDENTITY_HANDLER = new ContentHandler() {
		@Override
		public Object processContent(Object content) throws RedmineException {
			return content;
		}
	};

	private static final ContentHandler TRANSPORT_DECODER = new TransportDecoder();

	private static final ContentHandler CHARACTER_DECODER = new ContentHandler() {
		@Override
		public Reader processContent(BasicHttpResponse content) throws RedmineException {
			final String charset = content.getCharset();
			try {
				return new InputStreamReader(content.getStream(), charset);
			} catch (UnsupportedEncodingException e) {
				throw new RedmineTransportException(
						"Unsupported response charset " + charset, e);
			}
		}
	};
	
	private static final ContentHandler CHAR_CONTENT_READER = compose(
			Communicators::readAll, CHARACTER_DECODER);

	static String readAll(Reader r) throws RedmineException {
		final StringWriter writer = new StringWriter();
		final char[] buffer = new char[4096];
		int readed;
		try {
			while ((readed = r.read(buffer)) > 0) {
				writer.write(buffer, 0, readed);
			}
			r.close();
			writer.close();
			return writer.toString();
		} catch (IOException e) {
			throw new RedmineTransportException(e);
		}
	}

	public static  SimpleCommunicator simplify(
			Communicator communicator, ContentHandler handler) {
		return new BasicSimplifier<>(handler, communicator);
	}

	@SuppressWarnings("unchecked")
	public static  ContentHandler identityHandler() {
		return (ContentHandler) IDENTITY_HANDLER;
	}

	public static ContentHandler contentReader() {
		return CHAR_CONTENT_READER;
	}

	public static  ContentHandler compose(
			ContentHandler cont1, ContentHandler cont2) {
		return new ComposingHandler<>(cont1, cont2);
	}

	public static  Communicator fmap(Communicator comm,
			ContentHandler handler) {
		return new FmapCommunicator<>(handler, comm);
	}

	public static ContentHandler transportDecoder() {
		return TRANSPORT_DECODER;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy