Example usage for javax.servlet.http HttpServletRequest getRemotePort

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

Introduction

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

Prototype

public int getRemotePort();

Source Link

Document

Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request.

Usage

From source file:org.dataconservancy.dcs.lineage.http.support.RequestUtil.java

/**
 * Determine the port number that the client targeted with their {@code request}.  If {@code considerHostHeader} is
 * {@code true}, and a HTTP {@code Host} header is present, the value of the port in the header will be used as the
 * port number. If the header is not present, or if {@code considerHostHeader} is {@code false}, the port number
 * will be determined using {@link javax.servlet.http.HttpServletRequest#getRemotePort()}
 * (if {@code considerRemotePort} is {@code true}) followed by {@link javax.servlet.http.HttpServletRequest#getLocalPort()}
 * (if {@code considerLocalPort} is {@code true}).
 *
 * @param request the request/*  w w w .  j  av  a 2  s  .com*/
 * @return the port number targeted by the {@code request}
 */
private int determinePort(HttpServletRequest request) {

    int portNumber = -1;

    // If there is a 'Host' header with the request, and if
    // we are supposed to consider it when determining the port,
    // then use it.

    // This is the best way to go, because the client is indicating
    // what host and port they targeted
    final String hostHeader = request.getHeader(HOST_HEADER);
    if (considerHostHeader && hostHeader != null && hostHeader.trim().length() != 0) {
        String temp = parseHostHeader(hostHeader)[1];
        if (temp != null) {
            portNumber = Integer.parseInt(temp);
        }
    }

    // Either the 'Host' header wasn't considered, or parsing it failed for some reason.

    if (portNumber == -1 && considerRemotePort) {
        portNumber = request.getRemotePort();
    }

    if (portNumber == -1 && considerLocalPort) {
        portNumber = request.getLocalPort();
    }

    return portNumber;
}

From source file:org.deegree.services.controller.OGCFrontController.java

/**
 * Handles HTTP GET requests./*w  w w.  ja  v  a2  s.c om*/
 * <p>
 * An HTTP GET request implies that input parameters are specified as key-value pairs. However, at least one OGC
 * service specification allows the sending of XML requests via GET (see WCS 1.0.0 specification, section 6.3.3). In
 * this case, the query string contains no <code>key=value</code> pairs, but the (URL encoded) xml. The encoding
 * ensures that no <code>=</code> char (parameter/value delimiters) occur in the string.
 * </p>
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpResponseBuffer responseBuffer = createHttpResponseBuffer(request, response);

    try {
        long entryTime = System.currentTimeMillis();

        logHeaders(request);
        addHeaders(responseBuffer);
        responseBuffer = handleCompression(responseBuffer);

        String queryString = request.getQueryString();
        try {
            LOG.debug("doGet(), query string: '" + queryString + "'");

            if (queryString == null) {
                OWSException ex = new OWSException("The request did not contain any parameters.",
                        "MissingParameterValue");
                OWS ows = null;
                try {
                    ows = determineOWSByPathQuirk(request);
                } catch (OWSException e) {
                    sendException(null, e, responseBuffer, null);
                    return;
                }
                sendException(ows, ex, responseBuffer, null);
                return;
            }

            // handle as XML, if the request starts with '<'
            boolean isXML = queryString.startsWith("<");
            List<FileItem> multiParts = checkAndRetrieveMultiparts(request);
            if (isXML) {
                XMLStreamReader xmlStream = null;
                String dummySystemId = "HTTP Get request from " + request.getRemoteAddr() + ":"
                        + request.getRemotePort();
                if (multiParts != null && multiParts.size() > 0) {
                    InputStream is = multiParts.get(0).getInputStream();
                    xmlStream = XMLInputFactoryUtils.newSafeInstance().createXMLStreamReader(dummySystemId, is);
                } else {
                    // decode query string
                    String decodedString = URLDecoder.decode(queryString, DEFAULT_ENCODING);
                    StringReader reader = new StringReader(decodedString);
                    xmlStream = XMLInputFactoryUtils.newSafeInstance().createXMLStreamReader(dummySystemId,
                            reader);
                }
                if (isSOAPRequest(xmlStream)) {
                    dispatchSOAPRequest(xmlStream, request, responseBuffer, multiParts);
                } else {
                    dispatchXMLRequest(xmlStream, request, responseBuffer, multiParts);
                }
            } else {
                // for GET requests, there is no standard way for defining the used encoding
                Map<String, String> normalizedKVPParams = KVPUtils.getNormalizedKVPMap(request.getQueryString(),
                        DEFAULT_ENCODING);
                LOG.debug("parameter map: " + normalizedKVPParams);
                dispatchKVPRequest(normalizedKVPParams, request, responseBuffer, multiParts, entryTime);
            }
        } catch (XMLProcessingException e) {
            // the message might be more meaningful
            OWSException ex = new OWSException(
                    "The request did not contain KVP parameters and no parseable XML.", "MissingParameterValue",
                    "request");
            sendException(null, ex, responseBuffer, null);
            return;
        } catch (Throwable e) {
            e.printStackTrace();
            LOG.debug("Handling HTTP-GET request took: " + (System.currentTimeMillis() - entryTime)
                    + " ms before sending exception.");
            LOG.debug(e.getMessage(), e);
            OWSException ex = new OWSException(e.getLocalizedMessage(), e, "InvalidRequest");
            sendException(null, ex, responseBuffer, null);
            return;
        }
        LOG.debug("Handling HTTP-GET request with status 'success' took: "
                + (System.currentTimeMillis() - entryTime) + " ms.");
    } finally {
        getInstance().CONTEXT.remove();
        responseBuffer.flushBuffer();
        if (mainConfig.isValidateResponses() != null && mainConfig.isValidateResponses()) {
            validateResponse(responseBuffer);
        }
    }
}

From source file:org.deegree.services.controller.OGCFrontController.java

/**
 * Handles HTTP POST requests.//from   w  ww . j a  v  a  2  s . com
 * <p>
 * An HTTP POST request specifies parameters in the request body. OGC service specifications use three different
 * ways to encode the parameters:
 * <ul>
 * <li><b>KVP</b>: Parameters are given as <code>key=value</code> pairs which are separated using the &amp;
 * character. This is equivalent to standard HTTP GET requests, except that the parameters are not part of the query
 * string, but the POST body. In this case, the <code>content-type</code> field in the header must be
 * <code>application/x-www-form-urlencoded</code>.</li>
 * <li><b>XML</b>: The POST body contains an XML document. In this case, the <code>content-type</code> field in the
 * header has to be <code>text/xml</code>, but the implementation does not rely on this in order to be more tolerant
 * to clients.</li>
 * <li><b>SOAP</b>: TODO</li>
 * <li><b>Multipart</b>: TODO</li>
 * </ul>
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpResponseBuffer responseBuffer = createHttpResponseBuffer(request, response);

    try {
        logHeaders(request);
        addHeaders(responseBuffer);
        responseBuffer = handleCompression(responseBuffer);

        LOG.debug("doPost(), contentType: '" + request.getContentType() + "'");

        long entryTime = System.currentTimeMillis();
        try {
            // check if content-type implies that it's a KVP request
            String contentType = request.getContentType();
            boolean isKVP = false;
            if (contentType != null) {
                isKVP = request.getContentType().startsWith("application/x-www-form-urlencoded");
            }
            List<FileItem> multiParts = checkAndRetrieveMultiparts(request);
            InputStream is = request.getInputStream();

            if (isKVP) {
                String queryString = readPostBodyAsString(is);
                LOG.debug("Treating POST input stream as KVP parameters. Raw input: '" + queryString + "'.");
                Map<String, String> normalizedKVPParams = null;
                String encoding = request.getCharacterEncoding();
                if (encoding == null) {
                    LOG.debug("Request has no further encoding information. Defaulting to '" + DEFAULT_ENCODING
                            + "'.");
                    normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, DEFAULT_ENCODING);
                } else {
                    LOG.debug("Client encoding information :" + encoding);
                    normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, encoding);
                }
                dispatchKVPRequest(normalizedKVPParams, request, responseBuffer, multiParts, entryTime);
            } else {
                // if( handle multiparts, get first body from multipart (?)
                // body->requestDoc

                InputStream requestInputStream = null;
                if (multiParts != null && multiParts.size() > 0) {
                    for (int i = 0; i < multiParts.size() && requestInputStream == null; ++i) {
                        FileItem item = multiParts.get(i);
                        if (item != null) {
                            LOG.debug("Using multipart item: " + i + " with contenttype: "
                                    + item.getContentType() + " as the request.");
                            requestInputStream = item.getInputStream();
                        }
                    }
                } else {
                    requestInputStream = is;
                }
                if (requestInputStream == null) {
                    String msg = "Could not create a valid inputstream from request "
                            + ((multiParts != null && multiParts.size() > 0) ? "without" : "with")
                            + " multiparts.";
                    LOG.error(msg);
                    throw new IOException(msg);
                }

                String dummySystemId = "HTTP Post request from " + request.getRemoteAddr() + ":"
                        + request.getRemotePort();
                XMLStreamReader xmlStream = XMLInputFactoryUtils.newSafeInstance()
                        .createXMLStreamReader(dummySystemId, requestInputStream);
                // skip to start tag of root element
                XMLStreamUtils.nextElement(xmlStream);
                if (isSOAPRequest(xmlStream)) {
                    dispatchSOAPRequest(xmlStream, request, responseBuffer, multiParts);
                } else {
                    dispatchXMLRequest(xmlStream, request, responseBuffer, multiParts);
                }
            }
        } catch (Throwable e) {
            LOG.debug("Handling HTTP-POST request took: " + (System.currentTimeMillis() - entryTime)
                    + " ms before sending exception.");
            LOG.debug(e.getMessage(), e);
            OWSException ex = new OWSException(e.getLocalizedMessage(), "InvalidRequest");
            OWS ows = null;
            try {
                ows = determineOWSByPath(request);
            } catch (OWSException e2) {
                sendException(ows, e2, responseBuffer, null);
                return;
            }
            sendException(ows, ex, responseBuffer, null);
        }
        LOG.debug("Handling HTTP-POST request with status 'success' took: "
                + (System.currentTimeMillis() - entryTime) + " ms.");
    } finally {
        instance.CONTEXT.remove();
        responseBuffer.flushBuffer();
        if (mainConfig.isValidateResponses() != null && mainConfig.isValidateResponses()) {
            validateResponse(responseBuffer);
        }
    }
}

From source file:org.eclipse.kapua.app.console.server.KapuaRemoteServiceServlet.java

/**
 *
 * This method perform a XSRF validation on the given request and for the specific userToken.
 * This is a private method to support both, standard class validation or multipart Servlet validation.
 *
 * @param req/*from   w ww .  ja  v  a  2  s.  com*/
 * @param userToken
 */
static private void performXSRFTokenValidation(HttpServletRequest req, GwtXSRFToken userToken)
        throws GwtKapuaException {
    HttpSession session = req.getSession();

    if (!isValidXSRFToken(session, userToken)) {
        if (session != null) {
            s_logger.info("XSRF token is NOT VALID - Token={}", userToken.getToken());
            s_logger.debug("\tSender IP: {}", req.getRemoteAddr());
            s_logger.debug("\tSender Host: {}", req.getRemoteHost());
            s_logger.debug("\tSender Port: {}", req.getRemotePort());
            s_logger.debug("\tFull Request URL\n {}?{}\n\n", req.getRequestURL().toString(),
                    req.getQueryString());
        }

        // forcing the console log out
        session.invalidate();
        s_logger.debug("Session invalidated.");

        throw new GwtKapuaException(GwtKapuaErrorCode.XSRF_INVALID_TOKEN, null, "Invalid XSRF token");
    }
}

From source file:org.eclipse.kura.web.server.KuraRemoteServiceServlet.java

/**
 *
 * This method perform a XSRF validation on the given request and for the specific userToken.
 * This is a private method to support both, standard class validation or multipart Servlet validation.
 *
 * @param req/*  ww w. j  a v  a 2  s.c  o  m*/
 * @param userToken
 */
static private void performXSRFTokenValidation(HttpServletRequest req, GwtXSRFToken userToken)
        throws GwtKuraException {
    HttpSession session = req.getSession();

    if (!isValidXSRFToken(session, userToken)) {
        if (session != null) {
            s_logger.info("XSRF token is NOT VALID - Token={}", userToken.getToken());
            s_logger.debug("\tSender IP: {}", req.getRemoteAddr());
            s_logger.debug("\tSender Host: {}", req.getRemoteHost());
            s_logger.debug("\tSender Port: {}", req.getRemotePort());
            s_logger.debug("\tFull Request URL\n {}?{}\n\n", req.getRequestURL().toString(),
                    req.getQueryString());
        }

        // forcing the console log out
        session.invalidate();
        s_logger.debug("Session invalidated.");

        throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR, null, "Invalid XSRF token");
    }
}

From source file:org.encuestame.core.util.InternetUtils.java

/**
 * Build Domain./*w  w w  . j a  v a2  s.  c o  m*/
 * @param request {@link HttpServletRequest}.
 * @return
 */
private static String getRequestDomain(final HttpServletRequest request) {
    final StringBuffer stringBuffer = new StringBuffer(
            InternetUtils.isSecure(request) ? "https://" : "http://");
    stringBuffer.append(request.getServerName());
    if (request.getRemotePort() != 80) {
        stringBuffer.append(":");
        stringBuffer.append(request.getLocalPort());
    }
    stringBuffer.append(request.getContextPath());
    return stringBuffer.toString();
}

From source file:org.hx.rainbow.common.web.session.RainbowSession.java

public static void web2Service(HttpServletRequest request) {
    if (request == null) {
        return;//from w  w  w. ja  v  a  2 s .  c o m
    }
    setProperty(ThreadConstants.CONSTMER_IPADDRESS, request.getRemoteAddr());
    setProperty(ThreadConstants.CONSTMER_HOST, request.getRemoteHost());
    setProperty(ThreadConstants.CONSTMER_PORT, request.getRemotePort());
    setProperty(ThreadConstants.SERVICE_IPADDRESS, request.getLocalAddr());
    setProperty(ThreadConstants.SERVICE_HOST, request.getLocalName());
    setProperty(ThreadConstants.RAINBOW_REQUEST, request);

    HttpSession session = request.getSession();

    RainbowUser rainbowUser = (RainbowUser) session.getAttribute(ThreadConstants.RAINBOW_USER);
    if (rainbowUser != null) {
        setProperty(ThreadConstants.RAINBOW_SESSION, rainbowUser);
        setProperty(ThreadConstants.RAINBOW_LOGINID, rainbowUser.getUsername());
        setProperty(ThreadConstants.RAINBOW_USERNAME, rainbowUser.getSessionData().get("name"));

        String sessionKeys = (String) PropertiesUtil.getInstance().read(THREAD_LOACL_FILE)
                .get(ThreadConstants.SESSION_KEYS);
        if (sessionKeys != null) {
            if (sessionKeys.equals("*")) {
                Enumeration<String> attrNames = session.getAttributeNames();
                while (attrNames.hasMoreElements()) {
                    String attrName = (String) attrNames.nextElement();
                    if (SESSION_KEYS.contains(attrName)) {
                        continue;
                    }
                    if (attrName != null) {
                        Object session_attr = session.getAttribute(attrName);
                        if (session_attr != null) {
                            rainbowUser.getSessionData().put(attrName, session_attr);
                        }
                    }
                }
            } else {
                String[] s_sessionkey = StringUtils.split(sessionKeys, ",");
                for (int i = 0; i < s_sessionkey.length; i++) {
                    if (s_sessionkey[i] != null) {
                        Object session_attr = session.getAttribute(s_sessionkey[i]);
                        if (session_attr != null) {
                            rainbowUser.getSessionData().put(s_sessionkey[i], session_attr);
                        }
                    }
                }
            }
        }
    }
    //   
    //
    //
    //
    //      Map<String, Object> inCookie = new ConcurrentHashMap<String, Object>();
    //      String cookieKeys = (String)PropertiesUtil.get(ThreadConstants.resource_cookieKeys);
    //
    //      if (cookieKeys != null) {
    //         Cookie[] cookies = request.getCookies();
    //         if (cookies != null) {
    //            if (cookieKeys.equals("*")) {
    //               for (int i = 0; i < cookies.length; i++) {
    //                  Cookie cookie = cookies[i];
    //                  String cookieName = cookie.getName();
    //                  String cookieValue = cookie.getValue();
    //                  if(cookieName != null && cookieValue != null){
    //                     inCookie.put(cookieName, cookieValue);
    //                  }
    //               }
    //            } else {
    //               cookieKeys = cookieKeys + ",";
    //               for (int i = 0; i < cookies.length; i++) {
    //                  Cookie cookie = cookies[i];
    //                  String cookieName = cookie.getName();
    //                  if (cookieKeys.indexOf(cookieName + ",") > -1) {
    //                     String cookieValue = cookie.getValue();
    //                     if(cookieName != null && cookieValue != null){
    //                        inCookie.put(cookieName, cookieValue);
    //                     }
    //                  }
    //               }
    //            }
    //         }
    //         setProperty(ThreadConstants.IN_COOKIE, inCookie);
    //      }

}

From source file:org.jahia.bin.errors.ErrorLoggingFilter.java

/**
 * Returns the request information for logging purposes.
 *
 * @param request the http request object
 * @return the request information for logging purposes
 *//* ww  w .  ja  v  a  2  s. c o m*/
private static String getRequestInfo(HttpServletRequest request) {
    StringBuilder info = new StringBuilder(512);
    if (request != null) {
        String uri = (String) request.getAttribute("javax.servlet.error.request_uri");
        String queryString = (String) request.getAttribute("javax.servlet.forward.query_string");
        if (StringUtils.isNotEmpty(queryString)) {
            uri = uri + "?" + queryString;
        }
        info.append("Request information:").append("\nURL: ").append(uri).append("\nMethod: ")
                .append(request.getMethod()).append("\nProtocol: ").append(request.getProtocol())
                .append("\nRemote host: ").append(request.getRemoteHost()).append("\nRemote address: ")
                .append(request.getRemoteAddr()).append("\nRemote port: ").append(request.getRemotePort())
                .append("\nRemote user: ").append(request.getRemoteUser()).append("\nSession ID: ")
                .append(request.getRequestedSessionId()).append("\nSession user: ").append(getUserInfo(request))
                .append("\nRequest headers: ");

        @SuppressWarnings("unchecked")
        Iterator<String> headerNames = new EnumerationIterator(request.getHeaderNames());
        while (headerNames.hasNext()) {
            String headerName = headerNames.next();
            String headerValue = request.getHeader(headerName);
            info.append("\n  ").append(headerName).append(": ").append(headerValue);
        }
    }
    return info.toString();
}

From source file:org.jets3t.servlets.gatekeeper.GatekeeperServlet.java

/**
 * Handles POST requests that contain Gatekeeper messages encoded as POST form properties, and
 * sends a plain text response document containing the Gatekeeper response message encoded as
 * a properties file./* w  ww.jav a 2  s  . co  m*/
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("Handling POST request");
    }
    try {
        // Build Gatekeeper request from POST form parameters.
        GatekeeperMessage gatekeeperMessage = GatekeeperMessage.decodeFromProperties(request.getParameterMap());

        // Obtain client information
        ClientInformation clientInformation = new ClientInformation(request.getRemoteAddr(),
                request.getRemoteHost(), request.getRemoteUser(), request.getRemotePort(),
                request.getSession(false), request.getUserPrincipal(), request.getHeader("User-Agent"),
                request);

        // Generate Transaction ID, and store it in the message.
        String transactionId = transactionIdProvider.getTransactionId(gatekeeperMessage, clientInformation);
        if (transactionId != null) {
            gatekeeperMessage.addMessageProperty(GatekeeperMessage.PROPERTY_TRANSACTION_ID, transactionId);
        }

        if (!isInitCompleted) {
            if (log.isWarnEnabled()) {
                log.warn("Cannot process POST request as Gatekeeper servlet did not initialize correctly");
            }
            gatekeeperMessage.addApplicationProperty(GatekeeperMessage.APP_PROPERTY_GATEKEEPER_ERROR_CODE,
                    "GatekeeperInitializationError");
        } else if (gatekeeperMessage.getApplicationProperties()
                .containsKey(GatekeeperMessage.LIST_OBJECTS_IN_BUCKET_FLAG)) {
            // Handle "limited listing" requests.
            if (log.isDebugEnabled()) {
                log.debug("Listing objects");
            }
            boolean allowed = authorizer.allowBucketListingRequest(gatekeeperMessage, clientInformation);
            if (allowed) {
                bucketLister.listObjects(gatekeeperMessage, clientInformation);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Processing " + gatekeeperMessage.getSignatureRequests().length
                        + " object signature requests");
            }
            // Process each signature request.
            for (int i = 0; i < gatekeeperMessage.getSignatureRequests().length; i++) {
                SignatureRequest signatureRequest = gatekeeperMessage.getSignatureRequests()[i];

                // Determine whether the request will be allowed. If the request is not allowed, the
                // reason will be made available in the signature request object (with signatureRequest.declineRequest())
                boolean allowed = authorizer.allowSignatureRequest(gatekeeperMessage, clientInformation,
                        signatureRequest);

                // Sign requests when they are allowed. When a request is signed, the signed URL is made available
                // in the SignatureRequest object.
                if (allowed) {
                    String signedUrl = null;
                    if (SignatureRequest.SIGNATURE_TYPE_GET.equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signGet(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_HEAD
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signHead(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_PUT
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signPut(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_DELETE
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signDelete(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_ACL_LOOKUP
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signGetAcl(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_ACL_UPDATE
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signPutAcl(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    }
                    signatureRequest.signRequest(signedUrl);
                }
            }
        }

        // Build response as a set of properties, and return this document.
        Properties responseProperties = gatekeeperMessage.encodeToProperties();
        if (log.isDebugEnabled()) {
            log.debug("Sending response message as properties: " + responseProperties);
        }

        // Serialize properties to bytes.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        responseProperties.store(baos, "");

        // Send successful response.
        response.setStatus(200);
        response.setContentType("text/plain");
        response.getOutputStream().write(baos.toByteArray());
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Gatekeeper failed to send valid response", e);
        }
        response.setStatus(500);
        response.setContentType("text/plain");
        response.getWriter().println(e.toString());
    }
}

From source file:org.openqa.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {/*from  w w  w.  j  av  a  2s  .co  m*/
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}