Java tutorial
/* * Copyright 2012-2014 glodon paas All right reserved. This software is the confidential and proprietary information of * glodon paas ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into with glodon paas. */ package com.glodon.paas.document.api; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import net.sf.json.JSONObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.ClientContext; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.BasicHttpContext; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.Before; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import com.glodon.paas.document.api.bean.File; import com.glodon.paas.document.api.exception.ErrorHttpResponseCallException; import com.glodon.paas.document.api.exception.NoHttpResponseException; import com.glodon.paas.document.util.ResourceBundleTestManager; import com.glodon.paas.document.web.util.DocumentObjectMapper; import com.glodon.paas.util.DatabaseTestUtil; import com.glodon.paas.util.UUIDUtil; /** * * @author Administrator 2013-3-28 ?11:02:56 */ public abstract class AbstractDocumentAPITest { private final Logger logger = LoggerFactory.getLogger(AbstractDocumentAPITest.class); public static final ResourceBundleTestManager bundleManager = ResourceBundleTestManager.getInstance(); private static final String KEY_HOST = "document.server.host"; private static final String KEY_PORT = "document.server.port"; private static final String KEY_USER_NAME = "document.user.name"; private static final String KEY_USER_PASSWORD = "document.user.password"; private static final String KEY_ACCESS_PROTOCOL = "document.access.protocol"; protected String host = "127.0.0.1"; protected Integer port = 8080; public String user = "c@c.com"; protected String passwd; protected String accessProtocol = "http"; protected BasicHttpContext localcontext; protected static String prefix = "/document/internal"; protected String token = "Bearer 4c4ad5c2-9790-4d5e-abf6-e8696487d3af"; protected Header oauthorHeader = new BasicHeader("Authorization", token); private Header defaultHeader; protected HttpHost targetHost; protected DefaultHttpClient httpclient; private static DataSource storageDataSource; private static DataSource documentDataSource; private static DataSource accountDataSource; private static ObjectMapper mapper = new DocumentObjectMapper(); { host = bundleManager.getStringValue(KEY_HOST) == null ? host : bundleManager.getStringValue(KEY_HOST); port = bundleManager.getIntValue(KEY_PORT) == null ? port : bundleManager.getIntValue(KEY_PORT); user = bundleManager.getStringValue(KEY_USER_NAME) == null ? user : bundleManager.getStringValue(KEY_USER_NAME); passwd = bundleManager.getStringValue(KEY_USER_PASSWORD); accessProtocol = bundleManager.getStringValue(KEY_ACCESS_PROTOCOL) == null ? accessProtocol : bundleManager.getStringValue(KEY_ACCESS_PROTOCOL); localcontext = new BasicHttpContext(); defaultHeader = new BasicHeader("userId", user); } @BeforeClass public static void init() throws Exception { String databaseHost = "localhost"; storageDataSource = DatabaseTestUtil.createDataSource( "jdbc:mysql://" + databaseHost + "/paas_storage?useUnicode=true&characterEncoding=utf-8", "root", ""); DatabaseTestUtil.executeSqlScript(storageDataSource, "sql/storage_delete_table.sql"); DatabaseTestUtil.executeSqlScript(storageDataSource, "sql/storage_table.sql"); documentDataSource = DatabaseTestUtil.createDataSource( "jdbc:mysql://" + databaseHost + "/paas_document?useUnicode=true&characterEncoding=utf-8", "root", ""); DatabaseTestUtil.executeSqlScript(documentDataSource, "sql/file_table.sql"); DatabaseTestUtil.executeSqlScript(documentDataSource, "sql/project_table.sql"); accountDataSource = DatabaseTestUtil.createDataSource( "jdbc:mysql://" + databaseHost + "/paas_account?useUnicode=true&characterEncoding=utf-8", "root", ""); DatabaseTestUtil.executeSqlScript(accountDataSource, "sql/schema_paas_account_drop.sql"); DatabaseTestUtil.executeSqlScript(accountDataSource, "sql/schema_paas_account_create.sql"); DatabaseTestUtil.executeSqlScript(accountDataSource, "sql/schema_paas_account_data_init.sql"); DatabaseTestUtil.executeSqlScript(accountDataSource, "sql/account_04_add_column.sql"); } @Before public void setUp() { DatabaseTestUtil.executeSqlScript(storageDataSource, "sql/storage_test_data.sql"); DatabaseTestUtil.executeSqlScript(documentDataSource, "sql/file_test_data.sql"); DatabaseTestUtil.executeSqlScript(documentDataSource, "sql/project_test_data.sql"); DatabaseTestUtil.executeSqlScript(accountDataSource, "sql/account_test_init_data.sql"); } protected void initHttpClient() { targetHost = new HttpHost(host, port, accessProtocol); httpclient = new DefaultHttpClient(); setCredentials(host, port, user, passwd); setAuthCache(targetHost, localcontext); } private void setCredentials(String host, int port, String userName, String password) { setCredentials(httpclient, host, port, userName, password); } private void setCredentials(DefaultHttpClient client, String host, int port, String userName, String password) { if (client != null) { AuthScope authScope = new AuthScope(host, port); Credentials credentials = new UsernamePasswordCredentials(userName, password); client.getCredentialsProvider().setCredentials(authScope, credentials); } } private void setAuthCache(HttpHost host, BasicHttpContext context) { AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); if (context == null && localcontext != null) localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); else context.setAttribute(ClientContext.AUTH_CACHE, authCache); } protected void initOAuthHttpClient() { targetHost = new HttpHost(host, port, accessProtocol); httpclient = new DefaultHttpClient(); } protected HttpResponse call(HttpRequestBase method, boolean isBasic) { if (isBasic) { initHttpClient(); } else { initOAuthHttpClient(); } HttpResponse response = null; try { response = httpclient.execute(targetHost, method, localcontext); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { closeHttpClientConnection(); } return response; } protected HttpResponse call(HttpRequestBase method) { return this.call(method, false); } protected String simpleCall(HttpRequestBase method) { ResponseHandler<String> responseHandler = new BasicResponseHandler(); return this.call(method, responseHandler, false); } protected <T> T call(HttpRequestBase method, ResponseHandler<? extends T> responseHandler, boolean isBasic) { if (isBasic) { initHttpClient(); } else { initOAuthHttpClient(); } T response = null; try { response = httpclient.execute(targetHost, method, responseHandler, localcontext); } catch (ClientProtocolException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } catch (Exception e) { logger.error(e.getMessage()); } finally { closeHttpClientConnection(); } return response; } protected <T> T call(HttpRequestBase method, ResponseHandler<? extends T> responseHandler) { return this.call(method, responseHandler, false); } protected <T> T convertString2Obj(String str, Class<T> t) throws IOException { T result = mapper.readValue(str, t); return result; } protected <T> T convertString2Obj(String str, TypeReference<T> t) throws IOException { T result = mapper.readValue(str, t); return result; } private void closeHttpClientConnection() { httpclient.getConnectionManager().shutdown(); } protected File createFile(String id) throws IOException { // create folder id = id + UUIDUtil.getUUIDStr(); String url = "/file/" + id + "?folder&type=path"; HttpPost post = new HttpPost(prefix + url); post.setHeader(defaultHeader); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = this.call(post, responseHandler); return convertString2Obj(response, File.class); } protected void deleteFile(String id) { String url = "/file/" + id + "?purge&type=path"; HttpDelete delete = new HttpDelete(prefix + url); delete.setHeader(defaultHeader); this.call(delete); } protected void deleteFileWithoutPurge(String id) { String url = "/file/" + id + "?type=path"; HttpDelete delete = new HttpDelete(prefix + url); delete.setHeader(defaultHeader); this.call(delete); } private boolean containsTarget(String url) { if (StringUtils.isBlank(url)) return false; if (url.contains(accessProtocol + "://")) return true; return false; } private String detemineTargetUrl(String url) { return containsTarget(url) ? url : prefix + url; } protected HttpGet createGet(String url) { return createGet(url, null); } protected HttpGet createGet(String url, Header header) { HttpGet get = new HttpGet(detemineTargetUrl(url)); get.setHeader(header == null ? this.defaultHeader : header); get.setHeader("accept", "application/json"); return get; } protected HttpPost createPost(String url) { return createPost(url, null); } protected HttpPost createPost(String url, Header header) { HttpPost post = new HttpPost(detemineTargetUrl(url)); post.setHeader(header == null ? this.defaultHeader : header); return post; } protected HttpPut createPut(String url) { return createPut(url, null); } protected HttpPut createPut(String url, Header header) { HttpPut put = new HttpPut(detemineTargetUrl(url)); put.setHeader(header == null ? this.defaultHeader : header); return put; } protected HttpDelete createDelete(String url) { return createDelete(url, null); } protected HttpDelete createDelete(String url, Header header) { HttpDelete delete = new HttpDelete(detemineTargetUrl(url)); delete.setHeader(header == null ? this.defaultHeader : header); return delete; } protected <T> T callRest(HttpRequestBase method, Class<T> t) { return callRest(method, true, t); } private <T> T callRest(HttpRequestBase method, boolean isBasic, Class<T> t) { if (isBasic) { initHttpClient(); } else { initOAuthHttpClient(); } HttpResponse response = null; T result = null; try { response = httpclient.execute(method); checkResponseStatus(response); JSONObject json = JSONObject.fromObject(parseReponseToString(response)); result = (T) json.toBean(json, t); } catch (ClientProtocolException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } catch (Exception e) { logger.error(e.getMessage()); } finally { closeHttpClientConnection(); } return result; } private void checkResponseStatus(HttpResponse response) { if (response == null) { throw new NoHttpResponseException("Response can not be null"); } if (response.getStatusLine().getStatusCode() != 200) { logger.error(parseReponseToString(response)); throw new ErrorHttpResponseCallException("Error http call " + response.getStatusLine().getStatusCode()); } } private String parseReponseToString(HttpResponse response) { InputStream content = null; StringWriter writer = null; try { writer = new StringWriter(); content = response.getEntity().getContent(); IOUtils.copy(content, writer); return writer.toString(); } catch (IllegalStateException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { IOUtils.closeQuietly(content); IOUtils.closeQuietly(writer); } return null; } protected <T> T callGet(String url, Map<String, String> header, Class<T> t) { HttpGet method = createGet(url); setHttpHeaders(method, header); return this.callRest(method, t); } protected <T> T callPost(String url, Map<String, String> header, JSONObject body, Class<T> t) { HttpPost method = createPost(url); setHttpHeaders(method, header); setHttpBody(method, body); return this.callRest(method, t); } protected <T> T callPut(String url, Map<String, String> header, JSONObject body, Class<T> t) { HttpPut method = createPut(url); setHttpHeaders(method, header); setHttpBody(method, body); return this.callRest(method, t); } protected <T> T callDelete(String url, Map<String, String> header, Class<T> t) { HttpDelete method = createDelete(url); setHttpHeaders(method, header); return this.callRest(method, t); } private void setHttpHeaders(HttpRequestBase requestBase, Map<String, String> header) { if (header != null && !header.isEmpty()) { Set<String> keys = header.keySet(); Iterator<String> it = keys.iterator(); while (it.hasNext()) { String key = it.next(); String value = header.get(key); if (requestBase != null) { requestBase.setHeader(key, value); } } } if (!requestBase.containsHeader("Content-type")) { requestBase.setHeader("Content-type", "application/json"); } if (!requestBase.containsHeader("Host")) { requestBase.setHeader("Host", host + ":" + port); } if (!requestBase.containsHeader("Accept")) { requestBase.setHeader("Accept", "application/json"); } } private void setHttpBody(HttpEntityEnclosingRequestBase requestBase, JSONObject body) { if (body != null) { try { StringEntity entity = new StringEntity(body.toString()); entity.setContentType("application/json"); entity.setContentEncoding("UTF-8"); requestBase.setEntity(entity); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); } } } protected File createSimpleProject(String projectName) throws IOException { String url = "/project?asFolder"; HttpPost post = new HttpPost(prefix + url); StringEntity entity = new StringEntity("{\"name\":\"" + projectName + "\"}"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); post.setHeader(defaultHeader); String response = this.simpleCall(post); return convertString2Obj(response, File.class); } protected void deleteProject(String id) { String url = "/project/" + id; HttpDelete delete = new HttpDelete(prefix + url); delete.setHeader(defaultHeader); call(delete); } protected File getFile(String str, String key) throws IOException { if (key == null) { return this.convertString2Obj(str, File.class); } else { Map<String, File> map = this.convertString2Obj(str, new TypeReference<Map<String, File>>() { }); return map.get(key); } } protected List<File> getFiles(String str) throws IOException { Map<String, List<File>> map = this.convertString2Obj(str, new TypeReference<Map<String, List<File>>>() { }); return map.get("items"); } protected String uploadFile(String path) throws IOException { Resource resource = new ClassPathResource("file/testupload.file"); String uploadUrl = path + "?upload&position=0&type=path"; HttpPost post = createPost(uploadUrl); post.setHeader("content-type", "application/octet-stream"); FileEntity entity = new FileEntity(resource.getFile()); post.setEntity(entity); return simpleCall(post); } }