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:org.sakaiproject.util.Web.java

public static String snoop(PrintWriter out, boolean html, ServletConfig config, HttpServletRequest req) {
    // if no out, send to system out
    ByteArrayOutputStream ostream = null;
    if (out == null) {
        ostream = new ByteArrayOutputStream();
        out = new PrintWriter(ostream);
        html = false;//  w  w w .ja  v a2s .  c  o  m
    }

    String h1 = "";
    String h1x = "";
    String pre = "";
    String prex = "";
    String b = "";
    String bx = "";
    String p = "";
    if (html) {
        h1 = "<h1>";
        h1x = "</h1>";
        pre = "<pre>";
        prex = "</pre>";
        b = "<b>";
        bx = "</b>";
        p = "<p>";
    }

    Enumeration<?> e = null;

    out.println(h1 + "Snoop for request" + h1x);
    out.println(req.toString());

    if (config != null) {
        e = config.getInitParameterNames();
        if (e != null) {
            boolean first = true;
            while (e.hasMoreElements()) {
                if (first) {
                    out.println(h1 + "Init Parameters" + h1x);
                    out.println(pre);
                    first = false;
                }
                String param = (String) e.nextElement();
                out.println(" " + param + ": " + config.getInitParameter(param));
            }
            out.println(prex);
        }
    }

    out.println(h1 + "Request information:" + h1x);
    out.println(pre);

    print(out, "Request method", req.getMethod());
    String requestUri = req.getRequestURI();
    print(out, "Request URI", requestUri);
    displayStringChars(out, requestUri);
    print(out, "Request protocol", req.getProtocol());
    String servletPath = req.getServletPath();
    print(out, "Servlet path", servletPath);
    displayStringChars(out, servletPath);
    String contextPath = req.getContextPath();
    print(out, "Context path", contextPath);
    displayStringChars(out, contextPath);
    String pathInfo = req.getPathInfo();
    print(out, "Path info", pathInfo);
    displayStringChars(out, pathInfo);
    print(out, "Path translated", req.getPathTranslated());
    print(out, "Query string", req.getQueryString());
    print(out, "Content length", req.getContentLength());
    print(out, "Content type", req.getContentType());
    print(out, "Server name", req.getServerName());
    print(out, "Server port", req.getServerPort());
    print(out, "Remote user", req.getRemoteUser());
    print(out, "Remote address", req.getRemoteAddr());
    // print(out, "Remote host", req.getRemoteHost());
    print(out, "Authorization scheme", req.getAuthType());

    out.println(prex);

    e = req.getHeaderNames();
    if (e.hasMoreElements()) {
        out.println(h1 + "Request headers:" + h1x);
        out.println(pre);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            out.println(" " + name + ": " + req.getHeader(name));
        }
        out.println(prex);
    }

    e = req.getParameterNames();
    if (e.hasMoreElements()) {
        out.println(h1 + "Servlet parameters (Single Value style):" + h1x);
        out.println(pre);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            out.println(" " + name + " = " + req.getParameter(name));
        }
        out.println(prex);
    }

    e = req.getParameterNames();
    if (e.hasMoreElements()) {
        out.println(h1 + "Servlet parameters (Multiple Value style):" + h1x);
        out.println(pre);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            String vals[] = (String[]) req.getParameterValues(name);
            if (vals != null) {
                out.print(b + " " + name + " = " + bx);
                out.println(vals[0]);
                for (int i = 1; i < vals.length; i++)
                    out.println("           " + vals[i]);
            }
            out.println(p);
        }
        out.println(prex);
    }

    e = req.getAttributeNames();
    if (e.hasMoreElements()) {
        out.println(h1 + "Request attributes:" + h1x);
        out.println(pre);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            out.println(" " + name + ": " + req.getAttribute(name));
        }
        out.println(prex);
    }

    if (ostream != null) {
        out.flush();
        return ostream.toString();
    }

    return "";
}

From source file:io.hops.hopsworks.api.jobs.JobService.java

/**
 * Get the job ui for the specified job.
 * This act as a proxy to get the job ui from yarn
 * <p>// w w  w.  ja  va  2 s  .com
 * @param appId
 * @param param
 * @param sc
 * @param req
 * @return
 */
@GET
@Path("/{appId}/prox/{path: .+}")
@Produces(MediaType.WILDCARD)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getProxy(@PathParam("appId") final String appId, @PathParam("path") final String param,
        @Context SecurityContext sc, @Context HttpServletRequest req) {

    Response response = checkAccessRight(appId);
    if (response != null) {
        return response;
    }
    try {
        String trackingUrl;
        if (param.matches("http([a-zA-Z,:,/,.,0-9,-])+:([0-9])+(.)+")) {
            trackingUrl = param;
        } else {
            trackingUrl = "http://" + param;
        }
        trackingUrl = trackingUrl.replace("@hwqm", "?");
        if (!hasAppAccessRight(trackingUrl)) {
            LOGGER.log(Level.SEVERE, "A user is trying to access an app outside their project!");
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(trackingUrl, false);

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);

        final HttpMethod method = new GetMethod(uri.getEscapedURI());
        Enumeration<String> names = req.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = req.getHeader(name);
            if (PASS_THROUGH_HEADERS.contains(name)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (!name.toLowerCase().equals("accept-encoding") || trackingUrl.contains(".js")) {
                    method.setRequestHeader(name, value);
                }
            }
        }
        String user = req.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(method);
        Response.ResponseBuilder responseBuilder = noCacheResponse
                .getNoCacheResponseBuilder(Response.Status.OK);
        for (Header header : method.getResponseHeaders()) {
            responseBuilder.header(header.getName(), header.getValue());
        }
        //method.getPath().contains("/allexecutors") is needed to replace the links under Executors tab
        //which are in a json response object
        if (method.getResponseHeader("Content-Type") == null
                || method.getResponseHeader("Content-Type").getValue().contains("html")
                || method.getPath().contains("/allexecutors")) {
            final String source = "http://" + method.getURI().getHost() + ":" + method.getURI().getPort();
            if (method.getResponseHeader("Content-Length") == null) {
                responseBuilder.entity(new StreamingOutput() {
                    @Override
                    public void write(OutputStream out) throws IOException, WebApplicationException {
                        Writer writer = new BufferedWriter(new OutputStreamWriter(out));
                        InputStream stream = method.getResponseBodyAsStream();
                        Reader in = new InputStreamReader(stream, "UTF-8");
                        char[] buffer = new char[4 * 1024];
                        String remaining = "";
                        int n;
                        while ((n = in.read(buffer)) != -1) {
                            StringBuilder strb = new StringBuilder();
                            strb.append(buffer, 0, n);
                            String s = remaining + strb.toString();
                            remaining = s.substring(s.lastIndexOf(">") + 1, s.length());
                            s = hopify(s.substring(0, s.lastIndexOf(">") + 1), param, appId, source);
                            writer.write(s);
                        }
                        writer.flush();
                    }
                });
            } else {
                String s = hopify(method.getResponseBodyAsString(), param, appId, source);
                responseBuilder.entity(s);
                responseBuilder.header("Content-Length", s.length());
            }

        } else {
            responseBuilder.entity(new StreamingOutput() {
                @Override
                public void write(OutputStream out) throws IOException, WebApplicationException {
                    InputStream stream = method.getResponseBodyAsStream();
                    org.apache.hadoop.io.IOUtils.copyBytes(stream, out, 4096, true);
                    out.flush();
                }
            });
        }
        return responseBuilder.build();
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "exception while geting job ui " + e.getLocalizedMessage(), e);
        return noCacheResponse.getNoCacheResponseBuilder(Response.Status.NOT_FOUND).build();
    }

}

From source file:org.webdavaccess.servlet.WebdavServlet.java

/**
 * Handles the special WebDAV methods.//  w ww.j  a  va2 s.  co m
 */
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException, AuthenticationException {

    String method = req.getMethod();

    if (fdebug == 1) {
        log.debug("WebdavServlet REQUEST:  -----------------");
        log.debug("Method = " + method);
        log.debug("Time: " + System.currentTimeMillis());
        log.debug("Path: " + getRelativePath(req));
        Enumeration e = req.getHeaderNames();
        while (e.hasMoreElements()) {
            String s = (String) e.nextElement();
            log.debug("Header: " + s + " " + req.getHeader(s));
        }
        e = req.getAttributeNames();
        while (e.hasMoreElements()) {
            String s = (String) e.nextElement();
            log.debug("Attribute: " + s + " " + req.getAttribute(s));
        }
        e = req.getParameterNames();
        while (e.hasMoreElements()) {
            String s = (String) e.nextElement();
            log.debug("Parameter: " + s + " " + req.getParameter(s));
        }
    }

    try {
        fStore.begin(req, fParameter, getServletContext().getRealPath("/"));
        if (fAuthorize != null)
            fAuthorize.authorize(req);
        resp.setStatus(WebdavStatus.SC_OK);

        try {
            if (method.equals(METHOD_PROPFIND)) {
                doPropfind(req, resp);
            } else if (method.equals(METHOD_PROPPATCH)) {
                doProppatch(req, resp);
            } else if (method.equals(METHOD_MKCOL)) {
                doMkcol(req, resp);
            } else if (method.equals(METHOD_COPY)) {
                doCopy(req, resp);
            } else if (method.equals(METHOD_MOVE)) {
                doMove(req, resp);
            } else if (method.equals(METHOD_PUT)) {
                doPut(req, resp);
            } else if (method.equals(METHOD_GET)) {
                doGet(req, resp, true);
            } else if (method.equals(METHOD_OPTIONS)) {
                doOptions(req, resp);
            } else if (method.equals(METHOD_HEAD)) {
                doHead(req, resp);
            } else if (method.equals(METHOD_DELETE)) {
                doDelete(req, resp);
            } else {
                super.service(req, resp);
            }

            fStore.commit();

        } catch (IOException e) {
            log.error("WebdavServer internal error: ", e);
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            fStore.rollback();
            throw new ServletException(e);
        }

    } catch (UnauthenticatedException e) {
        log.error("WebdavServer not authenticated: ", e);
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
    } catch (WebdavException e) {
        log.error("WebdavServer internal error: ", e);
        throw new ServletException(e);
    }
}

From source file:org.ejbca.ui.web.pub.AutoEnrollServlet.java

/**
 * Recievies the request.//from ww  w. ja v a  2 s. c  o  m
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.trace(">doPost");
    try {

        AuthenticationToken internalAdmin = new AlwaysAllowLocalAuthenticationToken(
                new UsernamePrincipal("AutoEnrollServlet: " + request.getRemoteAddr()));
        //Admin internalAdmin = Admin.getInternalAdmin();
        GlobalConfiguration globalConfiguration = (GlobalConfiguration) globalConfigurationSession
                .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
        // Make sure we allow use of this Servlet
        if (!globalConfiguration.getAutoEnrollUse()) {
            log.info("Unauthorized access attempt from " + request.getRemoteAddr());
            response.getOutputStream().println("Not allowed.");
            return;
        }
        int caid = globalConfiguration.getAutoEnrollCA();
        if (caid == GlobalConfiguration.AUTOENROLL_DEFAULT_CA) {
            log.info("Configure a proper CA to use with enroll.");
            response.getOutputStream().println("Configure a proper CA to use with enroll.");
            return;
        }
        boolean debugRequest = "true".equalsIgnoreCase(request.getParameter("debug"));
        String debugInfo = "";

        RequestHelper.setDefaultCharacterEncoding(request);

        if (debugRequest) {
            debugInfo += "getAttributeNames:\n";
            Enumeration<?> enumeration = request.getAttributeNames();
            while (enumeration.hasMoreElements()) {
                String temp = enumeration.nextElement().toString();
                debugInfo += temp + " = " + request.getAttribute(temp) + "\n";
            }
            debugInfo += "\ngetParameterNames:\n";
            enumeration = request.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String temp = enumeration.nextElement().toString();
                debugInfo += temp + " = " + request.getParameter(temp) + "\n";
            }
            debugInfo += "\ngetHeaderNames:\n";
            enumeration = request.getHeaderNames();
            while (enumeration.hasMoreElements()) {
                String temp = enumeration.nextElement().toString();
                debugInfo += temp + " = " + request.getHeader(temp) + "\n";
            }
            debugInfo += "Remote address: " + request.getRemoteAddr() + "\n";
            log.info(debugInfo);
        }

        byte[] result = null;
        String requestData = MSCertTools.extractRequestFromRawData(request.getParameter("request"));
        if (requestData == null) {
            response.getOutputStream().println("No request supplied..");
            return;
        }
        log.info("Got request: " + requestData);
        // The next line expects apache to forward the kerberos-authenticated user as X-Remote-User"
        String remoteUser = request.getHeader("X-Remote-User");
        String usernameShort = StringTools.stripUsername(remoteUser.substring(0, remoteUser.indexOf("@")))
                .replaceAll("/", "");
        if (remoteUser == null || "".equals(remoteUser) || "(null)".equals(remoteUser)) {
            response.getOutputStream().println("X-Remote-User was not supplied..");
            return;
        }
        MSPKCS10RequestMessage req = null;
        String certificateTemplate = null;
        String command = request.getParameter("command");
        if (command != null && "status".equalsIgnoreCase(command)) {
            response.getOutputStream().println(returnStatus(internalAdmin,
                    "Autoenrolled-" + usernameShort + "-" + request.getParameter("template")));
            return;
        } else {
            // Default command "request"
        }
        req = new MSPKCS10RequestMessage(Base64.decode(requestData.getBytes()));
        certificateTemplate = req.getMSRequestInfoTemplateName();
        int templateIndex = MSCertTools.getTemplateIndex(certificateTemplate);
        /* TODO: Lookup requesting entity in AD here to verify that only Machines request Machine Certificates etc.. Also check permissions
          like who is allowed to enroll for what if possible. */
        // Create or edit a user "Autoenrolled-Username-Templatename"
        String username = "Autoenrolled-" + usernameShort + "-" + certificateTemplate;
        log.info("Got autoenroll request from " + remoteUser + " (" + username + ") for a "
                + certificateTemplate + "-certificate.");
        String fetchedSubjectDN = null;
        if (MSCertTools.isRequired(templateIndex, MSCertTools.GET_SUBJECTDN_FROM_AD, 0)) {
            fetchedSubjectDN = ActiveDirectoryTools.getUserDNFromActiveDirectory(globalConfiguration,
                    usernameShort);
        }
        int certProfileId = MSCertTools.getOrCreateCertificateProfile(internalAdmin, templateIndex,
                certificateProfileSession);

        int endEntityProfileId;
        try {
            endEntityProfileId = MSCertTools.getOrCreateEndEndtityProfile(internalAdmin, templateIndex,
                    certProfileId, caid, usernameShort, fetchedSubjectDN, raAdminSession,
                    endEntityProfileSession);
        } catch (EndEntityProfileNotFoundException e) {
            String msg = "Could not retrieve required information from AD.";
            log.error(msg, e);
            response.getOutputStream().println(msg);
            return;
        } catch (IllegalArgumentException e) {
            String msg = "Could not retrieve required information from AD.";
            log.error(msg, e);
            response.getOutputStream().println(msg);
            return;
        }

        // Create user

        // The CA needs to use non-LDAP order and we need to have the SAN like "CN=Users, CN=Username, DC=com, DC=company".. why??
        // TODO: fix this here.. or is this an general order issue?
        String subjectDN = fetchedSubjectDN;
        if (subjectDN == null) {
            if (MSCertTools.isRequired(templateIndex, DnComponents.COMMONNAME, 0)) {
                subjectDN = "CN=" + usernameShort;
            }
        }
        String subjectAN = "";
        if (MSCertTools.isRequired(templateIndex, DnComponents.UPN, 0)) {
            subjectAN += (subjectAN.length() == 0 ? "" : ",") + "UPN=" + remoteUser;
        }
        if (MSCertTools.isRequired(templateIndex, DnComponents.GUID, 0)) {
            String reqGUID = req.getMSRequestInfoSubjectAltnames()[0];
            subjectAN += (subjectAN.length() == 0 ? "" : ",") + "GUID=" + reqGUID;
        }
        if (MSCertTools.isRequired(templateIndex, DnComponents.DNSNAME, 0)) {
            String reqDNS = req.getMSRequestInfoSubjectAltnames()[1];
            subjectAN += (subjectAN.length() == 0 ? "" : ",") + "DNSNAME=" + reqDNS;
        }
        log.info("sdn=" + subjectDN + ", san=" + subjectAN);
        debugInfo += "\nsdn=" + subjectDN + ", san=" + subjectAN + "\n";
        EndEntityInformation userData = new EndEntityInformation(username, subjectDN, caid, subjectAN, null,
                EndEntityConstants.STATUS_NEW, new EndEntityType(EndEntityTypes.ENDUSER), endEntityProfileId,
                certProfileId, new Date(), new Date(), SecConst.TOKEN_SOFT_BROWSERGEN, 0, null);
        String password = PasswordGeneratorFactory
                .getInstance(PasswordGeneratorFactory.PASSWORDTYPE_LETTERSANDDIGITS).getNewPassword(8, 8);
        userData.setPassword(password);
        try {
            if (endEntityManagementSession.existsUser(username)) {
                endEntityManagementSession.changeUser(internalAdmin, userData, true);
            } else {
                endEntityManagementSession.addUser(internalAdmin, userData, true);
            }
        } catch (Exception e) {
            log.error("Could not add user " + username, e);
        }
        Certificate cert = null;
        debugInfo += "Request: " + requestData + "\n";
        req.setUsername(username);
        req.setPassword(password);
        ResponseMessage resp;
        try {
            resp = signSession.createCertificate(internalAdmin, req, X509ResponseMessage.class, null);
            cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
            result = signSession.createPKCS7(internalAdmin, cert, true);
            debugInfo += "Resulting cert: " + new String(Base64.encode(result, true)) + "\n";
        } catch (Exception e) {
            log.error("Noooo!!! ", e);
            response.getOutputStream().println("An error has occurred.");
            return;
        }
        if (debugRequest) {
            response.getOutputStream().println(StringEscapeUtils.escapeJavaScript(debugInfo));
        } else {
            // Output the certificate
            ServletOutputStream os = response.getOutputStream();
            os.print(RequestHelper.BEGIN_PKCS7_WITH_NL);
            os.print(new String(Base64.encode(result, true)));
            os.print(RequestHelper.END_PKCS7_WITH_NL);
            response.flushBuffer();
            log.info("Sent cert to client");
        }
    } catch (AuthorizationDeniedException e1) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e1.getMessage());
    }
    log.trace("<doPost");
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * Process a POST to the servlet by handing it off to the Axis Engine.
 * Here is where SOAP messages are received
 * @param req posted request/*from   ww w . j  a  v a  2s  .c o m*/
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
public void doPost(HttpServletRequest req, HttpServletResponse res, Component component)
        throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;

    Message rspMsg = null;
    String contentType = null;
    InputStream is = null;
    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            log.debug("No Engine!", se);
            throw se;
        }

        res.setBufferSize(1024 * 8); // provide performance boost.

        /** get message context w/ various properties set
         */
        msgContext = createMessageContext(engine, req, res, component);
        ComponentController.set(msgContext);

        // ? OK to move this to 'getMessageContext',
        // ? where it would also be picked up for 'doGet()' ?
        if (securityProvider != null) {
            if (isDebug) {
                log.debug("securityProvider:" + securityProvider);
            }
            msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider);
        }

        is = req.getInputStream();
        Message requestMsg = new Message(is, false, req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
        // Transfer HTTP headers to MIME headers for request message.
        MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements();) {
                String headerValue = (String) f.nextElement();
                requestMimeHeaders.addHeader(headerName, headerValue);
            }
        }

        if (isDebug) {
            log.debug("Request Message:" + requestMsg);

            /* Set the request(incoming) message field in the context */
            /**********************************************************/
        }
        msgContext.setRequestMessage(requestMsg);
        String url = HttpUtils.getRequestURL(req).toString().toLowerCase();
        msgContext.setProperty(MessageContext.TRANS_URL, url);
        // put character encoding of request to message context
        // in order to reuse it during the whole process.

        try {
            String reqEnc = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (reqEnc != null)
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, reqEnc);
        } catch (SOAPException e1) {
        }

        try {
            /**
             * Save the SOAPAction header in the MessageContext bag.
             * This will be used to tell the Axis Engine which service
             * is being invoked.  This will save us the trouble of
             * having to parse the Request message - although we will
             * need to double-check later on that the SOAPAction header
             * does in fact match the URI in the body.
             */
            // (is this last stmt true??? (I don't think so - Glen))
            /********************************************************/
            soapAction = getSoapAction(req);
            if (soapAction != null) {
                msgContext.setUseSOAPAction(true);
                msgContext.setSOAPActionURI(soapAction);
            }

            // Create a Session wrapper for the HTTP session.
            // These can/should be pooled at some point.
            // (Sam is Watching! :-)
            msgContext.setSession(new AxisHttpSession(req));

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }
            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug) {
                log.debug("Invoking Axis Engine.");
                //here we run the message by the engine
            }
            //msgContext.setProperty("disablePrettyXML", "false");
            engine.invoke(msgContext);
            if (isDebug) {
                log.debug("Return from Axis Engine.");
            }
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }

            rspMsg = msgContext.getResponseMessage();

            // We used to throw exceptions on null response messages.
            // They are actually OK in certain situations (asynchronous
            // services), so fall through here and return an ACCEPTED
            // status code below.  Might want to install a configurable
            // error check for this later.
        } catch (AxisFault fault) {

            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            rspMsg = msgContext.getResponseMessage();
            if (rspMsg == null) {
                rspMsg = new Message(fault);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException)
                t = ((InvocationTargetException) t).getTargetException();
            // Exception
            if (t instanceof Exception) {
                Exception e = (Exception) t;
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = convertExceptionToAxisFault(e, rspMsg);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);

            }
            // throwable
            else {
                logException(t);
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = new Message(new AxisFault(t.toString(), t));
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        }
    } catch (AxisFault fault) {

        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        rspMsg = msgContext.getResponseMessage();
        if (rspMsg == null) {
            rspMsg = new Message(fault);
            ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    } finally {
        IOUtil.closeEL(is);
    }

    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    // Send response back along the wire... 
    if (rspMsg != null) {

        // Transfer MIME headers to HTTP headers for response message.
        MimeHeaders responseMimeHeaders = rspMsg.getMimeHeaders();
        for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader responseMimeHeader = (MimeHeader) i.next();
            res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue());
        }
        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null) {
            try {
                rspMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
            } catch (SOAPException e) {
            }
        }

        //determine content type from message response
        contentType = rspMsg.getContentType(msgContext.getSOAPConstants());
        if (isDebug)
            log.debug("Returned Content-Type:" + contentType);

        // write result to response stream
        try {
            res.setContentType(contentType);
            rspMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }

        if (!res.isCommitted())
            res.flushBuffer(); // Force it right now.
    } else {
        // No content, so just indicate accepted
        res.setStatus(202);
    }

    if (isDebug) {
        log.debug("Response sent.");
        log.debug("Exit: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post="
                + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "."
                + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName()));
    }

}

From source file:org.sakaiproject.portal.charon.SkinnableCharonPortal.java

private void showSnoop(PortalRenderContext rcontext, boolean b, ServletConfig servletConfig,
        HttpServletRequest req) {
    Enumeration e = null;/*  w ww  . jav a 2 s . c o  m*/

    rcontext.put("snoopRequest", req.toString());

    if (servletConfig != null) {
        Map<String, Object> m = new HashMap<String, Object>();
        e = servletConfig.getInitParameterNames();

        if (e != null) {
            while (e.hasMoreElements()) {
                String param = (String) e.nextElement();
                m.put(param, servletConfig.getInitParameter(param));
            }
        }
        rcontext.put("snoopServletConfigParams", m);
    }
    rcontext.put("snoopRequest", req);

    e = req.getHeaderNames();
    if (e.hasMoreElements()) {
        Map<String, Object> m = new HashMap<String, Object>();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            m.put(name, req.getHeader(name));
        }
        rcontext.put("snoopRequestHeaders", m);
    }

    e = req.getParameterNames();
    if (e.hasMoreElements()) {
        Map<String, Object> m = new HashMap<String, Object>();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            m.put(name, req.getParameter(name));
        }
        rcontext.put("snoopRequestParamsSingle", m);
    }

    e = req.getParameterNames();
    if (e.hasMoreElements()) {
        Map<String, Object> m = new HashMap<String, Object>();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            String[] vals = (String[]) req.getParameterValues(name);
            StringBuilder sb = new StringBuilder();
            if (vals != null) {
                sb.append(vals[0]);
                for (int i = 1; i < vals.length; i++)
                    sb.append("           ").append(vals[i]);
            }
            m.put(name, sb.toString());
        }
        rcontext.put("snoopRequestParamsMulti", m);
    }

    e = req.getAttributeNames();
    if (e.hasMoreElements()) {
        Map<String, Object> m = new HashMap<String, Object>();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            m.put(name, req.getAttribute(name));

        }
        rcontext.put("snoopRequestAttr", m);
    }
}

From source file:org.codehaus.wadi.web.impl.StandardHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest req = context.getHreq();
    HttpServletResponse res = context.getHres();

    String requestURI = getRequestURI(req);
    String qs = req.getQueryString();
    if (qs != null) {
        requestURI = new StringBuffer(requestURI).append("?").append(qs).toString();
    }/* www. j a v  a  2s. c om*/

    URL url = null;
    try {
        url = new URL("http", uri.getHost(), uri.getPort(), requestURI);
        if (_log.isTraceEnabled())
            _log.trace("proxying to: " + url);
    } catch (MalformedURLException e) {
        if (_log.isWarnEnabled())
            _log.warn("bad proxy url: " + url, e);
        throw new IrrecoverableException("bad proxy url", e);
    }

    long startTime = System.currentTimeMillis();

    HttpURLConnection huc = null;
    String m = req.getMethod();
    try {
        huc = (HttpURLConnection) url.openConnection(); // IOException
        huc.setRequestMethod(m); // ProtocolException
    } catch (ProtocolException e) {
        if (_log.isWarnEnabled())
            _log.warn("unsupported http method: " + m, e);
        throw new IrrecoverableException("unsupported HTTP method: " + m, e);
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy IO problem", e);
        throw new RecoverableException("could not open proxy connection", e);
    }

    huc.setAllowUserInteraction(false);
    huc.setInstanceFollowRedirects(false);

    // check connection header
    // TODO - this might need some more time: see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
    String connectionHdr = req.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers - inefficient, but we are constrained by servlet API
    {
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String hdr = (String) e.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) // what is going on here ?
                continue;
            // HTTP/1.1 proxies MUST parse the Connection header field before a message is forwarded and, for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token. Connection options are signaled by the presence of a connection-token in the Connection header field, not by any corresponding additional header field(s), since the additional header field may not be sent if there are no parameters associated with that connection option
            if (_WADI_IsSecure.equals(hdr)) // don't worry about case - we should be the only one messing with this header...
                continue; // strip this out - we may be being spoofed

            for (Enumeration f = req.getHeaders(hdr); f.hasMoreElements();) {
                String val = (String) f.nextElement();
                if (val != null) {
                    huc.addRequestProperty(hdr, val);
                }
            }
        }
    }

    // content ?
    boolean hasContent = false;
    {
        int contentLength = 0;
        String tmp = huc.getRequestProperty("Content-Length");
        if (tmp != null) {
            try {
                contentLength = Integer.parseInt(tmp);
            } catch (NumberFormatException ignore) {
                // ignore
            }
        }

        if (contentLength > 0)
            hasContent = true;
        else
            hasContent = (huc.getRequestProperty("Content-Type") != null);
    }

    // proxy
    {
        huc.addRequestProperty("Via", "1.1 " + req.getLocalName() + ":" + req.getLocalPort() + " \"WADI\""); // TODO - should we be giving out personal details ?
        huc.addRequestProperty("X-Forwarded-For", req.getRemoteAddr()); // adds last link in request chain...
        // String tmp=uc.getRequestProperty("Max-Forwards"); // TODO - do we really need to bother with this ?
    }

    // cache-control
    {
        String cacheControl = huc.getRequestProperty("Cache-Control");
        if (cacheControl != null
                && (cacheControl.indexOf("no-cache") >= 0 || cacheControl.indexOf("no-store") >= 0))
            huc.setUseCaches(false);
    }

    // confidentiality
    {
        if (req.isSecure()) {
            huc.addRequestProperty(_WADI_IsSecure, req.getLocalAddr().toString());
        }

        // at the other end, if this header is present we must :

        // wrap the request so that req.isSecure()=true, before processing...
        // mask the header - so it is never seen by the app.

        // the code for the other end should live in this class.

        // this code should also confirm that it not being spoofed by confirming that req.getRemoteAddress() is a cluster member...
    }
    // customize Connection
    huc.setDoInput(true);

    // client->server
    int client2ServerTotal = 0;
    {
        if (hasContent) {
            huc.setDoOutput(true);

            OutputStream toServer = null;
            try {
                InputStream fromClient = req.getInputStream(); // IOException
                toServer = huc.getOutputStream(); // IOException
                client2ServerTotal = copy(fromClient, toServer, 8192);
            } catch (IOException e) {
                new IrrecoverableException("problem proxying client request to server", e);
            } finally {
                if (toServer != null) {
                    try {
                        toServer.close(); // IOException
                    } catch (IOException e) {
                        _log.warn("problem closing server request stream", e);
                    }
                }
            }
        }
    }

    // Connect
    try {
        huc.connect(); // IOException
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy connection problem: " + url, e);
        throw new RecoverableException("could not connect to proxy target", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 0;
    if (huc == null) {
        try {
            fromServer = huc.getInputStream(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring client output", e);
        }
    } else {
        code = 502;
        //         String message="Bad Gateway: could not read server response code or message";
        try {
            code = huc.getResponseCode(); // IOException
            //            message=huc.getResponseMessage(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring http server response code/message", e);
        } finally {
            //            res.setStatus(code, message); - deprecated
            res.setStatus(code);
        }

        if (code < 400) {
            // 1XX:continue, 2XX:successful, 3XX:multiple-choices...
            try {
                fromServer = huc.getInputStream(); // IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem acquiring http client output", e);
            }
        } else {
            // 4XX:client, 5XX:server error...
            fromServer = huc.getErrorStream(); // why does this not throw IOException ?
            // TODO - do we need to use sendError()?
        }
    }

    // clear response defaults.
    res.setHeader("Date", null);
    res.setHeader("Server", null);

    // set response headers
    if (false) {
        int h = 0;
        String hdr = huc.getHeaderFieldKey(h);
        String val = huc.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = (hdr != null) ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr))
                res.addHeader(hdr, val);

            // if (_log.isDebugEnabled()) _log.debug("res " + hdr + ": " + val);

            h++;
            hdr = huc.getHeaderFieldKey(h);
            val = huc.getHeaderField(h);
        }
    } else {
        // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
        // Try this inside Tomcat...
        String key;
        for (int i = 1; (key = huc.getHeaderFieldKey(i)) != null; i++) {
            key = key.toLowerCase();
            String val = huc.getHeaderField(i);
            if (val != null && !_DontProxyHeaders.contains(key)) {
                res.addHeader(key, val);
            }
        }
    }

    // do we need another Via header in the response...

    // server->client
    int server2ClientTotal = 0;
    {
        if (fromServer != null) {
            try {
                OutputStream toClient = res.getOutputStream();// IOException
                server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem proxying server response back to client", e);
            } finally {
                try {
                    fromServer.close();
                } catch (IOException e) {
                    // well - we did our best...
                    _log.warn("problem closing server response stream", e);
                }
            }
        }
    }

    huc.disconnect();

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled())
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", url:" + url);
}

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

/**
 * @param httpServletRequest/*from ww w .j a  va  2s  .  c  om*/
 * @param httpServletResponse
 * @throws ServletException
 * @throws java.io.IOException
 */
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "PathInfo = "
            + httpServletRequest.getPathInfo());
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "QueryString = "
            + httpServletRequest.getQueryString());

    String patronid = "";
    String service = "";
    String accept = "";
    String authorization = "";

    String path = httpServletRequest.getPathInfo();
    if (path != null) {
        String[] params = path.substring(1, path.length()).split("/");

        if (params.length == 1) {
            patronid = params[0];
            service = "patron";
        } else if (params.length == 2) {
            patronid = params[0];
            service = params[1];
        }
    }

    // 1. Schritt: Hole 'Accept' und 'Authorization' aus dem Header;
    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = (String) headerNames.nextElement();
        this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "headerNameKey = "
                + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Accept")) {
            accept = httpServletRequest.getHeader(headerNameKey);
        }
        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }
    }

    if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null
            && !httpServletRequest.getParameter("access_token").equals("")) {
        authorization = "Bearer " + httpServletRequest.getParameter("access_token");
    }

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Patron: " + patronid);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Service: " + service);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Accept: " + accept);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Authorization: " + authorization);

    this.logger.error("[" + this.config.getProperty("service.name") + "] "
            + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "GET for '" + service + "' not allowed!");

    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA Core\"");
    httpServletResponse.setContentType("application/json");
    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

    // Error handling mit suppress_response_codes=true
    if (httpServletRequest.getParameter("suppress_response_codes") != null
            && !httpServletRequest.getParameter("suppress_response_codes").equals("")) {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    }
    // Error handling mit suppress_response_codes=false (=default)
    else {
        httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    // Json fr Response body
    RequestError requestError = new RequestError();
    requestError.setError(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED)));
    requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    requestError.setDescription(this.config.getProperty(
            "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description"));
    requestError.setErrorUri(this.config
            .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri"));

    StringWriter json = new StringWriter();
    mapper.writeValue(json, requestError);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

    // send response
    httpServletResponse.getWriter().println(json);
}

From source file:com.cloud.bridge.service.EC2RestServlet.java

private void logRequest(HttpServletRequest request) {
    if (logger.isInfoEnabled()) {
        logger.info("EC2 Request method: " + request.getMethod());
        logger.info("Request contextPath: " + request.getContextPath());
        logger.info("Request pathInfo: " + request.getPathInfo());
        logger.info("Request pathTranslated: " + request.getPathTranslated());
        logger.info("Request queryString: " + request.getQueryString());
        logger.info("Request requestURI: " + request.getRequestURI());
        logger.info("Request requestURL: " + request.getRequestURL());
        logger.info("Request servletPath: " + request.getServletPath());
        Enumeration<?> headers = request.getHeaderNames();
        if (headers != null) {
            while (headers.hasMoreElements()) {
                Object headerName = headers.nextElement();
                logger.info("Request header " + headerName + ":" + request.getHeader((String) headerName));
            }/*from w w  w  . j a  va 2  s  . c  o  m*/
        }

        Enumeration<?> params = request.getParameterNames();
        if (params != null) {
            while (params.hasMoreElements()) {
                Object paramName = params.nextElement();
                logger.info("Request parameter " + paramName + ":" + request.getParameter((String) paramName));
            }
        }
    }
}

From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java

/**
 * Returns the request that points to the backend service defined by the provided 
 * <code>urlToService</code> URL. The headers of the origin request are copied to 
 * the backend request, except of "host" and "content-length".   
 * /*from  w  ww  .j  a va  2 s . c o  m*/
 * @param request
 *            original request to the Web application
 * @param urlToService
 *            URL to the targeted backend service
 * @return initialized backend service request
 * @throws IOException 
 */
private HttpRequestBase getBackendRequest(HttpServletRequest request, String urlToService) throws IOException {
    String method = request.getMethod();
    LOGGER.debug("HTTP method: " + method);

    HttpRequestBase backendRequest = null;
    if (HttpPost.METHOD_NAME.equals(method)) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pipe(request.getInputStream(), out);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        entity.setContentType(request.getHeader("Content-Type"));
        HttpPost post = new HttpPost(urlToService);
        post.setEntity(entity);
        backendRequest = post;
    } else if (HttpGet.METHOD_NAME.equals(method)) {
        HttpGet get = new HttpGet(urlToService);
        backendRequest = get;
    } else if (HttpPut.METHOD_NAME.equals(method)) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pipe(request.getInputStream(), out);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        entity.setContentType(request.getHeader("Content-Type"));
        HttpPut put = new HttpPut(urlToService);
        put.setEntity(entity);
        backendRequest = put;
    } else if (HttpDelete.METHOD_NAME.equals(method)) {
        HttpDelete delete = new HttpDelete(urlToService);
        backendRequest = delete;
    }

    // copy headers from Web application request to backend request, while
    // filtering the blocked headers

    LOGGER.debug("backend request headers:");

    Collection<String> blockedHeaders = mergeLists(securityHandler, Arrays.asList(BLOCKED_REQUEST_HEADERS));

    Enumeration<String> setCookieHeaders = request.getHeaders("Cookie");
    while (setCookieHeaders.hasMoreElements()) {
        String cookieHeader = setCookieHeaders.nextElement();
        if (blockedHeaders.contains(cookieHeader.toLowerCase())) {
            String replacedCookie = removeJSessionID(cookieHeader);
            backendRequest.addHeader("Cookie", replacedCookie);
        }
        LOGGER.debug("Cookie header => " + cookieHeader);
    }

    for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
        String headerName = e.nextElement().toString();
        if (!blockedHeaders.contains(headerName.toLowerCase())) {
            backendRequest.addHeader(headerName, request.getHeader(headerName));
            LOGGER.debug("    => " + headerName + ": " + request.getHeader(headerName));
        } else {
            LOGGER.debug("    => " + headerName + ": blocked request header");
        }
    }

    return backendRequest;
}