com.nervousync.utils.RequestUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nervousync-utils Show documentation
Show all versions of nervousync-utils Show documentation
Java Utils collections, development by Nervousync Studio (NSYC)
/*
* Licensed to the Nervousync Studio (NSYC) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nervousync.utils;
import com.nervousync.commons.beans.servlet.request.RequestAttribute;
import com.nervousync.commons.beans.servlet.request.RequestInfo;
import com.nervousync.commons.beans.servlet.response.HttpResponseContent;
import com.nervousync.commons.core.Globals;
import com.nervousync.commons.core.RegexGlobals;
import com.nervousync.commons.http.cookie.CookieInfo;
import com.nervousync.commons.http.entity.HttpEntity;
import com.nervousync.commons.http.header.SimpleHeader;
import com.nervousync.commons.http.proxy.ProxyInfo;
import com.nervousync.enumerations.web.HttpMethodOption;
import javax.jws.WebService;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.handler.HandlerResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Request Utils
*
* @author Steven Wee [email protected]
* @version $Revision: 1.0 $ $Date: Jan 13, 2010 11:23:13 AM $
*/
public final class RequestUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtils.class);
private static final String STOWED_REQUEST_ATTRIBS = "ssl.redirect.attrib.stowed";
private static final int DEFAULT_TIME_OUT = 5;
private static final String HTTP_METHOD_GET = "GET";
private static final String HTTP_METHOD_POST = "POST";
private static final String HTTP_METHOD_PUT = "PUT";
private static final String HTTP_METHOD_TRACE = "TRACE";
private static final String HTTP_METHOD_HEAD = "HEAD";
private static final String HTTP_METHOD_DELETE = "DELETE";
private static final String HTTP_METHOD_OPTIONS = "OPTIONS";
static {
try {
RequestUtils.initTrustManager("changeit");
} catch (Exception e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Initialize trust manager error! ", e);
}
}
}
private RequestUtils() {
}
public static String resolveDomain(String domainName) {
try {
return InetAddress.getByName(domainName).getHostAddress();
} catch (UnknownHostException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Resolve domain error! ", e);
}
}
return null;
}
public static String convertIPv4ToCompatibleIPv6(String ipAddress) {
if (StringUtils.matches(ipAddress, RegexGlobals.IPV4_REGEX)) {
return "::" + ipAddress;
}
return null;
}
public static String convertIPv4ToIPv6(String ipAddress) {
return convertIPv4ToIPv6(ipAddress, true);
}
public static String convertIPv4ToIPv6(String ipAddress, boolean collapse) {
if (StringUtils.matches(ipAddress, RegexGlobals.IPV4_REGEX)) {
String[] splitAddr = StringUtils.tokenizeToStringArray(ipAddress, ".");
StringBuilder stringBuilder = null;
if (collapse) {
stringBuilder = new StringBuilder(":");
} else {
stringBuilder = new StringBuilder("0000:0000:0000:0000:0000:0000");
}
int index = 0;
for (String addrItem : splitAddr) {
if (index % 2 == 0) {
stringBuilder.append(":");
}
stringBuilder.append(Integer.toHexString(Integer.parseInt(addrItem)));
index++;
}
return stringBuilder.toString().toUpperCase();
}
return null;
}
public static byte[] convertIPv4ToBytes(String ipAddress) {
if (StringUtils.matches(ipAddress, RegexGlobals.IPV4_REGEX)) {
String[] splitAddr = StringUtils.tokenizeToStringArray(ipAddress, ".");
byte[] addrBytes = new byte[4];
addrBytes[0] = (byte)Integer.parseInt(splitAddr[0]);
addrBytes[1] = (byte)Integer.parseInt(splitAddr[1]);
addrBytes[2] = (byte)Integer.parseInt(splitAddr[2]);
addrBytes[3] = (byte)Integer.parseInt(splitAddr[3]);
return addrBytes;
}
return null;
}
public static BigInteger convertIPtoBigInteger(String ipAddress) {
if (StringUtils.matches(ipAddress, RegexGlobals.IPV4_REGEX)) {
return RequestUtils.convertIPv4ToBigInteger(ipAddress);
} else {
return RequestUtils.convertIPv6ToBigInteger(ipAddress);
}
}
public static BigInteger convertIPv4ToBigInteger(String ipAddress) {
if (StringUtils.matches(ipAddress, RegexGlobals.IPV4_REGEX)) {
String[] splitAddr = StringUtils.tokenizeToStringArray(ipAddress, ".");
if (splitAddr.length == 4) {
BigInteger bigInteger = BigInteger.ZERO;
for (int i = 0 ; i < splitAddr.length ; i++) {
BigInteger currentInteger = BigInteger.valueOf(Long.parseLong(splitAddr[3 - i])).shiftLeft(i * 8);
bigInteger = bigInteger.add(currentInteger);
}
return bigInteger;
}
}
return null;
}
public static BigInteger convertIPv6ToBigInteger(String ipAddress) {
if (StringUtils.matches(ipAddress, RegexGlobals.IPV6_REGEX)) {
ipAddress = appendIgnore(ipAddress);
String[] splitAddr = StringUtils.tokenizeToStringArray(ipAddress, ":");
if (splitAddr.length == 8) {
BigInteger bigInteger = BigInteger.ZERO;
int index = 0;
for (String split : splitAddr) {
BigInteger currentInteger = null;
if (StringUtils.matches(split, RegexGlobals.IPV4_REGEX)) {
currentInteger = convertIPv4ToBigInteger(split);
} else {
currentInteger = BigInteger.valueOf(Long.valueOf(split, 16));
}
bigInteger = bigInteger.add(currentInteger.shiftLeft(16 * (splitAddr.length - index - 1)));
index++;
}
return bigInteger;
}
}
return null;
}
public static String convertBigIntegerToIPv4(BigInteger bigInteger) {
String ipv4Addr = "";
BigInteger ff = BigInteger.valueOf(0xFFL);
for (int i = 0 ; i < 4 ; i++) {
ipv4Addr = bigInteger.and(ff).toString() + "." + ipv4Addr;
bigInteger = bigInteger.shiftRight(8);
}
return ipv4Addr.substring(0, ipv4Addr.length() - 1);
}
public static String convertBigIntegerToIPv6Addr(BigInteger bigInteger) {
String ipv6Addr = "";
BigInteger ff = BigInteger.valueOf(0xFFFFL);
for (int i = 0 ; i < 8 ; i++) {
ipv6Addr = bigInteger.and(ff).toString(16) + ":" + ipv6Addr;
bigInteger = bigInteger.shiftRight(16);
}
return ipv6Addr.substring(0, ipv6Addr.length() - 1).replaceFirst(RegexGlobals.IPV6_COMPRESS_REGEX, "::");
}
public static T generateSOAPClient(String endPointUrl, Class serviceEndpointInterface, HandlerResolver handlerResolver)
throws MalformedURLException {
if (endPointUrl == null || endPointUrl.length() == 0 || serviceEndpointInterface == null
|| !serviceEndpointInterface.isAnnotationPresent(WebService.class)) {
return null;
}
URL wsdlDocumentLocation = new URL(endPointUrl);
WebService webService = serviceEndpointInterface.getAnnotation(WebService.class);
String namespaceURI = webService.targetNamespace();
String serviceName = webService.serviceName();
String portName = webService.portName();
if (namespaceURI == null || namespaceURI.length() == 0) {
String packageName = serviceEndpointInterface.getPackage().getName();
String[] packageNames = StringUtils.tokenizeToStringArray(packageName, ".");
namespaceURI = wsdlDocumentLocation.getProtocol() + "://";
for (int i = packageNames.length - 1 ; i >= 0 ; i--) {
namespaceURI += (packageNames[i] + ".");
}
namespaceURI = namespaceURI.substring(0, namespaceURI.length() - 1) + "/";
}
if (serviceName == null || serviceName.length() == 0) {
serviceName = serviceEndpointInterface.getSimpleName() + "Service";
}
if (portName == null || portName.length() == 0) {
portName = serviceEndpointInterface.getSimpleName() + "Port";
}
Service service = Service.create(wsdlDocumentLocation, new QName(namespaceURI, serviceName));
if (handlerResolver != null) {
service.setHandlerResolver(handlerResolver);
}
return service.getPort(new QName(namespaceURI, portName), serviceEndpointInterface);
}
public static long retrieveContentLength(String requestUrl) throws UnsupportedEncodingException {
HttpResponseContent httpResponseContent = sendRequest(requestUrl, HttpMethodOption.HEAD);
long contentLength = Globals.DEFAULT_VALUE_LONG;
if (httpResponseContent.getStatusCode() == HttpURLConnection.HTTP_OK) {
contentLength = httpResponseContent.getContentLength();
}
return contentLength;
}
public static HttpResponseContent sendRequest(String requestUrl)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, int beginPosition, int endPosition)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, null, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, int beginPosition, int endPosition, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, timeOut,
beginPosition, endPosition, null, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data)
throws UnsupportedEncodingException {
return sendRequest(requestUrl, data, null, HttpMethodOption.DEFAULT, Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT);
}
public static HttpResponseContent sendRequest(String requestUrl, String data, int beginPosition, int endPosition)
throws UnsupportedEncodingException {
return sendRequest(requestUrl, data, null, HttpMethodOption.DEFAULT, beginPosition, endPosition);
}
public static HttpResponseContent sendRequest(String requestUrl, List headers)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, List headers, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, List headers, int beginPosition, int endPosition)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, headers, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, List headers, int beginPosition, int endPosition, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, timeOut,
beginPosition, endPosition, headers, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, List headers)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, List headers, int timeOut)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, List headers,
int beginPosition, int endPosition)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, List headers,
int beginPosition, int endPosition, int timeOut)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, timeOut,
beginPosition, endPosition, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
int beginPosition, int endPosition)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
int beginPosition, int endPosition, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.DEFAULT, requestUrl, timeOut,
beginPosition, endPosition, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, HttpMethodOption httpMethodOption)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, HttpMethodOption httpMethodOption, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, HttpMethodOption httpMethodOption,
int beginPosition, int endPosition)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, null, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, HttpMethodOption httpMethodOption,
int beginPosition, int endPosition, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, timeOut,
beginPosition, endPosition, null, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, HttpMethodOption httpMethodOption)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data,
HttpMethodOption httpMethodOption, int beginPosition, int endPosition)
throws UnsupportedEncodingException {
return sendRequest(requestUrl, data, null, httpMethodOption, beginPosition, endPosition);
}
public static HttpResponseContent sendRequest(String requestUrl, List headers,
HttpMethodOption httpMethodOption)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, List headers,
HttpMethodOption httpMethodOption, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, List headers,
HttpMethodOption httpMethodOption, int beginPosition, int endPosition)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, headers, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, List headers,
HttpMethodOption httpMethodOption, int beginPosition, int endPosition, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(HttpMethodOption.GET, requestUrl, timeOut,
beginPosition, endPosition, headers, null, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, List headers,
HttpMethodOption httpMethodOption)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, List headers,
HttpMethodOption httpMethodOption, int timeOut)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, List headers,
HttpMethodOption httpMethodOption, int beginPosition, int endPosition)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, String data, List headers,
HttpMethodOption httpMethodOption, int beginPosition, int endPosition, int timeOut)
throws UnsupportedEncodingException {
Map parameters = (data == null ? null : getRequestParametersFromString(data));
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, timeOut,
beginPosition, endPosition, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
HttpMethodOption httpMethodOption)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
HttpMethodOption httpMethodOption, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
List headers, HttpMethodOption httpMethodOption)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
List headers, HttpMethodOption httpMethodOption, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
HttpMethodOption httpMethodOption, int beginPosition, int endPosition)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
HttpMethodOption httpMethodOption, int beginPosition, int endPosition, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
beginPosition, endPosition, null, parameters, null));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
Map uploadParam, List headers, HttpMethodOption httpMethodOption)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, Globals.DEFAULT_VALUE_INT,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, parameters, uploadParam));
}
public static HttpResponseContent sendRequest(String requestUrl, Map parameters,
Map uploadParam, List headers,
HttpMethodOption httpMethodOption, int timeOut)
throws UnsupportedEncodingException {
return sendRequest(new RequestInfo(httpMethodOption, requestUrl, timeOut,
Globals.DEFAULT_VALUE_INT, Globals.DEFAULT_VALUE_INT, headers, parameters, uploadParam));
}
public static HttpResponseContent sendRequest(RequestInfo requestInfo) {
return RequestUtils.sendRequest(requestInfo, null);
}
public static HttpResponseContent sendRequest(RequestInfo requestInfo, List cookieInfos) {
HttpURLConnection urlConnection = null;
OutputStream outputStream = null;
try {
urlConnection = openConnection(requestInfo, cookieInfos);
int timeout = requestInfo.getTimeOut() == Globals.DEFAULT_VALUE_INT ? DEFAULT_TIME_OUT : requestInfo.getTimeOut();
urlConnection.setConnectTimeout(timeout * 1000);
urlConnection.setReadTimeout(timeout * 1000);
HttpEntity httpEntity = generateEntity(requestInfo.getParameters(), requestInfo.getUploadParam());
urlConnection.setRequestProperty("Content-Type",
httpEntity.generateContentType(requestInfo.getCharset(), requestInfo.getHttpMethodOption()));
if (HttpMethodOption.POST.equals(requestInfo.getHttpMethodOption())
|| HttpMethodOption.PUT.equals(requestInfo.getHttpMethodOption())) {
outputStream = urlConnection.getOutputStream();
httpEntity.writeData(requestInfo.getCharset(), outputStream);
}
String redirectUrl = urlConnection.getHeaderField("Location");
if (redirectUrl != null) {
if (cookieInfos == null) {
cookieInfos = new ArrayList();
}
Iterator>> iterator = urlConnection.getHeaderFields().entrySet().iterator();
while (iterator.hasNext()) {
Entry> entry = iterator.next();
if ("Set-Cookie".equals(entry.getKey())) {
for (String cookieValue : entry.getValue()) {
cookieInfos.add(new CookieInfo(cookieValue));
}
}
}
return RequestUtils.sendRequest(new RequestInfo(redirectUrl, requestInfo), cookieInfos);
}
return new HttpResponseContent(urlConnection);
} catch (Exception e) {
if (RequestUtils.LOGGER.isDebugEnabled()) {
RequestUtils.LOGGER.debug("Send Request ERROR: ", e);
}
return null;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
public static void initTrustManager(String passPhrase) throws Exception {
NervousyncX509TrustManager.init(passPhrase);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[0], new TrustManager[]{NervousyncX509TrustManager.getInstance()}, new SecureRandom());
SSLContext.setDefault(sslContext);
}
public static void addCustomCert(String certPath, String passPhrase) throws Exception {
NervousyncX509TrustManager.getInstance().addCustomCert(new TrustedCert(certPath, passPhrase));
}
public static void removeCustomCert(String certPath, String passPhrase) throws Exception {
NervousyncX509TrustManager.getInstance().removeCustomCert(certPath);
}
/**
* Creates query String from request body parameters
*
* @param request The request that will supply parameters
* @return Query string corresponding to that request parameters
*/
public static String getRequestParameters(HttpServletRequest request) {
// set the ALGORIGTHM as defined for the application
//ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM);
Map m = request.getParameterMap();
return createQueryStringFromMap(m, "&").toString();
}
/**
* Creates map of request parameters from given query string. Values are
* decoded.
*
* @param queryString Query string to get parameters from
* @return Map with request parameters mapped to their values
*/
public static Map getRequestParametersFromString(String queryString) {
return getRequestParametersFromString(queryString, true);
}
/**
* Creates map of request parameters from given query string
*
* @param queryString Query string to get parameters from
* @param decodeValues Whether to decode values (which are URL-encoded)
* @return Map with request parameters mapped to their values
*/
public static Map getRequestParametersFromString(String queryString,
boolean decodeValues) {
HashMap parameterMap = new HashMap();
if (queryString == null) {
return parameterMap;
}
for (int k = 0; k < queryString.length();) {
int ampPos = queryString.indexOf('&', k);
if (ampPos == -1) {
ampPos = queryString.length();
}
String parameter = queryString.substring(k, ampPos);
int equalsSignPos = parameter.indexOf('=');
if (equalsSignPos != -1) {
String key = parameter.substring(0, equalsSignPos);
String value = parameter.substring(equalsSignPos + 1).trim();
try {
key = URLDecoder.decode(key, Globals.DEFAULT_ENCODING);
if (decodeValues) {
value = URLDecoder.decode(value, Globals.DEFAULT_ENCODING);
}
parameterMap.put(key, mergeValues(parameterMap.get(key), value));
} catch (UnsupportedEncodingException e) {
// do nothing
}
}
k = ampPos + 1;
}
return parameterMap;
}
/**
* Creates a map of request parameters from URI.
*
* @param uri An address to extract request parameters from
* @return map of request parameters
*/
public static Map getRequestParametersFromUri(String uri) {
if (ObjectUtils.isNull(uri) || uri.trim().length() == 0) {
return new HashMap();
}
int qSignPos = uri.indexOf('?');
if (qSignPos == -1) {
return new HashMap();
}
return RequestUtils.getRequestParametersFromString(uri.substring(qSignPos + 1));
}
/**
* Extracts a base address from URI (that is, part of address before '?')
*
* @param uri An address to extract base address from
* @return base address
*/
public static String getBaseFromUri(String uri) {
if (ObjectUtils.isNull(uri) || uri.trim().length() == 0) {
return "";
}
int qSignPos = uri.indexOf('?');
if (qSignPos == -1) {
return uri;
}
return uri.substring(0, qSignPos);
}
/**
* Builds a query string from a given map of parameters
*
* @param m A map of parameters
* @param ampersand String to use for ampersands (e.g. "&" or "&")
* @param encode Whether or not to encode non-ASCII characters
* @return query string (with no leading "?")
*/
public static StringBuffer createQueryStringFromMap(Map m, String ampersand, boolean encode) {
StringBuffer result = new StringBuffer("");
Set> entrySet = m.entrySet();
Iterator> entrySetIterator = entrySet.iterator();
while (entrySetIterator.hasNext()) {
Entry entry = entrySetIterator.next();
String[] values = entry.getValue();
if (values == null) {
append(entry.getKey(), "", result, ampersand, encode);
} else {
for (int i = 0; i < values.length; i++) {
append(entry.getKey(), values[i], result, ampersand, encode);
}
}
}
return result;
}
/**
* Builds a query string from a given map of parameters
*
* @param m A map of parameters
* @param ampersand String to use for ampersands (e.g. "&" or "&")
* @return query string (with no leading "?")
*/
public static StringBuffer createQueryStringFromMap(Map m, String ampersand) {
return createQueryStringFromMap(m, ampersand, true);
}
/**
* Append parameters to base URI.
*
* @param uri An address that is base for adding params
* @param params A map of parameters
* @return resulting URI
*/
public static String appendParams(String uri, Map params) {
String delim = (uri.indexOf('?') == -1) ? "?" : "&";
return uri + delim + RequestUtils.createQueryStringFromMap(params, "&").toString();
}
/**
* Stores request attributes in session
*
* @param aRequest the current request
*/
public static void stowRequestAttributes(HttpServletRequest aRequest) {
if (aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null) {
return;
}
aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, RequestAttribute.newInstance(aRequest));
}
/**
* Returns request attributes from session to request
*
* @param aRequest a request to which saved in session parameters will be
* assigned
*/
public static void reclaimRequestAttributes(HttpServletRequest aRequest) {
RequestAttribute requestAttribute =
(RequestAttribute)aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS);
if (requestAttribute == null) {
return;
}
Map attributeMap = requestAttribute.getAttributeMap();
Iterator itr = attributeMap.keySet().iterator();
while (itr.hasNext()) {
String name = (String) itr.next();
aRequest.setAttribute(name, attributeMap.get(name));
}
aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
}
/**
* Convenience method to get the application's URL based on request
* variables.
*
* @param request the request from which the URL is calculated
* @return Application URL
*/
public static String getAppURL(HttpServletRequest request) {
StringBuffer requestUrl = new StringBuffer();
int port = request.getServerPort();
if (port < 0) {
port = 80; // Work around java.net.URL bug
}
String scheme = request.getScheme();
requestUrl.append(scheme);
requestUrl.append("://");
requestUrl.append(request.getServerName());
if ((scheme.equalsIgnoreCase("http") && (port != 80))
|| (scheme.equalsIgnoreCase("https") && (port != 443))) {
requestUrl.append(':');
requestUrl.append(port);
}
requestUrl.append(request.getContextPath());
return requestUrl.toString();
}
public static boolean isUserInRole(Iterator