Example usage for javax.servlet.http HttpServletRequest getContentType

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

Introduction

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

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

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  .j a  v a  2 s.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:org.red5.server.net.rtmpt.RTMPTServlet.java

/**
 * Main entry point for the servlet.//from  ww w.  ja v a  2s . co m
 * 
 * @param req
 *            Request object
 * @param resp
 *            Response object
 * @throws IOException
 *             I/O exception
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    if (applicationContext == null) {
        ServletContext ctx = getServletContext();
        applicationContext = WebApplicationContextUtils.getWebApplicationContext(ctx);
        if (applicationContext == null) {
            applicationContext = (WebApplicationContext) ctx
                    .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        }
        log.debug("Application context: {}", applicationContext);
        // ensure we have a connection manager
        if (manager == null) {
            log.warn("Class instance connection manager was null, looking up in application context");
            manager = (RTMPConnManager) applicationContext.getBean("rtmpConnManager");
            if (manager == null) {
                log.warn("Connection manager was null in context, getting class instance");
                manager = RTMPConnManager.getInstance();
                if (manager == null) {
                    log.error("Connection manager is still null, this is bad");
                }
            }
        }
    }
    log.debug("Request - method: {} content type: {} path: {}",
            new Object[] { req.getMethod(), req.getContentType(), req.getServletPath() });
    // allow only POST requests with valid content length
    if (!REQUEST_METHOD.equals(req.getMethod()) || req.getContentLength() == 0) {
        // Bad request - return simple error page
        handleBadRequest("Bad request, only RTMPT supported.", resp);
        return;
    }
    // decide whether or not to enforce request content checks
    if (enforceContentTypeCheck && !CONTENT_TYPE.equals(req.getContentType())) {
        handleBadRequest(String.format("Bad request, unsupported content type: %s.", req.getContentType()),
                resp);
        return;
    }
    // get the uri
    String uri = req.getRequestURI().trim();
    log.debug("URI: {}", uri);
    // get the path
    String path = req.getServletPath();
    // since the only current difference in the type of request that we are interested in is the 'second' character, we can double
    // the speed of this entry point by using a switch on the second character.
    char p = path.charAt(1);
    switch (p) {
    case 'o': // OPEN_REQUEST
        handleOpen(req, resp);
        break;
    case 'c': // CLOSE_REQUEST
        setRequestInfo(req);
        handleClose(req, resp);
        requestInfo.remove();
        break;
    case 's': // SEND_REQUEST
        setRequestInfo(req);
        handleSend(req, resp);
        requestInfo.remove();
        break;
    case 'i': // IDLE_REQUEST
        setRequestInfo(req);
        handleIdle(req, resp);
        requestInfo.remove();
        break;
    case 'f': // HTTPIdent request (ident and ident2)
        //if HTTPIdent is requested send back some Red5 info
        //http://livedocs.adobe.com/flashmediaserver/3.0/docs/help.html?content=08_xmlref_011.html         
        String ident = "<fcs><Company>Red5</Company><Team>Red5 Server</Team></fcs>";
        // handle ident2 slightly different to appease osx clients
        if (uri.charAt(uri.length() - 1) == '2') {
            // check for pre-configured ident2 value
            if (ident2 != null) {
                ident = ident2;
            } else {
                // just send 404 back if no ident2 value is set
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                resp.setHeader("Connection", "Keep-Alive");
                resp.setHeader("Cache-Control", "no-cache");
                resp.flushBuffer();
                break;
            }
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setHeader("Connection", "Keep-Alive");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setContentType(CONTENT_TYPE);
        resp.setContentLength(ident.length());
        resp.getWriter().write(ident);
        resp.flushBuffer();
        break;
    default:
        handleBadRequest(String.format("RTMPT command %s is not supported.", path), resp);
    }
    // clear thread local reference
    Red5.setConnectionLocal(null);
}

From source file:ORG.oclc.os.SRW.SRWServlet.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   w  w  w .ja  v  a 2s .c  o m
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;
    if (isDebug)
        servletLog.debug("Enter: doPost()");
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }

    Message responseMsg = null;
    String contentType = req.getContentType().toLowerCase();
    if (log.isDebugEnabled())
        log.debug("in SRWServlet.doPost: contentType=" + contentType);
    if (contentType.indexOf("atom+xml") > 0) {
        msgContext = createMessageContext(getEngine(), req, res);
        if (!srwInfo.setSRWStuff(req, res, msgContext)) {
            servletLog.error("srwInfo.setSRWStuff failed!");
            return;
        }
        SRWDatabase db = (SRWDatabase) msgContext.getProperty("db");
        if (log.isDebugEnabled())
            log.debug("adding to database " + db);
        if (log.isDebugEnabled())
            log.debug("adding to database " + db.dbname);
        InputStream is = req.getInputStream();
        int len, offset = 0, totlen = req.getContentLength();
        byte[] b = new byte[totlen];
        while (totlen > 0) {
            len = is.read(b, offset, totlen);
            totlen -= len;
            offset += len;
        }
        db.add(b);
        if (db.httpHeaderSetter != null)
            db.httpHeaderSetter.setPostResponseHeaders(new String(b, "UTF-8"), req, res);
        res.setStatus(201);
        return;
    }

    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            servletLog.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);

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

        /* Get request message
         */
        Message requestMsg = new Message(req.getInputStream(), false,
                req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));

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

        /* Set the request(incoming) message field in the context */
        /**********************************************************/
        msgContext.setRequestMessage(requestMsg);
        //String url = HttpUtils.getRequestURL(req).toString();
        String url = req.getRequestURL().toString();
        msgContext.setProperty(MessageContext.TRANS_URL, url);

        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);
            } else { // not a SOAP request
                String content = new String(((SOAPPart) (requestMsg.getSOAPPart())).getAsBytes());
                if (content.startsWith("<")) { // must be an ATOM request
                    return;
                }
                if (content.indexOf("query=") >= 0 || content.indexOf("scanClause=") >= 0) {
                    processMethodRequest(msgContext,
                            new LateContentParsingHttpServletRequestWrapper(req, content), res);
                    return;
                }

                // nothing I recognize
                AxisFault af = new AxisFault("Client.NoSOAPAction",
                        Messages.getMessage("noHeader00", "SOAPAction"), null, null);

                exceptionLog.error(Messages.getMessage("genFault00"), af);

                throw af;
            }

            // 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();
            }

            srwInfo.setSRWStuff(req, res, msgContext);

            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug)
                servletLog.debug("Invoking Axis Engine.");
            //here we run the message by the engine
            engine.invoke(msgContext);
            if (isDebug)
                servletLog.debug("Return from Axis Engine.");
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                //tell everyone that something is wrong
                throw new Exception(Messages.getMessage("noResponse01"));
            }
        } catch (AxisFault fault) {
            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(fault);
            }
        } catch (Exception e) {
            //other exceptions are internal trouble
            responseMsg = msgContext.getResponseMessage();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            responseMsg = convertExceptionToAxisFault(e, responseMsg);
        }
    } catch (AxisFault fault) {
        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        responseMsg = msgContext.getResponseMessage();
        if (responseMsg == null) {
            responseMsg = new Message(fault);
        }
    }
    //determine content type from message response
    contentType = responseMsg.getContentType(msgContext.getSOAPConstants());
    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    /* Send response back along the wire...  */
    /***********************************/
    if (responseMsg != null) {
        sendResponse(getProtocolVersion(req), contentType, res, responseMsg);
    }

    if (isDebug) {
        servletLog.debug("Response sent.");
        servletLog.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.sprintapi.api.http.HttpServlet.java

protected void doService(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ErrorException, IOException {

    final RequestHolder<Object> request = new RequestHolder<Object>(getUri(httpRequest));
    request.setContext(httpRequest.getContextPath());

    // Resolve incoming URL and get resource descriptor
    final ResourceDescriptor resourceDsc = resolve(request.getUri());

    // Does the requested resource exist?
    if (resourceDsc == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_FOUND);
    }//from   w w w .  java2 s . c o m

    // Is requested method supported?
    if (httpRequest.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        request.setMethod(Method.valueOf(httpRequest.getMethod().toUpperCase(Locale.US)));

    } catch (IllegalArgumentException ex) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    if (request.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    // Get supported methods for requested resource
    Map<Method, MethodDescriptor<?, ?>> methods = resourceDsc.methods();

    // Get requested method descriptors for the resource
    MethodDescriptor<?, ?> methodDsc = (methods != null) ? methods.get(request.getMethod()) : null;

    // Is requested method supported?
    if ((methodDsc == null)) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    ContentAdapter<InputStream, ?> inputContentAdapter = null;

    // Is request body expected?
    if (request.getMethod().isRequestBody()) {
        String requestContentType = httpRequest.getContentType();

        inputContentAdapter = (methodDsc.consumes() != null) ? methodDsc.consumes().get(requestContentType)
                : null;
        if (inputContentAdapter == null) {
            throw new ErrorException(request.getUri(), HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        }

    } else if (httpRequest.getContentLength() > 0) {
        // Unexpected request body
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    ContentAdapter<?, InputStream> outputContentAdapter = null;

    String responseContentType = null;

    // Is response body expected?
    if (request.getMethod().isResponseBody()) {
        // Check Accept header
        HttpAcceptHeader acceptHeader = HttpAcceptHeader
                .read(httpRequest.getHeader(ContentDescriptor.META_ACCEPT));
        if (acceptHeader != null) {

            Map<String, ?> produces = methodDsc.produces();

            // Response content negotiation 
            if (produces != null) {
                int weight = 0;

                for (String ct : produces.keySet()) {
                    int tw = acceptHeader.accept(ct);
                    if (tw > weight) {
                        weight = tw;
                        responseContentType = ct;
                        outputContentAdapter = (ContentAdapter<?, InputStream>) produces.get(ct);
                    }
                }
            }
            if (outputContentAdapter == null) {
                throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_ACCEPTABLE);
            }
        }
    }

    if (inputContentAdapter != null) {
        ContentHolder<Object> lc = new ContentHolder<Object>();
        lc.setBody(inputContentAdapter.transform(request.getUri(), httpRequest.getInputStream()));
        request.setContent(lc);
    }

    // Invoke resource method
    Response response = methodDsc.invoke((Request) request);

    if (response == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // Write response status
    int responseStatus = (response.getStatus() > 0) ? response.getStatus() : HttpServletResponse.SC_OK;
    httpResponse.setStatus(responseStatus);

    if (response.getContent() == null) {
        return;
    }

    // Write response headers
    if (response.getContent().getMetaNames() != null) {
        for (String metaName : response.getContent().getMetaNames()) {
            Object metaValue = response.getContent().getMeta(metaName);
            if (metaValue != null) {
                if (metaValue instanceof Date) {
                    httpResponse.setHeader(metaName, HttpDate.RFC1123_FORMAT.format(((Date) metaValue)));
                } else {
                    httpResponse.setHeader(metaName, metaValue.toString());
                }
            }
        }
    }

    if ((HttpServletResponse.SC_CREATED == responseStatus)) {
        httpResponse.setHeader(ContentDescriptor.META_LOCATION, response.getContext() + response.getUri());
    }

    if ((response.getContent().getBody() == null) || (HttpServletResponse.SC_NOT_MODIFIED == responseStatus)) {
        return;
    }

    // Write response body
    if (outputContentAdapter != null) {
        httpResponse.setHeader(ContentDescriptor.META_CONTENT_TYPE, responseContentType);
        InputStream is = ((ContentAdapter<Object, InputStream>) outputContentAdapter)
                .transform(request.getUri(), response.getContent().getBody());
        if (is != null) {
            CopyUtils.copy(is, httpResponse.getOutputStream());
        }
    }
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Create debug string containing all parameter names and their values from
 * the request, all attributes, all cookies and other data characterizing the
 * request./*from   w  w w.  j a v  a 2s . c  o m*/
 *
 * @param  hsrqRequest - the servlet request.
 * @return String - debug string containing all parameter names and their
 *                  values from the request
 */
public static String debug(HttpServletRequest hsrqRequest) {
    Enumeration enumNames;
    Enumeration enumValues;
    Iterator iterValues;
    String strName;
    String[] arValues;
    Cookie[] arCookies;
    int iIndex;
    Map<String, String[]> mpParamMap;
    StringBuilder sbfReturn = new StringBuilder();

    sbfReturn.append("HttpServletRequest=[");
    sbfReturn.append("\nRemoteAddress=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemotePort=");
    sbfReturn.append(hsrqRequest.getRemotePort());
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteHost=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteUser=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser()));
    sbfReturn.append(";");
    sbfReturn.append("\nFullURL=");
    sbfReturn.append(getFullRequestURL(hsrqRequest));
    sbfReturn.append(";");
    sbfReturn.append("\nContextPath=");
    sbfReturn.append(hsrqRequest.getContextPath());
    sbfReturn.append(";");
    sbfReturn.append("\nServletPath=");
    sbfReturn.append(hsrqRequest.getServletPath());
    sbfReturn.append(";");
    sbfReturn.append("\nPathInfo =");
    sbfReturn.append(hsrqRequest.getPathInfo());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURI=");
    sbfReturn.append(hsrqRequest.getRequestURI());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURL=");
    sbfReturn.append(hsrqRequest.getRequestURL());
    sbfReturn.append(";");
    sbfReturn.append("\nMethod=");
    sbfReturn.append(hsrqRequest.getMethod());
    sbfReturn.append(";");
    sbfReturn.append("\nAuthenticationType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType()));
    sbfReturn.append(";");
    sbfReturn.append("\nCharacterEncoding=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding()));
    sbfReturn.append(";");
    sbfReturn.append("\nContentType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType()));
    sbfReturn.append(";");
    sbfReturn.append("\nMultiPart=");
    sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest));
    sbfReturn.append(";");

    // Parameters ////////////////////////////////////////////////////////////

    try {
        Map.Entry<String, String[]> entry;

        // Use getParameterMap rather than request.getParameterNames since it 
        // correctly handles multipart requests
        mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest);
        for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) {
            entry = (Map.Entry<String, String[]>) iterValues.next();
            strName = entry.getKey();
            arValues = entry.getValue();
            sbfReturn.append("\nParam=");
            sbfReturn.append(strName);
            sbfReturn.append(" values=");
            for (iIndex = 0; iIndex < arValues.length; iIndex++) {
                sbfReturn.append(arValues[iIndex]);
                if (iIndex < (arValues.length - 1)) {
                    sbfReturn.append(";");
                }
            }
            if (iterValues.hasNext()) {
                sbfReturn.append(";");
            }
        }
    } catch (OSSInvalidDataException ex) {
        sbfReturn.append("<Cannot access parameter map of the request>");
        s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex);
    }

    // Uploaded files ////////////////////////////////////////////////////////

    if (ServletFileUpload.isMultipartContent(hsrqRequest)) {
        try {
            FileItem item;
            Map<String, FileItem> mpFiles;
            TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params;

            params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest);
            mpFiles = params.getSecond();

            for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) {
                item = (FileItem) iterValues.next();
                sbfReturn.append("\nUpload=");
                sbfReturn.append(item.getName());
                sbfReturn.append(" field=");
                sbfReturn.append(item.getFieldName());
                sbfReturn.append(" contentType=");
                sbfReturn.append(item.getContentType());
                sbfReturn.append(" isInMemory=");
                sbfReturn.append(item.isInMemory());
                sbfReturn.append(" sizeInBytes=");
                sbfReturn.append(item.getSize());
                if (iterValues.hasNext()) {
                    sbfReturn.append(";");
                }
            }
        } catch (OSSInvalidDataException ex) {
            sbfReturn.append("<Cannot access list of multipart parameters>");
            s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex);
        }
    }

    // Headers ///////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nHeader=");
        sbfReturn.append(strName);
        sbfReturn.append(" values=");
        for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) {
            sbfReturn.append(enumValues.nextElement());
            if (enumValues.hasMoreElements()) {
                sbfReturn.append(";");
            }
        }
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Cookies ///////////////////////////////////////////////////////////////

    arCookies = hsrqRequest.getCookies();
    if (arCookies != null) {
        Cookie cookie;

        for (iIndex = 0; iIndex < arCookies.length; iIndex++) {
            cookie = arCookies[iIndex];
            sbfReturn.append("\nCookie=");
            sbfReturn.append(cookie.getName());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getPath());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getDomain());
            sbfReturn.append(" maxage=");
            sbfReturn.append(cookie.getMaxAge());
            sbfReturn.append(" version=");
            sbfReturn.append(cookie.getVersion());
            sbfReturn.append(" secure=");
            sbfReturn.append(cookie.getSecure());
            sbfReturn.append(" value=");
            sbfReturn.append(cookie.getValue());
            sbfReturn.append(" comment=");
            sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment()));
            if (iIndex < (arCookies.length - 1)) {
                sbfReturn.append(";");
            }
        }
    }
    if (enumNames.hasMoreElements()) {
        sbfReturn.append(";");
    }

    // Attributes ////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nAttribute=");
        sbfReturn.append(strName);
        sbfReturn.append(" value=");
        sbfReturn.append(hsrqRequest.getAttribute(strName));
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Content ///////////////////////////////////////////////////////////////

    sbfReturn.append("\nContent=");
    try {
        sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true));
    } catch (IOException ex) {
        sbfReturn.append("<Cannot access input stream of the request>");
        s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex);
    }
    sbfReturn.append(";");

    return sbfReturn.toString();
}

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;//from  w  w w .j  a va  2s  .  c  o m
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        // Execute the request

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        String method = servletRequest.getMethod();
        HttpMethod m;
        if (method.equalsIgnoreCase("PUT")) {
            m = new PutMethod(proxyRequestUri);
            RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(),
                    servletRequest.getContentType());
            ((PutMethod) m).setRequestEntity(requestEntity);
        } else {
            m = new GetMethod(proxyRequestUri);
        }
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //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 (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void addContentMetdataFromHttpRequest(BlobBuilder.PayloadBlobBuilder builder,
        HttpServletRequest request) {/*from w  ww.ja v a 2  s.  co m*/
    ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        if (startsWithIgnoreCase(headerName, USER_METADATA_PREFIX)) {
            userMetadata.put(headerName.substring(USER_METADATA_PREFIX.length()),
                    Strings.nullToEmpty(request.getHeader(headerName)));
        }
    }
    builder.cacheControl(request.getHeader(HttpHeaders.CACHE_CONTROL))
            .contentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION))
            .contentEncoding(request.getHeader(HttpHeaders.CONTENT_ENCODING))
            .contentLanguage(request.getHeader(HttpHeaders.CONTENT_LANGUAGE))
            .userMetadata(userMetadata.build());
    String contentType = request.getContentType();
    if (contentType != null) {
        builder.contentType(contentType);
    }
    long expires = request.getDateHeader(HttpHeaders.EXPIRES);
    if (expires != -1) {
        builder.expires(new Date(expires));
    }
}

From source file:org.betaconceptframework.astroboa.console.security.ResourceApiProxy.java

@GET
@PUT//from   w w  w  .jav  a 2  s. co m
@POST
@DELETE
@Path("{resourceApiPath:.*}")
@Produces("*/*")
public Response dispatchToAstroboaRepository(@PathParam("resourceApiPath") String resourceApiPath,
        @Context UriInfo uriInfo, @Context HttpServletRequest httpServletRequest) {

    try {

        String repositoryId = AstroboaClientContextHolder.getActiveRepositoryId();
        if (StringUtils.isBlank(repositoryId)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        CmsRepository activeCmsRepository = AstroboaClientContextHolder.getActiveCmsRepository();
        if (activeCmsRepository == null) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        SecurityContext securityContext = AstroboaClientContextHolder.getActiveSecurityContext();
        if (securityContext == null) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        String username = securityContext.getIdentity();

        if (StringUtils.isBlank(username)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        String resourceApiBasePath = activeCmsRepository.getRestfulApiBasePath();

        if (StringUtils.isBlank(resourceApiBasePath)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        HttpSession httpSession = httpServletRequest.getSession();
        String password = (String) httpSession.getAttribute("repositoryPassword");

        if (StringUtils.isBlank(password)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        String httpMethod = httpServletRequest.getMethod();

        String requestPath = uriInfo.getPath();
        MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();

        ClientRequest request = new ClientRequest(
                "http://localhost:8080" + resourceApiBasePath + "/" + repositoryId + requestPath);

        // read the payload if the http method is put or post
        if (httpMethod.equals("POST") || httpMethod.equals("PUT")) {
            request.body(httpServletRequest.getContentType(), getBody(httpServletRequest));
        }

        // add authorization header (BASIC AUTH)
        String basicAuthString = username + ":" + password;
        String authorization = "BASIC " + Base64.encodeBytes(basicAuthString.getBytes());
        request.header(HttpHeaders.AUTHORIZATION, authorization);

        // add headers
        Enumeration headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            request.header(headerName, httpServletRequest.getHeader(headerName));
        }

        // add query parameters
        for (Map.Entry queryParamEntry : queryParameters.entrySet()) {
            String parameterValue = ((List<String>) queryParamEntry.getValue()).get(0);

            //ClientRequest (request) encodes the values before the execution of the request.
            //Therefore we need to decode the values before we feed them to the ClientRequest instance
            request.queryParameter((String) queryParamEntry.getKey(),
                    URLDecoder.decode(parameterValue, "UTF-8"));
        }

        String uri = request.getUri();

        ClientResponse clientResponse = request.httpMethod(httpMethod, new GenericType<InputStream>() {
        });

        return clientResponse;

    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        logger.error("A problem occured while sending request to Astroboa Repository", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:org.pentaho.platform.web.refactor.SubscriptionAdminUIComponent.java

public Document doImport() {

    HttpServletRequest request = ((HttpRequestParameterProvider) getParameterProviders()
            .get(HttpRequestParameterProvider.SCOPE_REQUEST)).getRequest();
    String contentType = request.getContentType();
    if ((contentType == null) || ((contentType.indexOf("multipart/form-data") < 0) //$NON-NLS-1$
            && (contentType.indexOf("multipart/mixed stream") < 0))) { //$NON-NLS-1$
        return (showCommandResultUI(
                getErrorMessage(//  w  w w  .  j  a v  a 2 s  .  c  o  m
                        Messages.getString("SubscriptionAdminUIComponent.ERROR_IMPORT_FILE_NOT_UPLOADED")), //$NON-NLS-1$
                SubscriptionAdminUIComponent.NODE_STATUS_ERROR));
    }
    Enumeration enumer = request.getParameterNames();
    while (enumer.hasMoreElements()) {
        System.out.println(enumer.nextElement().toString());
    }
    try {
        String publishPassword = null;
        FileItem publishFile = null;

        // DiskFileUpload uploader = new DiskFileUpload();
        ServletFileUpload uploader = new ServletFileUpload(new DiskFileItemFactory());

        List fileList = uploader.parseRequest(request);
        Iterator iter = fileList.iterator();
        while (iter.hasNext()) {
            FileItem fi = (FileItem) iter.next();
            if (fi.isFormField()) {
                publishPassword = new String(fi.get());
            } else {
                publishFile = fi;
            }
        }
        saveFileItem(publishFile, publishPassword);
    } catch (Throwable t) {
        return (showCommandResultUI(
                getException(Messages.getString("SubscriptionAdminUIComponent.ERROR_UNABLE_TO_PARSE_FILE"), t), //$NON-NLS-1$
                SubscriptionAdminUIComponent.NODE_STATUS_ERROR));
    }

    return (showCommandResultUI(
            getOkMessage(Messages.getString("SubscriptionAdminUIComponent.USER_IMPORT_SUCCESSFUL")), //$NON-NLS-1$
            SubscriptionAdminUIComponent.NODE_STATUS_OK));

}