Example usage for javax.servlet.http HttpServletRequest getHeaderNames

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

Introduction

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

Prototype

public Enumeration<String> getHeaderNames();

Source Link

Document

Returns an enumeration of all the header names this request contains.

Usage

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ZimbraLog.clearContext();//from www .  ja va  2s. co m
    addRemoteIpToLoggingContext(req);

    log.info("Handling autodiscover request...");

    byte[] reqBytes = null;
    reqBytes = ByteUtil.getContent(req.getInputStream(), req.getContentLength());
    if (reqBytes == null) {
        log.warn("No content found in the request");
        sendError(resp, 600, "No content found in the request");
        return;
    }
    String content = new String(reqBytes, "UTF-8");
    log.debug("Request before auth: %s", content);

    if (log.isDebugEnabled()) {
        Enumeration<String> enm = req.getHeaderNames();
        while (enm.hasMoreElements()) {
            String header = enm.nextElement();
            log.info("POST header: %s", header + ":" + req.getHeader(header));
        }
    }

    String email = null;
    String responseSchema = null;

    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(content)));
        NodeList nList = doc.getElementsByTagName("Request");

        for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                email = getTagValue("EMailAddress", element);
                responseSchema = getTagValue("AcceptableResponseSchema", element);

                if (email != null)
                    break;
            }
        }
    } catch (Exception e) {
        log.warn("cannot parse body: %s", content);
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Body cannot be parsed");
        return;
    }

    //Return an error if there's no email address specified!
    if (email == null || email.length() == 0) {
        log.warn("No Email address is specified in the Request, %s", content);
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "No Email address is specified in the Request");
        return;
    }

    //Return an error if the response schema doesn't match ours!
    if (responseSchema != null && responseSchema.length() > 0) {

        if (!(responseSchema.equals(NS_MOBILE) || responseSchema.equals(NS_OUTLOOK))) {
            log.warn("Requested response schema not available " + responseSchema);
            sendError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "Requested response schema not available " + responseSchema);
            return;
        }
    }

    log.debug("Authenticating user");
    Account acct = authenticate(req, resp, responseSchema);
    if (acct == null) {
        return;
    }
    log.debug("Authentication finished successfully");

    log.debug("content length: %d, content type: %s", req.getContentLength(), req.getContentType());
    if (req.getContentLength() == 0 || req.getContentType() == null) {
        log.warn("No suitable content found in the request");
        sendError(resp, 600, "No suitable content found in the request");
        return;
    }

    try {
        if (!(AccountUtil.addressMatchesAccount(acct, email) || acct.isAvailabilityServiceProvider())) { //Exchange server sends dummy email address from service account.
            log.warn(email + " doesn't match account addresses for user " + acct.getName());
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    email + " doesn't match account addresses");
            return;
        }
    } catch (ServiceException e) {
        log.warn("Account access error; user=" + acct.getName(), e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Account access error; user=" + acct.getName());
        return;
    }

    String respDoc = null;
    try {
        String serviceUrl = getServiceUrl(acct, responseSchema);
        String displayName = acct.getDisplayName() == null ? email : acct.getDisplayName();
        if (displayName.contains("@")) {
            displayName = displayName.substring(0, displayName.indexOf("@"));
        }
        log.debug("displayName: %s, email: %s, serviceUrl: %s", displayName, email, serviceUrl);
        if (isEwsClient(responseSchema)) {
            respDoc = createResponseDocForEws(displayName, email, serviceUrl, acct);
        } else {
            respDoc = createResponseDoc(displayName, email, serviceUrl);
        }
    } catch (Exception e) {
        log.warn(e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }

    log.info("Response: %s", respDoc);
    log.debug("response length: %d", respDoc.length());

    try {
        ByteUtil.copy(new ByteArrayInputStream(respDoc.getBytes("UTF-8")), true, resp.getOutputStream(), false);
    } catch (IOException e) {
        log.error("copy response error", e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }

    log.debug("setting content type to text/xml");
    resp.setContentType("text/xml");
    log.info("sending autodiscover response...");
}

From source file:net.wastl.webmail.server.WebMailServlet.java

/**
 * Handle a request to the WebMail servlet. This is the central method of
 * the WebMailServlet. It first gathers all of the necessary information
 * from the client, then either creates or gets a Session and executes the
 * URL handler for the given path.//  w  ww  .  j a  v  a2s. co  m
 */
public void service(ServletRequest req1, ServletResponse res1) throws ServletException {
    final HttpServletRequest req = (HttpServletRequest) req1;
    final HttpServletResponse res = (HttpServletResponse) res1;
    final HTTPRequestHeader http_header = new HTTPRequestHeader();

    if (req.getServletPath().equals("/admin"))
        try {
            log.debug("Forwarding /admin request back to self");
            req.getRequestDispatcher("WebMail/admin").forward(req1, res1);
            return;
        } catch (IOException ioe) {
            log.fatal("Forward from '/admin' failed", ioe);
            throw new ServletException(ioe.getMessage());
        }

    final Enumeration en = req.getHeaderNames();
    while (en.hasMoreElements()) {
        final String s = (String) en.nextElement();
        http_header.setHeader(s, req.getHeader(s));
    }

    http_header.setPath(req.getPathInfo() == null ? "/" : req.getPathInfo());

    InetAddress addr;
    try {
        addr = InetAddress.getByName(req.getRemoteHost());
    } catch (final UnknownHostException e) {
        try {
            addr = InetAddress.getByName(req.getRemoteAddr());
        } catch (final Exception ex) {
            throw new ServletException("Remote host must identify!");
        }
    }

    HTMLDocument content = null;
    final int err_code = 400;
    HTTPSession sess = null;

    /*
     * Here we try to parse the MIME content that the Client sent in his
     * POST since the JServ doesn't do that for us:-( At least we can use
     * the functionality provided by the standalone server where we need to
     * parse the content ourself anyway.
     */
    try {
        final BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());

        /*
         * First we try to use the Servlet API's methods to parse the
         * parameters. Unfortunately, it doesn't know how to handle MIME
         * multipart POSTs, so we will have to handle that ourselves
         */

        /*
         * First get all the parameters and set their values into
         * http_header
         */
        Enumeration enum2 = req.getParameterNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setContent(s, req.getParameter(s));
            // log.info("Parameter "+s);
        }

        /* Then we set all the headers in http_header */
        enum2 = req.getHeaderNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setHeader(s, req.getHeader(s));
        }

        /*
         * In Servlet API 2.2 we might want to fetch the attributes also,
         * but this doesn't work in API 2.0, so we leave it commented out
         */
        // enum2=req.getAttributeNames();
        // while(enum2.hasMoreElements()) {
        // String s=(String)enum2.nextElement();
        // log.info("Attribute "+s);
        // }

        /* Now let's try to handle multipart/form-data posts */

        if (req.getContentType() != null
                && req.getContentType().toUpperCase().startsWith("MULTIPART/FORM-DATA")) {
            final int size = Integer.parseInt(WebMailServer.getStorage().getConfig("max attach size"));
            final MultipartParser mparser = new MultipartParser(req, size);
            Part p;
            while ((p = mparser.readNextPart()) != null) {
                if (p.isFile()) {
                    final ByteStore bs = ByteStore.getBinaryFromIS(((FilePart) p).getInputStream(), size);
                    bs.setName(((FilePart) p).getFileName());
                    bs.setContentType(getStorage().getMimeType(((FilePart) p).getFileName()));
                    http_header.setContent(p.getName(), bs);
                    log.info("File name " + bs.getName());
                    log.info("Type      " + bs.getContentType());

                } else if (p.isParam()) {
                    http_header.setContent(p.getName(), ((ParamPart) p).getStringValue());
                }

                // log.info("Parameter "+p.getName());
            }
        }

        try {
            final String url = http_header.getPath();

            try {
                /* Find out about the session id */
                sess = req.getSession(false) == null ? null
                        : (HTTPSession) req.getSession(false).getAttribute("webmail.session");

                /*
                 * If the user was logging on, he doesn't have a session id,
                 * so generate one. If he already had one, all the better,
                 * we will take the old one
                 */
                if (sess == null && url.startsWith("/login")) {
                    sess = newSession(req, http_header);
                } else if (sess == null && url.startsWith("/admin/login")) {
                    http_header.setHeader("LOGIN", "Administrator");
                    sess = newAdminSession(req, http_header);
                }
                if (sess == null && !url.equals("/") && !url.startsWith("/passthrough")
                        && !url.startsWith("/admin")) {
                    content = getURLHandler().handleURL("/logout", sess, http_header);
                } else {
                    /* Ensure that the session state is up-to-date */
                    if (sess != null) {
                        sess.setEnv();
                    }

                    /* Let the URLHandler determine the result of the query */
                    content = getURLHandler().handleURL(url, sess, http_header);
                }
            } catch (final InvalidPasswordException e) {
                log.error("Connection to " + addr.toString() + ": Authentication failed!");
                if (url.startsWith("/admin/login")) {
                    content = getURLHandler().handleURL("/admin", null, http_header);
                } else if (url.startsWith("/login")) {
                    content = getURLHandler().handleURL("/", null, http_header);
                } else
                    // content=new
                    // HTMLErrorMessage(getStorage(),e.getMessage());
                    throw new ServletException("Invalid URL called!");
            } catch (final Exception ex) {
                content = getURLHandler().handleException(ex, sess, http_header);
                log.debug("Some strange error while handling request", ex);
            }

            /*
             * Set some HTTP headers: Date is now, the document should
             * expire in 5 minutes, proxies and clients shouldn't cache it
             * and all WebMail documents must be revalidated when they think
             * they don't have to follow the "no-cache".
             */
            res.setDateHeader("Date:", System.currentTimeMillis());
            res.setDateHeader("Expires", System.currentTimeMillis() + 300000);
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Cache-Control", "must-revalidate");

            synchronized (out) {
                res.setStatus(content.getReturnCode());

                if (content.hasHTTPHeader()) {
                    final Enumeration enumVar = content.getHTTPHeaderKeys();
                    while (enumVar.hasMoreElements()) {
                        final String s = (String) enumVar.nextElement();
                        res.setHeader(s, content.getHTTPHeader(s));
                    }
                }

                /*
                 * What we will send is an image or some other sort of
                 * binary
                 */
                if (content instanceof HTMLImage) {
                    final HTMLImage img = (HTMLImage) content;
                    /*
                     * the HTMLImage class provides us with most of the
                     * necessary information that we want to send
                     */
                    res.setHeader("Content-Type", img.getContentType());
                    res.setHeader("Content-Transfer-Encoding", img.getContentEncoding());
                    res.setHeader("Content-Length", "" + img.size());
                    res.setHeader("Connection", "Keep-Alive");

                    /* Send 8k junks */
                    int offset = 0;
                    while (offset + chunk_size < img.size()) {
                        out.write(img.toBinary(), offset, chunk_size);
                        offset += chunk_size;
                    }
                    out.write(img.toBinary(), offset, img.size() - offset);
                    out.flush();

                    out.close();
                } else {
                    final byte[] encoded_content = content.toString().getBytes("UTF-8");

                    /*
                     * We are sending HTML text. Set the encoding to UTF-8
                     * for Unicode messages
                     */
                    res.setHeader("Content-Length", "" + (encoded_content.length + 2));
                    res.setHeader("Connection", "Keep-Alive");
                    res.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

                    out.write(encoded_content);
                    out.write("\r\n".getBytes());

                    out.flush();

                    out.close();
                }
            }
        } catch (final DocumentNotFoundException e) {
            log.info("Connection to " + addr.toString() + ": Could not handle request (" + err_code
                    + ") (Reason: " + e.getMessage() + ")");
            throw new ServletException("Error: " + e.getMessage(), e);
            // res.setStatus(err_code);
            // res.setHeader("Content-type","text/html");
            // res.setHeader("Connection","close");

            // content=new HTMLErrorMessage(getStorage(),e.getMessage());
            // out.write((content+"\r\n").getBytes("UTF-8"));
            // out.write("</HTML>\r\n".getBytes());
            // out.flush();
            // out.close();
        }
    } catch (final Exception e) {
        log.info("Connection to " + addr.toString() + " closed unexpectedly", e);
        throw new ServletException(e.getMessage());
    }
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Snoop on the request if the request parameter snoop=1 output appears in the log, at
 * level INFO/*  www. j av a 2  s .co m*/
 *
 * @param request
 */
private void snoopRequest(HttpServletRequest request) {
    boolean snoop = "1".equals(request.getParameter("snoop"));
    if (snoop) {
        StringBuilder sb = new StringBuilder("SData Request :");
        sb.append("\n\tRequest Path :").append(request.getPathInfo());
        sb.append("\n\tMethod :").append(request.getMethod());
        for (Enumeration<?> hnames = request.getHeaderNames(); hnames.hasMoreElements();) {
            String name = (String) hnames.nextElement();
            sb.append("\n\tHeader :").append(name).append("=[").append(request.getHeader(name)).append("]");
        }
        if (request.getCookies() != null) {
            for (Cookie c : request.getCookies()) {
                sb.append("\n\tCookie:");
                sb.append("name[").append(c.getName());
                sb.append("]path[").append(c.getPath());
                sb.append("]value[").append(c.getValue());
            }
        }
        sb.append("]");
        LOG.info(sb.toString());
    }
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpProtocol.java

public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException {
    debug(request, "forward");

    Packet packet = new Packet();
    packet.reset();//from  w  w w  .j a  v  a2s  . c  o  m
    // AJP13_FORWARD_REQUEST
    packet.write(Type.REQUEST_FORWARD.code);
    packet.write(computeMethod(request.getMethod()).code);
    packet.write(request.getProtocol());
    packet.write(request.getRequestURI());
    packet.write(request.getRemoteAddr());
    packet.write(request.getRemoteAddr());
    packet.write(request.getServerName());
    packet.write(request.getServerPort());
    packet.write(request.isSecure());

    // request headers
    Map<String, String> headers = new HashMap<String, String>();
    @SuppressWarnings("rawtypes")
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement().toString();
        String headerValue = request.getHeader(headerName);
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
            headers.put(headerName, headerValue);
        }
    }
    packet.write(headers.size());
    for (Map.Entry<String, String> header : headers.entrySet()) {
        HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey());
        if (headerType != null) {
            packet.write(headerType.code);
        } else {
            packet.write(header.getKey());
        }
        String headerValue = header.getValue();
        packet.write(headerValue == null ? "" : headerValue);
    }

    // request attributes
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        packet.write(Attribute.REMOTE_USER.code);
        packet.write(authentication.getName());
    }

    String queryString = request.getQueryString();
    if (queryString != null) {
        packet.write(Attribute.QUERY_STRING.code);
        packet.write(queryString);
    }

    // packet terminator
    packet.write((byte) 0xff);

    final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort);
    Socket connection;

    try {
        connection = allocateSocket(socketKey);
        debug("allocated", connection);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    boolean invalidate = true;
    try {
        OutputStream outputStream = connection.getOutputStream();
        InputStream inputStream = connection.getInputStream();
        packet.write(outputStream);
        packet.reset();

        int bytesWritten = 0;

        int contentLength = request.getContentLength();
        if (contentLength == -1) { // Unknown content length
            contentLength = Integer.MAX_VALUE;
        }
        ServletInputStream requestInput = request.getInputStream();

        OutputStream responseOutput = null;
        boolean reuse = false;

        if (request.getHeader("Content-Length") != null) {
            bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput,
                    contentLength);
            debug("sent [" + bytesWritten + "] initial body bytes", connection);
        }

        for (;; packet.reset()) {
            debug("reading packet", connection);
            packet.read(inputStream);

            Type packetType = Type.fromCode(packet.readByte());
            debug("received " + packetType, connection);
            if (packetType == Type.END_RESPONSE) {
                reuse = packet.readBoolean();
                break;
            }
            switch (packetType) {
            case GET_BODY_CHUNK:
                int requestedSize = packet.readInt();
                packet.reset();
                int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength,
                        requestInput, requestedSize);
                bytesWritten += chunkSize;
                debug("sent [" + chunkSize + "] bytes of body chunk", connection);
                break;
            case SEND_HEADERS: {
                response.reset();
                int httpStatusCode = packet.readInt();
                packet.readString(); // status message, not used
                response.setStatus(httpStatusCode);
                int headerCount = packet.readInt();
                for (int x = 0; x < headerCount; ++x) {
                    byte b = packet.readByte();
                    packet.unreadByte();
                    String headerName;
                    if (b == ((byte) 0xA0)) {
                        int headerCode = packet.readInt();
                        headerName = HttpResponseHeader.fromCode(headerCode).headerName;
                    } else {
                        headerName = packet.readString();
                    }
                    String headerValue = packet.readString();
                    headerValue = headerFilter.processResponseHeader(headerName, headerValue);
                    if (headerValue != null) {
                        response.setHeader(headerName, headerValue);
                    }
                }
            }
                break;
            case SEND_BODY_CHUNK:
                if (responseOutput == null) {
                    responseOutput = response.getOutputStream();
                }
                packet.copy(responseOutput);
                break;
            }
        }

        // ORDER DEPENDENCY: this should come last
        invalidate = !reuse;

        if (responseOutput != null) {
            responseOutput.close();
        }
    } finally {
        if (!shareConnections) {
            invalidate = true;
        }
        deallocateSocket(socketKey, connection, invalidate);
        debug("released " + (invalidate ? "invalidate" : "reuse"), connection);
    }
}

From source file:ezbake.security.client.EzbakeSecurityClient.java

/**
 * Make a best attempt to get the user DN from the OFE headers.
 *
 * The method will never return null. It will either successfully extract a
 * Security Principal or it will throw an EzSecurityTokenException. If in mock mode,
 * return a mock Principal//from w w  w .  ja  v  a 2  s .  c o m
 *
 * @deprecated EFE headers no longer contain a valid EzSecurityPrincipal. Use
 * {@link ezbake.security.client.EzbakeSecurityClient#requestPrincipalFromRequest(javax.servlet.http.HttpServletRequest)} instead
 *
 * @param request HTTP request carrying the OFE headers
 * @return valid EzSecurityPrincipal if able to get one
 */
@Deprecated
public EzSecurityPrincipal clientDnFromRequest(HttpServletRequest request) throws EzSecurityTokenException {
    // Return user from configuration if in 'mock' mode
    if (securityConfigurationHelper.useMock()) {
        return new EzSecurityPrincipal(securityConfigurationHelper.getMockUser(),
                new ValidityCaveats("EzSecurity", "", System.currentTimeMillis() + expiry, ""));
    }

    if (log.isTraceEnabled()) {
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = headers.nextElement();
            log.trace("Header: " + headerName + " = " + request.getHeader(headerName));
        }
    }

    String dnHeader = getHeaderValue(request, EFE_USER_HEADER);
    String dnSignature = getHeaderValue(request, EFE_SIGNATURE_HEADER);

    EzSecurityPrincipal dn = null;
    if (dnHeader != null && dnSignature != null) {
        verifyProxyUserToken(dnHeader, dnSignature);
        ProxyUserToken put = EzSecurityTokenUtils.deserializeProxyUserToken(dnHeader);
        dn = new EzSecurityPrincipal(put.getX509().getSubject(),
                new ValidityCaveats(put.getIssuedBy(), put.getIssuedTo(), put.getNotAfter(), dnSignature));

    }
    if (dn == null) {
        throw new EzSecurityTokenException("Unable to get user DN from HttpServletRequest");
    }

    return dn;
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 * @param req servlet request//ww w  .jav  a2s .  c om
 * @param resp servlet response
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {

        URL url = getURL(req, req.getParameter("uri"));
        HttpURLConnection con = (HttpURLConnection) (url.openConnection());
        con.setAllowUserInteraction(false);
        con.setUseCaches(false);

        // TODO: figure out why this is necessary for HTTPS URLs
        if (con instanceof HttpsURLConnection) {
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                        return true;
                    } else {
                        log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                        return false;
                    }
                }
            };
            ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
        }
        // pass along all appropriate HTTP headers
        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hname = (String) headerNames.nextElement();
            if (!unproxiedHeaders.contains(hname.toLowerCase())) {
                con.addRequestProperty(hname, req.getHeader(hname));
            }
        }
        con.connect();

        // read result headers of GET, write to response
        Map<String, List<String>> headers = con.getHeaderFields();
        for (String key : headers.keySet()) {
            if (key != null) { // TODO: why is this check necessary!
                List<String> header = headers.get(key);
                if (header.size() > 0)
                    resp.setHeader(key, header.get(0));
            }
        }

        InputStream in = con.getInputStream();
        OutputStream out = resp.getOutputStream();
        final byte[] buf = new byte[8192];
        int len;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();

    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }/*from   w  ww.java2 s .c  o m*/
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}

From source file:com.telefonica.iot.cygnus.handlers.NGSIRestHandler.java

@Override
public List<Event> getEvents(javax.servlet.http.HttpServletRequest request) throws Exception {
    // Set some MDC logging fields to 'N/A' for this thread
    // Value for the component field is inherited from main thread (CygnusApplication.java)
    org.apache.log4j.MDC.put(CommonConstants.LOG4J_CORR, CommonConstants.NA);
    org.apache.log4j.MDC.put(CommonConstants.LOG4J_TRANS, CommonConstants.NA);
    org.apache.log4j.MDC.put(CommonConstants.LOG4J_SVC, CommonConstants.NA);
    org.apache.log4j.MDC.put(CommonConstants.LOG4J_SUBSVC, CommonConstants.NA);

    // Result/*from w w w . jav  a  2  s .c om*/
    ArrayList<Event> ngsiEvents = new ArrayList<>();

    // Update the counters
    numReceivedEvents++;

    // Check the headers looking for not supported content type and/or invalid FIWARE service and service path
    Enumeration headerNames = request.getHeaderNames();
    String corrId = null;
    String contentType = null;
    String service = defaultService;
    String servicePath = defaultServicePath;

    while (headerNames.hasMoreElements()) {
        String headerName = ((String) headerNames.nextElement()).toLowerCase(Locale.ENGLISH);
        String headerValue = request.getHeader(headerName);
        LOGGER.debug("[NGSIRestHandler] Header " + headerName + " received with value " + headerValue);

        switch (headerName) {
        case CommonConstants.HEADER_CORRELATOR_ID:
            corrId = headerValue;
            break;
        case CommonConstants.HTTP_HEADER_CONTENT_TYPE:
            if (wrongContentType(headerValue)) {
                LOGGER.warn("[NGSIRestHandler] Bad HTTP notification (" + headerValue
                        + " content type not supported)");
                throw new HTTPBadRequestException(headerValue + " content type not supported");
            } else {
                contentType = headerValue;
            } // if else

            break;
        case CommonConstants.HEADER_FIWARE_SERVICE:
            if (wrongServiceHeaderLength(headerValue)) {
                LOGGER.warn("[NGSIRestHandler] Bad HTTP notification ('" + CommonConstants.HEADER_FIWARE_SERVICE
                        + "' header length greater than " + NGSIConstants.SERVICE_HEADER_MAX_LEN + ")");
                throw new HTTPBadRequestException("'" + CommonConstants.HEADER_FIWARE_SERVICE
                        + "' header length greater than " + NGSIConstants.SERVICE_HEADER_MAX_LEN + ")");
            } else {
                service = headerValue;
            } // if else

            break;
        case CommonConstants.HEADER_FIWARE_SERVICE_PATH:
            String[] splitValues = headerValue.split(",");

            for (String splitValue : splitValues) {
                if (wrongServicePathHeaderLength(splitValue)) {
                    LOGGER.warn("[NGSIRestHandler] Bad HTTP notification ('"
                            + CommonConstants.HEADER_FIWARE_SERVICE_PATH + "' header value length greater than "
                            + NGSIConstants.SERVICE_PATH_HEADER_MAX_LEN + ")");
                    throw new HTTPBadRequestException("'fiware-servicePath' header length greater than "
                            + NGSIConstants.SERVICE_PATH_HEADER_MAX_LEN + ")");
                } else if (wrongServicePathHeaderInitialCharacter(splitValue)) {
                    LOGGER.warn("[NGSIRestHandler] Bad HTTP notification ('"
                            + CommonConstants.HEADER_FIWARE_SERVICE_PATH
                            + "' header value must start with '/'");
                    throw new HTTPBadRequestException("'" + CommonConstants.HEADER_FIWARE_SERVICE_PATH
                            + "' header value must start with '/'");
                } // if else
            } // for

            servicePath = headerValue;

            break;
        default:
            LOGGER.debug("[NGSIRestHandler] Unnecessary header");
        } // switch
    } // while

    // Get a service and servicePath and store it in the log4j Mapped Diagnostic Context (MDC)
    MDC.put(CommonConstants.LOG4J_SVC, service == null ? defaultService : service);
    MDC.put(CommonConstants.LOG4J_SUBSVC, servicePath == null ? defaultServicePath : servicePath);

    // If the configuration is invalid, nothing has to be done but to return null
    if (invalidConfiguration) {
        serviceMetrics.add(service, servicePath, 1, request.getContentLength(), 0, 0, 0, 0, 0, 0, 0);
        LOGGER.debug("[NGSIRestHandler] Invalid configuration, thus returning an empty list of Flume events");
        return new ArrayList<>();
    } // if

    // Check the method
    String method = request.getMethod().toUpperCase(Locale.ENGLISH);

    if (!method.equals("POST")) {
        serviceMetrics.add(service, servicePath, 1, request.getContentLength(), 0, 1, 0, 0, 0, 0, 0);
        LOGGER.warn("[NGSIRestHandler] Bad HTTP notification (" + method + " method not supported)");
        // It would be more precise to use 405 Method Not Allowed (along with the explanatory "Allow" header
        // in the response. However, we are limited to the ones provided by Flume
        // (see https://flume.apache.org/releases/content/1.9.0/apidocs/org/apache/flume/FlumeException.html)
        // so we HTTPBadRequestException for 400 Bad Request instead
        throw new HTTPBadRequestException(method + " method not supported");
    } // if

    // Check the notificationTarget
    String target = request.getRequestURI();

    if (!target.equals(notificationTarget)) {
        serviceMetrics.add(service, servicePath, 1, request.getContentLength(), 0, 1, 0, 0, 0, 0, 0);
        LOGGER.warn("[NGSIRestHandler] Bad HTTP notification (" + target + " target not supported)");
        throw new HTTPBadRequestException(target + " target not supported");
    } // if

    // Check if received content type is null
    if (contentType == null) {
        serviceMetrics.add(service, servicePath, 1, request.getContentLength(), 0, 1, 0, 0, 0, 0, 0);
        LOGGER.warn("[NGSIRestHandler] Missing content type. Required 'application/json; charset=utf-8'");
        throw new HTTPBadRequestException("Missing content type. Required 'application/json; charset=utf-8'");
    } // if

    // Get an internal transaction ID.
    String transId = CommonUtils.generateUniqueId(null, null);

    // Get also a correlator ID if not sent in the notification. Id correlator ID is not notified
    // then correlator ID and transaction ID must have the same value.
    corrId = CommonUtils.generateUniqueId(corrId, transId);

    // Store both of them in the log4j Mapped Diagnostic Context (MDC), this way it will be accessible
    // by the whole source code.
    MDC.put(CommonConstants.LOG4J_CORR, corrId);
    MDC.put(CommonConstants.LOG4J_TRANS, transId);
    LOGGER.info("[NGSIRestHandler] Starting internal transaction (" + transId + ")");

    // Get the data content
    String data = "";
    String line;

    try (BufferedReader reader = request.getReader()) {
        while ((line = reader.readLine()) != null) {
            data += line;
        } // while
    } // try

    if (data.length() == 0) {
        serviceMetrics.add(service, servicePath, 1, request.getContentLength(), 0, 1, 0, 0, 0, 0, 0);
        LOGGER.warn("[NGSIRestHandler] Bad HTTP notification (No content in the request)");
        throw new HTTPBadRequestException("No content in the request");
    } // if

    LOGGER.info("[NGSIRestHandler] Received data (" + data + ")");

    // Parse the original data into a NotifyContextRequest object
    NotifyContextRequest ncr;
    Gson gson = new Gson();

    try {
        ncr = gson.fromJson(data, NotifyContextRequest.class);
        LOGGER.debug("[NGSIRestHandler] Parsed NotifyContextRequest: " + ncr.toString());
    } catch (JsonSyntaxException e) {
        serviceMetrics.add(service, servicePath, 1, request.getContentLength(), 0, 1, 0, 0, 0, 0, 0);
        LOGGER.error("[NGSIRestHandler] Runtime error (" + e.getMessage() + ")");
        return null;
    } // try catch

    // Split the notified service path and check if it matches the number of notified context responses
    String[] servicePaths = servicePath.split(",");

    if (servicePaths.length != ncr.getContextResponses().size()) {
        serviceMetrics.add(service, servicePath, 1, request.getContentLength(), 0, 1, 0, 0, 0, 0, 0);
        LOGGER.warn("[NGSIRestHandler] Bad HTTP notification ('" + CommonConstants.HEADER_FIWARE_SERVICE_PATH
                + "' header value does not match the number of notified context responses");
        throw new HTTPBadRequestException("'" + CommonConstants.HEADER_FIWARE_SERVICE_PATH
                + "' header value does not match the number of notified context responses");
    } // if

    // Iterate on the NotifyContextRequest object in order to create an event per ContextElement
    String ids = "";

    for (int i = 0; i < ncr.getContextResponses().size(); i++) {
        ContextElementResponse cer = ncr.getContextResponses().get(i);
        LOGGER.debug("[NGSIRestHandler] NGSI event created for ContextElementResponse: " + cer.toString());

        // Create the appropiate headers
        Map<String, String> headers = new HashMap<>();
        headers.put(CommonConstants.HEADER_FIWARE_SERVICE, service);
        LOGGER.debug("[NGSIRestHandler] Header added to NGSI event (" + CommonConstants.HEADER_FIWARE_SERVICE
                + ": " + service + ")");
        headers.put(CommonConstants.HEADER_FIWARE_SERVICE_PATH, servicePaths[i]);
        LOGGER.debug("[NGSIRestHandler] Header added to NGSI event ("
                + CommonConstants.HEADER_FIWARE_SERVICE_PATH + ": " + servicePaths[i] + ")");
        headers.put(CommonConstants.HEADER_CORRELATOR_ID, corrId);
        LOGGER.debug("[NGSIRestHandler] Header added to NGSI event (" + CommonConstants.HEADER_CORRELATOR_ID
                + ": " + corrId + ")");
        headers.put(NGSIConstants.FLUME_HEADER_TRANSACTION_ID, transId);
        LOGGER.debug("[NGSIRestHandler] Header added to NGSI event ("
                + NGSIConstants.FLUME_HEADER_TRANSACTION_ID + ": " + transId + ")");

        // Create the NGSI event and add it to the list
        NGSIEvent ngsiEvent = new NGSIEvent(
                // Headers
                headers,
                // Bytes version of the notified ContextElement
                (cer.getContextElement().toString() + CommonConstants.CONCATENATOR).getBytes(),
                // Object version of the notified ContextElement
                cer.getContextElement(),
                // Will be set with the mapped object version of the notified ContextElement, by
                // NGSINameMappingsInterceptor (if configured). Currently, null
                null);
        ngsiEvents.add(ngsiEvent);

        if (ids.isEmpty()) {
            ids += ngsiEvent.hashCode();
        } else {
            ids += "," + ngsiEvent.hashCode();
        } // if else
    } // for

    // Return the NGSIEvent list
    serviceMetrics.add(service, servicePath, 1, request.getContentLength(), 0, 0, 0, 0, 0, 0, 0);
    LOGGER.debug("[NGSIRestHandler] NGSI events put in the channel, ids=" + ids);
    numProcessedEvents++;
    return ngsiEvents;
}

From source file:org.mocksy.rules.http.HttpProxyRule.java

protected HttpRequestBase getProxyMethod(HttpServletRequest request) {
    String proxyUrl = this.proxyUrl;
    proxyUrl += request.getPathInfo();//  www .  j  a v a2 s . c  om
    if (request.getQueryString() != null) {
        proxyUrl += "?" + request.getQueryString();
    }
    HttpRequestBase method = null;
    if ("GET".equals(request.getMethod())) {
        method = new HttpGet(proxyUrl);
        method.addHeader("Cache-Control", "no-cache");
        method.addHeader("Pragma", "no-cache");
    } else if ("POST".equals(request.getMethod())) {
        method = new HttpPost(proxyUrl);

        Map<String, String[]> paramMap = request.getParameterMap();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String paramName : paramMap.keySet()) {
            String[] values = paramMap.get(paramName);
            for (String value : values) {
                NameValuePair param = new BasicNameValuePair(paramName, value);
                params.add(param);
            }
        }

        try {
            ((HttpPost) method).setEntity(new UrlEncodedFormEntity(params));
        } catch (UnsupportedEncodingException e) {
            // don't worry, this won't happen
        }
    }

    Enumeration headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        String header = (String) headers.nextElement();
        if ("If-Modified-Since".equals(header) || "Content-Length".equals(header)
                || "Transfer-Encoding".equals(header))
            continue;
        Enumeration values = request.getHeaders(header);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            method.addHeader(header, value);
        }
    }

    return method;
}

From source file:eu.fusepool.p3.webid.proxy.ProxyServlet.java

/**
 * The service method from HttpServlet, performs handling of all
 * HTTP-requests independent of their method. Requests and responses within
 * the method can be distinguished by belonging to the "frontend" (i.e. the
 * client connecting to the proxy) or the "backend" (the server being
 * contacted on behalf of the client)//from  w  w  w. ja va  2 s . c om
 *
 * @param frontendRequest Request coming in from the client
 * @param frontendResponse Response being returned to the client
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void service(final HttpServletRequest frontendRequest, final HttpServletResponse frontendResponse)
        throws ServletException, IOException {
    log(LogService.LOG_INFO,
            "Proxying request: " + frontendRequest.getRemoteAddr() + ":" + frontendRequest.getRemotePort()
                    + " (" + frontendRequest.getHeader("Host") + ") " + frontendRequest.getMethod() + " "
                    + frontendRequest.getRequestURI());

    if (targetBaseUri == null) {
        // FIXME return status page
        return;
    }

    //////////////////// Setup backend request
    final HttpEntityEnclosingRequestBase backendRequest = new HttpEntityEnclosingRequestBase() {
        @Override
        public String getMethod() {
            return frontendRequest.getMethod();
        }
    };
    try {
        backendRequest.setURI(new URL(targetBaseUri + frontendRequest.getRequestURI()).toURI());
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }

    //////////////////// Copy headers to backend request
    final Enumeration<String> frontendHeaderNames = frontendRequest.getHeaderNames();
    while (frontendHeaderNames.hasMoreElements()) {
        final String headerName = frontendHeaderNames.nextElement();
        final Enumeration<String> headerValues = frontendRequest.getHeaders(headerName);
        while (headerValues.hasMoreElements()) {
            final String headerValue = headerValues.nextElement();
            if (!headerName.equalsIgnoreCase("Content-Length")) {
                backendRequest.setHeader(headerName, headerValue);
            }
        }
    }

    //////////////////// Copy Entity - if any
    final byte[] inEntityBytes = IOUtils.toByteArray(frontendRequest.getInputStream());
    if (inEntityBytes.length > 0) {
        backendRequest.setEntity(new ByteArrayEntity(inEntityBytes));
    }

    //////////////////// Execute request to backend
    try (CloseableHttpResponse backendResponse = httpclient.execute(backendRequest)) {
        frontendResponse.setStatus(backendResponse.getStatusLine().getStatusCode());

        // Copy back headers
        final Header[] backendHeaders = backendResponse.getAllHeaders();
        final Set<String> backendHeaderNames = new HashSet<>(backendHeaders.length);
        for (Header header : backendHeaders) {
            if (backendHeaderNames.add(header.getName())) {
                frontendResponse.setHeader(header.getName(), header.getValue());
            } else {
                frontendResponse.addHeader(header.getName(), header.getValue());
            }
        }

        final ServletOutputStream outStream = frontendResponse.getOutputStream();

        // Copy back entity
        final HttpEntity entity = backendResponse.getEntity();
        if (entity != null) {
            try (InputStream inStream = entity.getContent()) {
                IOUtils.copy(inStream, outStream);
            }
        }
        outStream.flush();
    }
}