/*
 * Copyright, 2009 Koichi Takahashi. All Rights Reserved.
 * 
 * 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.
 */
package com.nec.exi.editor;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

/**
 * @author Koichi Takahashi
 */
public final class Util {

	public byte[] inputStreamToByteArray(InputStream inputStream) throws Exception {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ReadableByteChannel srcChannel = Channels.newChannel(inputStream);
		WritableByteChannel destChannel = Channels.newChannel(outputStream);
		ByteBuffer buffer = null;
        byte[] byteArray = null;
		try {
            buffer = ByteBuffer.allocateDirect(1024);
            while (true) {
                buffer.clear();
                if (srcChannel.read(buffer) < 0) {
                	byteArray = outputStream.toByteArray();
                	break;
                }
                buffer.flip();
                destChannel.write(buffer);
            }
        } finally {
        	if(inputStream.markSupported()){
        		inputStream.reset();
        	}else{
                srcChannel.close();        		
        	}
            destChannel.close();
        }
		return byteArray;
	}
	
	public void inputStreamToOutputStream(InputStream inputStream, OutputStream outputStream) throws Exception {
        ReadableByteChannel srcChannel = Channels.newChannel(inputStream);
        WritableByteChannel destChannel = Channels.newChannel(outputStream);
        try {
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
            while (true) {
                buffer.clear();
                if (srcChannel.read(buffer) < 0) {
                    break;
                }
                buffer.flip();
                destChannel.write(buffer);
            }
        } finally {
        	if(inputStream.markSupported()){
        		inputStream.reset();
        	}else{
                srcChannel.close();        		
        	}
            destChannel.close();
        }
	}
	
}
