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:net.lightbody.bmp.proxy.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 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();

}

From source file:net.xy.jcms.shared.adapter.HttpRequestDataAccessContext.java

/**
 * default constructor//from  w w  w  .ja  v a2s  .co  m
 * 
 * @param request
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
public HttpRequestDataAccessContext(final HttpServletRequest request)
        throws MalformedURLException, URISyntaxException {
    // gets cappsubrand default locale and various other jj related
    // informations mendatory to retrieve jj configuration
    try {
        request.setCharacterEncoding("UTF-8");
    } catch (final UnsupportedEncodingException e) {
    }
    contextPath = request.getContextPath() + "/";
    requestPath = request.getPathInfo().length() > 0 && request.getPathInfo().charAt(0) == '/'
            ? request.getPathInfo().substring(1)
            : request.getPathInfo();
    rootUrl = new URI(request.getProtocol().split("/", 2)[0], null, request.getLocalName(),
            request.getLocalPort(), "/", null, null);

    // properties
    if (request.getParameter("flushConfig") != null) {
        properties.put("flushConfig", true);
    }
}

From source file:org.ambraproject.action.debug.DebugInfoAction.java

@Override
public String execute() throws Exception {
    if (!checkAccess()) {
        return ERROR;
    }/* ww w  .j  a v  a  2 s .com*/
    timestamp = new Date(System.currentTimeMillis());
    Runtime rt = Runtime.getRuntime();
    jvmFreeMemory = (double) rt.freeMemory() / (1024.0 * 1024.0);
    jvmTotalMemory = (double) rt.totalMemory() / (1024.0 * 1024.0);
    jvmMaxMemory = (double) rt.maxMemory() / (1024.0 * 1024.0);
    HttpServletRequest req = ServletActionContext.getRequest();
    tomcatVersion = ServletActionContext.getServletContext().getServerInfo();
    sessionCount = SessionCounter.getSessionCount();
    host = req.getLocalName();
    hostIp = req.getLocalAddr();
    buildInfo = generateBuildInfo();

    // The easiest way I found to get the URL and username for the DB.
    // It's not that easy and involves opening a connection...
    Context initialContext = new InitialContext();
    Context context = (Context) initialContext.lookup("java:comp/env");
    DataSource ds = (DataSource) context.lookup("jdbc/AmbraDS");
    Connection conn = null;
    try {
        conn = ds.getConnection();
        DatabaseMetaData metadata = conn.getMetaData();
        dbUrl = metadata.getURL();
        dbUser = metadata.getUserName();
    } finally {
        conn.close();
    }

    Configuration config = ConfigurationStore.getInstance().getConfiguration();
    FileStoreService filestoreService = (FileStoreService) context.lookup("ambra/FileStore");
    filestore = filestoreService.toString();
    solrUrl = (String) config.getProperty("ambra.services.search.server.url");
    configuration = dumpConfig(config);
    cmdLine = IOUtils.toString(new FileInputStream("/proc/self/cmdline"));

    return SUCCESS;
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteResponseTest.java

@Test
public void testResolveGatewayParams() throws Exception {

    UrlRewriteProcessor rewriter = EasyMock.createNiceMock(UrlRewriteProcessor.class);

    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
    EasyMock.expect(context.getAttribute(UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME))
            .andReturn(rewriter).anyTimes();

    FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
    EasyMock.expect(config.getServletContext()).andReturn(context).anyTimes();

    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getScheme()).andReturn("mock-scheme").anyTimes();
    EasyMock.expect(request.getLocalName()).andReturn("mock-host").anyTimes();
    EasyMock.expect(request.getLocalPort()).andReturn(42).anyTimes();
    EasyMock.expect(request.getContextPath()).andReturn("/mock-path").anyTimes();
    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);

    EasyMock.replay(rewriter, context, config, request, response);

    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse(config, request, response);

    List<String> url = rewriteResponse.resolve("gateway.url");
    assertThat(url, hasItems(new String[] { "mock-scheme://mock-host:42/mock-path" }));

    List<String> scheme = rewriteResponse.resolve("gateway.scheme");
    assertThat(scheme, hasItems(new String[] { "mock-scheme" }));

    List<String> host = rewriteResponse.resolve("gateway.host");
    assertThat(host, hasItems(new String[] { "mock-host" }));

    List<String> port = rewriteResponse.resolve("gateway.port");
    assertThat(port, hasItems(new String[] { "42" }));

    List<String> addr = rewriteResponse.resolve("gateway.addr");
    assertThat(addr, hasItems(new String[] { "mock-host:42" }));

    List<String> address = rewriteResponse.resolve("gateway.addr");
    assertThat(address, hasItems(new String[] { "mock-host:42" }));

    List<String> path = rewriteResponse.resolve("gateway.path");
    assertThat(path, hasItems(new String[] { "/mock-path" }));
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {//from  w w  w  . j a va 2  s .c  o  m
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:org.apache.nifi.web.api.SiteToSiteResource.java

/**
 * Returns the available Peers and its status of this NiFi.
 *
 * @return A peersEntity.//from  ww w.  ja  v a2s. c  om
 */
@GET
@Path("/peers")
@Consumes(MediaType.WILDCARD)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@ApiOperation(value = "Returns the available Peers and its status of this NiFi", response = PeersEntity.class, authorizations = {
        @Authorization(value = "Read - /site-to-site", type = "") })
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
        @ApiResponse(code = 401, message = "Client could not be authenticated."),
        @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
        @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response getPeers(@Context HttpServletRequest req) {

    authorizeSiteToSite();

    if (!properties.isSiteToSiteHttpEnabled()) {
        return responseCreator.httpSiteToSiteIsNotEnabledResponse();
    }

    final Integer transportProtocolVersion;
    try {
        transportProtocolVersion = negotiateTransportProtocolVersion(req, transportProtocolVersionNegotiator);
    } catch (BadRequestException e) {
        return responseCreator.badRequestResponse(e);
    }

    final List<PeerDTO> peers = new ArrayList<>();
    if (properties.isNode()) {

        try {
            final Map<NodeIdentifier, NodeWorkload> clusterWorkload = clusterCoordinator.getClusterWorkload();
            clusterWorkload.entrySet().stream().forEach(entry -> {
                final PeerDTO peer = new PeerDTO();
                final NodeIdentifier nodeId = entry.getKey();
                final String siteToSiteAddress = nodeId.getSiteToSiteAddress();
                peer.setHostname(siteToSiteAddress == null ? nodeId.getApiAddress() : siteToSiteAddress);
                peer.setPort(nodeId.getSiteToSiteHttpApiPort() == null ? nodeId.getApiPort()
                        : nodeId.getSiteToSiteHttpApiPort());
                peer.setSecure(nodeId.isSiteToSiteSecure());
                peer.setFlowFileCount(entry.getValue().getFlowFileCount());
                peers.add(peer);
            });
        } catch (IOException e) {
            throw new RuntimeException("Failed to retrieve cluster workload due to " + e, e);
        }

    } else {
        // Standalone mode.
        final PeerDTO peer = new PeerDTO();

        // Private IP address or hostname may not be accessible from client in some environments.
        // So, use the value defined in nifi.properties instead when it is defined.
        final String remoteInputHost = properties.getRemoteInputHost();
        String localName;
        try {
            // Get local host name using InetAddress if available, same as RAW socket does.
            localName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to get local host name using InetAddress.", e);
            }
            localName = req.getLocalName();
        }

        peer.setHostname(isEmpty(remoteInputHost) ? localName : remoteInputHost);
        peer.setPort(properties.getRemoteInputHttpPort());
        peer.setSecure(properties.isSiteToSiteSecure());
        peer.setFlowFileCount(0); // doesn't matter how many FlowFiles we have, because we're the only host.

        peers.add(peer);
    }

    final PeersEntity entity = new PeersEntity();
    entity.setPeers(peers);

    return clusterContext(
            noCache(setCommonHeaders(Response.ok(entity), transportProtocolVersion, transactionManager)))
                    .build();
}

From source file:org.apache.openaz.xacml.rest.XACMLRest.java

/**
 * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
 *
 * @param request - Servlet request (from a POST/GET/PUT/etc.)
 *///from www  .  j  a v a  2s  .c  om
public static void dumpRequest(HttpServletRequest request) {
    if (logger.isDebugEnabled()) {
        // special-case for receiving heartbeat - don't need to repeatedly output all of the information
        // in multiple lines
        if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))) {
            logger.debug("GET type=hb : heartbeat received");
            return;
        }
        logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " "
                + request.getRemotePort());
        logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
        Enumeration<String> en = request.getHeaderNames();
        logger.debug("Headers:");
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            Enumeration<String> values = request.getHeaders(element);
            while (values.hasMoreElements()) {
                String value = values.nextElement();
                logger.debug(element + ":" + value);
            }
        }
        logger.debug("Attributes:");
        en = request.getAttributeNames();
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            logger.debug(element + ":" + request.getAttribute(element));
        }
        logger.debug("ContextPath: " + request.getContextPath());
        if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) {
            // POST and PUT are allowed to have parameters in the content, but in our usage the parameters
            // are always in the Query string.
            // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it
            // might contain a Policy file).
            // Unfortunately the request.getParameterMap method reads the content to see if there are any
            // parameters,
            // and once the content is read it cannot be read again.
            // Thus for PUT and POST we must avoid reading the content here so that the main code can read
            // it.
            logger.debug("Query String:" + request.getQueryString());
            try {
                if (request.getInputStream() == null) {
                    logger.debug("Content: No content inputStream");
                } else {
                    logger.debug("Content available: " + request.getInputStream().available());
                }
            } catch (Exception e) {
                logger.debug("Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)");
            }
        } else {
            logger.debug("Parameters:");
            Map<String, String[]> params = request.getParameterMap();
            Set<String> keys = params.keySet();
            for (String key : keys) {
                String[] values = params.get(key);
                logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
            }
        }
        logger.debug("Request URL:" + request.getRequestURL());
    }
}

From source file:org.apache.roller.weblogger.webservices.atomprotocol.RollerAtomHandler.java

private String authenticationOAUTH(HttpServletRequest request, HttpServletResponse response) {
    try {/* w  w  w  . j  a  v a 2  s .  c  o m*/
        OAuthManager omgr = WebloggerFactory.getWeblogger().getOAuthManager();
        OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);
        OAuthAccessor accessor = omgr.getAccessor(requestMessage);
        omgr.getValidator().validateMessage(requestMessage, accessor);
        return (String) accessor.consumer.getProperty("userId");

    } catch (Exception ex) {
        log.debug("ERROR authenticating user", ex);
        String realm = (request.isSecure()) ? "https://" : "http://";
        realm += request.getLocalName();
        try {
            OAuthServlet.handleException(response, ex, realm, true);
        } catch (Exception ioe) {
            log.debug("ERROR writing error response", ioe);
        }
    }
    return null;
}

From source file:org.apache.roller.weblogger.webservices.oauth.AccessTokenServlet.java

public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response,
        boolean sendBody) throws IOException, ServletException {
    log.debug("ERROR authorizing token", e);
    String realm = (request.isSecure()) ? "https://" : "http://";
    realm += request.getLocalName();
    OAuthServlet.handleException(response, e, realm, sendBody);
}

From source file:org.archive.wayback.core.WaybackRequest.java

/**
 * extract REFERER, remote IP and authorization information from the
 * HttpServletRequest/*from w ww.j av  a  2s  .co m*/
 * 
 * @param httpRequest
 */
private void extractHttpRequestInfo(HttpServletRequest httpRequest) {
    // attempt to get the HTTP referer if present..
    put(WaybackConstants.REQUEST_REFERER_URL, emptyIfNull(httpRequest.getHeader("REFERER")));
    put(WaybackConstants.REQUEST_REMOTE_ADDRESS, emptyIfNull(httpRequest.getRemoteAddr()));
    put(WaybackConstants.REQUEST_WAYBACK_HOSTNAME, emptyIfNull(httpRequest.getLocalName()));
    put(WaybackConstants.REQUEST_WAYBACK_PORT, String.valueOf(httpRequest.getLocalPort()));
    put(WaybackConstants.REQUEST_WAYBACK_CONTEXT, emptyIfNull(httpRequest.getContextPath()));
    put(WaybackConstants.REQUEST_AUTH_TYPE, emptyIfNull(httpRequest.getAuthType()));
    put(WaybackConstants.REQUEST_REMOTE_USER, emptyIfNull(httpRequest.getRemoteUser()));
    put(WaybackConstants.REQUEST_LOCALE_LANG, getUserLocale(httpRequest));

    Cookie[] cookies = httpRequest.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            put(cookie.getName(), cookie.getValue());
        }
    }
}