/*
 * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * $Id: IOUtil.java 74237 2014-12-08 14:22:43Z jsupol $
 */

package com.sun.ts.tests.websocket.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.ByteBuffer;

/**
 * A class that works with java.io The patterns that would reappear
 */
public abstract class IOUtil {

	public static final//
	String readFromReader(Reader reader) throws IOException {
		BufferedReader br = new BufferedReader(reader);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = br.readLine()) != null) {
			if (sb.length() != 0)
				sb.append("\n");
			sb.append(line);
		}
		br.close();
		return sb.toString();
	}

	public static final//
	String printStackTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		t.printStackTrace(pw);
		String value = sw.toString();
		pw.close();
		return value;
	}

	public static final//
	String readFromStream(InputStream stream) throws IOException {
		InputStreamReader isr = new InputStreamReader(stream);
		return readFromReader(isr);
	}

	public static final//
	String byteBufferToString(ByteBuffer buffer) {
		byte[] ret = new byte[buffer.remaining()];

		if (buffer.hasArray()) {
			byte[] array = buffer.array();
			System.arraycopy(array, buffer.arrayOffset() + buffer.position(),
					ret, 0, ret.length);
		} else {
			buffer.asReadOnlyBuffer().get(ret);
		}

		return new String(ret);
	}
}
