package org.jerrymouse.cc.site.web.upload;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PutMethod;
import org.jerrymouse.cc.site.bean.Resource;

public class UploadToGoogle implements Upload {
	private String host = "commoncouldstorage.googlecode.com";
	private String username = "KaiYanNju";
	private String password = "QM7YE6gj9dk7";
	private String path = "/svn/trunk/";

	private String creatFilename(Resource resource) {
		return resource.getOrgType().addSuffix(resource.getFilename());
	}

	public String putResource(Resource resource) {
		String filename = creatFilename(resource);
		PutMethod putMethod = new PutMethod("https://" + host + path + filename);
		ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(
				resource.getOrgBytes());
		putMethod.setRequestEntity(requestEntity);
		HttpClient httpClient = new HttpClient();
		Credentials defaultcreds = new UsernamePasswordCredentials(username,
				password);
		httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
		httpClient.getParams().setAuthenticationPreemptive(true);
		try {
			httpClient.executeMethod(putMethod);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "http://" + host + path + filename;
	}
}
