Example usage for javax.servlet.http HttpServletRequest getHeaderNames

List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getHeaderNames.

Prototype

public Enumeration<String> getHeaderNames();

Source Link

Document

Returns an enumeration of all the header names this request contains.

Usage

From source file:org.wso2.carbon.identity.provider.openid.handlers.OpenIDHandler.java

/**
 * Returns the login page URL. User will be redirected to this URL when they
 * are not authenticated./*w  w  w . j  a  v  a 2s .  c  o m*/
 *
 * @param claimedID
 * @param request
 * @param params
 * @return loginPageUrl
 * @throws IdentityException
 * @throws IOException
 */
private String getLoginPageUrl(String claimedID, HttpServletRequest request, ParameterList params)
        throws IdentityException, IOException {

    /*
     * We are setting the request's openid identifier to the session
     * here.  
     */
    request.getSession().setAttribute(OpenIDConstants.SessionAttribute.OPENID, claimedID);

    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH);
    String selfPath = URLEncoder.encode("/" + FrameworkConstants.OPENID_SERVER, "UTF-8");
    String sessionDataKey = UUIDGenerator.generateUUID();

    //Authentication context keeps data which should be sent to commonAuth endpoint
    AuthenticationRequest authenticationRequest = new AuthenticationRequest();
    authenticationRequest.setRelyingParty(getRelyingParty(request));
    authenticationRequest.setCommonAuthCallerPath(selfPath);
    String username = null;
    String tenantDomain = null;
    if (params.getParameterValue(FrameworkConstants.OPENID_IDENTITY) != null) {
        username = OpenIDUtil.getUserName(params.getParameterValue(FrameworkConstants.OPENID_IDENTITY));
        authenticationRequest.addRequestQueryParam(FrameworkConstants.USERNAME, new String[] { username });
    }
    if (params.getParameterValue(FrameworkConstants.RequestParams.TENANT_DOMAIN) != null) {
        tenantDomain = params.getParameterValue(FrameworkConstants.RequestParams.TENANT_DOMAIN);
        authenticationRequest.setTenantDomain(tenantDomain);
    }

    boolean forceAuthenticate = false;
    if (!claimedID.endsWith("/openid/")) {
        String authenticatedUser = (String) request.getSession()
                .getAttribute(OpenIDConstants.SessionAttribute.AUTHENTICATED_OPENID);
        if (log.isDebugEnabled()) {
            log.debug("claimedID : " + claimedID + ", authenticated user : " + authenticatedUser);
        }
        if (authenticatedUser != null && !"".equals(authenticatedUser.trim())
                && !claimedID.equals(authenticatedUser.trim())) {
            if (log.isDebugEnabled()) {
                log.debug("Overriding previously authenticated OpenID : " + authenticatedUser
                        + " with the OpenID in the current request :" + claimedID
                        + " and setting forceAuthenticate.");
            }
            forceAuthenticate = true;
        }
    }
    authenticationRequest.setForceAuth(forceAuthenticate);
    //Add request headers to authentication request context. ie to cache
    authenticationRequest.setRequestQueryParams(request.getParameterMap());
    for (Enumeration headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
        String headerName = headerNames.nextElement().toString();
        authenticationRequest.addHeader(headerName, request.getHeader(headerName));
    }

    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest);
    FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest);
    StringBuilder queryStringBuilder = new StringBuilder();
    queryStringBuilder.append(commonAuthURL).append("?").append(FrameworkConstants.SESSION_DATA_KEY).append("=")
            .append(sessionDataKey).append("&").append(FrameworkConstants.RequestParams.TYPE).append("=")
            .append(FrameworkConstants.RequestType.CLAIM_TYPE_OPENID);
    // reading the authorization header for request path authentication
    FrameworkUtils.setRequestPathCredentials(request);

    return queryStringBuilder.toString();
}

From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServletUtils.java

protected Map<String, Map<String, String>> getHeadersParams(HttpServletRequest request,
        boolean readFormDataPost) throws IOException {
    Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();

    Map<String, String> reqparams = new HashMap<String, String>();
    Map<String, String> reqheaders = new HashMap<String, String>();
    map.put("params", reqparams);
    map.put("headers", reqheaders);

    if (readFormDataPost) {
        // servlet api <3.0 will return null values for formdata post, from 3.0 servlet api use request.getParts()
        //using 2.0 api and parsing ourselves parts

        // in the javascript we use jquery object.serialize() to submit the form with ajax
        //this format is used:
        /**FORM DATA will be:
         * //from  ww w . j  av a  2 s . co  m
         * ------WebKitFormBoundary3UAOvASvkiQACgBY
        Content-Disposition: form-data; name="formsubmitdata"
                
        dropId=1406409768959&md5_1=5b9f16527d8d27f541cbb3fabf432eb6&filename_1=17.csv&doctype_1=
        ------WebKitFormBoundary3UAOvASvkiQACgBY--
         */
        InputStream in = request.getInputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buff = new byte[10000];
        int bytesread = 0;
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = null;
        //while((line=br.readLine()).length()>0){
        while ((bytesread = in.read(buff)) > 0) {
            bout.write(buff, 0, bytesread);

            //System.out.println("FORMDATA:"+new String(buff,0,bytesread));
            //         System.out.println("FORMDATA:"+line);
            //bout.write(buff,0,bytesread);

            //                if(!line.startsWith("Content-Disposition")){
            //                         //bout.write(buff,0,bytesread);
            //                       bout.write(line.getBytes());
            //           }
        }
        String formparamsStr = new String(bout.toByteArray());
        logger.logTrace("FORMDATA:" + formparamsStr);
        int jj = formparamsStr.indexOf("name=\"formsubmitdata\"");
        formparamsStr = formparamsStr.substring(jj + 21);
        jj = formparamsStr.indexOf("---");
        formparamsStr = formparamsStr.substring(0, jj);

        String[] formParamPairs = formparamsStr.split("&");
        if (formParamPairs != null) {
            for (String pair : formParamPairs) {

                int ii = pair.indexOf("=");
                if (ii <= 0) {
                    continue;
                }
                String key = pair.substring(0, ii).trim();
                String value = pair.substring(ii + 1).trim();
                value = URLDecoder.decode(value, "UTF-8");
                reqparams.put(key, value);
                logger.logTrace("FORM PARAM:" + key + ":" + value);

            }
        }
        logger.logTrace("FORM PARAMZZ:" + reqparams);

    }

    Enumeration<String> headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        String val = request.getHeader(header);
        logger.logTrace("HEADER:" + header + "=" + val);
        reqheaders.put(header, val);
    }

    Enumeration<String> params = request.getParameterNames();
    if (params == null)
        return map;

    while (params.hasMoreElements()) {
        String param = params.nextElement();
        if (param == null)
            continue;

        String val = request.getHeader(param);
        logger.logTrace("PARAM:" + param + "=" + val);
        reqparams.put(param, val);

    }
    return map;
}

From source file:com.jpeterson.littles3.S3ObjectRequest.java

/**
 * Create an <code>S3Object</code> based on the request supporting virtual
 * hosting of buckets./*from  w  ww . j a  v  a2 s.  com*/
 * 
 * @param req
 *            The original request.
 * @param baseHost
 *            The <code>baseHost</code> is the HTTP Host header that is
 *            "expected". This is used to help determine how the bucket name
 *            will be interpreted. This is used to implement the "Virtual
 *            Hosting of Buckets".
 * @param authenticator
 *            The authenticator to use to authenticate this request.
 * @return An object initialized from the request.
 * @throws IllegalArgumentException
 *             Invalid request.
 */
@SuppressWarnings("unchecked")
public static S3ObjectRequest create(HttpServletRequest req, String baseHost, Authenticator authenticator)
        throws IllegalArgumentException, AuthenticatorException {
    S3ObjectRequest o = new S3ObjectRequest();
    String pathInfo = req.getPathInfo();
    String contextPath = req.getContextPath();
    String requestURI = req.getRequestURI();
    String undecodedPathPart = null;
    int pathInfoLength;
    String requestURL;
    String serviceEndpoint;
    String bucket = null;
    String key = null;
    String host;
    String value;
    String timestamp;

    baseHost = baseHost.toLowerCase();

    host = req.getHeader("Host");
    if (host != null) {
        host = host.toLowerCase();
    }

    try {
        requestURL = URLDecoder.decode(req.getRequestURL().toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // should never happen
        e.printStackTrace();
        IllegalArgumentException t = new IllegalArgumentException("Unsupport encoding: UTF-8");
        t.initCause(e);
        throw t;
    }

    if (!requestURL.endsWith(pathInfo)) {
        String m = "requestURL [" + requestURL + "] does not end with pathInfo [" + pathInfo + "]";
        throw new IllegalArgumentException(m);
    }

    pathInfoLength = pathInfo.length();

    serviceEndpoint = requestURL.substring(0, requestURL.length() - pathInfoLength);

    if (debug) {
        System.out.println("---------------");
        System.out.println("requestURI: " + requestURI);
        System.out.println("serviceEndpoint: " + serviceEndpoint);
        System.out.println("---------------");
    }

    if ((host == null) || // http 1.0 form
            (host.equals(baseHost))) { // ordinary method
        // http 1.0 form
        // bucket first part of path info
        // key second part of path info
        if (pathInfoLength > 1) {
            int index = pathInfo.indexOf('/', 1);
            if (index > -1) {
                bucket = pathInfo.substring(1, index);

                if (pathInfoLength > (index + 1)) {
                    key = pathInfo.substring(index + 1);
                    undecodedPathPart = requestURI.substring(contextPath.length() + 1 + bucket.length(),
                            requestURI.length());
                }
            } else {
                bucket = pathInfo.substring(1);
            }
        }
    } else if (host.endsWith("." + baseHost)) {
        // bucket prefix of host
        // key is path info
        bucket = host.substring(0, host.length() - 1 - baseHost.length());
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    } else {
        // bucket is host
        // key is path info
        bucket = host;
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    }

    // timestamp
    timestamp = req.getHeader("Date");

    // CanonicalizedResource
    StringBuffer canonicalizedResource = new StringBuffer();

    canonicalizedResource.append('/');
    if (bucket != null) {
        canonicalizedResource.append(bucket);
    }
    if (undecodedPathPart != null) {
        canonicalizedResource.append(undecodedPathPart);
    }
    if (req.getParameter(PARAMETER_ACL) != null) {
        canonicalizedResource.append("?").append(PARAMETER_ACL);
    }

    // CanonicalizedAmzHeaders
    StringBuffer canonicalizedAmzHeaders = new StringBuffer();
    Map<String, String> headers = new TreeMap<String, String>();
    String headerName;
    String headerValue;

    for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
        headerName = ((String) headerNames.nextElement()).toLowerCase();

        if (headerName.startsWith("x-amz-")) {
            for (Enumeration headerValues = req.getHeaders(headerName); headerValues.hasMoreElements();) {
                headerValue = (String) headerValues.nextElement();
                String currentValue = headers.get(headerValue);

                if (currentValue != null) {
                    // combine header fields with the same name
                    headers.put(headerName, currentValue + "," + headerValue);
                } else {
                    headers.put(headerName, headerValue);
                }

                if (headerName.equals("x-amz-date")) {
                    timestamp = headerValue;
                }
            }
        }
    }

    for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
        headerName = iter.next();
        headerValue = headers.get(headerName);
        canonicalizedAmzHeaders.append(headerName).append(":").append(headerValue).append("\n");
    }

    StringBuffer stringToSign = new StringBuffer();

    stringToSign.append(req.getMethod()).append("\n");
    value = req.getHeader("Content-MD5");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Content-Type");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Date");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    stringToSign.append(canonicalizedAmzHeaders);
    stringToSign.append(canonicalizedResource);

    if (debug) {
        System.out.println(":v:v:v:v:");
        System.out.println("undecodedPathPart: " + undecodedPathPart);
        System.out.println("canonicalizedAmzHeaders: " + canonicalizedAmzHeaders);
        System.out.println("canonicalizedResource: " + canonicalizedResource);
        System.out.println("stringToSign: " + stringToSign);
        System.out.println(":^:^:^:^:");
    }

    o.setServiceEndpoint(serviceEndpoint);
    o.setBucket(bucket);
    o.setKey(key);
    try {
        if (timestamp == null) {
            o.setTimestamp(null);
        } else {
            o.setTimestamp(DateUtil.parseDate(timestamp));
        }
    } catch (DateParseException e) {
        o.setTimestamp(null);
    }
    o.setStringToSign(stringToSign.toString());
    o.setRequestor(authenticate(req, o));

    return o;
}

From source file:org.infoscoop.web.MultiRssServlet.java

private void mergeRssAnd2JSON(HttpServletRequest request, HttpServletResponse response, String uid,
        String widgetId, int pageSize, NodeList urlList) throws Exception {

    try {/*from   w  w  w  . j  a  v  a2  s .co  m*/
        RssJsonResultBuilder resultBuilder = new SortedRssJsonResultBuilder(pageSize);

        String dateTimeFormat = request.getHeader("X-IS-DATETIMEFORMAT");
        if (dateTimeFormat != null) {
            dateTimeFormat = URLDecoder.decode(dateTimeFormat, "UTF-8");
        }
        String freshTime = request.getHeader("X-IS-FRESHTIME");
        String maxCountString = request.getHeader("X-IS-RSSMAXCOUNT");
        int maxCount = 1000;
        if (maxCountString != null) {
            try {
                int paramMaxCount = Integer.parseInt(maxCountString);
                if (paramMaxCount >= 0) {
                    maxCount = paramMaxCount;
                }
            } catch (NumberFormatException e) {
                log.warn("rssmaxcount \"" + maxCountString + "\" isn't integer value.");
            }
        }

        // Norrowing
        String titleFilter = request.getHeader("X-IS-TITLEFILTER");
        if (titleFilter != null)
            titleFilter = URLDecoder.decode(titleFilter, "UTF-8");
        String creatorFilter = request.getHeader("X-IS-CREATORFILTER");
        if (creatorFilter != null)
            creatorFilter = URLDecoder.decode(creatorFilter, "UTF-8");
        String categoryFilter = request.getHeader("X-IS-CATEGORYFILTER");
        if (categoryFilter != null)
            categoryFilter = URLDecoder.decode(categoryFilter, "UTF-8");

        int DEFAULT_TIMEOUT = 15 * 1000;

        boolean modified = false;
        Map cacheHeaders = new HashMap();
        Map errorMap = new HashMap();
        List siteCacheHeaders = new ArrayList();
        for (int i = 0; i < urlList.getLength(); i++) {
            Element rssEl = (Element) urlList.item(i);
            String url = rssEl.getAttribute("url");

            ProxyRequest proxyRequest = new ProxyRequest(url, "NoOperation");
            proxyRequest.setLocales(request.getLocales());
            proxyRequest.setPortalUid(uid);

            int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000;
            proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT);
            //proxyRequest.setTimeout(timeout);

            proxyRequest.addIgnoreHeader("user-agent");
            proxyRequest.addIgnoreHeader("X-IS-DATETIMEFORMAT");
            proxyRequest.addIgnoreHeader("X-IS-FRESHTIME");
            proxyRequest.addIgnoreHeader("X-IS-REFRESH");
            proxyRequest.addIgnoreHeader("X-IS-RSSMAXCOUNT");
            proxyRequest.addIgnoreHeader("X-IS-PAGESIZE");

            Enumeration headers = request.getHeaderNames();
            while (headers.hasMoreElements()) {
                String headerName = (String) headers.nextElement();
                proxyRequest.putRequestHeader(headerName, request.getHeader(headerName));
            }

            NodeList rssChildNodes = rssEl.getElementsByTagName("header");
            for (int j = 0; j < rssChildNodes.getLength(); j++) {
                Element header = (Element) rssChildNodes.item(j);
                if (header.getFirstChild() != null) {
                    String name = header.getAttribute("name");
                    String value = header.getFirstChild().getNodeValue();
                    if (name == null || name.trim().length() == 0 || value == null
                            || value.trim().length() == 0)
                        continue;

                    proxyRequest.putRequestHeader(name, value);
                }
            }

            int statusCode = 0;
            String methodType = rssEl.getAttribute("method");
            try {
                if ("post".equals(methodType)) {
                    statusCode = proxyRequest.executePost();
                } else {
                    statusCode = proxyRequest.executeGet();
                }
            } catch (SocketTimeoutException ex) {
                log.error("url: [" + url + "] socket timeout.", ex);
                errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_TIMEOUT));
            } catch (ConnectTimeoutException ex) {
                log.error("url: [" + url + "] connection timeout.", ex);
                errorMap.put(url, new Integer(500));
            } catch (SocketException ex) {
                log.error("url: [" + url + "] socket error.", ex);
                errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND));
            } catch (IOException ex) {
                log.error("url: [" + url + "] I/O error.", ex);
                errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND));
            } catch (Exception ex) {
                log.error("url: [" + url + "]" + ex.getMessage(), ex);
                errorMap.put(url, new Integer(500));
            }

            BufferedInputStream bis = null;
            if (errorMap.containsKey(url)) {
                // nothing

            } else if (statusCode == 204) {
                log.warn("url:[" + url + "] is no content #" + statusCode);
                modified = true;
            } else if (statusCode == 304) {
                log.warn("url:[" + url + "] is not modified #" + statusCode);
            } else if (statusCode != 200) {
                log.error("url:[" + url + "] had error status code #" + statusCode);
                errorMap.put(url, new Integer(statusCode));
            } else {
                log.info("url:[" + url + "] is succed #" + statusCode);

                try {
                    modified = true;

                    bis = new BufferedInputStream(proxyRequest.getResponseBody());

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[10240];
                    int c;
                    while ((c = bis.read(buf)) != -1) {
                        baos.write(buf, 0, c);
                        baos.flush();
                    }
                    bis.close();

                    byte[] data = baos.toByteArray();
                    baos.close();

                    //RssCacheDAO.newInstance().insertCache(uid, widgetId+url, -1,data );

                    Map responseHeaders = proxyRequest.getResponseHeaders();
                    String lastModifiedName = "Last-Modified".toLowerCase();
                    if (responseHeaders.containsKey(lastModifiedName)) {
                        siteCacheHeaders.add(lastModifiedName);
                        siteCacheHeaders.add(responseHeaders.get(lastModifiedName));
                    }

                    String etagName = "ETag".toLowerCase();
                    if (responseHeaders.containsKey(etagName)) {
                        siteCacheHeaders.add(etagName);
                        siteCacheHeaders.add(responseHeaders.get(etagName));
                    }

                    if (siteCacheHeaders.size() > 0) {
                        cacheHeaders.put(url, siteCacheHeaders.toArray());
                        siteCacheHeaders.clear();
                    }

                    bis = new BufferedInputStream(new ByteArrayInputStream(data));
                } catch (IOException ex) {
                    log.error("rss reading " + url + " is failed.", ex);
                    cacheHeaders.remove(url);
                    errorMap.put(url, new Integer(500));

                    bis.close();
                    bis = null;
                }
            }

            if (bis == null)
                continue;

            RssHandler handler;

            boolean isAtom = RssFilter.isAtom(bis);

            XMLFilter.skipEmptyLine(bis);
            if (isAtom) {
                handler = new AtomHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter,
                        creatorFilter, categoryFilter, i);
            } else {
                handler = new RssHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter,
                        creatorFilter, categoryFilter, i);
            }

            try {
                XMLReader reader = factory.newSAXParser().getXMLReader();
                reader.setEntityResolver(NoOpEntityResolver.getInstance());
                reader.setContentHandler(handler);
                reader.parse(new InputSource(bis));
            } catch (SAXException e) {
                log.info("Parsing rss " + url + " is failed.", e);
                cacheHeaders.remove(url);
                errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_CONTENT_PARSE_ERROR));
            }
        }

        if (!modified && errorMap.isEmpty()) {
            log.warn("multi rss is not modified.");
            response.setStatus(304);

            return;
        } else {
            try {
                long freshTimeLong = new Date().getTime();
                if (freshTime != null)
                    freshTimeLong = Long.parseLong(freshTime.trim());
                setOldData(resultBuilder, uid, widgetId, freshTimeLong, titleFilter, creatorFilter,
                        categoryFilter);

            } catch (NumberFormatException e) {
                log.error("", e);
            }

            //}

            int pageCount = resultBuilder.getPageCount();
            // We create the result cash by all means.
            //if( pageCount > 1 ) {
            for (int pageNum = 0; pageNum < pageCount; pageNum++) {
                RssCacheDAO.newInstance().insertCache(uid, widgetId, pageNum, resultBuilder.getResult(pageNum));
            }
            //}
        }

        response.addHeader("Content-Type", "text/plain; charset=UTF-8");

        String result = resultBuilder.getResult();

        if (!errorMap.isEmpty()) {
            JSONObject errors = new JSONObject(errorMap);
            result = "{errors:" + errors.toString() + "," + result.substring(result.indexOf("{") + 1);
        }
        if (!cacheHeaders.isEmpty()) {
            StringBuffer cacheHeadersBuf = new StringBuffer();
            cacheHeadersBuf.append("cacheHeaders : {");
            for (Iterator keys = cacheHeaders.keySet().iterator(); keys.hasNext();) {
                String url = (String) keys.next();
                Object[] headers = (Object[]) cacheHeaders.get(url);

                cacheHeadersBuf.append("\"").append(url).append("\" : {");
                for (int i = 0; i < headers.length; i += 2) {
                    cacheHeadersBuf.append("\"").append(headers[i]).append("\"");
                    cacheHeadersBuf.append(" : '").append(headers[i + 1]).append("'");
                    if (i + 2 < headers.length)
                        cacheHeadersBuf.append(",");
                }
                cacheHeadersBuf.append("}");
                if (keys.hasNext())
                    cacheHeadersBuf.append(",");
            }
            cacheHeadersBuf.append("}");

            result = "{" + cacheHeadersBuf.toString() + "," + result.substring(result.indexOf("{") + 1);
        }

        response.setContentLength(result.getBytes("UTF-8").length);

        OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
        try {
            out.write(result);

            out.flush();
        } catch (SocketException ex) {
            // ignore client abort exception
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (Exception e) {
        log.error("unexpected error occurred.", e);
        response.sendError(500, e.getMessage());
    }

}

From source file:org.basket3.web.S3ObjectRequest.java

/**
 * Create an <code>S3Object</code> based on the request supporting virtual
 * hosting of buckets.// w  w  w . j a v a 2s .c  om
 * 
 * @param req
 *            The original request.
 * @param baseHost
 *            The <code>baseHost</code> is the HTTP Host header that is
 *            "expected". This is used to help determine how the bucket name
 *            will be interpreted. This is used to implement the "Virtual
 *            Hosting of Buckets".
 * @param authenticator
 *            The authenticator to use to authenticate this request.
 * @return An object initialized from the request.
 * @throws IllegalArgumentException
 *             Invalid request.
 */
@SuppressWarnings("unchecked")
public static S3ObjectRequest create(HttpServletRequest req, String baseHost, Authenticator authenticator)
        throws IllegalArgumentException, AuthenticatorException {
    S3ObjectRequest o = new S3ObjectRequest();
    String pathInfo = req.getPathInfo();
    String contextPath = req.getContextPath();
    String requestURI = req.getRequestURI();
    String undecodedPathPart = null;
    int pathInfoLength;
    String requestURL;
    String serviceEndpoint;
    String bucket = null;
    String key = null;
    String host;
    String value;
    String timestamp;

    baseHost = baseHost.toLowerCase();

    host = req.getHeader("Host");
    if (host != null) {
        host = host.toLowerCase();
    }

    try {
        requestURL = URLDecoder.decode(req.getRequestURL().toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // should never happen
        e.printStackTrace();
        IllegalArgumentException t = new IllegalArgumentException("Unsupport encoding: UTF-8");
        t.initCause(e);
        throw t;
    }

    if (!requestURL.endsWith(pathInfo)) {
        String m = "requestURL [" + requestURL + "] does not end with pathInfo [" + pathInfo + "]";
        throw new IllegalArgumentException(m);
    }

    pathInfoLength = pathInfo.length();

    serviceEndpoint = requestURL.substring(0, requestURL.length() - pathInfoLength);

    if (debug) {
        System.out.println("---------------");
        System.out.println("requestURI: " + requestURI);
        System.out.println("serviceEndpoint: " + serviceEndpoint);
        System.out.println("---------------");
    }
    Preconditions.checkNotNull(contextPath, "Context path cannot be null");

    if ((host == null) || // http 1.0 form
            (host.equals(baseHost))) { // ordinary method
        // http 1.0 form
        // bucket first part of path info
        // key second part of path info
        if (pathInfoLength > 1) {
            int index = pathInfo.indexOf('/', 1);
            if (index > -1) {
                bucket = pathInfo.substring(1, index);

                if (pathInfoLength > (index + 1)) {
                    key = pathInfo.substring(index + 1);
                    undecodedPathPart = requestURI.substring(contextPath.length() + 1 + bucket.length(),
                            requestURI.length());
                }
            } else {
                bucket = pathInfo.substring(1);
            }
        }
    } else if (host.endsWith("." + baseHost)) {
        // bucket prefix of host
        // key is path info
        bucket = host.substring(0, host.length() - 1 - baseHost.length());
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    } else {
        // bucket is host
        // key is path info
        bucket = host;
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    }

    // timestamp
    timestamp = req.getHeader("Date");

    // CanonicalizedResource
    StringBuffer canonicalizedResource = new StringBuffer();

    canonicalizedResource.append('/');
    if (bucket != null) {
        canonicalizedResource.append(bucket);
    }
    if (undecodedPathPart != null) {
        canonicalizedResource.append(undecodedPathPart);
    }
    if (req.getParameter(PARAMETER_ACL) != null) {
        canonicalizedResource.append("?").append(PARAMETER_ACL);
    }

    // CanonicalizedAmzHeaders
    StringBuffer canonicalizedAmzHeaders = new StringBuffer();
    Map<String, String> headers = new TreeMap<String, String>();
    String headerName;
    String headerValue;

    Preconditions.checkNotNull(req.getHeaderNames(), "Http Request Header names cannot be null");

    for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
        headerName = ((String) headerNames.nextElement()).toLowerCase();

        if (headerName.startsWith("x-amz-")) {
            for (Enumeration headerValues = req.getHeaders(headerName); headerValues.hasMoreElements();) {
                headerValue = (String) headerValues.nextElement();
                String currentValue = headers.get(headerValue);

                if (currentValue != null) {
                    // combine header fields with the same name
                    headers.put(headerName, currentValue + "," + headerValue);
                } else {
                    headers.put(headerName, headerValue);
                }

                if (headerName.equals("x-amz-date")) {
                    timestamp = headerValue;
                }
            }
        }
    }

    for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
        headerName = iter.next();
        headerValue = headers.get(headerName);
        canonicalizedAmzHeaders.append(headerName).append(":").append(headerValue).append("\n");
    }

    StringBuffer stringToSign = new StringBuffer();

    stringToSign.append(req.getMethod()).append("\n");
    value = req.getHeader("Content-MD5");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Content-Type");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Date");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    stringToSign.append(canonicalizedAmzHeaders);
    stringToSign.append(canonicalizedResource);

    if (debug) {
        System.out.println(":v:v:v:v:");
        System.out.println("undecodedPathPart: " + undecodedPathPart);
        System.out.println("canonicalizedAmzHeaders: " + canonicalizedAmzHeaders);
        System.out.println("canonicalizedResource: " + canonicalizedResource);
        System.out.println("stringToSign: " + stringToSign);
        System.out.println(":^:^:^:^:");
    }

    o.setServiceEndpoint(serviceEndpoint);
    o.setBucket(bucket);
    o.setKey(key);
    try {
        if (timestamp == null) {
            o.setTimestamp(null);
        } else {
            o.setTimestamp(DateUtil.parseDate(timestamp));
        }
    } catch (DateParseException e) {
        o.setTimestamp(null);
    }
    o.setStringToSign(stringToSign.toString());
    o.setRequestor(authenticate(req, o));

    return o;
}

From source file:com.comcast.cmb.common.controller.EndpointServlet.java

protected void doReceiveMessage(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    globalMessageCounter.incrementAndGet();

    EndpointMessage msg = parseMessage(request);

    // obey error behavior only after first message (typically subscription confirmation request) was received successfully

    if (request.getParameter("errorCode") != null && messageMap.containsKey(msg.id)) {

        int errorCode = Integer.parseInt(request.getParameter("errorCode"));

        double chance = 1.0;

        if (request.getParameter("chance") != null) {
            chance = Double.parseDouble(request.getParameter("chance"));
        }//from  w  w w .  j  a  v a 2s  .  com

        if (rand.nextDouble() <= chance) {
            doOutput(errorCode, response, "Failed", "Failed");
            return;
        }
    }

    if (request.getParameter("delayMS") != null && messageMap.containsKey(msg.id)) {

        long delayMS = Integer.parseInt(request.getParameter("delayMS"));

        double chance = 1.0;

        if (request.getParameter("chance") != null) {
            chance = Double.parseDouble(request.getParameter("chance"));
        }

        if (rand.nextDouble() <= chance) {
            try {
                Thread.sleep(delayMS);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
    }

    if (request.getParameter("numResponseBytes") != null && messageMap.containsKey(msg.id)) {

        int numResponseBytes = Integer.parseInt(request.getParameter("numResponseBytes"));

        double chance = 1.0;

        if (request.getParameter("chance") != null) {
            chance = Double.parseDouble(request.getParameter("chance"));
        }

        if (rand.nextDouble() <= chance) {
            char[] bytes = new char[numResponseBytes];
            Arrays.fill(bytes, 'A');
            doRawOutput(200, response, bytes);
            return;
        }
    }

    /*if (failureConfigMap.containsKey(msg.id)) {
               
       EndpointFailureConfiguration failureConfig = failureConfigMap.get(msg.id);
            
    logger.info("[doReceiveMessage] currentFailureCounter="+failureConfig.currentFailureCounter+" numFailuresBeforeSuccess="+failureConfig.numFailuresBeforeSuccess);
            
    if (failureConfig.currentFailureCounter < failureConfig.numFailuresBeforeSuccess) {
              
      failureConfig.currentFailureCounter++;
      msg.failure = true;
            
        logger.info("[doReceiveMessage] event=failedResponse");
      doOutput(failureConfig.httpErrorCode, response, "Failed", "Failed");
              
      return;
       }
    }*/

    Enumeration<String> headerNames = request.getHeaderNames();
    String header = "";
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        header += headerName + ": " + request.getHeader(headerName) + "\n";
    }
    msg.httpHeader = header;

    addMessage(msg);
    //logger.info("event=received_message status_code=200 msg_id=" + msg.id);
    doOutput(200, response, "Ok", "Ok");
}

From source file:org.wings.session.SessionServlet.java

/**
 * Verarbeitet Informationen vom Browser:
 * <UL>/*w  w w .j a v a2 s .  co  m*/
 * <LI> setzt Locale
 * <LI> Dispatch Get Parameter
 * <LI> feuert Form Events
 * </UL>
 * Ist synchronized, damit nur ein Frame gleichzeitig bearbeitet
 * werden kann.
 */
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) {
    // Special case: You double clicked i.e. a "logout button"
    // First request arrives, second is on hold. First invalidates session and sends redirect as response,
    // but browser ignores and expects response in second request. But second request has longer a valid session.
    if (session == null) {
        try {
            response.sendRedirect(exitSessionWorkaround != null ? exitSessionWorkaround : "");
            return;
        } catch (IOException e) {
            log.info("Session exit workaround failed to to IOException (triple click?)");
        }
    }

    SessionManager.setSession(session);
    session.setServletRequest(req);
    session.setServletResponse(response);

    session.fireRequestEvent(SRequestEvent.REQUEST_START);

    // in case, the previous thread did not clean up.
    SForm.clearArmedComponents();

    Device outputDevice = null;

    ReloadManager reloadManager = session.getReloadManager();

    try {
        /*
         * The tomcat 3.x has a bug, in that it does not encode the URL
         * sometimes. It does so, when there is a cookie, containing some
         * tomcat sessionid but that is invalid (because, for instance,
         * we restarted the tomcat in-between).
         * [I can't think of this being the correct behaviour, so I assume
         *  it is a bug. ]
         *
         * So we have to workaround this here: if we actually got the
         * session id from a cookie, but it is not valid, we don't do
         * the encodeURL() here: we just leave the requestURL as it is
         * in the properties .. and this is url-encoded, since
         * we had set it up in the very beginning of this session
         * with URL-encoding on  (see WingServlet::newSession()).
         *
         * Vice versa: if the requestedSessionId is valid, then we can
         * do the encoding (which then does URL-encoding or not, depending
         * whether the servlet engine detected a cookie).
         * (hen)
         */
        RequestURL requestURL = null;
        if (req.isRequestedSessionIdValid()) {
            requestURL = new RequestURL("", getSessionEncoding(response));
            // this will fire an event, if the encoding has changed ..
            session.setProperty("request.url", requestURL);
        }

        if (log.isDebugEnabled()) {
            log.debug("Request URL: " + requestURL);
            log.debug("HTTP header:");
            for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) {
                String header = (String) en.nextElement();
                log.debug("    " + header + ": " + req.getHeader(header));
            }
        }
        handleLocale(req);

        // The pathInfo addresses the resource
        String pathInfo = req.getPathInfo(); // Note: Websphere returns <code>null</code> here!
        if (pathInfo != null && pathInfo.length() > 0) {
            // strip of leading /
            pathInfo = pathInfo.substring(1);
        }
        if (log.isDebugEnabled())
            log.debug("pathInfo: " + pathInfo);

        ResourceMapper mapper = session.getResourceMapper();

        // The externalizer is able to handle static and dynamic resources
        ExternalizeManager extManager = getSession().getExternalizeManager();

        ExternalizedResource extInfo;
        Resource resource;
        if (pathInfo == null || pathInfo.length() == 0)
            extInfo = extManager.getExternalizedResource(retrieveCurrentRootFrameResource().getId());
        else if (mapper != null && (resource = mapper.mapResource(pathInfo)) != null)
            extInfo = extManager.getExternalizedResource(resource.getId());
        else if (firstRequest) {
            extInfo = extManager.getExternalizedResource(retrieveCurrentRootFrameResource().getId());
        } else
            extInfo = extManager.getExternalizedResource(pathInfo);

        firstRequest = false;

        // Special case handling: We request a .html resource of a session which is not accessible.
        // This happens some times and leads to a 404, though it should not be possible.
        if (extInfo == null && pathInfo != null && (pathInfo.endsWith(".html") || pathInfo.endsWith(".xml"))) {
            log.info("Got a request to an invalid .html during a valid session .. redirecting to root frame.");
            response.sendRedirect("");
            return;
        }

        if (extInfo != null && extInfo.getObject() instanceof UpdateResource) {
            reloadManager.setUpdateMode(true);

            String eventEpoch = req.getParameter("event_epoch");
            UpdateResource updateResource = (UpdateResource) extInfo.getObject();
            updateResource.getFrame().getEventEpoch();

            if (eventEpoch != null && !eventEpoch.equals(updateResource.getFrame().getEventEpoch())) {
                reloadManager.setUpdateMode(false);
            }
        } else {
            reloadManager.setUpdateMode(false);
        }

        // Prior to dispatching the actual events we have to detect
        // their epoch and inform the dispatcher which will then be
        // able to check if the request is valid and processed. If
        // this is not the case, we force a complete page reload.
        LowLevelEventDispatcher eventDispatcher = session.getDispatcher();
        eventDispatcher.setEventEpoch(req.getParameter("event_epoch"));

        Enumeration en = req.getParameterNames();
        final Cookie[] cookies = req.getCookies();
        final Collection<Cookie> cookiesToDispatch = new ArrayList<Cookie>();

        // handle debug.cookie - read it every time. 
        session.removeProperty("debug.cookie");
        if (cookies != null) {
            //handle cookies
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                String paramName = cookie.getName();

                if ("DEBUG".equals(paramName)) {
                    // Cookies have a limited length, therefore we copy
                    // them trustingly into the session.

                    // Use a Tokenizer for performance.
                    String paramValue = URLDecoder.decode(cookie.getValue(), "ISO-8859-1");
                    StringTokenizer tokenizer = new StringTokenizer(paramValue, "|");
                    String[] values = new String[tokenizer.countTokens()];
                    for (int j = 0; j < values.length; j++) {
                        values[j] = tokenizer.nextToken();
                    }
                    session.setProperty("debug.cookie", values);
                } else {
                    cookiesToDispatch.add(cookie);
                }
            }
        }

        // are there parameters/low level events to dispatch
        if (en.hasMoreElements()) {
            // only fire DISPATCH_START if we have parameters to dispatch
            session.fireRequestEvent(SRequestEvent.DISPATCH_START);

            eventDispatcher.startLowLevelEventPhase();
            if (cookiesToDispatch != null) {
                //dispatch cookies
                for (Cookie cookie : cookiesToDispatch) {
                    String paramName = cookie.getName();
                    String value = cookie.getValue();

                    if (log.isDebugEnabled())
                        log.debug("dispatching cookie " + paramName + " = " + value);

                    eventDispatcher.dispatch(paramName, new String[] { value });
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("Parameters:");
                for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
                    String paramName = (String) e.nextElement();
                    StringBuilder param = new StringBuilder();
                    param.append("    ").append(paramName).append(": ");
                    final String[] values = req.getParameterValues(paramName);
                    param.append(values != null ? Arrays.toString(values) : "null");
                    log.debug(param);
                }
            }

            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String[] values = req.getParameterValues(paramName);

                //We do not need to dispatch the event epoch since it is already
                // handled a few lines above. Furthermore we will not dispatch any
                // names that start with an '_' (e.g. _xhrId or parts of XCalendar).
                if (paramName.equals("event_epoch") || paramName.startsWith("_") || paramName.equals("comet")
                        || paramName.equals("polling")) {
                    continue;
                }

                String value = values[0];

                // Split the values of the event trigger
                if (paramName.equals("event_trigger")) {
                    int pos = value.indexOf('|');
                    paramName = value.substring(0, pos);
                    values = new String[] { value.substring(pos + 1) };
                }

                // Handle form submit via default button
                if (paramName.equals("default_button")) {
                    if (value.equals("undefined")) {
                        continue;
                    } else {
                        paramName = values[0];
                        values = new String[] { "1" };
                    }
                }

                if (log.isDebugEnabled())
                    log.debug("dispatching " + paramName + " = " + Arrays.asList(values));

                eventDispatcher.dispatch(paramName, values);
            }
            eventDispatcher.endLowLevelEventPhase();

            SForm.fireEvents();

            // only fire DISPATCH DONE if we have parameters to dispatch
            session.fireRequestEvent(SRequestEvent.DISPATCH_DONE);
        }

        session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST);
        eventDispatcher.invokeRunnables();

        // if the user chose to exit the session as a reaction on an
        // event, we got an URL to redirect after the session.
        /*
         * where is the right place?
         * The right place is
         *    - _after_ we processed the events
         *        (e.g. the 'Pressed Exit-Button'-event or gave
         *         the user the chance to exit this session in the custom
         *         processRequest())
         *    - but _before_ the rendering of the page,
         *      because otherwise an redirect won't work, since we must
         *      not have sent anything to the output stream).
         */
        if (session.getExitAddress() != null) {
            try {
                session.firePrepareExit();
                session.fireRequestEvent(SRequestEvent.REQUEST_END);

                String redirectAddress;
                if (session.getExitAddress().length() > 0) {
                    // redirect to user requested URL.
                    redirectAddress = session.getExitAddress();
                } else {
                    // redirect to a fresh session.
                    redirectAddress = req.getRequestURL().toString();
                    if (pathInfo != null) { // Websphere pathinfo is null
                        // Make sure that the redirect address doesn't contain any path info.
                        redirectAddress = redirectAddress.substring(0,
                                redirectAddress.length() - pathInfo.length());
                    }
                }

                exitSessionWorkaround = redirectAddress;

                if (reloadManager.isUpdateMode()) {
                    ScriptListener listener = new JavaScriptListener(null, null,
                            "location.href='" + redirectAddress + "'");
                    ScriptManager.getInstance().addScriptListener(listener);
                    req.getSession().invalidate(); // calls destroy implicitly
                } else {
                    response.sendRedirect(redirectAddress);
                    req.getSession().invalidate(); // calls destroy implicitly
                    return;
                }
            } catch (ExitVetoException ex) {
                session.exit(null);
            } // end of try-catch
        }

        if (session.getRedirectAddress() != null) {
            handleRedirect(response);
            return;
        }

        reloadManager.invalidateFrames();

        if (extInfo != null) {
            outputDevice = DeviceFactory.createDevice(extInfo);
            try {
                session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo);

                long startTime = System.currentTimeMillis();
                extManager.deliver(extInfo, response, outputDevice);
                if (log.isDebugEnabled()) {
                    log.debug("Rendering time: " + (System.currentTimeMillis() - startTime) + " ms");
                }

            } finally {
                session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo);
            }
        } else {
            handleUnknownResourceRequested(req, response);
        }

    } catch (Throwable e) {
        log.error("Uncaught Exception", e);
        handleException(response, e);
    } finally {
        if (session != null) {
            session.fireRequestEvent(SRequestEvent.REQUEST_END);
        }

        if (outputDevice != null) {
            try {
                outputDevice.close();
            } catch (Exception e) {
            }
        }

        /*
         * the session might be null due to destroy().
         */
        if (session != null) {
            reloadManager.clear();
            session.setServletRequest(null);
            session.setServletResponse(null);
        }

        // make sure that the session association to the thread is removed
        // from the SessionManager
        SessionManager.removeSession();
        SForm.clearArmedComponents();
    }
}

From source file:org.josso.tc60.gateway.reverseproxy.ReverseProxyValve.java

/**
 * Intercepts Http request and redirects it to the configured SSO partner application.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *  in the current processing pipeline//from  w  ww  .j a va  2s. co  m
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException {

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve Acting.");

    ProxyContextConfig[] contexts = _rpc.getProxyContexts();

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    HttpServletRequest hsr = (HttpServletRequest) request.getRequest();
    String uri = hsr.getRequestURI();

    String uriContext = null;

    StringTokenizer st = new StringTokenizer(uri.substring(1), "/");
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        uriContext = "/" + token;
        break;
    }

    if (uriContext == null)
        uriContext = uri;

    // Obtain the target host from the
    String proxyForwardHost = null;
    String proxyForwardUri = null;

    for (int i = 0; i < contexts.length; i++) {
        if (contexts[i].getContext().equals(uriContext)) {
            log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost()
                    + contexts[i].getForwardUri());
            proxyForwardHost = contexts[i].getForwardHost();
            proxyForwardUri = contexts[i].getForwardUri();
            break;
        }
    }

    if (proxyForwardHost == null) {
        log("URI '" + uri + "' can't be mapped to host");
        getNext().invoke(request, response);
        return;
    }

    if (proxyForwardUri == null) {
        // trim the uri context before submitting the http request
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = uri.substring(uriTrailStartPos);
    } else {
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos);
    }

    // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri);

    HttpMethod method;

    // to be moved to a builder which instantiates and build concrete methods.
    if (hsr.getMethod().equals(METHOD_GET)) {
        // Create a method instance.
        HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = getMethod;
    } else if (hsr.getMethod().equals(METHOD_POST)) {
        // Create a method instance.
        PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        postMethod.setRequestBody(hsr.getInputStream());
        method = postMethod;
    } else if (hsr.getMethod().equals(METHOD_HEAD)) {
        // Create a method instance.
        HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = headMethod;
    } else if (hsr.getMethod().equals(METHOD_PUT)) {
        method = new PutMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
    } else
        throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod());

    // copy incoming http headers to reverse proxy request
    Enumeration hne = hsr.getHeaderNames();
    while (hne.hasMoreElements()) {
        String hn = (String) hne.nextElement();

        // Map the received host header to the target host name
        // so that the configured virtual domain can
        // do the proper handling.
        if (hn.equalsIgnoreCase("host")) {
            method.addRequestHeader("Host", proxyForwardHost);
            continue;
        }

        Enumeration hvals = hsr.getHeaders(hn);
        while (hvals.hasMoreElements()) {
            String hv = (String) hvals.nextElement();
            method.addRequestHeader(hn, hv);
        }
    }

    // Add Reverse-Proxy-Host header
    String reverseProxyHost = getReverseProxyHost(request);
    method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost);

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost);

    // DO NOT follow redirects !
    method.setFollowRedirects(false);

    // By default the httpclient uses HTTP v1.1. We are downgrading it
    // to v1.0 so that the target server doesn't set a reply using chunked
    // transfer encoding which doesn't seem to be handled properly.
    client.getParams().setVersion(new HttpVersion(1, 0));

    // Execute the method.
    int statusCode = -1;
    try {
        // execute the method.
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log("A recoverable exception occurred " + e.getMessage());
    } catch (IOException e) {
        log("Failed to connect.");
        e.printStackTrace();
    }

    // Check that we didn't run out of retries.
    if (statusCode == -1) {
        log("Failed to recover from exception.");
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

    // Release the connection.
    method.releaseConnection();

    HttpServletResponse sres = (HttpServletResponse) response.getResponse();

    // First thing to do is to copy status code to response, otherwise
    // catalina will do it as soon as we set a header or some other part of the response.
    sres.setStatus(method.getStatusCode());

    // copy proxy response headers to client response
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header responseHeader = responseHeaders[i];
        String name = responseHeader.getName();
        String value = responseHeader.getValue();

        // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses
        // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the
        // backend servers which stay behind the reverse proxy
        switch (method.getStatusCode()) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:

            if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name)
                    || "URI".equalsIgnoreCase(name)) {

                // Check that this redirect must be adjusted.
                if (value.indexOf(proxyForwardHost) >= 0) {
                    String trail = value.substring(proxyForwardHost.length());
                    value = getReverseProxyHost(request) + trail;
                    if (container.getLogger().isDebugEnabled())
                        container.getLogger().debug("Adjusting redirect header to " + value);
                }
            }
            break;

        } //end of switch
        sres.addHeader(name, value);

    }

    // Sometimes this is null, when no body is returned ...
    if (responseBody != null && responseBody.length > 0)
        sres.getOutputStream().write(responseBody);

    sres.getOutputStream().flush();

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve finished.");

    return;
}

From source file:org.josso.tc55.gateway.reverseproxy.ReverseProxyValve.java

/**
 * Intercepts Http request and redirects it to the configured SSO partner application.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *  in the current processing pipeline// ww w  .j  a  va  2s. co m
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException {

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve Acting.");

    ProxyContextConfig[] contexts = _rpc.getProxyContexts();

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    HttpServletRequest hsr = (HttpServletRequest) request.getRequest();
    String uri = hsr.getRequestURI();

    String uriContext = null;

    StringTokenizer st = new StringTokenizer(uri.substring(1), "/");
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        uriContext = "/" + token;
        break;
    }

    if (uriContext == null)
        uriContext = uri;

    // Obtain the target host from the
    String proxyForwardHost = null;
    String proxyForwardUri = null;

    for (int i = 0; i < contexts.length; i++) {
        if (contexts[i].getContext().equals(uriContext)) {
            log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost()
                    + contexts[i].getForwardUri());
            proxyForwardHost = contexts[i].getForwardHost();
            proxyForwardUri = contexts[i].getForwardUri();
            break;
        }
    }

    if (proxyForwardHost == null) {
        log("URI '" + uri + "' can't be mapped to host");
        getNext().invoke(request, response);
        return;
    }

    if (proxyForwardUri == null) {
        // trim the uri context before submitting the http request
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = uri.substring(uriTrailStartPos);
    } else {
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos);
    }

    // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri);

    HttpMethod method;

    // to be moved to a builder which instantiates and build concrete methods.
    if (hsr.getMethod().equals(METHOD_GET)) {
        // Create a method instance.
        HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = getMethod;
    } else if (hsr.getMethod().equals(METHOD_POST)) {
        // Create a method instance.
        PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        postMethod.setRequestBody(hsr.getInputStream());
        method = postMethod;
    } else if (hsr.getMethod().equals(METHOD_HEAD)) {
        // Create a method instance.
        HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = headMethod;
    } else if (hsr.getMethod().equals(METHOD_PUT)) {
        method = new PutMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
    } else
        throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod());

    // copy incoming http headers to reverse proxy request
    Enumeration hne = hsr.getHeaderNames();
    while (hne.hasMoreElements()) {
        String hn = (String) hne.nextElement();

        // Map the received host header to the target host name
        // so that the configured virtual domain can
        // do the proper handling.
        if (hn.equalsIgnoreCase("host")) {
            method.addRequestHeader("Host", proxyForwardHost);
            continue;
        }

        Enumeration hvals = hsr.getHeaders(hn);
        while (hvals.hasMoreElements()) {
            String hv = (String) hvals.nextElement();
            method.addRequestHeader(hn, hv);
        }
    }

    // Add Reverse-Proxy-Host header
    String reverseProxyHost = getReverseProxyHost(request);
    method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost);

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost);

    // DO NOT follow redirects !
    method.setFollowRedirects(false);

    // By default the httpclient uses HTTP v1.1. We are downgrading it
    // to v1.0 so that the target server doesn't set a reply using chunked
    // transfer encoding which doesn't seem to be handled properly.
    // Check how to make chunked transfer encoding work.
    client.getParams().setVersion(new HttpVersion(1, 0));

    // Execute the method.
    int statusCode = -1;
    try {
        // execute the method.
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log("A recoverable exception occurred " + e.getMessage());
    } catch (IOException e) {
        log("Failed to connect.");
        e.printStackTrace();
    }

    // Check that we didn't run out of retries.
    if (statusCode == -1) {
        log("Failed to recover from exception.");
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

    // Release the connection.
    method.releaseConnection();

    HttpServletResponse sres = (HttpServletResponse) response.getResponse();

    // First thing to do is to copy status code to response, otherwise
    // catalina will do it as soon as we set a header or some other part of the response.
    sres.setStatus(method.getStatusCode());

    // copy proxy response headers to client response
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header responseHeader = responseHeaders[i];
        String name = responseHeader.getName();
        String value = responseHeader.getValue();

        // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses
        // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the
        // backend servers which stay behind the reverse proxy
        switch (method.getStatusCode()) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:

            if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name)
                    || "URI".equalsIgnoreCase(name)) {

                // Check that this redirect must be adjusted.
                if (value.indexOf(proxyForwardHost) >= 0) {
                    String trail = value.substring(proxyForwardHost.length());
                    value = getReverseProxyHost(request) + trail;
                    if (container.getLogger().isDebugEnabled())
                        container.getLogger().debug("Adjusting redirect header to " + value);
                }
            }
            break;

        } //end of switch
        sres.addHeader(name, value);

    }

    // Sometimes this is null, when no body is returned ...
    if (responseBody != null && responseBody.length > 0)
        sres.getOutputStream().write(responseBody);

    sres.getOutputStream().flush();

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve finished.");

    return;
}

From source file:org.josso.tc50.gateway.reverseproxy.ReverseProxyValve.java

/**
 * Intercepts Http request and redirects it to the configured SSO partner application.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 * @param valveContext The valve _context used to invoke the next valve
 *  in the current processing pipeline//from  w  w  w . j a v a2 s.com
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response, ValveContext valveContext)
        throws IOException, javax.servlet.ServletException {

    if (debug >= 1)
        log("ReverseProxyValve Acting.");

    ProxyContextConfig[] contexts = _rpc.getProxyContexts();

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    HttpServletRequest hsr = (HttpServletRequest) request.getRequest();
    String uri = hsr.getRequestURI();

    String uriContext = null;

    StringTokenizer st = new StringTokenizer(uri.substring(1), "/");
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        uriContext = "/" + token;
        break;
    }

    if (uriContext == null)
        uriContext = uri;

    // Obtain the target host from the
    String proxyForwardHost = null;
    String proxyForwardUri = null;

    for (int i = 0; i < contexts.length; i++) {
        if (contexts[i].getContext().equals(uriContext)) {
            log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost()
                    + contexts[i].getForwardUri());
            proxyForwardHost = contexts[i].getForwardHost();
            proxyForwardUri = contexts[i].getForwardUri();
            break;
        }
    }

    if (proxyForwardHost == null) {
        log("URI '" + uri + "' can't be mapped to host");
        valveContext.invokeNext(request, response);
        return;
    }

    if (proxyForwardUri == null) {
        // trim the uri context before submitting the http request
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = uri.substring(uriTrailStartPos);
    } else {
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos);
    }

    // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri);

    HttpMethod method;

    // to be moved to a builder which instantiates and build concrete methods.
    if (hsr.getMethod().equals(METHOD_GET)) {
        // Create a method instance.
        HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = getMethod;
    } else if (hsr.getMethod().equals(METHOD_POST)) {
        // Create a method instance.
        PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        postMethod.setRequestBody(hsr.getInputStream());
        method = postMethod;
    } else if (hsr.getMethod().equals(METHOD_HEAD)) {
        // Create a method instance.
        HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = headMethod;
    } else if (hsr.getMethod().equals(METHOD_PUT)) {
        method = new PutMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
    } else
        throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod());

    // copy incoming http headers to reverse proxy request
    Enumeration hne = hsr.getHeaderNames();
    while (hne.hasMoreElements()) {
        String hn = (String) hne.nextElement();

        // Map the received host header to the target host name
        // so that the configured virtual domain can
        // do the proper handling.
        if (hn.equalsIgnoreCase("host")) {
            method.addRequestHeader("Host", proxyForwardHost);
            continue;
        }

        Enumeration hvals = hsr.getHeaders(hn);
        while (hvals.hasMoreElements()) {
            String hv = (String) hvals.nextElement();
            method.addRequestHeader(hn, hv);
        }
    }

    // Add Reverse-Proxy-Host header
    String reverseProxyHost = getReverseProxyHost(request);
    method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost);

    if (debug >= 1)
        log("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost);

    // DO NOT follow redirects !
    method.setFollowRedirects(false);

    // By default the httpclient uses HTTP v1.1. We are downgrading it
    // to v1.0 so that the target server doesn't set a reply using chunked
    // transfer encoding which doesn't seem to be handled properly.
    // Check how to make chunked transfer encoding work.
    client.getParams().setVersion(new HttpVersion(1, 0));

    // Execute the method.
    int statusCode = -1;
    try {
        // execute the method.
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log("A recoverable exception occurred " + e.getMessage());
    } catch (IOException e) {
        log("Failed to connect.");
        e.printStackTrace();
    }

    // Check that we didn't run out of retries.
    if (statusCode == -1) {
        log("Failed to recover from exception.");
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

    // Release the connection.
    method.releaseConnection();

    HttpServletResponse sres = (HttpServletResponse) response.getResponse();

    // First thing to do is to copy status code to response, otherwise
    // catalina will do it as soon as we set a header or some other part of the response.
    sres.setStatus(method.getStatusCode());

    // copy proxy response headers to client response
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header responseHeader = responseHeaders[i];
        String name = responseHeader.getName();
        String value = responseHeader.getValue();

        // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses
        // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the
        // backend servers which stay behind the reverse proxy
        switch (method.getStatusCode()) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:

            if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name)
                    || "URI".equalsIgnoreCase(name)) {

                // Check that this redirect must be adjusted.
                if (value.indexOf(proxyForwardHost) >= 0) {
                    String trail = value.substring(proxyForwardHost.length());
                    value = getReverseProxyHost(request) + trail;
                    if (debug >= 1)
                        log("Adjusting redirect header to " + value);
                }
            }
            break;

        } //end of switch
        sres.addHeader(name, value);

    }

    // Sometimes this is null, when no body is returned ...
    if (responseBody != null && responseBody.length > 0)
        sres.getOutputStream().write(responseBody);

    sres.getOutputStream().flush();

    if (debug >= 1)
        log("ReverseProxyValve finished.");

    return;
}