/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.appserv.management.helper;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.sun.appserv.management.base.UploadDownloadMgr;

/**
	Miscellaneous helper routines specific to AMX.  These routines
	may be moved prior to the release of 9.0
	@since AppServer 9.0
 */
public class Misc
{
	private	Misc()	{}
	
	/**
		Upload a file to the server and return an opaque identifier which server-side
		code may use to identify and use the file.  Uploading a file is typically done
		prior to deploying it, but may be done for other purposes.
		
		@param mgr  an instance of UploadDownloadMgr,
			obtained via getDomainRoot().getUploadDownloadMgr()
		@param theFile	the file to upload
		@return an upload ID
	 */
		public static Object
	uploadFile(
		final UploadDownloadMgr	mgr,
		final File	theFile  )
		throws IOException
	{
		final FileInputStream	input	= new FileInputStream( theFile );
		final long		length	= input.available();
		final Object	uploadID	= mgr.initiateUpload( theFile.getName(), length );
			
		try
		{
			final int	chunkSize	= 256 * 1024;
			long remaining	= length;
			while ( remaining != 0 )
			{
				final int	actual	= remaining < chunkSize ? (int)remaining : chunkSize;
				
				final byte[]	bytes	= new byte[ actual ];
				final int	num	= input.read( bytes );
				if ( num != actual )
				{
					throw new IOException();
				}

				mgr.uploadBytes( uploadID, bytes );
				remaining	-= actual;
			}
		}
		finally
		{
			input.close();
		}
		
		return( uploadID );
	}
}


