Example usage for javax.servlet.http HttpServletRequest getRemotePort

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

Introduction

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

Prototype

public int getRemotePort();

Source Link

Document

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

Usage

From source file:com.streamsets.pipeline.lib.http.HttpReceiverServlet.java

@VisibleForTesting
boolean validatePostRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    boolean valid = false;
    if (validateAppId(req, res)) {
        String compression = req.getHeader(HttpConstants.X_SDC_COMPRESSION_HEADER);
        if (compression == null) {
            valid = true;/*from   w  ww . j ava 2s.  c o  m*/
        } else {
            switch (compression) {
            case HttpConstants.SNAPPY_COMPRESSION:
                valid = true;
                break;
            default:
                String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
                LOG.warn("Invalid compression '{}' in request from '{}', returning error", compression,
                        requestor);
                res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                        "Unsupported compression: " + compression);
                break;
            }
        }
    }
    return valid && getReceiver().validate(req, res);
}

From source file:org.iwethey.forums.web.HeaderInterceptor.java

/**
 * Load the request attributes with the User object (if authenticated)
 * and start time for the page for audit purposes.
 * <p>/*  www  .  jav  a 2 s .c  om*/
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Date now = new Date();
    request.setAttribute("now", now);

    long start = now.getTime();
    request.setAttribute("start", new Long(start));

    Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE);

    User user = null;

    if (id == null) {
        user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE);

        if (user == null) {
            user = new User("Anonymous");
            WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user);
        }
    } else {
        user = mUserManager.getUserById(id.intValue());
        user.setLastPresent(new Date());
        mUserManager.saveUserAttributes(user);
    }

    request.setAttribute("username", user.getNickname());
    request.setAttribute(USER_ATTRIBUTE, user);

    System.out.println("Local Address  = [" + request.getLocalAddr() + "]");
    System.out.println("Local Name     = [" + request.getLocalName() + "]");
    System.out.println("Remote Address = [" + request.getRemoteAddr() + "]");
    System.out.println("Remote Host    = [" + request.getRemoteHost() + "]");
    System.out.println("Remote Port    = [" + request.getRemotePort() + "]");
    System.out.println("Remote User    = [" + request.getRemoteUser() + "]");
    System.out.println("Context Path   = [" + request.getContextPath() + "]");
    System.out.println("====================");

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            System.out.println("Cookie Domain = [" + cookie.getDomain() + "]");
            System.out.println("Cookie Name   = [" + cookie.getName() + "]");
            System.out.println("Cookie Value  = [" + cookie.getValue() + "]");
            System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]");
            System.out.println("====================");

            if ("iwt_cookie".equals(cookie.getName())) {
                cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
                response.addCookie(cookie);
            }
        }
    } else {
        System.out.println("No cookies were found in the request");
    }

    Cookie newCookie = new Cookie("iwt_cookie", "harrr2!");
    newCookie.setPath(request.getContextPath());
    newCookie.setDomain(request.getLocalName());
    newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
    response.addCookie(newCookie);

    request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png");

    return true;
}

From source file:org.wrml.server.WrmlServlet.java

/**
 * Get the requested resource's id from the the {@link HttpServletRequest}.
 *
 * @param request The {@link HttpServletRequest} that holds the {@link URI}.
 * @return The requested resource's id from the the {@link HttpServletRequest}.
 * @throws URISyntaxException Thrown if there is a syntax problem when constructing the {@link URI}.
 *///  w  ww .  ja  v  a 2  s .c  o  m
URI getRequestUri(final HttpServletRequest request) throws URISyntaxException {
    // Due to the quirky nature of a servlet container, we're after the entire path.  
    // This seems to work with servlet 3.0 and Tomcat 7.X
    String path = request.getServletPath();
    String extra = request.getPathInfo();
    if (path != null && extra != null) {
        path += request.getPathInfo();
    } else if (path == null) {
        path = extra;
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    final String host = StringUtils.defaultIfEmpty(request.getHeader(WRML_HOST_HEADER_NAME),
            request.getRemoteHost());
    final String portString = StringUtils.defaultIfEmpty(request.getHeader(WRML_PORT_HEADER_NAME),
            Integer.toString(request.getRemotePort()));
    final String scheme = StringUtils.defaultIfEmpty(request.getHeader(WRML_SCHEME_HEADER_NAME),
            request.getScheme());
    int port = -1;

    port = Integer.parseInt(portString);
    if (port == 80) {
        port = -1;
    }
    final URI requestUri = new URI(scheme, null, host, port, path, null, null);

    LOGGER.debug("Determined request URI: {}", requestUri);
    return requestUri;
}

From source file:io.datenwelt.cargo.rest.Request.java

public Request(HttpServletRequest servletRequest, List<ContentType> supportedContentTypes,
        List<ContentEncoding> supportedContentEncodings) throws APIException {
    this.servletRequest = servletRequest;
    this.supportedContentTypes = supportedContentTypes;
    this.supportedContentEncodings = supportedContentEncodings;
    this.method = servletRequest.getMethod();
    this.path = Segment.normalize(servletRequest.getPathInfo());

    StringBuffer url = servletRequest.getRequestURL();
    String query = servletRequest.getQueryString();
    if (query != null && !query.isEmpty()) {
        url.append("?").append(query);
    }//from w  ww . j a v  a 2 s  . co  m

    // Parse request URI and construct the base URI.
    try {
        requestURI = new URI(url.toString());
        String basePath = (servletRequest.getContextPath() == null ? "" : servletRequest.getContextPath())
                + (servletRequest.getServletPath() == null ? "" : servletRequest.getServletPath());
        baseURI = URI.create(new StringBuffer().append(requestURI.getScheme()).append("://")
                .append(requestURI.getRawAuthority()).append("/").append(basePath).toString());
        path = Segment.normalize(requestURI.getPath());
        if (path.startsWith(basePath)) {
            path = path.substring(basePath.length());
        }
    } catch (URISyntaxException ex) {
        throw new APIException(new InternalServerError(), "Unable to parse request URI from string '"
                + requestURI + "'. Using defaut value for base URI. Error: " + ex.getMessage(), ex);
    }

    // Parse query string.
    String queryString = servletRequest.getQueryString();
    this.queries.addAll(Query.parseQueryString(queryString));

    // Parse header values
    Enumeration headerNames = servletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement().toString();
        Enumeration values = servletRequest.getHeaders(name);
        while (values.hasMoreElements()) {
            Header header = headers.get(name);
            if (header == null) {
                header = new Header(name);
                headers.put(header.getName(), header);
            }
            String value = values.nextElement().toString();
            header.add(Header.decode(name, value));
        }
    }

    // Collect infos about the remote end.
    remoteAddress = servletRequest.getRemoteAddr();
    remoteHost = servletRequest.getRemoteHost();
    remotePort = servletRequest.getRemotePort();

}

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 w w  . j a v a 2s.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:nz.co.fortytwo.signalk.processor.RestApiProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    // the Restlet request should be available if needed
    HttpServletRequest request = exchange.getIn(HttpMessage.class).getRequest();
    HttpSession session = request.getSession();
    if (logger.isDebugEnabled()) {

        logger.debug("Request = " + exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST).getClass());
        logger.debug("Session = " + session.getId());
    }//from  ww  w.  j  a v  a2s  .c o  m

    if (session.getId() != null) {
        exchange.getIn().setHeader(REST_REQUEST, "true");
        String remoteAddress = request.getRemoteAddr();
        String localAddress = request.getLocalAddr();
        if (Util.sameNetwork(localAddress, remoteAddress)) {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.INTERNAL_IP);
        } else {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.EXTERNAL_IP);
        }
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_IP, remoteAddress);
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_IP_PORT, request.getRemotePort());
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_BUS, "rest." + remoteAddress.replace('.', '_'));
        exchange.getIn().setHeader(WebsocketConstants.CONNECTION_KEY, session.getId());

        String path = (String) exchange.getIn().getHeader(Exchange.HTTP_URI);
        if (logger.isDebugEnabled()) {
            logger.debug(exchange.getIn().getHeaders());
            logger.debug(path);
        }

        if (logger.isDebugEnabled())
            logger.debug("Processing the path = " + path);
        if (!isValidPath(path)) {
            exchange.getIn().setBody("Bad Request");
            exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/plain");
            exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpServletResponse.SC_BAD_REQUEST);
            // response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("GET")) {
            processGet(exchange, path);
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("PUT")) {
            processPut(exchange, path);
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("POST")) {
            if (exchange.getIn().getBody() instanceof StreamCache) {
                StreamCache cache = exchange.getIn().getBody(StreamCache.class);
                ByteArrayOutputStream writer = new ByteArrayOutputStream();
                cache.writeTo(writer);
                if (logger.isDebugEnabled())
                    logger.debug("Reading the POST request:" + writer.toString());
                exchange.getIn().setBody(writer.toString());

                // POST here
                if (logger.isDebugEnabled())
                    logger.debug("Processing the POST request:" + exchange.getIn().getBody());
            } else {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Skipping processing the POST request:" + exchange.getIn().getBody().getClass());
            }
        }

    } else {
        // HttpServletResponse response =
        // exchange.getIn(HttpMessage.class).getResponse();
        exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpServletResponse.SC_MOVED_TEMPORARILY);
        // constant("http://somewhere.com"))
        exchange.getIn().setHeader("Location", SignalKConstants.SIGNALK_AUTH);
        exchange.getIn().setBody("Authentication Required");
    }

}

From source file:org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter.java

public boolean authenticateRequest(ServletContext context, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    // Check if there is an authorization header with an SPNEGO security blob

    String authHdr = req.getHeader("Authorization");
    boolean reqAuth = false;

    if (authHdr != null) {
        // Check for a Kerberos/SPNEGO authorization header

        if (authHdr.startsWith("Negotiate"))
            reqAuth = true;/*from w  w  w  .  ja  v  a2 s .  c  o  m*/
        else if (authHdr.startsWith("NTLM")) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Received NTLM logon from client");

            // Restart the authentication

            restartLoginChallenge(context, req, resp);
            return false;
        } else if (isFallbackEnabled()) {
            return performFallbackAuthentication(context, req, resp);
        }
    }

    // Check if the user is already authenticated        
    SessionUser user = getSessionUser(context, req, resp, true);
    HttpSession httpSess = req.getSession(true);
    if (user == null) {
        user = (SessionUser) httpSess.getAttribute("_alfAuthTicket");
        // MNT-13191 Opening /alfresco/webdav from a Kerberos-authenticated IE11 browser causes HTTP error 500
        if (user != null) {
            String userName = user.getUserName();
            AuthenticationUtil.setFullyAuthenticatedUser(userName);
        }
    }

    // If the user has been validated and we do not require re-authentication then continue to
    // the next filter
    if (user != null && reqAuth == false) {
        // Filter validate hook
        onValidate(context, req, resp, new TicketCredentials(user.getTicket()));

        // Debug

        if (getLogger().isDebugEnabled())
            getLogger().debug("Authentication not required (user), chaining ...");

        // Chain to the next filter

        return true;
    }

    // Check if the login page is being accessed, do not intercept the login page
    if (checkLoginPage(req, resp)) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Login page requested, chaining ...");

        // Chain to the next filter

        return true;
    }

    // Check the authorization header

    if (authHdr == null) {

        // If ticket based logons are allowed, check for a ticket parameter

        if (allowsTicketLogons()) {
            // Check if a ticket parameter has been specified in the reuqest

            if (checkForTicketParameter(context, req, resp)) {
                // Filter validate hook
                if (getLogger().isDebugEnabled())
                    getLogger().debug("Authenticated with a ticket parameter.");

                if (user == null) {
                    user = (SessionUser) httpSess.getAttribute(getUserAttributeName());
                }
                onValidate(context, req, resp, new TicketCredentials(user.getTicket()));

                // Chain to the next filter

                return true;
            }
        }

        // Debug

        if (getLogger().isDebugEnabled())
            getLogger().debug("New Kerberos auth request from " + req.getRemoteHost() + " ("
                    + req.getRemoteAddr() + ":" + req.getRemotePort() + ")");

        // Send back a request for SPNEGO authentication
        logonStartAgain(context, req, resp, true);
        return false;
    } else {
        // Decode the received SPNEGO blob and validate

        final byte[] spnegoByts = Base64.decodeBase64(authHdr.substring(10).getBytes());

        // Check if the client sent an NTLMSSP blob

        if (isNTLMSSPBlob(spnegoByts, 0)) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Client sent an NTLMSSP security blob");

            // Restart the authentication

            restartLoginChallenge(context, req, resp);
            return false;
        }

        //  Check the received SPNEGO token type

        int tokType = -1;

        try {
            tokType = SPNEGO.checkTokenType(spnegoByts, 0, spnegoByts.length);
        } catch (IOException ex) {
        }

        // Check for a NegTokenInit blob

        if (tokType == SPNEGO.NegTokenInit) {
            //  Parse the SPNEGO security blob to get the Kerberos ticket

            NegTokenInit negToken = new NegTokenInit();

            try {
                // Decode the security blob

                negToken.decode(spnegoByts, 0, spnegoByts.length);

                //  Determine the authentication mechanism the client is using and logon

                String oidStr = null;
                if (negToken.numberOfOids() > 0)
                    oidStr = negToken.getOidAt(0).toString();

                if (oidStr != null && (oidStr.equals(OID.ID_MSKERBEROS5) || oidStr.equals(OID.ID_KERBEROS5))) {
                    //  Kerberos logon

                    try {
                        NegTokenTarg negTokenTarg = doKerberosLogon(negToken, req, resp, httpSess);
                        if (negTokenTarg != null) {
                            // Allow the user to access the requested page
                            onValidate(context, req, resp, new KerberosCredentials(negToken, negTokenTarg));
                            if (getLogger().isDebugEnabled())
                                getLogger().debug("Authenticated through Kerberos.");
                            return true;
                        } else {
                            // Send back a request for SPNEGO authentication
                            if (getLogger().isDebugEnabled())
                                getLogger().debug("Failed SPNEGO authentication.");
                            restartLoginChallenge(context, req, resp);
                            return false;
                        }
                    } catch (AuthenticationException ex) {
                        // Even though the user successfully authenticated, the ticket may not be granted, e.g. to
                        // max user limit
                        if (getLogger().isDebugEnabled())
                            getLogger().debug("Validate failed.", ex);
                        onValidateFailed(context, req, resp, httpSess, new TicketCredentials(user.getTicket()));
                        return false;
                    }
                } else {
                    //  Unsupported mechanism, e.g. NegoEx

                    if (getLogger().isDebugEnabled())
                        getLogger().debug("Unsupported SPNEGO mechanism " + oidStr);

                    // Try again!

                    restartLoginChallenge(context, req, resp);
                }
            } catch (IOException ex) {
                // Log the error

                if (getLogger().isDebugEnabled())
                    getLogger().debug(ex);
            }
        } else {
            //  Unknown SPNEGO token type

            if (getLogger().isDebugEnabled())
                getLogger().debug("Unknown SPNEGO token type");

            // Send back a request for SPNEGO authentication

            restartLoginChallenge(context, req, resp);
        }
    }
    return false;
}

From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java

public boolean authenticateRequest(ServletContext context, HttpServletRequest sreq, HttpServletResponse sresp)
        throws IOException, ServletException {
    // Check if there is an authorization header with an NTLM security blob
    String authHdr = sreq.getHeader(AUTHORIZATION);
    boolean reqAuth = false;

    // Check if an NTLM authorization header was received

    if (authHdr != null) {
        // Check for an NTLM authorization header

        if (authHdr.startsWith(AUTH_NTLM))
            reqAuth = true;/*from  w w w  .ja va  2s  .c o  m*/
        else if (authHdr.startsWith("Negotiate")) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Received 'Negotiate' from client, may be SPNEGO/Kerberos logon");

            // Restart the authentication

            restartLoginChallenge(context, sreq, sresp);
            return false;
        } else if (isFallbackEnabled()) {
            return performFallbackAuthentication(context, sreq, sresp);
        }
    }

    // Check if the user is already authenticated
    SessionUser user = getSessionUser(context, sreq, sresp, true);

    // If the user has been validated and we do not require re-authentication then continue to
    // the next filter
    if (user != null && reqAuth == false) {
        // Filter validate hook
        onValidate(context, sreq, sresp, new TicketCredentials(user.getTicket()));

        if (getLogger().isDebugEnabled())
            getLogger().debug("Authentication not required (user), chaining ...");

        // Chain to the next filter
        return true;
    }

    // Check if the login page is being accessed, do not intercept the login page
    if (hasLoginPage() && sreq.getRequestURI().endsWith(getLoginPage()) == true) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Login page requested, chaining ...");

        // Chain to the next filter
        return true;
    }

    // Check if the browser is Opera, if so then display the login page as Opera does not
    // support NTLM and displays an error page if a request to use NTLM is sent to it
    String userAgent = sreq.getHeader("user-agent");
    if (userAgent != null && userAgent.indexOf("Opera ") != -1) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Opera detected, redirecting to login page");

        // If there is no login page configured (WebDAV) then just keep requesting the user details from the client

        if (hasLoginPage())
            redirectToLoginPage(sreq, sresp);
        else
            restartLoginChallenge(context, sreq, sresp);
        return false;
    }

    // Check the authorization header
    if (authHdr == null) {
        // Check for a ticket based logon, if enabled

        if (allowsTicketLogons()) {
            // Check if the request includes an authentication ticket

            if (checkForTicketParameter(context, sreq, sresp)) {

                // Authentication was bypassed using a ticket parameter
                return true;
            }
        }

        // DEBUG

        if (getLogger().isDebugEnabled())
            getLogger().debug("New NTLM auth request from " + sreq.getRemoteHost() + " (" + sreq.getRemoteAddr()
                    + ":" + sreq.getRemotePort() + ") SID:" + sreq.getSession().getId());

        // Send back a request for NTLM authentication
        restartLoginChallenge(context, sreq, sresp);
        return false;
    } else {
        HttpSession session = sreq.getSession();
        Object sessionMutex = WebUtils.getSessionMutex(session);
        // Decode the received NTLM blob and validate
        final byte[] ntlmByts = Base64.decodeBase64(authHdr.substring(5).getBytes());
        int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
        if (ntlmTyp == NTLM.Type1) {
            // Process the type 1 NTLM message
            Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType1(type1Msg, sreq, sresp);
            }
            return false;
        } else if (ntlmTyp == NTLM.Type3) {
            // Process the type 3 NTLM message
            Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                return processType3(type3Msg, context, sreq, sresp);
            }
        } else {
            if (getLogger().isDebugEnabled())
                getLogger().debug("NTLM blob not handled, redirecting to login page.");

            if (hasLoginPage())
                redirectToLoginPage(sreq, sresp);
            else
                restartLoginChallenge(context, sreq, sresp);
            return false;
        }
    }
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

/**
 * Run the filter//w  w w .  j  a  va2  s  . co m
 * 
 * @param sreq ServletRequest
 * @param sresp ServletResponse
 * @param chain FilterChain
 * 
 * @exception IOException
 * @exception ServletException
 */
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain)
        throws IOException, ServletException {
    NDC.remove();
    NDC.push(Thread.currentThread().getName());
    final boolean debug = logger.isDebugEnabled();

    // Wrap externally authenticated requests that provide the user in an HTTP header
    // with one that returns the correct name from getRemoteUser(). For use in our own
    // calls to this method and any chained filters.
    sreq = wrapHeaderAuthenticatedRequest(sreq);

    // Bypass the filter if we don't have an endpoint with external auth enabled
    if (this.endpoint == null) {
        if (debug)
            logger.debug("There is no endpoint with external auth enabled.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // Get the HTTP request/response/session
    HttpServletRequest req = (HttpServletRequest) sreq;
    HttpServletResponse res = (HttpServletResponse) sresp;
    HttpSession session = req.getSession();

    if (req.getServletPath() != null && req.getServletPath().startsWith(UNAUTHENTICATED_ACCESS_PROXY)) {
        if (debug)
            logger.debug("SSO is by-passed for unauthenticated access endpoint.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // external invitation link should not trigger any SSO
    if (PAGE_SERVLET_PATH.equals(req.getServletPath()) && IGNORE_LINK.equals(req.getPathInfo())) {
        if (debug)
            logger.debug("SSO is by-passed for external invitation link.");
        chain.doFilter(sreq, sresp);
        return;
    }

    if (debug)
        logger.debug("Processing request " + req.getRequestURI() + " SID:" + session.getId());

    // Login page or login submission
    String pathInfo;
    if (PAGE_SERVLET_PATH.equals(req.getServletPath())
            && (LOGIN_PATH_INFORMATION.equals(pathInfo = req.getPathInfo())
                    || pathInfo == null && LOGIN_PARAMETER.equals(req.getParameter("pt")))) {
        if (debug)
            logger.debug("Login page requested, chaining ...");

        // Chain to the next filter
        chain.doFilter(sreq, sresp);
        return;
    }

    // initialize a new request context
    RequestContext context = null;
    try {
        // perform a "silent" init - i.e. no user creation or remote connections
        context = RequestContextUtil.initRequestContext(getApplicationContext(), req, true);
    } catch (Exception ex) {
        logger.error("Error calling initRequestContext", ex);
        throw new ServletException(ex);
    }

    // get the page from the model if any - it may not require authentication
    Page page = context.getPage();
    if (page != null && page.getAuthentication() == RequiredAuthentication.none) {
        if (logger.isDebugEnabled())
            logger.debug("Unauthenticated page requested - skipping auth filter...");
        chain.doFilter(sreq, sresp);
        return;
    }

    // If userHeader (X-Alfresco-Remote-User or similar) external auth - does not require a challenge/response
    if (this.userHeader != null) {
        String userId = AuthenticationUtil.getUserId(req);
        if (userId != null && req.getRemoteUser() != null) {
            if (logger.isDebugEnabled())
                logger.debug("userHeader external auth - skipping auth filter...");
            setExternalAuthSession(session);
            onSuccess(req, res, session, req.getRemoteUser());
            chain.doFilter(sreq, sresp);
            return;
        } else {
            // initial external user login requires a ping check to authenticate remote Session
            challengeOrPassThrough(chain, req, res, session);
            return;
        }
    }

    // Check if there is an authorization header with a challenge response
    String authHdr = req.getHeader(HEADER_AUTHORIZATION);

    // We are not passing on a challenge response and we have sufficient client session information
    if (authHdr == null && AuthenticationUtil.isAuthenticated(req)) {
        if (debug)
            logger.debug("Touching the repo to ensure we still have an authenticated session.");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }

    // Check the authorization header
    if (authHdr == null) {
        if (debug)
            logger.debug("New auth request from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":"
                    + req.getRemotePort() + ")");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }
    // SPNEGO / Kerberos authentication
    else if (authHdr.startsWith(AUTH_SPNEGO) && this.krbRealm != null) {
        if (debug)
            logger.debug("Processing SPNEGO / Kerberos authentication.");
        // Decode the received SPNEGO blob and validate

        final byte[] spnegoByts = Base64.decode(authHdr.substring(10).getBytes());

        // Check if the client sent an NTLMSSP blob

        if (isNTLMSSPBlob(spnegoByts, 0)) {
            if (logger.isDebugEnabled())
                logger.debug("Client sent an NTLMSSP security blob");

            // Restart the authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
            return;
        }

        //  Check the received SPNEGO token type

        int tokType = -1;

        try {
            tokType = SPNEGO.checkTokenType(spnegoByts, 0, spnegoByts.length);
        } catch (IOException ex) {
        }

        // Check for a NegTokenInit blob

        if (tokType == SPNEGO.NegTokenInit) {
            if (debug)
                logger.debug("Parsing the SPNEGO security blob to get the Kerberos ticket.");

            NegTokenInit negToken = new NegTokenInit();

            try {
                // Decode the security blob

                negToken.decode(spnegoByts, 0, spnegoByts.length);

                //  Determine the authentication mechanism the client is using and logon

                String oidStr = null;
                if (negToken.numberOfOids() > 0)
                    oidStr = negToken.getOidAt(0).toString();

                if (oidStr != null && (oidStr.equals(OID.ID_MSKERBEROS5) || oidStr.equals(OID.ID_KERBEROS5))) {
                    if (debug)
                        logger.debug("Kerberos logon.");
                    //  Kerberos logon

                    if (doKerberosLogon(negToken, req, res, session) != null) {
                        // Allow the user to access the requested page

                        chain.doFilter(req, res);
                        if (logger.isDebugEnabled())
                            logger.debug("Request processing ended");
                    } else {
                        // Send back a request for SPNEGO authentication

                        restartAuthProcess(session, req, res, AUTH_SPNEGO);
                    }
                } else {
                    //  Unsupported mechanism, e.g. NegoEx

                    if (logger.isDebugEnabled())
                        logger.debug("Unsupported SPNEGO mechanism " + oidStr);

                    // Try again!

                    restartAuthProcess(session, req, res, AUTH_SPNEGO);
                }
            } catch (IOException ex) {
                // Log the error

                if (logger.isDebugEnabled())
                    logger.debug(ex);
            }
        } else {
            //  Unknown SPNEGO token type

            if (logger.isDebugEnabled())
                logger.debug("Unknown SPNEGO token type");

            // Send back a request for SPNEGO authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
        }
    }
    // NTLM authentication
    else if (authHdr.startsWith(AUTH_NTLM)) {
        if (debug)
            logger.debug("Processing NTLM authentication.");
        // Decode the received NTLM blob and validate
        final byte[] authHdrByts = authHdr.substring(5).getBytes();
        final byte[] ntlmByts = Base64.decode(authHdrByts);
        int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
        Object sessionMutex = WebUtils.getSessionMutex(session);

        if (ntlmTyp == NTLM.Type1) {
            if (debug)
                logger.debug("Process the type 1 NTLM message.");
            Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType1(type1Msg, req, res, session);
            }
        } else if (ntlmTyp == NTLM.Type3) {
            if (debug)
                logger.debug("Process the type 3 NTLM message.");
            Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType3(type3Msg, req, res, session, chain);
            }
        } else {
            if (debug)
                logger.debug("NTLM not handled, redirecting to login page");

            redirectToLoginPage(req, res);
        }
    }
    // Possibly basic auth - allow through
    else {
        if (debug)
            logger.debug("Processing Basic Authentication.");
        // ACE-3257 fix, it looks like basic auth header was sent.
        // However lets check for presence of remote_user CGI variable in AJP.
        // If remote user is not null then it most likely that apache proxy with mod_auth_basic module is used
        if (AuthenticationUtil.isAuthenticated(req) || req.getRemoteUser() != null) {
            if (debug)
                logger.debug("Ensuring the session is still valid.");
            challengeOrPassThrough(chain, req, res, session);
        } else {
            if (debug)
                logger.debug("Establish a new session or bring up the login page.");
            chain.doFilter(req, res);
        }
    }
}