Java tutorial
/* * Digital Assets Management * ========================= * * Copyright 2009 Fundacin Iavante * * Authors: * Francisco Jos Moreno Llorca <packo@assamita.net> * Francisco Jess Gonzlez Mata <chuspb@gmail.com> * Juan Antonio Guzmn Hidalgo <juan@guzmanhidalgo.com> * Daniel de la Cuesta Navarrete <cues7a@gmail.com> * Manuel Jos Cobo Fernndez <ranrrias@gmail.com> * * Licensed under the EUPL, Version 1.1 or as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * */ package org.iavante.sling.gad.administration.impl; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthPolicy; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * General GET, POST abstracts operations. */ public abstract class AbstractHttpOperation extends TestCase { /** Default log. */ private final Logger log = LoggerFactory.getLogger(getClass()); /** Default content types. */ public static final String CONTENT_TYPE_HTML = "text/html"; public static final String CONTENT_TYPE_XML = "application/xml"; public static final String CONTENT_TYPE_PLAIN = "text/plain"; public static final String CONTENT_TYPE_JSON = "application/json"; public static final String CONTENT_TYPE_JS = "application/javascript"; public static final String CONTENT_TYPE_CSS = "text/css"; /** Means "don't care about Content-Type" in getContent(...) methods. */ public static final String CONTENT_TYPE_DONTCARE = "*"; /** Http base url. */ public static String HTTP_BASE_URL = removeEndingSlash( System.getProperty("launchpad.http.server.url", "http://localhost:8888")); public AbstractHttpOperation() { if (log.isInfoEnabled()) log.info("HTTP_BASE_URL: " + HTTP_BASE_URL); // assume http and webdav are on the same host + port URL url = null; try { url = new URL(HTTP_BASE_URL); } catch (MalformedURLException mfe) { // MalformedURLException doesn't tell us the URL by default // throw new IOException("MalformedURLException: " + HTTP_BASE_URL); mfe.printStackTrace(); } } /** Execute a POST request and check status */ protected Header[] assertAuthenticatedPostStatus(Credentials creds, String url, List<String> expectedStatusCode, List<NameValuePair> postParams, String assertMessage) throws IOException { Header[] headers = null; URL baseUrl = new URL(HTTP_BASE_URL); List authPrefs = new ArrayList(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getState().setCredentials(AuthScope.ANY, creds); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); PostMethod post = new PostMethod(url); post.setFollowRedirects(false); post.setDoAuthentication(true); try { if (postParams != null) { final NameValuePair[] nvp = {}; post.setRequestBody(postParams.toArray(nvp)); } final int status = httpClient.executeMethod(post); if (!expectedStatusCode.contains("" + status)) { log.error("ResponseCode: " + status + " isn't in " + expectedStatusCode.toString()); throw new IOException("ResponseCode: " + status + " isn't in " + expectedStatusCode.toString()); } headers = post.getResponseHeaders(); } finally { post.releaseConnection(); } return headers; } /** Execute a POST request and check status */ protected Header[] assertAuthenticatedPostMultipartStatus(Credentials creds, String url, List<String> expectedStatusCode, Part[] parts, String assertMessage) throws IOException { Header[] headers = null; URL baseUrl = new URL(HTTP_BASE_URL); List authPrefs = new ArrayList(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getState().setCredentials(AuthScope.ANY, creds); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); PostMethod post = new PostMethod(url); post.setFollowRedirects(false); post.setDoAuthentication(true); try { if (parts != null) { post.setRequestEntity((RequestEntity) new MultipartRequestEntity(parts, post.getParams())); } final int status = httpClient.executeMethod(post); if (!expectedStatusCode.contains("" + status)) { log.error("ResponseCode: " + status + " isn't in " + expectedStatusCode.toString()); throw new IOException("ResponseCode: " + status + " isn't in " + expectedStatusCode.toString()); } headers = post.getResponseHeaders(); } finally { post.releaseConnection(); } return headers; } /** * Retrieve the contents of given URL and assert its content type * * @param expectedContentType * use CONTENT_TYPE_DONTCARE if must not be checked * @throws IOException * @throws HttpException */ protected String getAuthenticatedContent(Credentials creds, String url, String expectedContentType, List<NameValuePair> params, int expectedStatusCode) throws IOException { URL baseUrl = new URL(HTTP_BASE_URL); List authPrefs = new ArrayList(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getState().setCredentials(AuthScope.ANY, creds); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); GetMethod get = new GetMethod(url); try { if (params != null) { final NameValuePair[] nvp = new NameValuePair[0]; get.setQueryString(params.toArray(nvp)); } final int status = httpClient.executeMethod(get); final InputStream is = get.getResponseBodyAsStream(); final StringBuffer content = new StringBuffer(); final String charset = get.getResponseCharSet(); final byte[] buffer = new byte[16384]; int n = 0; while ((n = is.read(buffer, 0, buffer.length)) > 0) { content.append(new String(buffer, 0, n, charset)); } assertEquals("Expected status " + expectedStatusCode + " for " + url + " (content=" + content + ")", expectedStatusCode, status); final Header h = get.getResponseHeader("Content-Type"); if (expectedContentType == null) { if (h != null) { fail("Expected null Content-Type, got " + h.getValue()); } } else if (CONTENT_TYPE_DONTCARE.equals(expectedContentType)) { // no check } else if (h == null) { fail("Expected Content-Type that starts with '" + expectedContentType + " but got no Content-Type header at " + url); } else { assertTrue("Expected Content-Type that starts with '" + expectedContentType + "' for " + url + ", got '" + h.getValue() + "'", h.getValue().startsWith(expectedContentType)); } return content.toString(); } finally { get.releaseConnection(); } } /** * Verify that given URL returns expectedStatusCode * * @throws IOException */ protected void assertAuthenticatedHttpStatus(Credentials creds, String urlString, int expectedStatusCode, String assertMessage) throws IOException { URL baseUrl = new URL(HTTP_BASE_URL); List authPrefs = new ArrayList(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getState().setCredentials(AuthScope.ANY, creds); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); GetMethod getMethod = new GetMethod(urlString); getMethod.setDoAuthentication(true); try { final int status = httpClient.executeMethod(getMethod); if (assertMessage == null) { assertEquals(urlString, expectedStatusCode, status); } else { assertEquals(assertMessage, expectedStatusCode, status); } } finally { getMethod.releaseConnection(); } } /** * Remove ending slash. * @param str * @return */ protected static String removeEndingSlash(String str) { if (str != null && str.endsWith("/")) { return str.substring(0, str.length() - 1); } return str; } }