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

src-main.org.awakefw.file.http.InputStreamBodyForEngine Maven / Gradle / Ivy

/*
 * This file is part of Awake File. 
 * Awake file: Easy file upload & download over HTTP with Java.                                    
 * Copyright (C) 2013,  KawanSoft SAS
 * (http://www.kawansoft.com). All rights reserved.                                
 *                                                                               
 * Awake File is free software; you can redistribute it and/or                 
 * modify it under the terms of the GNU Lesser General Public                    
 * License as published by the Free Software Foundation; either                  
 * version 2.1 of the License, or (at your option) any later version.            
 *                                                                               
 * Awake File is distributed in the hope that it will be useful,               
 * but WITHOUT ANY WARRANTY; without even the implied warranty of                
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU             
 * Lesser General Public License for more details.                               
 *                                                                               
 * You should have received a copy of the GNU Lesser General Public              
 * License along with this library; if not, write to the Free Software           
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
 * 02110-1301  USA
 *
 * Any modifications to this file must keep this entire header
 * intact.
 */
package org.awakefw.file.http;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.awakefw.commons.api.client.AwakeProgressManager;
import org.awakefw.commons.api.client.HttpProtocolParameters;
import org.awakefw.file.api.util.DefaultParms;
import org.awakefw.file.http.exception.HttpTransferInterruptedException;
import org.awakefw.file.util.AwakeClientLogger;

/**
 * @author Nicolas de Pomereu
 * 
 *         this class externalize InputStreamBody only to provide a sendData()
 *         implementation. Each write on the output stream set the progress
 *         indicator for the file transfer engine.
 */
public class InputStreamBodyForEngine extends InputStreamBody {
    /** The debug flag */
    public boolean DEBUG = false;

    /** The http protocol parameters */
    private HttpProtocolParameters httpProtocolParameters;

    /** The calling/owner thread */
    private AwakeProgressManager awakeProgressManager = null;

    /** The file we wan to upload */
    private long filesLength = 0;

    /**
     * InputStreamBody Constructor.
     * 
     * @param in
     *            the input stream to post
     * @param mimeType
     *            the mime Type
     * @param httpProtocolParameters
     *            the http protocol parameters
     * @param awakeProgressManager
     *            the AwakeProgressManager instance
     * 
     * @throws FileNotFoundException
     *             if the file is not a normal file or if it is not
     *             readable.
     */
    public InputStreamBodyForEngine(InputStream in, String mimeType,
	    HttpProtocolParameters httpProtocolParameters,
	    AwakeProgressManager awakeProgressManager)
	    throws FileNotFoundException {
	super(in, mimeType);

	if (in == null) {
	    throw new IllegalArgumentException("in can not be null!");
	}

	this.httpProtocolParameters = httpProtocolParameters;
	this.awakeProgressManager = awakeProgressManager;

    }

    /**
     * @return true is there is an owner AND it's interrupted
     */
    private boolean isAwakeProgressManagerInterrupted() {
	if (awakeProgressManager == null) {
	    return false;
	}

	return awakeProgressManager.isCancelled();
    }

    /**
     * Set the owner current value for progression bar
     * 
     * @param current
     */
    private void addOneToAwakeProgressManager() {
	if (awakeProgressManager != null) {
	    int current = awakeProgressManager.getProgress();
	    current++;

	    if (current < HttpTransfer.MAXIMUM_PROGRESS_100) {
		awakeProgressManager.setProgress(current);
	    }
	}
    }

    /**
     * Write the data in "source" to the specified stream.
     * 
     * @param out
     *            The output stream.
     * @throws IOException
     *             if an IO problem occurs.
     * @see org.apache.commons.httpclient.methods.multipart.Part#sendData(OutputStream)
     */

    @Override
    public void writeTo(final OutputStream out) throws IOException {
	debug("send data!");
	debug("filesLength: " + filesLength);

	addOneToAwakeProgressManager();

	// For ProgressMonitor
	int tempLen = 0;

	int uploadBufferSize = DefaultParms.DEFAULT_UPLOAD_BUFFER_SIZE;
	if (httpProtocolParameters != null) {
	    uploadBufferSize = httpProtocolParameters.getUploadBufferSize();
	}

	byte[] tmp = new byte[uploadBufferSize]; // Keep a huge
						 // size,
						 // otherwise
						 // it's very
						 // slow

	InputStream instream = super.getInputStream();

	try {
	    int len;

	    if (awakeProgressManager != null) {
		this.filesLength = awakeProgressManager.getLengthToTransfer();
	    }

	    while ((len = instream.read(tmp)) >= 0) {
		tempLen += len;

		if (filesLength > 0
			&& tempLen > filesLength
				/ HttpTransfer.MAXIMUM_PROGRESS_100) {
		    tempLen = 0;
		    try {
			Thread.sleep(10); // TODO: adjust sleep time
			// depending on fileIn length
		    } catch (InterruptedException e) {
			e.printStackTrace();
		    }
		    addOneToAwakeProgressManager(); // For ProgressMonitor
		    // progress bar

		    if (isAwakeProgressManagerInterrupted()) {
			throw new HttpTransferInterruptedException();
		    }
		}

		// debug("len: " + len);

		out.write(tmp, 0, len);
	    }
	} finally {
	    // we're done with the stream, close it
	    // instream.close();
	    IOUtils.closeQuietly(instream);
	}
    }

    /**
     * debug tool
     */
    private void debug(String s) {
	if (DEBUG) {
	    AwakeClientLogger.log(s);
	}
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy