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

com.daioware.net.http.client.HttpSender Maven / Gradle / Ivy

package com.daioware.net.http.client;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLSocketFactory;

import com.daioware.commons.ProgressNotifier;
import com.daioware.commons.wrapper.WrapperInt;
import com.daioware.commons.wrapper.WrapperString;
import com.daioware.net.http.HttpResponse;
import com.daioware.net.http.items.HttpHeader;
import com.daioware.net.http.request.HttpRequest;
import com.daioware.net.socket.TCPClientSocket;

public class HttpSender {

	public static final int DEFAULT_TIME_OUT_MILLIS=5000;
	
	private HttpRequest request;
	private HttpResponse response;
	private int downloadSpeedInBytes;
	private int uploadSpeedInBytes;
	private ResponseHandler respHandler;
	private ProgressNotifier progressNotifier;
	private File outputFolder;
	private int maxSizeToSaveInMemory;
	
	public HttpSender(HttpRequest request) {
		this(request,512,512);
	}
	
	public HttpSender(HttpRequest request,int downloadSpeedInBytes,int uploadSpeedInBytes) {
		this(request,downloadSpeedInBytes,uploadSpeedInBytes,new File("."));
	}
	
	public HttpSender(HttpRequest request,int downloadSpeedInBytes,int uploadSpeedInBytes,File outputFolder) {
		this(request,downloadSpeedInBytes,uploadSpeedInBytes,outputFolder,true);
	}
	
	public HttpSender(HttpRequest request,int downloadSpeedInBytes,int uploadSpeedInBytes,File outputFolder,boolean saveResponseInMemory) {
		setRequest(request);
		setRespHandler(null);
		setDownloadSpeedInBytes(downloadSpeedInBytes);
		setUploadSpeedInBytes(uploadSpeedInBytes);
		setProgressNotifier(new ProgressNotifier(null));
		setOutputFolder(outputFolder);
		setSaveResponseInMemory(saveResponseInMemory);
	}

	public HttpSender(HttpRequest request,int downloadSpeedInBytes,int uploadSpeedInBytes,File outputFolder,int maxSizeToSaveInMemory) {
		setRequest(request);
		setRespHandler(null);
		setDownloadSpeedInBytes(downloadSpeedInBytes);
		setUploadSpeedInBytes(uploadSpeedInBytes);
		setProgressNotifier(new ProgressNotifier(null));
		setOutputFolder(outputFolder);
		setMaxSizeToSaveInMemory(maxSizeToSaveInMemory);
	}
	
	public boolean isSaveResponseInMemory() {
		return getMaxSizeToSaveInMemory()!=-1;
	}

	public void setSaveResponseInMemory(boolean saveResponseInMemory) {
		setMaxSizeToSaveInMemory(saveResponseInMemory?Integer.MAX_VALUE:-1);
	}

	public int getMaxSizeToSaveInMemory() {
		return maxSizeToSaveInMemory;
	}

	public void setMaxSizeToSaveInMemory(int maxSizeToSaveInMemory) {
		this.maxSizeToSaveInMemory = maxSizeToSaveInMemory;
	}

	public File getOutputFolder() {
		return outputFolder;
	}
	public void setOutputFolder(File outputFolder) {
		this.outputFolder = outputFolder;
	}
	public int getUploadSpeedInBytes() {
		return uploadSpeedInBytes;
	}
	public void setUploadSpeedInBytes(int uploadSpeedInBytes) {
		this.uploadSpeedInBytes = uploadSpeedInBytes;
	}
	public int getDownloadSpeedInBytes() {
		return downloadSpeedInBytes;
	}

	public File getOutputFile() throws UnsupportedEncodingException {
		return new File(outputFolder.getAbsolutePath()+File.separator+getRequest().getFileName());
	}
	
	public void setDownloadSpeedInBytes(int downloadSpeedInBytes) {
		this.downloadSpeedInBytes = downloadSpeedInBytes;
	}

	public HttpRequest getRequest() {
		return request;
	}

	public void setRequest(HttpRequest request) {
		this.request = request;
	}
	
	public ResponseHandler getRespHandler() {
		return respHandler;
	}

	public void setRespHandler(ResponseHandler respHandler) {
		this.respHandler=respHandler==null?EmptyHandler.DEFAULT_INSTANCE:respHandler;
	}
	public ProgressNotifier getProgressNotifier() {
		return progressNotifier;
	}
	public void setProgressNotifier(ProgressNotifier progressNotifier) {
		this.progressNotifier = progressNotifier;
	}
	public HttpResponse send() throws UnknownHostException, IOException, HandlingException{
		return send(DEFAULT_TIME_OUT_MILLIS);
	}
	public HttpResponse send(int timeOutMillis) throws UnknownHostException, IOException, HandlingException {
		HttpRequest request=getRequest();
		TCPClientSocket socket=new TCPClientSocket(request.getHost(),request.getPort(),
				Charset.forName(request.getEncoding()));
		socket.setSoTimeout(timeOutMillis);
		return send(createSocket(timeOutMillis));
	}
	public TCPClientSocket createSocket(int timeOutMillis) throws UnknownHostException, IOException {
		HttpRequest req=getRequest();
		if(req.getUrl().getProtocol().equals("https")){
			SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
			Socket socket=sslsocketfactory.createSocket(req.getHost(),req.getPort());
			socket.setSoTimeout(timeOutMillis);
			return new TCPClientSocket(socket,Charset.forName(req.getEncoding()));
		}
		else {
			TCPClientSocket socket=new TCPClientSocket(request.getHost(),request.getPort(),
					Charset.forName(request.getEncoding()));
			socket.setSoTimeout(timeOutMillis);
			return socket;
		}
	}
	public HttpResponse send(TCPClientSocket socket) throws UnsupportedEncodingException, IOException, HandlingException {
		socket.write(request.getMetadataAsString());
		byte bodyBytes[];
		int length,bytesRead;
		if(request.startReadingBody()) {
			try {
				bodyBytes=new byte[length=getUploadSpeedInBytes()];
				while((bytesRead=request.readBody(bodyBytes, 0, length))>=1) {
					socket.write(bodyBytes, 0, bytesRead);
				}
			}
			finally {
				request.stopReadingBody();
			}
		}
		return parse(socket);		
	}
	protected HttpResponse parse(TCPClientSocket socket) throws IOException, HandlingException {
		List bodyBytes = null;
		List headersBytes=new LinkedList<>();
		int bytesRead,currentIndexToRead,readingHeaderState,maxSizeToSaveInMemory=getMaxSizeToSaveInMemory(),
				currentProgressInBytes=0;
		boolean readHeaders=true,isSaveResponseInMemory=isSaveResponseInMemory();
		byte bytes[]=new byte[getDownloadSpeedInBytes()];
		Integer totalBytesToRead=null;
		Map headers=new HashMap<>();
		byte byteRead;
		WrapperInt status=new WrapperInt();
		WrapperString statusMessage=new WrapperString();
		WrapperString version=new WrapperString();
		HttpResponse httpResponse;
		ProgressNotifier progressNotifier=getProgressNotifier();
		progressNotifier.setCurrentProgress(0);
		try {
			readingHeaderState=0;
			respHandler.open(this);
			do {
				if(socket.getSocket().isClosed()) {
					break;
				}
				bytesRead=socket.readBytes(bytes);
				if(bytesRead==-1 || bytesRead==0) {
					break;
				}
				if(readHeaders) {
					respHandler.handleHeaders(bytes, 0, bytesRead);
					for(currentIndexToRead=0;currentIndexToRead=totalBytesToRead) {
											bodyBytes=new ArrayList<>(totalBytesToRead);
											progressNotifier.setTotalProgress((float) totalBytesToRead.intValue());
											isSaveResponseInMemory=true;										}
										else {
											isSaveResponseInMemory=false;
										}
									}
									else if(isSaveResponseInMemory){
										bodyBytes=new LinkedList<>();
										isSaveResponseInMemory=true;
									}//else isSaveResponseInMemory already false
									readHeaders=false;
									break;
								}
								else {
									readingHeaderState=0;
								}
								break;
						}
						if(!readHeaders) {
							break;
						}
					}
				}
				else {
					currentIndexToRead=0;
				}
				if(!readHeaders) {
					respHandler.handleBody(bytes,currentIndexToRead, bytesRead-currentIndexToRead);
					currentProgressInBytes+=bytesRead-currentIndexToRead;
					progressNotifier.setCurrentProgress(currentProgressInBytes);
					if(isSaveResponseInMemory) {
						for(;currentIndexToRead=1);
			httpResponse=createHttpResponse(headers,bodyBytes,version.value,status.value,statusMessage.value,request);
			setResponse(httpResponse);
			return httpResponse;
		}catch (IOException | HandlingException e) {
			throw e;
		}finally {
			socket.close();
			respHandler.close();
		}
	}
	
	protected HttpResponse createHttpResponse(Map headers, List bodyBytes, String version, 
			Integer status,String statusMessage, HttpRequest r) {
		return new HttpResponse(headers,bodyBytes,version,status,statusMessage,request);
	}
	public HttpResponse getResponse() {
		return response;
	}

	public void setResponse(HttpResponse response) {
		this.response = response;
	}

	protected Integer getTotalBytesToRead(Map headers) {
		HttpHeader header=headers.get("Content-Length");
		return header!=null?Integer.parseInt(header.getValue()):null;
	}
	protected void setMetadata(String string,Map headers,WrapperInt status,
			WrapperString statusMessage,WrapperString version) {
		int i,j;
		String line;
		String lines[]=string.split("\r\n");
		String keyAndValue[];
		String firstLine;
		for(i=1,j=lines.length-1;i




© 2015 - 2025 Weber Informatics LLC | Privacy Policy