Example usage for javax.servlet.http HttpServletRequest getLocalName

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

Introduction

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

Prototype

public String getLocalName();

Source Link

Document

Returns the host name of the Internet Protocol (IP) interface on which the request was received.

Usage

From source file:org.onebusaway.presentation.impl.ProxyServlet.java

/****
 * Private Method/*from   www .j av  a 2 s.c  o  m*/
 ****/

private String proxyUrl(HttpServletRequest req) {

    String pathInfo = req.getRequestURI();

    if (_source != null)
        pathInfo = pathInfo.replaceFirst(_source, "");

    String url = _target + pathInfo;

    if (!_target.startsWith("http"))
        url = "http://" + req.getLocalName() + ":" + req.getLocalPort() + url;

    if (req.getQueryString() != null)
        url += "?" + req.getQueryString();
    return url;
}

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  ww  .  j  a  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.projectforge.web.imagecropper.ImageCropperPage.java

/**
 * See list of constants PARAM_* for supported parameters.
 * @param parameters//from   w  ww  . j  av  a  2 s  . co m
 */
public ImageCropperPage(final PageParameters parameters) {
    super(parameters);
    if (WicketUtils.contains(parameters, PARAM_SHOW_UPLOAD_BUTTON) == true) {
        setEnableWhiteBoardFilter(WicketUtils.getAsBoolean(parameters, PARAM_SHOW_UPLOAD_BUTTON));
    }
    if (WicketUtils.contains(parameters, PARAM_ENABLE_WHITEBOARD_FILTER) == true) {
        setEnableWhiteBoardFilter(WicketUtils.getAsBoolean(parameters, PARAM_ENABLE_WHITEBOARD_FILTER));
    }
    if (WicketUtils.contains(parameters, PARAM_LANGUAGE) == true) {
        setDefaultLanguage(WicketUtils.getAsString(parameters, PARAM_LANGUAGE));
    }
    if (WicketUtils.contains(parameters, PARAM_RATIOLIST) == true) {
        setRatioList(WicketUtils.getAsString(parameters, PARAM_RATIOLIST));
    }
    if (WicketUtils.contains(parameters, PARAM_DEFAULT_RATIO) == true) {
        setDefaultRatio(WicketUtils.getAsString(parameters, PARAM_DEFAULT_RATIO));
    }
    if (WicketUtils.contains(parameters, PARAM_FILE_FORMAT) == true) {
        setFileFormat(WicketUtils.getAsString(parameters, PARAM_FILE_FORMAT));
    }
    final ServletWebRequest req = (ServletWebRequest) this.getRequest();
    final HttpServletRequest hreq = req.getContainerRequest();
    String domain;
    if (StringUtils.isNotBlank(ConfigXml.getInstance().getDomain()) == true) {
        domain = ConfigXml.getInstance().getDomain();
    } else {
        domain = hreq.getScheme() + "://" + hreq.getLocalName() + ":" + hreq.getLocalPort();
    }
    final String url = domain + hreq.getContextPath() + "/secure/";
    final StringBuffer buf = new StringBuffer();
    appendVar(buf, "serverURL", url); // TODO: Wird wohl nicht mehr gebraucht.
    appendVar(buf, "uploadImageFileTemporaryServlet", url + "UploadImageFileTemporary");
    appendVar(buf, "uploadImageFileTemporaryServletParams", "filedirectory=tempimages;filename=image");
    appendVar(buf, "downloadImageFileServlet", url + "DownloadImageFile");
    appendVar(buf, "downloadImageFileServletParams", "filedirectory=tempimages;filename=image");
    appendVar(buf, "uploadImageFileServlet", url + "UploadImageFile");
    appendVar(buf, "uploadImageFileServletParams", "filedirectory=images;filename=image;croppedname=cropped");
    appendVar(buf, "upAndDownloadImageFileAsByteArrayServlet", url + "UpAndDownloadImageFileAsByteArray");
    appendVar(buf, "upAndDownloadImageFileAsByteArrayServletParams", "filename=image;croppedname=cropped");
    final HttpSession httpSession = hreq.getSession();
    appendVar(buf, "sessionid", httpSession.getId());
    appendVar(buf, "ratioList", ratioList);
    appendVar(buf, "defaultRatio", defaultRatio);
    appendVar(buf, "isUploadBtn", showUploadButton);
    appendVar(buf, "whiteBoardFilter", enableWhiteBoardFilter);
    appendVar(buf, "language", getDefaultLanguage());
    appendVar(buf, "fileFormat", fileFormat);
    appendVar(buf, "flashFile", WicketUtils.getAbsoluteUrl("/imagecropper/MicromataImageCropper"));
    add(new Label("javaScriptVars", buf.toString()).setEscapeModelStrings(false));
}

From source file:org.red5.server.net.rtmpt.RTMPTConnection.java

/**
  * Setter for servlet request./*from ww  w .  j a v  a  2  s  .com*/
  *
  * @param request  Servlet request
  */
public void setServletRequest(HttpServletRequest request) {
    host = request.getLocalName();
    remoteAddress = request.getRemoteAddr();
    remoteAddresses = ServletUtils.getRemoteAddresses(request);
    remotePort = request.getRemotePort();
}

From source file:org.sakaiproject.nakamura.messagebucket.UntrustedMessageBucketServiceImpl.java

public String getBucketUrl(HttpServletRequest request, String context) throws MessageBucketException {
    String[] trackingCookies = clusterService.getRequestTrackingCookie(request);
    if (trackingCookies != null) {
        for (String trackingCookie : trackingCookies) {
            ClusterUser clusterUser = clusterService.getUser(trackingCookie);
            if (clusterUser != null) {
                String token = getToken(clusterUser.getUser(), context);
                return MessageFormat.format(urlPattern, request.getScheme(), request.getLocalName(),
                        String.valueOf(request.getLocalPort()), token, token.substring(0, 1),
                        token.substring(0, 2), clusterUser.getServerId(), request.getRemoteUser());
            }/*w  ww.j a  v  a  2 s  .c om*/
        }
    }
    throw new MessageBucketException("No Cluster tracking is available");
}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {//from   w ww .j  ava2  s  .  co m
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}

From source file:se.natusoft.osgi.aps.rpchttpextender.servlet.RPCServlet.java

/**
 * Handles the first page with general information inlcuding protocols and services.
 *
 * @param html The HTMLWriter to write to.
 * @param req  The HttpServletRequest.//  w w w.j  av a  2  s  .  co m
 * @throws IOException
 */
private void handleFirstPage(HTMLWriter html, HttpServletRequest req) throws IOException {
    html.tag("html");
    {
        html.tag("body", "", BG_COLOR);
        {
            html.tagc("h1",
                    "ApplicationPlatformServices (APS) Remote service call over HTTP transport provider");
            html.tagc("p",
                    "This provides an http transport for simple remote requests to OSGi services that have the \"APS-Externalizable: "
                            + "true\" in their META-INF/MANIFEST.MF. This follows the OSGi extender pattern and makes any registered "
                            + "OSGi services of bundles having the above manifest entry available for remote calls over HTTP. This "
                            + "transport makes use of the aps-external-protocol-extender which exposes services with the above "
                            + "mentioned manifest entry with each service method available as an APSExternallyCallable."
                            + "The aps-ext-protocol-http-transport acts as a mediator between the protocol implementations and "
                            + "aps-external-protocol-extender for requests over HTTP.");
            html.tagc("p",
                    "<b>Please note</b> that depending on protocol not every service method will be callable. It depends on "
                            + "its arguments and return value. It mostly depends on how well the protocol handles types and can convert "
                            + "between the caller and the service. Also note that bundles can specify \"APS-Externalizable: false\" in their "
                            + "META-INF/MANIFEST.MF. In that case none of the bundles services will be callable this way!");
            html.tagc("p", "This does not provide any protocol, only transport! For services "
                    + "to be able to be called at least one protocol is needed. Protocols are provided by providing an "
                    + "implementation of se.natusoft.osgi.aps.api.net.rpc.service.StreamedRPCProtocolService and registering "
                    + "it as an OSGi service. The StreamedRPCProtocolService API provides a protocol name and protocol "
                    + "version getter which is used to identify it. A call to an RPC service looks like this:");
            html.text(
                    "<ul><code>http://host:port/apsrpc/<i>protocol</i>/<i>version</i>[/<i>service</i>][/<i>method</i>]</code></ul>");
            html.text("<ul>" + "<i>protocol</i>" + "<ul>"
                    + "This is the name of the protocol to use. An implementation of that protocol must of course be available "
                    + "for this to work. If it isn't you will get a 404 back!" + "</ul>" + "</ul>");
            html.text("<ul>" + "<i>version</i>" + "<ul>"
                    + "This is the version of the protocol. If this doesn't match any protocols available you will also get a "
                    + "404 back." + "</ul>" + "</ul>");
            html.text("<ul>" + "<i>service</i>" + "<ul>"
                    + "This is the service to call. Depending on the protocol you might not need this. But for protocols that "
                    + "only provide method in the stream data like JSONRPC for example, then this is needed. When provided it "
                    + "has to be a fully qualified service interface class name." + "</ul>" + "</ul>");
            html.text("<ul>" + "<i>method</i>" + "<ul>"
                    + "This is a method of the service to call. The requirement for this also depends on the protocol. "
                    + "The JSONRPC protocols does not need this since they provide the method in the request. A REST "
                    + "protocol however would need this." + "</ul>" + "</ul>");

            html.tagc("h2", "Security");
            html.tagc("p",
                    "This help page always require authentication. This is because it register itself with the APSAdminWeb and "
                            + "is available as a tab there and thereby joins in the admin web authentication. For service calls however "
                            + "authentication is only required if you enable it in the configuration (network/rpc-http-transport). "
                            + "There are 2 variants of authentication for services:" + "<ul>"
                            + "<li>http://.../apsrpc/<b>auth:user:password</b>/protocol/...</li>"
                            + "<li>Basic HTTP authentication using header: 'Authorization: Basic {base 64 encoded user:password}'.</li>"
                            + "</ul>");
            html.tagc("p",
                    "Note that this is only a transport (over http)! It has nothing to say about protocols which is why the "
                            + "above auth methods are outside of the protocol, only part of this transport. If you make services that you "
                            + "expose this way it is also possible to leave the authentication config at false and provide authentication "
                            + "in your service by using the APSSimpleUserService or something else.");

            html.tagc("h2", "Found Protocols");

            for (StreamedRPCProtocol protocol : this.externalProtocolService.getAllStreamedProtocols()) {
                html.tagc("h3",
                        protocol.getServiceProtocolName() + " : " + protocol.getServiceProtocolVersion());
                html.tagc("p", protocol.getRPCProtocolDescription());

                html.tagc("p",
                        "<b>Request URL:</b>&nbsp;http://" + req.getLocalName() + ":" + req.getLocalPort()
                                + "/apsrpc/" + protocol.getServiceProtocolName() + "/"
                                + protocol.getServiceProtocolVersion() + "[/&lt;service&gt;][/&lt;method&gt;]");

                String reqContentType = protocol.getRequestContentType();
                String respContentType = protocol.getResponseContentType();
                if (reqContentType != null && reqContentType.trim().length() > 0) {
                    html.tagc("p", "<b>Request Content-type:</b> " + reqContentType);
                }
                if (respContentType != null && respContentType.trim().length() > 0) {
                    html.tagc("p", "<b>Response Content-type:</b> " + respContentType);
                }
            }

            html.tagc("h2", "Found Services");
            for (String service : this.externalProtocolService.getAvailableServices()) {
                ServiceReference sref = this.bundleContext.getServiceReference(service);
                if (sref != null) {
                    html.tagc("p",
                            "<a href=\"" + service + "\">" + service + "</a> <i>Bundle version:</i> "
                                    + sref.getBundle().getVersion() + ", <i>Bundle symbolic name:</i> "
                                    + sref.getBundle().getSymbolicName() + ", " + "<i>Bundle id:</i> "
                                    + sref.getBundle().getBundleId());
                }
            }
        }
        html.tage("body");
    }
    html.tage("html");
}

From source file:se.natusoft.osgi.aps.rpchttpextender.servlet.RPCServlet.java

/**
 * Handles the service page showing information about a specific service, like all its methods.
 *
 * @param html    The HTMLWriter to write to.
 * @param service The service to show information about.
 * @param req     The HTTPServletRequest.
 * @throws IOException//w  w  w.j a v  a2 s .c  o  m
 */
private void handleServicePage(HTMLWriter html, String service, HttpServletRequest req) throws IOException {
    Set<String> methodNames = this.externalProtocolService.getAvailableServiceFunctionNames(service);

    html.tag("html");
    {
        html.tag("body", "", BG_COLOR);
        {
            html.tagc("h1",
                    "ApplicationPlatformServices (APS) Remote service call over HTTP transport provider");
            html.tagc("p",
                    "Here the service and all its methods are displayed. Each method is clickable for details on the method.");

            html.tagc("h2", "Service");
            if (!methodNames.isEmpty()) {
                html.tagc("h3", service + " {");
                html.tag("ul");
                for (String method : methodNames) {
                    APSExternallyCallable<Object> callable = this.externalProtocolService.getCallable(service,
                            method);

                    //                        String params = "";
                    //                        String comma = "";
                    //                        for (DataTypeDescription parameter : callable.getParameterDataDescriptions()) {
                    //                            params = params + comma + toTypeName(parameter);
                    //                            comma = ", ";
                    //                        }

                    html.tagc("h4", toMethodDecl(callable, service, method));
                }
                html.tage("ul");
                html.tagc("h3", "}");

                html.tagc("h2", "Protocol URLs");
                html.tagc("p",
                        "Please note that even though these urls include the service, not all protocols require the service in "
                                + "the URL!");

                for (StreamedRPCProtocol protocol : this.externalProtocolService.getAllStreamedProtocols()) {
                    html.tagc("h3",
                            protocol.getServiceProtocolName() + " : " + protocol.getServiceProtocolVersion());

                    html.tagc("p",
                            "http://" + req.getLocalName() + ":" + req.getLocalPort() + "/apsrpc/"
                                    + protocol.getServiceProtocolName() + "/"
                                    + protocol.getServiceProtocolVersion() + "/" + service + "/");
                }

            } else {
                html.tagc("h2", "Service '" + service + "' not found!");
            }
        }
        html.tage("body");
    }
    html.tage("html");
}

From source file:unUtils.ActionError.java

@Override
public Object doAction(WikittyPublicationContext context) {
    error.printStackTrace();//from ww w.  ja  va2 s .  co  m

    HttpServletRequest req = context.getRequest();
    String result = "<html><body>Error: " + "<br>context: " + context + "<br>" + "<br>getContextPath: "
            + req.getContextPath() + "<br>getMethod: " + req.getMethod() + "<br>getPathInfo: "
            + req.getPathInfo() + "<br>getPathTranslated: " + req.getPathTranslated() + "<br>getQueryString: "
            + req.getQueryString() + "<br>getRemoteUser: " + req.getRemoteUser() + "<br>getRequestURI: "
            + req.getRequestURI() + "<br>getRequestURI: " + req.getRequestURI() + "<br>getRequestedSessionId: "
            + req.getRequestedSessionId() + "<br>getServletPath: " + req.getServletPath()
            + "<br>getCharacterEncoding: " + req.getCharacterEncoding() + "<br>getContentType: "
            + req.getContentType() + "<br>getLocalAddr: " + req.getLocalAddr() + "<br>getLocalName: "
            + req.getLocalName() + "<br>getProtocol: " + req.getProtocol() + "<br>getRemoteAddr: "
            + req.getRemoteAddr() + "<br>getRemoteHost: " + req.getRemoteHost() + "<br>getScheme: "
            + req.getScheme() + "<br>getServerName: " + req.getServerName() + "<br>" + "<br>error:<pre>"
            + StringEscapeUtils.escapeHtml(ExceptionUtil.stackTrace(error)) + "</pre>" + "</body></html>";
    return result;
}