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:com.ark.website.filter.CORSFilter.java

/**
 * Determines the request type./*from  w  w  w.ja  v a2 s . c o m*/
 * 
 * @param request
 * @return
 */
public CORSRequestType checkRequestType(final HttpServletRequest request) {
    CORSRequestType requestType = CORSRequestType.INVALID_CORS;
    if (request == null) {
        throw new IllegalArgumentException("HttpServletRequest object is null");
    }
    String originHeader = request.getHeader(REQUEST_HEADER_ORIGIN);
    // Section 6.1.1 and Section 6.2.1
    if (originHeader != null) {
        if (originHeader.isEmpty()) {
            requestType = CORSRequestType.INVALID_CORS;
        } else if (!isValidOrigin(originHeader)) {
            requestType = CORSRequestType.INVALID_CORS;
        } else {
            String method = request.getMethod();
            if (method != null && HTTP_METHODS.contains(method)) {
                if ("OPTIONS".equals(method)) {
                    String accessControlRequestMethodHeader = request
                            .getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
                    if (accessControlRequestMethodHeader != null
                            && !accessControlRequestMethodHeader.isEmpty()) {
                        requestType = CORSRequestType.PRE_FLIGHT;
                    } else if (accessControlRequestMethodHeader != null
                            && accessControlRequestMethodHeader.isEmpty()) {
                        requestType = CORSRequestType.INVALID_CORS;
                    } else {
                        requestType = CORSRequestType.ACTUAL;
                    }
                } else if ("GET".equals(method) || "HEAD".equals(method)) {
                    requestType = CORSRequestType.SIMPLE;
                } else if ("POST".equals(method)) {
                    String contentType = request.getContentType();
                    if (contentType != null) {
                        contentType = contentType.toLowerCase().trim();
                        if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES.contains(contentType)) {
                            requestType = CORSRequestType.SIMPLE;
                        } else {
                            requestType = CORSRequestType.ACTUAL;
                        }
                    }
                } else if (COMPLEX_HTTP_METHODS.contains(method)) {
                    requestType = CORSRequestType.ACTUAL;
                }
            }
        }
    } else {
        requestType = CORSRequestType.NOT_CORS;
    }

    return requestType;
}

From source file:net.gplatform.sudoor.server.cors.CorsFilter.java

/**
 * Determines the request type.//from  w  w  w .j  a v  a 2  s .c o  m
 * 
 * @param request
 */
protected CORSRequestType checkRequestType(final HttpServletRequest request) {
    CORSRequestType requestType = CORSRequestType.INVALID_CORS;
    if (request == null) {
        throw new IllegalArgumentException(sm.getString("corsFilter.nullRequest"));
    }
    String originHeader = request.getHeader(REQUEST_HEADER_ORIGIN);
    // Section 6.1.1 and Section 6.2.1
    if (originHeader != null) {
        if (originHeader.isEmpty()) {
            requestType = CORSRequestType.INVALID_CORS;
        } else if (!isValidOrigin(originHeader)) {
            requestType = CORSRequestType.INVALID_CORS;
        } else {
            String method = request.getMethod();
            if (method != null && HTTP_METHODS.contains(method)) {
                if ("OPTIONS".equals(method)) {
                    String accessControlRequestMethodHeader = request
                            .getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
                    if (accessControlRequestMethodHeader != null
                            && !accessControlRequestMethodHeader.isEmpty()) {
                        requestType = CORSRequestType.PRE_FLIGHT;
                    } else if (accessControlRequestMethodHeader != null
                            && accessControlRequestMethodHeader.isEmpty()) {
                        requestType = CORSRequestType.INVALID_CORS;
                    } else {
                        requestType = CORSRequestType.ACTUAL;
                    }
                } else if ("GET".equals(method) || "HEAD".equals(method)) {
                    requestType = CORSRequestType.SIMPLE;
                } else if ("POST".equals(method)) {
                    String contentType = request.getContentType();
                    if (contentType != null) {
                        contentType = contentType.toLowerCase().trim();
                        if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES.contains(contentType)) {
                            requestType = CORSRequestType.SIMPLE;
                        } else {
                            requestType = CORSRequestType.ACTUAL;
                        }
                    }
                } else if (COMPLEX_HTTP_METHODS.contains(method)) {
                    requestType = CORSRequestType.ACTUAL;
                }
            }
        }
    } else {
        requestType = CORSRequestType.NOT_CORS;
    }

    return requestType;
}

From source file:it.greenvulcano.gvesb.adapter.http.formatters.handlers.ExtendedInboundParamHandlerFormatter.java

/**
 * @see it.greenvulcano.gvesb.adapter.http.formatters.Formatter#marshall(java.util.Map)
 *///from  w  w w  . j av a  2  s .  com
@Override
public void marshall(Map<String, Object> environment) throws FormatterExecutionException {
    String operationType = null;
    GVBuffer inputGVBuffer = null;

    logger.debug("ExtendedInboundParamHandlerFormatter: BEGIN marshall");
    String requestContent = null;
    Properties requestParam = new Properties();

    try {
        environment.put(AdapterHttpConstants.ENV_KEY_MARSHALL_ENCODING, reqCharacterEncoding);
        inputGVBuffer = setDefaultGVBufferFields(inputGVBuffer);

        HttpServletRequest httpRequest = (HttpServletRequest) environment
                .get(AdapterHttpConstants.ENV_KEY_HTTP_SERVLET_REQUEST);
        if (httpRequest == null) {
            logger.error(
                    "ExtendedInboundParamHandlerFormatter - Error: HttpServletRequest object received is null");
            throw new FormatterExecutionException("GVHTTP_HTTP_SERVLET_REQUEST_MISSING");
        }
        logger.debug("Reading header: " + getFromRequestHeader);
        if (getFromRequestHeader) {
            Enumeration<?> e = httpRequest.getHeaderNames();
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                logger.debug("header: " + key);
                requestParam.put(key, httpRequest.getHeader(key));
            }
        }

        Enumeration<?> pNames = httpRequest.getParameterNames();
        while (pNames.hasMoreElements()) {
            String paramName = (String) pNames.nextElement();
            String paramValue = httpRequest.getParameter(paramName);
            logger.debug("manageRequest - paramName: " + paramName + " - paramValue: " + paramValue);
            requestParam.put(paramName, paramValue);
        }

        String reqMethod = httpRequest.getMethod();
        if (reqMethod.equals("POST") || reqMethod.equals("PUT")) {
            byte[] requestContentBytes = IOUtils.toByteArray(httpRequest.getInputStream());
            logger.debug("INPUT - HTTP request content:\n");
            logger.debug(new Dump(requestContentBytes).toString());

            requestContent = convertContentToString(requestContentBytes, reqCharacterEncoding);

            /*if (!httpRequest.getContentType().equals(AdapterHttpConstants.URLENCODED_MIMETYPE_NAME)
                && handlePostBodyAsParams) {*/
            if (httpRequest.getContentType().equals(AdapterHttpConstants.URLENCODED_MIMETYPE_NAME)
                    || handlePostBodyAsParams) {
                List<String> entriesList = TextUtils.splitByStringSeparator(requestContent,
                        reqParamEntrySeparator);
                for (String element : entriesList) {
                    int indexSeparator = element.indexOf(reqParamNameValueSeparator);
                    String paramName = element.substring(0, indexSeparator);
                    String paramValue = URLDecoder.decode(
                            element.substring(indexSeparator + reqParamNameValueSeparator.length()),
                            reqCharacterEncoding);
                    logger.debug("manageRequest - paramName: " + paramName + " - paramValue: " + paramValue);
                    requestParam.put(paramName, paramValue);
                }
            }
        }

        if (reqParamHandlers.size() > 0) {
            for (Entry<String, List<InterfaceParametersHandler>> entry : reqParamHandlers.entrySet()) {
                String currParamName = entry.getKey();
                List<InterfaceParametersHandler> currParamHandlerList = entry.getValue();
                String reqParamValue = requestParam.getProperty(currParamName);
                logger.debug(
                        "manageRequest - request parameter " + currParamName + " = [" + reqParamValue + "]");
                if ((reqParamValue != null) && !reqParamValue.equals("")) {
                    for (InterfaceParametersHandler currHandler : currParamHandlerList) {
                        currHandler.setCharEncoding(reqCharacterEncoding);
                        if (currHandler.getHandlerType() == InterfaceParametersHandler.OPTYPE_HANDLER) {
                            operationType = (String) currHandler.build(reqParamValue, null);
                            logger.debug("manageRequest - current handler is an OpType handler"
                                    + "- operationType = " + operationType);
                            operationType = (String) currHandler.build(reqParamValue, null);
                        } else if (currHandler
                                .getHandlerType() == InterfaceParametersHandler.GVBUFFER_HANDLER) {
                            logger.debug("manageRequest - current handler is an GVBuffer handler");
                            inputGVBuffer = (GVBuffer) currHandler.build(reqParamValue, inputGVBuffer);
                        }
                    }
                } else if (reqParamRequired.contains(currParamName)) {
                    logger.error("manageRequest - Required request parameter missing: " + currParamName);
                    throw new FormatterExecutionException("GVHTTP_MISSING_HTTP_REQUEST_PARAMETER_ERROR",
                            new String[][] { { "paramName", currParamName } });
                } else {
                    logger.debug("manageRequest - not required request parameter missing: " + currParamName);
                }
            }
        }
        if (reqContentHandlers.size() > 0) {
            String reqParamValue = requestContent;

            if ((reqParamValue != null) && !reqParamValue.equals("")) {
                for (InterfaceParametersHandler currHandler : reqContentHandlers) {
                    currHandler.setCharEncoding(reqCharacterEncoding);

                    if (currHandler.getHandlerType() == InterfaceParametersHandler.OPTYPE_HANDLER) {
                        logger.debug("manageRequest - operationType = " + operationType);
                        operationType = (String) currHandler.build(reqParamValue, null);
                    } else if (currHandler.getHandlerType() == InterfaceParametersHandler.GVBUFFER_HANDLER) {
                        logger.debug("manageRequest - current handler is an GVBuffer handler");
                        inputGVBuffer = (GVBuffer) currHandler.build(reqParamValue, inputGVBuffer);
                    }
                }
            } else {
                logger.error("manageRequest - request content missing.");
                throw new FormatterExecutionException("GVHTTP_BAD_HTTP_REQUEST_ERROR",
                        new String[][] { { "errorName", "http request content missing" } });
            }
        }

        if (inputGVBuffer == null) {
            logger.error("manageRequest - input data missing.");
            throw new FormatterExecutionException("GVHTTP_HANDLER_ERROR",
                    new String[][] { { "errorName", "input GVBuffer not generated" } });
        }

        GVTransactionInfo transInfo = null;
        transInfo = (GVTransactionInfo) environment.get(AdapterHttpConstants.ENV_KEY_TRANS_INFO);
        if (transInfo == null) {
            transInfo = new GVTransactionInfo();
            environment.put(AdapterHttpConstants.ENV_KEY_TRANS_INFO, transInfo);
        }
        transInfo.setSystem(inputGVBuffer.getSystem());
        transInfo.setService(inputGVBuffer.getService());
        transInfo.setId(inputGVBuffer.getId());

        environment.put(AdapterHttpConstants.ENV_KEY_GVBUFFER_INPUT, inputGVBuffer);

        if ((operationType == null) || operationType.equals("")) {
            if ((defaultOperationType != null) && !defaultOperationType.equals("")) {
                operationType = defaultOperationType;
            } else {
                logger.error("manageRequest - Operation type information missing.");
                throw new FormatterExecutionException("GVHTTP_UNDEFINED_OPERATION_TYPE");

            }
        }

        environment.put(AdapterHttpConstants.ENV_KEY_OP_TYPE, operationType);
        logger.debug("ExtendedInboundParamHandlerFormatter: END marshall");
    } catch (FormatterExecutionException exc) {
        throw exc;
    } catch (HttpParamHandlerException exc) {
        if (requestContent != null) {
            logger.error(new Dump(requestContent.getBytes(), -1).toString());
        } else {
            logger.error("ExtendedInboundParamHandlerFormatter - Unable to decode the http request body");
        }
        throw new FormatterExecutionException("GVHTTP_CHARACTER_ENCODING_ERROR",
                new String[][] { { "encName", reqCharacterEncoding }, { "errorName", "" + exc } }, exc);
    } catch (UnsupportedEncodingException exc) {
        logger.error(
                "ExtendedInboundParamHandlerFormatter - Error while converting inbound request content to string: "
                        + exc);
        throw new FormatterExecutionException("GVHTTP_CHARACTER_ENCODING_ERROR",
                new String[][] { { "encName", reqCharacterEncoding }, { "errorName", "" + exc } }, exc);
    } catch (IOException exc) {
        logger.error(
                "ExtendedInboundParamHandlerFormatter - Error while reading inbound request content: " + exc);
        throw new FormatterExecutionException("GVHTTP_BAD_HTTP_REQUEST_ERROR",
                new String[][] { { "errorName", "" + exc } }, exc);
    } catch (HandlerException exc) {
        logger.error(
                "ExtendedInboundParamHandlerFormatter - Error while building input GVBuffer object or retrieving operation type: "
                        + exc);
        throw new FormatterExecutionException("GVHTTP_HANDLER_ERROR",
                new String[][] { { "errorName", "" + exc } }, exc);
    } catch (GVException exc) {
        logger.error("manageRequest - Error while setting GVBuffer fields with default values: " + exc);
        throw new FormatterExecutionException("GVHTTP_GVBUFFER_SETTING_ERROR",
                new String[][] { { "errorName", "" + exc } }, exc);
    } catch (Throwable exc) {
        logger.error(
                "ExtendedInboundParamHandlerFormatter - Runtime error while managing inbound request: " + exc);
        throw new FormatterExecutionException("GVHTTP_RUNTIME_ERROR",
                new String[][] { { "phase", "managing inbound request" }, { "errorName", "" + exc } }, exc);
    }
}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Set all the values from a request on this request object and set this request
 * as the one which the values were copied from
 * @param req any request/*w w w  .  j  av a 2 s  . c  om*/
 */
public void setRequestValues(HttpServletRequest req) {
    if (req == null) {
        throw new IllegalArgumentException("request cannot be null");
    }
    // get the collections of values out
    Enumeration<String> attribNames = req.getAttributeNames();
    while (attribNames.hasMoreElements()) {
        String name = (String) attribNames.nextElement();
        Object obj = req.getAttribute(name);
        if (obj != null) {
            attributes.put(name, obj);
        }
    }
    Cookie[] ck = req.getCookies();
    if (ck != null) {
        for (int i = 0; i < ck.length; i++) {
            cookies.add(ck[i]);
        }
    }
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        Enumeration<String> henum = req.getHeaders(name);
        Vector<String> v = new Vector<String>(1);
        while (henum.hasMoreElements()) {
            String h = henum.nextElement();
            v.add(h);
        }
    }
    for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    // get the basic values out
    this.locale = req.getLocale();
    this.method = req.getMethod();
    this.contentType = req.getContentType();
    this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding();
    this.contentLength = req.getContentLength();

    this.contextPath = req.getContextPath();
    this.pathInfo = req.getPathInfo();
    this.queryString = req.getQueryString();
    this.requestURI = req.getRequestURI();
    this.servletPath = req.getServletPath();

    this.scheme = req.getScheme();
    this.protocol = req.getProtocol();
    this.serverName = req.getServerName();
    this.serverPort = req.getServerPort();
    this.remoteAddr = req.getRemoteAddr();
    this.remoteHost = req.getRemoteHost();

    this.realDispatcher = true;
}

From source file:fr.paris.lutece.plugins.workflow.web.WorkflowJspBean.java

public String doImportWorkflow(HttpServletRequest request)
        throws JsonParseException, IOException, ClassNotFoundException {
    String contentType = request.getContentType();
    if (contentType.indexOf("multipart/form-data") >= 0) {
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        FileItem item = mRequest.getFile("import_file");

        if ((item != null) && (item.getName() != null) && StringUtils.isNotBlank(item.getName())) {
            byte[] bytes = item.get();
            String json = new String(bytes);
            boolean res = parseJSON(json);
            if (res) {
                return AdminMessageService.getMessageUrl(request, MESSAGE_DUPLICATED_WORKFLOW,
                        AdminMessage.TYPE_ERROR);

            }//  w w  w .  java2  s  .  c  o m
        }
    }
    return getJspManageWorkflow(request);
}

From source file:edu.slu.action.ObjectAction.java

/**
 * All actions come here to process the request body. We check if it is JSON.
 * DELETE is a special case because the content could be JSON or just the @id string and it only has to specify a content type if passing a JSONy object.  
 * and pretty format it. Returns pretty stringified JSON or fail to null.
 * Methods that call this should handle requestBody==null as unexpected.
 * @param http_request Incoming request to check.
 * @param supportStringID The request may be allowed to pass the @id as the body.
 * @return String of anticipated JSON format.
 * @throws java.io.IOException//from  w  w  w .  j a v a2 s. co m
 * @throws javax.servlet.ServletException
 * @throws java.lang.Exception
 */
public String processRequestBody(HttpServletRequest http_request, boolean supportStringID)
        throws IOException, ServletException, Exception {
    String cType = http_request.getContentType();
    http_request.setCharacterEncoding("UTF-8");
    String requestBody;
    JSONObject complianceInfo = new JSONObject();
    /* UTF-8 special character support for requests */
    //http://biercoff.com/malformedinputexception-input-length-1-exception-solution-for-scala-and-java/
    ServletInputStream input = http_request.getInputStream();
    //CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
    //decoder.onMalformedInput(CodingErrorAction.REPLACE);
    InputStreamReader reader = new InputStreamReader(input, "utf-8");
    //bodyReader = new BufferedReader( reader );
    //System.out.println("Process req body...");
    bodyReader = new BufferedReader(reader);
    //System.out.println("...got reader");
    bodyString = new StringBuilder();
    String line;
    JSONObject test;
    JSONArray test2;
    if (null != cType && (cType.contains("application/json") || cType.contains("application/ld+json"))) {
        //System.out.println("Processing because it was jsony");
        //Note special characters cause this to break right here. 
        try {
            while ((line = bodyReader.readLine()) != null) {
                bodyString.append(line);
            }
        } catch (Exception e) {
            System.out.println("Couldn't access body to read");
            System.out.println(e);
        }

        //System.out.println("built body string");
        requestBody = bodyString.toString();
        //System.out.println("here is the bodyString");
        //System.out.println(requestBody);
        try {
            //JSONObject test
            test = JSONObject.fromObject(requestBody);
        } catch (Exception ex) {
            System.out.println("not a json object for processing");
            if (supportStringID) {
                //We do not allow arrays of ID's for DELETE, so if it failed JSONObject parsing then this is a hard fail for DELETE.
                //They attempted to provide a JSON object for DELETE but it was not valid JSON
                writeErrorResponse("The data passed was not valid JSON.  Could not get @id: " + requestBody,
                        HttpServletResponse.SC_BAD_REQUEST);
                requestBody = null;
            } else {
                //Maybe it was an action on a JSONArray, check that before failing JSON parse test.
                try {
                    //JSONArray test
                    test2 = JSONArray.fromObject(requestBody);
                } catch (Exception ex2) {
                    // not a JSONObject or a JSONArray. 
                    writeErrorResponse("The data passed was not valid JSON:\n" + requestBody,
                            HttpServletResponse.SC_BAD_REQUEST);
                    requestBody = null;
                }
            }
        }
        // no-catch: Is either JSONObject or JSON Array
    } else {
        if (supportStringID) { //Content type is not JSONy, looking for @id string as body
            while ((line = bodyReader.readLine()) != null) {
                bodyString.append(line);
            }
            requestBody = bodyString.toString();
            try {
                test = JSONObject.fromObject(requestBody);
                if (test.containsKey("@id")) {
                    requestBody = test.getString("@id");
                    if ("".equals(requestBody)) {
                        //No ID provided
                        writeErrorResponse(
                                "Must provide an id or a JSON object containing @id of object to perform this action.",
                                HttpServletResponse.SC_BAD_REQUEST);
                        requestBody = null;
                    } else {
                        // This string could be ANYTHING.  ANY string is valid at this point.  Create a wrapper JSONObject for elegant handling in deleteObject().  
                        // We will check against the string for existing objects in deleteObject(), processing the body is completed as far as this method is concerned.
                        JSONObject modifiedDeleteRequest = new JSONObject();
                        modifiedDeleteRequest.element("@id", requestBody);
                        requestBody = modifiedDeleteRequest.toString();
                    }
                }
            } catch (Exception e) {
                //This is good, they should not be using a JSONObject
                if ("".equals(requestBody)) {
                    //No ID provided
                    writeErrorResponse(
                            "Must provide an id or a JSON object containing @id of object to delete.",
                            HttpServletResponse.SC_BAD_REQUEST);
                    requestBody = null;
                } else {
                    // This string could be ANYTHING.  ANY string is valid at this point.  Create a wrapper JSONObject for elegant handling in deleteObject().  
                    // We will check against the string for existing objects in deleteObject(), processing the body is completed as far as this method is concerned.
                    JSONObject modifiedDeleteRequest = new JSONObject();
                    modifiedDeleteRequest.element("@id", requestBody);
                    requestBody = modifiedDeleteRequest.toString();
                }
            }
        } else { //This is an error, actions must use the correct content type
            writeErrorResponse("Invalid Content-Type. Please use 'application/json' or 'application/ld+json'",
                    HttpServletResponse.SC_BAD_REQUEST);
            requestBody = null;
        }
    }
    //@cubap @theHabes TODO IIIF compliance handling on action objects
    /*
    if(null != requestBody){
    complianceInfo = checkIIIFCompliance(requestBody, "2.1");
    if(complianceInfo.getInt("okay") < 1){
        writeErrorResponse(complianceInfo.toString(), HttpServletResponse.SC_CONFLICT);
        requestBody = null;
    }
    }
    */
    reader.close();
    input.close();
    content = requestBody;
    response.setContentType("application/json; charset=utf-8"); // We create JSON objects for the return body in most cases.  
    response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    response.addHeader("Access-Control-Allow-Methods", "GET,OPTIONS,HEAD,PUT,PATCH,DELETE,POST"); // Must have OPTIONS for @webanno 
    return requestBody;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Show HTTP header information./*from www  .  j  av a  2s.co  m*/
 *
 * @param req Description of the Parameter
 */
protected void showRequestInfo(HttpServletRequest req) {

    System.out.println();
    System.out.println("SlideDAV Request Info");
    System.out.println();

    // Show generic info
    System.out.println("Encoding : " + req.getCharacterEncoding());
    System.out.println("Length : " + req.getContentLength());
    System.out.println("Type : " + req.getContentType());

    System.out.println();
    System.out.println("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
        System.out.println();
    }

    System.out.println();

    System.out.println("Protocol : " + req.getProtocol());
    System.out.println("Address : " + req.getRemoteAddr());
    System.out.println("Host : " + req.getRemoteHost());
    System.out.println("Scheme : " + req.getScheme());
    System.out.println("Server Name : " + req.getServerName());
    System.out.println("Server Port : " + req.getServerPort());

    System.out.println();
    System.out.println("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        System.out.println(req.getAttribute(attributeName).toString());
    }

    System.out.println();

    // Show HTTP info
    System.out.println();
    System.out.println("HTTP Header Info");
    System.out.println();

    System.out.println("Authentication Type : " + req.getAuthType());
    System.out.println("HTTP Method : " + req.getMethod());
    System.out.println("Path Info : " + req.getPathInfo());
    System.out.println("Path translated : " + req.getPathTranslated());
    System.out.println("Query string : " + req.getQueryString());
    System.out.println("Remote user : " + req.getRemoteUser());
    System.out.println("Requested session id : " + req.getRequestedSessionId());
    System.out.println("Request URI : " + req.getRequestURI());
    System.out.println("Context path : " + req.getContextPath());
    System.out.println("Servlet path : " + req.getServletPath());
    System.out.println("User principal : " + req.getUserPrincipal());

    System.out.println();
    System.out.println("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        System.out.println(req.getHeader(headerName));
    }

    System.out.println();
    System.out.println();

}

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * Update the resource in the specified path.
 *
 * @param req the HTTP request//from   www  .  ja v  a  2  s  .  c  om
 * @param resp the HTTP response
 * @param path the path of the resource
 * @throws IOException if an input/output error occurs
 */
private void updateResource(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException {
    final User user = getUser(req);
    User owner = getOwner(req);
    Object resource = null;

    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    StringBuffer input = new StringBuffer();
    JSONObject json = null;
    if (req.getContentType() != null && req.getContentType().startsWith("application/x-www-form-urlencoded"))
        input.append(req.getParameter(RESOURCE_UPDATE_PARAMETER));
    else {
        // Assume application/json
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8"));
        String line = null;
        while ((line = reader.readLine()) != null)
            input.append(line);
        reader.close();
    }
    try {
        json = new JSONObject(input.toString());
        if (logger.isDebugEnabled())
            logger.debug("JSON update: " + json);
        if (resource instanceof Folder) {
            final Folder folderLocal = (Folder) resource;
            String name = json.optString("name");
            if (!isValidResourceName(name)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            JSONArray permissions = json.optJSONArray("permissions");
            Set<Permission> perms = null;
            if (permissions != null)
                perms = parsePermissions(user, permissions);
            Boolean readForAll = null;
            if (json.opt("readForAll") != null)
                readForAll = json.optBoolean("readForAll");
            if (!name.isEmpty() || permissions != null || readForAll != null) {
                final String fName = name.isEmpty() ? null : name;
                final Boolean freadForAll = readForAll;
                final Set<Permission> fPerms = perms;
                Folder folderUpdated = new TransactionHelper<Folder>().tryExecute(new Callable<Folder>() {
                    @Override
                    public Folder call() throws Exception {
                        return getService().updateFolder(user.getId(), folderLocal.getId(), fName, freadForAll,
                                fPerms);
                    }

                });
                resp.getWriter().println(getNewUrl(req, folderUpdated));
            }
        } else {
            final FileHeader fileLocal = (FileHeader) resource;
            String name = null;
            if (json.opt("name") != null)
                name = json.optString("name");
            if (name != null)
                if (!isValidResourceName(name)) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
            Long modificationDate = null;
            if (json.optLong("modificationDate") != 0)
                modificationDate = json.optLong("modificationDate");
            Boolean versioned = null;
            if (json.opt("versioned") != null)
                versioned = json.getBoolean("versioned");
            JSONArray tagset = json.optJSONArray("tags");
            String tags = null;
            StringBuffer t = new StringBuffer();
            if (tagset != null) {
                for (int i = 0; i < tagset.length(); i++)
                    t.append(tagset.getString(i) + ',');
                tags = t.toString();
            }
            JSONArray permissions = json.optJSONArray("permissions");
            Set<Permission> perms = null;
            if (permissions != null)
                perms = parsePermissions(user, permissions);
            Boolean readForAll = null;
            if (json.opt("readForAll") != null)
                readForAll = json.optBoolean("readForAll");
            if (name != null || tags != null || modificationDate != null || versioned != null || perms != null
                    || readForAll != null) {
                final String fName = name;
                final String fTags = tags;
                final Date mDate = modificationDate != null ? new Date(modificationDate) : null;
                final Boolean fVersioned = versioned;
                final Boolean fReadForAll = readForAll;
                final Set<Permission> fPerms = perms;
                new TransactionHelper<Object>().tryExecute(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        getService().updateFile(user.getId(), fileLocal.getId(), fName, fTags, mDate,
                                fVersioned, fReadForAll, fPerms);
                        return null;
                    }

                });
            }
        }
    } catch (JSONException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
}

From source file:org.pentaho.platform.web.servlet.GenericServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    if (showDeprecationMessage) {
        String deprecationMessage = "GenericServlet is deprecated and should no longer be handling requests. More detail below..."
                + "\n | You have issued a {0} request to {1} from referer {2} "
                + "\n | Please consider using one of the following REST services instead:"
                + "\n | * GET /api/repos/<pluginId>/<path> to read files from a plugin public dir"
                + "\n | * POST|GET /api/repos/<pathId>/generatedContent to create content resulting from execution of a "
                + "repo file"
                + "\n | * POST|GET /api/repos/<pluginId>/<contentGeneratorId> to execute a content generator by name (RPC "
                + "compatibility service)"
                + "\n \\ To turn this message off, set init-param 'showDeprecationMessage' to false in the GenericServlet "
                + "declaration" + "";
        String referer = StringUtils.defaultString(request.getHeader("Referer"), "");
        logger.warn(MessageFormat.format(deprecationMessage, request.getMethod(), request.getRequestURL(),
                referer));//from w  ww.j  ava2s .  co  m
    }

    PentahoSystem.systemEntryPoint();

    IOutputHandler outputHandler = null;
    // BISERVER-2767 - grabbing the current class loader so we can replace it at the end
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    try {
        InputStream in = request.getInputStream();
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        String contentGeneratorId = ""; //$NON-NLS-1$
        String urlPath = ""; //$NON-NLS-1$
        SimpleParameterProvider pathParams = new SimpleParameterProvider();
        if (StringUtils.isEmpty(pathInfo)) {
            logger.error(
                    Messages.getInstance().getErrorString("GenericServlet.ERROR_0005_NO_RESOURCE_SPECIFIED")); //$NON-NLS-1$
            response.sendError(403);
            return;
        }

        String path = pathInfo.substring(1);
        int slashPos = path.indexOf('/');
        if (slashPos != -1) {
            pathParams.setParameter("path", pathInfo.substring(slashPos + 1)); //$NON-NLS-1$
            contentGeneratorId = path.substring(0, slashPos);
        } else {
            contentGeneratorId = path;
        }
        urlPath = "content/" + contentGeneratorId; //$NON-NLS-1$

        pathParams.setParameter("query", request.getQueryString()); //$NON-NLS-1$
        pathParams.setParameter("contentType", request.getContentType()); //$NON-NLS-1$
        pathParams.setParameter("inputstream", in); //$NON-NLS-1$
        pathParams.setParameter("httpresponse", response); //$NON-NLS-1$
        pathParams.setParameter("httprequest", request); //$NON-NLS-1$
        pathParams.setParameter("remoteaddr", request.getRemoteAddr()); //$NON-NLS-1$
        if (PentahoSystem.debug) {
            debug("GenericServlet contentGeneratorId=" + contentGeneratorId); //$NON-NLS-1$
            debug("GenericServlet urlPath=" + urlPath); //$NON-NLS-1$
        }
        IPentahoSession session = getPentahoSession(request);
        IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, session);
        if (pluginManager == null) {
            OutputStream out = response.getOutputStream();
            String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0001_BAD_OBJECT", //$NON-NLS-1$
                    IPluginManager.class.getSimpleName());
            error(message);
            out.write(message.getBytes());
            return;
        }

        // TODO make doing the HTTP headers configurable per content generator
        SimpleParameterProvider headerParams = new SimpleParameterProvider();
        Enumeration names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = request.getHeader(name);
            headerParams.setParameter(name, value);
        }

        String pluginId = pluginManager.getServicePlugin(pathInfo);

        if (pluginId != null && pluginManager.isStaticResource(pathInfo)) {
            boolean cacheOn = "true"
                    .equals(pluginManager.getPluginSetting(pluginId, "settings/cache", "false")); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
            String maxAge = (String) pluginManager.getPluginSetting(pluginId, "settings/max-age", null); //$NON-NLS-1$
            allowBrowserCache(maxAge, pathParams);

            String mimeType = MimeHelper.getMimeTypeFromFileName(pathInfo);
            if (mimeType != null) {
                response.setContentType(mimeType);
            }
            OutputStream out = response.getOutputStream();

            // do we have this resource cached?
            ByteArrayOutputStream byteStream = null;

            if (cacheOn) {
                byteStream = (ByteArrayOutputStream) cache.getFromRegionCache(CACHE_FILE, pathInfo);
            }

            if (byteStream != null) {
                IOUtils.write(byteStream.toByteArray(), out);
                return;
            }
            InputStream resourceStream = pluginManager.getStaticResource(pathInfo);
            if (resourceStream != null) {
                try {
                    byteStream = new ByteArrayOutputStream();
                    IOUtils.copy(resourceStream, byteStream);

                    // if cache is enabled, drop file in cache
                    if (cacheOn) {
                        cache.putInRegionCache(CACHE_FILE, pathInfo, byteStream);
                    }

                    // write it out
                    IOUtils.write(byteStream.toByteArray(), out);
                    return;
                } finally {
                    IOUtils.closeQuietly(resourceStream);
                }
            }
            logger.error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0004_RESOURCE_NOT_FOUND", //$NON-NLS-1$
                    pluginId, pathInfo));
            response.sendError(404);
            return;
        }

        // content generators defined in plugin.xml are registered with 2 aliases, one is the id, the other is type
        // so, we can still retrieve a content generator by id, even though this is not the correct way to find
        // it. the correct way is to look up a content generator by pluginManager.getContentGenerator(type,
        // perspectiveName)
        IContentGenerator contentGenerator = (IContentGenerator) pluginManager.getBean(contentGeneratorId);
        if (contentGenerator == null) {
            OutputStream out = response.getOutputStream();
            String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR",
                    ESAPI.encoder().encodeForHTML(contentGeneratorId)); //$NON-NLS-1$
            error(message);
            out.write(message.getBytes());
            return;
        }

        // set the classloader of the current thread to the class loader of
        // the plugin so that it can load its libraries
        // Note: we cannot ask the contentGenerator class for it's classloader, since the cg may
        // actually be a proxy object loaded by main the WebAppClassloader
        Thread.currentThread().setContextClassLoader(pluginManager.getClassLoader(pluginId));

        // String proxyClass = PentahoSystem.getSystemSetting( module+"/plugin.xml" ,
        // "plugin/content-generators/"+contentGeneratorId,
        // "content generator not found");
        IParameterProvider requestParameters = new HttpRequestParameterProvider(request);
        // see if this is an upload

        // File uploading is a service provided by UploadFileServlet where appropriate protections
        // are in place to prevent uploads that are too large.

        // boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // if (isMultipart) {
        // requestParameters = new SimpleParameterProvider();
        // // Create a factory for disk-based file items
        // FileItemFactory factory = new DiskFileItemFactory();
        //
        // // Create a new file upload handler
        // ServletFileUpload upload = new ServletFileUpload(factory);
        //
        // // Parse the request
        // List<?> /* FileItem */items = upload.parseRequest(request);
        // Iterator<?> iter = items.iterator();
        // while (iter.hasNext()) {
        // FileItem item = (FileItem) iter.next();
        //
        // if (item.isFormField()) {
        // ((SimpleParameterProvider) requestParameters).setParameter(item.getFieldName(), item.getString());
        // } else {
        // String name = item.getName();
        // ((SimpleParameterProvider) requestParameters).setParameter(name, item.getInputStream());
        // }
        // }
        // }

        response.setCharacterEncoding(LocaleHelper.getSystemEncoding());

        IMimeTypeListener listener = new HttpMimeTypeListener(request, response);

        outputHandler = getOutputHandler(response, true);
        outputHandler.setMimeTypeListener(listener);

        IParameterProvider sessionParameters = new HttpSessionParameterProvider(session);
        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
        Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>();
        parameterProviders.put(IParameterProvider.SCOPE_REQUEST, requestParameters);
        parameterProviders.put(IParameterProvider.SCOPE_SESSION, sessionParameters);
        parameterProviders.put("headers", headerParams); //$NON-NLS-1$
        parameterProviders.put("path", pathParams); //$NON-NLS-1$
        SimpleUrlFactory urlFactory = new SimpleUrlFactory(requestContext.getContextPath() + urlPath + "?"); //$NON-NLS-1$ //$NON-NLS-2$
        List<String> messages = new ArrayList<String>();
        contentGenerator.setOutputHandler(outputHandler);
        contentGenerator.setMessagesList(messages);
        contentGenerator.setParameterProviders(parameterProviders);
        contentGenerator.setSession(session);
        contentGenerator.setUrlFactory(urlFactory);
        // String contentType = request.getContentType();
        // contentGenerator.setInput(input);
        contentGenerator.createContent();
        if (PentahoSystem.debug) {
            debug("Generic Servlet content generate successfully"); //$NON-NLS-1$
        }

    } catch (Exception e) {
        StringBuffer buffer = new StringBuffer();
        error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR", //$NON-NLS-1$
                request.getQueryString()), e);
        List errorList = new ArrayList();
        String msg = e.getMessage();
        errorList.add(msg);
        PentahoSystem.get(IMessageFormatter.class, PentahoSessionHolder.getSession())
                .formatFailureMessage("text/html", null, buffer, errorList); //$NON-NLS-1$
        response.getOutputStream().write(buffer.toString().getBytes(LocaleHelper.getSystemEncoding()));

    } finally {
        // reset the classloader of the current thread
        Thread.currentThread().setContextClassLoader(origContextClassloader);
        PentahoSystem.systemExitPoint();
    }
}