Example usage for javax.servlet.http HttpServletRequest getRequestedSessionId

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

Introduction

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

Prototype

public String getRequestedSessionId();

Source Link

Document

Returns the session ID specified by the client.

Usage

From source file:org.nuxeo.opensocial.shindig.gadgets.NXMakeRequestHandler.java

@Override
protected HttpRequest buildHttpRequest(HttpServletRequest request) throws GadgetException {
    HttpRequest req = super.buildHttpRequest(request);

    if (!svc.propagateJSESSIONIDToTrustedHosts()) {
        return req;
    }//from w ww . j  a  v  a2 s. c  o  m

    String auth = req.getUri().getAuthority();
    boolean done = false;
    if (auth != null) {
        if (auth.indexOf(':') != -1) {
            auth = auth.substring(0, auth.indexOf(':')); // foo:8080
        }
        for (String host : svc.getTrustedHosts()) {
            if (host.trim().equalsIgnoreCase(auth.trim())) {
                if (request.isRequestedSessionIdValid()) {
                    if (request.isRequestedSessionIdFromCookie()) {
                        req.addHeader(COOKIE, JSESSIONCOOKIE + request.getRequestedSessionId());
                        done = true;
                    }
                }
                break;
            }
        }
        if (!done) {
            String path = req.getUri().getPath();
            if ((path.startsWith(NUXEO_REST)) || (path.startsWith(NUXEO_WEBENG))) {
                req.addHeader(COOKIE, JSESSIONCOOKIE + request.getRequestedSessionId());
            }
        }
    }
    return req;
}

From source file:org.opencps.dossiermgt.portlet.DossierMgtFrontOfficePortlet.java

/**
 * @param renderRequest//from w  w  w  . j  ava 2s. co m
 * @param renderResponse
 * @throws PortletException
 * @throws IOException
 */
@Override
public void render(RenderRequest renderRequest, RenderResponse renderResponse)
        throws PortletException, IOException {

    // Reset check permission flag
    setHasPermission(true);

    HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest);

    HttpSession session = PortalSessionContext.get(request.getRequestedSessionId());

    // HttpSession session = request.getSession();

    validatePermission(renderRequest, renderResponse);

    AccountBean accountBean = AccountUtil.getAccountBean(renderRequest);

    if (_hasPermission) {

        ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);

        Dossier dossier = (Dossier) renderRequest.getAttribute(WebKeys.DOSSIER_ENTRY);

        DictCollection dictCollection = null;

        long dossierId = ParamUtil.getLong(renderRequest, DossierDisplayTerms.DOSSIER_ID);

        long dossierFileId = ParamUtil.getLong(renderRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID);

        long dossierPartId = ParamUtil.getLong(renderRequest, DossierFileDisplayTerms.DOSSIER_PART_ID);

        long serviceConfigId = ParamUtil.getLong(renderRequest, DossierDisplayTerms.SERVICE_CONFIG_ID);

        String accountType = GetterUtil.getString(session.getAttribute(WebKeys.ACCOUNT_TYPE));

        String selectedItems = StringPool.BLANK;

        try {

            if (dossierId > 0) {
                dossier = DossierLocalServiceUtil.getDossier(dossierId);
            }

            dictCollection = DictCollectionLocalServiceUtil.getDictCollection(themeDisplay.getScopeGroupId(),
                    PortletPropsValues.DATAMGT_MASTERDATA_ADMINISTRATIVE_REGION);

            if (dossier != null) {
                renderRequest.setAttribute(WebKeys.DOSSIER_ENTRY, dossier);
                serviceConfigId = dossier.getServiceConfigId();
                selectedItems = getSelectedItems(dossier, dictCollection);

            } else {

                if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_CITIZEN)) {

                    // Citizen citizen =
                    // (Citizen)
                    // session.getAttribute(WebKeys.CITIZEN_ENTRY);

                    Citizen citizen = (Citizen) accountBean.getAccountInstance();
                    selectedItems = getSelectedItems(citizen, dictCollection);

                } else if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_BUSINESS)) {
                    // Business business =
                    // (Business)
                    // session.getAttribute(WebKeys.BUSINESS_ENTRY);

                    Business business = (Business) accountBean.getAccountInstance();
                    selectedItems = getSelectedItems(business, dictCollection);

                }
            }
            renderRequest.setAttribute(WebKeys.DICT_ITEM_SELECTED, selectedItems);

            if (serviceConfigId > 0) {
                ServiceConfig serviceConfig = ServiceConfigLocalServiceUtil.getServiceConfig(serviceConfigId);

                renderRequest.setAttribute(WebKeys.SERVICE_CONFIG_ENTRY, serviceConfig);

                if (serviceConfig != null && serviceConfig.getServiceInfoId() > 0) {
                    ServiceInfo serviceInfo = ServiceInfoLocalServiceUtil
                            .getServiceInfo(serviceConfig.getServiceInfoId());

                    renderRequest.setAttribute(WebKeys.SERVICE_INFO_ENTRY, serviceInfo);

                    DossierTemplate dossierTemplate = DossierTemplateLocalServiceUtil
                            .getDossierTemplate(serviceConfig.getDossierTemplateId());
                    renderRequest.setAttribute(WebKeys.DOSSIER_TEMPLATE_ENTRY, dossierTemplate);
                }
            }

            if (dossierFileId > 0) {
                DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId);
                renderRequest.setAttribute(WebKeys.DOSSIER_FILE_ENTRY, dossierFile);
            }

            if (dossierPartId > 0) {
                DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId);
                renderRequest.setAttribute(WebKeys.DOSSIER_PART_ENTRY, dossierPart);
            }
        } catch (Exception e) {
            _log.error(e);
        }
    }

    super.render(renderRequest, renderResponse);

}

From source file:org.openmrs.module.fhir.filter.AuthorizationFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from  www  .j a v  a2s.co m*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // check the IP address first.  If its not valid, return a 403
    if (false) {
        // the ip address is not valid, set a 403 http error code
        HttpServletResponse httpresponse = (HttpServletResponse) response;
        httpresponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                "IP address '" + request.getRemoteAddr() + "' is not authorized");
    }

    // skip if the session has timed out, we're already authenticated, or it's not an HTTP request
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Session timed out");
        }

        if (!Context.isAuthenticated()) {
            String basicAuth = httpRequest.getHeader("Authorization");
            if (basicAuth != null) {
                // this is "Basic ${base64encode(username + ":" + password)}"
                try {
                    basicAuth = basicAuth.substring(6); // remove the leading "Basic "
                    String decoded = new String(Base64.decodeBase64(basicAuth), Charset.forName("UTF-8"));
                    String[] userAndPass = decoded.split(":");
                    Context.authenticate(userAndPass[0], userAndPass[1]);
                    if (log.isDebugEnabled()) {
                        log.debug("authenticated " + userAndPass[0]);
                    }
                } catch (Exception ex) {
                    // This filter never stops execution. If the user failed to
                    // authenticate, that will be caught later.
                }
            }
        }
    }

    // continue with the filter chain in all circumstances
    chain.doFilter(request, response);
}

From source file:org.openmrs.module.patientportaltoolkit.web.filter.AuthorizationFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///from  ww  w . ja  va2  s  .co  m
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // skip if the session has timed out, we're already authenticated, or it's not an HTTP request
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Session timed out");
        }
        if (!Context.isAuthenticated()) {
            String basicAuth = httpRequest.getHeader("Authorization");
            if (basicAuth != null) {
                // this is "Basic ${base64encode(username + ":" + password)}"
                try {
                    basicAuth = basicAuth.substring(6); // remove the leading "Basic "
                    String decoded = new String(Base64.decodeBase64(basicAuth), Charset.forName("UTF-8"));
                    String[] userAndPass = decoded.split(":");
                    Context.authenticate(userAndPass[0], userAndPass[1]);
                    if (log.isDebugEnabled())
                        log.debug("authenticated " + userAndPass[0]);
                } catch (Exception ex) {
                    // This filter never stops execution. If the user failed to
                    // authenticate, that will be caught later.
                }
            }
        }
    }
    // continue with the filter chain in all circumstances
    chain.doFilter(request, response);
}

From source file:org.openmrs.module.webservices.rest.web.filter.AuthorizationFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from   ww  w.j  a  va  2s .c  om*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // check the IP address first.  If its not valid, return a 403
    if (!RestUtil.isIpAllowed(request.getRemoteAddr())) {
        // the ip address is not valid, set a 403 http error code
        HttpServletResponse httpresponse = (HttpServletResponse) response;
        httpresponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                "IP address '" + request.getRemoteAddr() + "' is not authorized");
    }

    // skip if the session has timed out, we're already authenticated, or it's not an HTTP request
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Session timed out");
        }

        if (!Context.isAuthenticated()) {
            String basicAuth = httpRequest.getHeader("Authorization");
            if (basicAuth != null) {
                // this is "Basic ${base64encode(username + ":" + password)}"
                try {
                    basicAuth = basicAuth.substring(6); // remove the leading "Basic "
                    String decoded = new String(Base64.decodeBase64(basicAuth), Charset.forName("UTF-8"));
                    String[] userAndPass = decoded.split(":");
                    Context.authenticate(userAndPass[0], userAndPass[1]);
                    if (log.isDebugEnabled())
                        log.debug("authenticated " + userAndPass[0]);
                } catch (Exception ex) {
                    // This filter never stops execution. If the user failed to
                    // authenticate, that will be caught later.
                }
            }
        }
    }

    // continue with the filter chain in all circumstances
    chain.doFilter(request, response);
}

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

private String newSessionId(HttpServletRequest request, long created) {
    synchronized (__allSessions) {
        // A requested session ID can only be used if it is in the global map of
        // ID but not in this contexts map.  Ie it is an ID in use by another context
        // in this server and thus we are doing a cross context dispatch.
        if (_crossContextSessionIDs) {
            String requested_id = (String) request.getAttribute(__NEW_SESSION_ID);
            if (requested_id == null)
                requested_id = request.getRequestedSessionId();
            if (requested_id != null && requested_id != null && __allSessions.containsKey(requested_id)
                    && !_sessions.containsKey(requested_id))
                return requested_id;
        }//  w ww  .jav a  2s  .  c om

        // pick a new unique ID!
        String id = null;
        while (id == null || id.length() == 0 || __allSessions.containsKey(id)) {
            long r = _weakRandom
                    ? (hashCode() ^ Runtime.getRuntime().freeMemory() ^ _random.nextInt()
                            ^ (((long) request.hashCode()) << 32))
                    : _random.nextLong();
            r ^= created;
            if (request != null && request.getRemoteAddr() != null)
                r ^= request.getRemoteAddr().hashCode();
            if (r < 0)
                r = -r;
            id = Long.toString(r, 36);

            String worker = (String) request.getAttribute("org.openqa.jetty.http.ajp.JVMRoute");
            if (worker != null)
                id += "." + worker;
            else if (_workerName != null)
                id += "." + _workerName;
        }
        return id;
    }
}

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  .  ja v  a  2  s .c  o  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();

}

From source file:org.osaf.cosmo.dav.servlet.StandardRequestHandler.java

@SuppressWarnings("unchecked")
private void dumpRequest(HttpServletRequest req) {
    if (!log.isTraceEnabled())
        return;/*  w  w  w. ja  v  a  2 s.  c o  m*/

    StringBuffer sb = new StringBuffer("\n------------------------ Dump of request -------------------\n");
    try {
        Enumeration names = req.getHeaderNames();

        sb.append("Request headers:\n");
        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String val = req.getHeader(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"\n");
        }

        names = req.getParameterNames();
        String title = "Request parameters";

        sb.append(title).append(" - global info and uris:").append("\n");
        sb.append("getMethod = ").append(req.getMethod()).append("\n");
        sb.append("getRemoteAddr = ").append(req.getRemoteAddr()).append("\n");
        sb.append("getRequestURI = ").append(req.getRequestURI()).append("\n");
        sb.append("getRemoteUser = ").append(req.getRemoteUser()).append("\n");
        sb.append("getRequestedSessionId = ").append(req.getRequestedSessionId()).append("\n");
        sb.append("HttpUtils.getRequestURL(req) = ").append(req.getRequestURL()).append("\n");
        sb.append("contextPath=").append(req.getContextPath()).append("\n");
        sb.append("query=").append(req.getQueryString()).append("\n");
        sb.append("contentlen=").append(req.getContentLength()).append("\n");
        sb.append("request=").append(req).append("\n");
        sb.append(title).append(":\n");

        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String val = req.getParameter(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"").append("\n");
            ;
        }
        sb.append("Request attributes:\n");
        for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            Object val = req.getAttribute(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"").append("\n");
            ;
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    sb.append("------------------------ End dump of request -------------------");
    log.trace(sb);
}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * Show HTTP header information.//from  w ww .  j  a v  a2s .c  om
 */
@SuppressWarnings("unchecked")
protected void showRequestInfo(HttpServletRequest req) {

    if (M_log.isDebugEnabled())
        M_log.debug("DefaultServlet Request Info");

    // Show generic info
    if (M_log.isDebugEnabled())
        M_log.debug("Encoding : " + req.getCharacterEncoding());
    if (M_log.isDebugEnabled())
        M_log.debug("Length : " + req.getContentLength());
    if (M_log.isDebugEnabled())
        M_log.debug("Type : " + req.getContentType());

    if (M_log.isDebugEnabled())
        M_log.debug("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
    }

    if (M_log.isDebugEnabled())
        M_log.debug("Protocol : " + req.getProtocol());
    if (M_log.isDebugEnabled())
        M_log.debug("Address : " + req.getRemoteAddr());
    if (M_log.isDebugEnabled())
        M_log.debug("Host : " + req.getRemoteHost());
    if (M_log.isDebugEnabled())
        M_log.debug("Scheme : " + req.getScheme());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Name : " + req.getServerName());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Port : " + req.getServerPort());

    if (M_log.isDebugEnabled())
        M_log.debug("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        if (M_log.isDebugEnabled())
            M_log.debug(req.getAttribute(attributeName).toString());
    }

    // Show HTTP info
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Header Info");

    if (M_log.isDebugEnabled())
        M_log.debug("Authentication Type : " + req.getAuthType());
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Method : " + req.getMethod());
    if (M_log.isDebugEnabled())
        M_log.debug("Path Info : " + req.getPathInfo());
    if (M_log.isDebugEnabled())
        M_log.debug("Path translated : " + req.getPathTranslated());
    if (M_log.isDebugEnabled())
        M_log.debug("Query string : " + req.getQueryString());
    if (M_log.isDebugEnabled())
        M_log.debug("Remote user : " + req.getRemoteUser());
    if (M_log.isDebugEnabled())
        M_log.debug("Requested session id : " + req.getRequestedSessionId());
    if (M_log.isDebugEnabled())
        M_log.debug("Request URI : " + req.getRequestURI());
    if (M_log.isDebugEnabled())
        M_log.debug("Context path : " + req.getContextPath());
    if (M_log.isDebugEnabled())
        M_log.debug("Servlet path : " + req.getServletPath());
    if (M_log.isDebugEnabled())
        M_log.debug("User principal : " + req.getUserPrincipal());
    if (M_log.isDebugEnabled())
        M_log.debug("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        if (M_log.isDebugEnabled())
            M_log.debug(req.getHeader(headerName));
    }
}

From source file:org.sakaiproject.kernel.rest.test.RestMySitesProviderKernelUnitT.java

@Test
public void testUserWithEnv() throws ServletException, IOException, JCRNodeFactoryServiceException,
        LoginException, RepositoryException {

    KernelManager km = new KernelManager();
    SessionManagerService sessionManagerService = km.getService(SessionManagerService.class);
    CacheManagerService cacheManagerService = km.getService(CacheManagerService.class);
    UserResolverService userResolverService = km.getService(UserResolverService.class);
    AuthzResolverService authzResolverService = km.getService(AuthzResolverService.class);
    JCRService jcrService = km.getService(JCRService.class);
    // bypass security
    authzResolverService.setRequestGrant("Populating Test JSON");

    // login to the repo with super admin
    SakaiJCRCredentials credentials = new SakaiJCRCredentials();
    Session jsession = jcrService.getRepository().login(credentials);
    jcrService.setSession(jsession);//from   w  ww  . java2s .c o m

    // setup the user environment for the admin user.
    /*
     * for (String userName : USERS) { String prefix =
     * PathUtils.getUserPrefix(userName); String userEnvironmentPath =
     * "/userenv" + prefix + "userenv";
     *
     * LOG.info("Saving "+userEnvironmentPath);
     * jcrNodeFactoryService.createFile(userEnvironmentPath); InputStream in =
     * ResourceLoader.openResource(USERBASE + userName + ".json",
     * RestMySitesProviderTest.class.getClassLoader());
     * jcrNodeFactoryService.setInputStream(userEnvironmentPath, in);
     * jsession.save(); in.close(); }
     */

    LOG.info("Getting RestMySitesProvider using key: " + RestMySitesProvider.SITES_ELEMENT);
    RegistryService registryService = km.getService(RegistryService.class);
    Registry<String, RestProvider> registry = registryService.getRegistry(RestProvider.REST_REGISTRY);
    RestMySitesProvider rmsp = (RestMySitesProvider) registry.getMap().get(RestMySitesProvider.SITES_ELEMENT);
    for (String key : registry.getMap().keySet()) {
        LOG.info(key + "--->" + registry.getMap().get(key));
    }
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);
    HttpSession session = createMock(HttpSession.class);

    Assert.assertNotNull(rmsp);

    expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();

    expect(request.getSession(true)).andReturn(session).anyTimes();
    expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
    expect(session.getAttribute("_u")).andReturn(new InternalUser("ib236")).anyTimes();
    expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
    expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
    expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
    expect(request.getParameter(RestMySitesProvider.INPUT_PARAM_NAME_STARTINDEX)).andReturn(null).anyTimes();
    expect(request.getParameter(RestMySitesProvider.INPUT_PARAM_NAME_COUNT)).andReturn(null).anyTimes();
    expect(request.getRequestedSessionId()).andReturn("sessionId").anyTimes();

    Cookie c = new Cookie("JSESSIONID", "sessionId");

    expect(request.getCookies()).andReturn(new Cookie[] { c }).anyTimes();
    expect(session.getId()).andReturn("sessionId").anyTimes();
    response.addCookie((Cookie) anyObject());
    expectLastCall().atLeastOnce();
    response.setContentType(RestProvider.CONTENT_TYPE);
    expectLastCall().atLeastOnce();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    expect(response.getOutputStream()).andReturn(new ServletOutputStream() {

        @Override
        public void write(int b) throws IOException {
            baos.write(b);
        }

    });
    expectLastCall().atLeastOnce();
    replay(request, response, session);

    SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request, response, userResolverService,
            sessionManagerService);
    sessionManagerService.bindRequest(sakaiServletRequest);

    LOG.info("Dispatching to provider... /rest/" + RestMySitesProvider.SITES_ELEMENT);
    rmsp.dispatch(new String[] { RestMySitesProvider.SITES_ELEMENT }, request, response);

    String responseString = new String(baos.toByteArray(), "UTF-8");
    LOG.info("Response was " + responseString);
    // FIXME: My sites works differently at the moment.    assertTrue(responseString.indexOf("\"entry\"") > 0);

    cacheManagerService.unbind(CacheScope.REQUEST);
    verify(request, response, session);

}