Example usage for javax.servlet.http HttpServletRequest getContentLength

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

Introduction

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

Prototype

public int getContentLength();

Source Link

Document

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than Integer.MAX_VALUE.

Usage

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

protected void uploadContent(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String sessionId = extractSessionId(req);

    RepositoryHttpEndpointImpl elem = repoHttpManager.getHttpRepoItemElem(sessionId);

    if (elem == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;//from w  w  w .  j a  v  a  2  s  .  c o  m
    }

    elem.stopCurrentTimer();
    elem.fireStartedEventIfFirstTime();

    try (InputStream requestInputStream = req.getInputStream()) {

        try (OutputStream repoItemOutputStream = elem.getRepoItemOutputStream()) {

            Range range = parseContentRange(req, resp);

            if (range != null) {

                if (range.start > elem.getWrittenBytes()) {
                    resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
                    resp.getOutputStream().println(
                            "The server doesn't support writing ranges " + "ahead of previously written bytes");
                } else if (range.end == elem.getWrittenBytes()) {

                    // TODO We assume that the put range is the same than
                    // the
                    // previous one. Do we need to check this?

                    resp.setStatus(SC_OK);
                    resp.getOutputStream().println("The server has detected that the submited range "
                            + "has already submited in a previous request");
                } else if (range.start < elem.getWrittenBytes() && range.end > elem.getWrittenBytes()) {

                    Range copyRange = new Range();
                    copyRange.start = elem.getWrittenBytes() - range.start;
                    copyRange.end = range.end - range.start;

                    copyStreamsRange(requestInputStream, repoItemOutputStream, copyRange);

                    resp.setStatus(SC_OK);

                } else if (range.start == elem.getWrittenBytes()) {

                    IOUtils.copy(requestInputStream, repoItemOutputStream);

                    resp.setStatus(SC_OK);

                }

            } else {

                boolean isMultipart = ServletFileUpload.isMultipartContent(req);

                if (isMultipart) {

                    uploadMultipart(req, resp, repoItemOutputStream);

                } else {

                    try {

                        log.info("Start to receive bytes (estimated " + req.getContentLength() + " bytes)");
                        int bytes = IOUtils.copy(requestInputStream, repoItemOutputStream);
                        resp.setStatus(SC_OK);
                        log.info("Bytes received: " + bytes);

                    } catch (Exception e) {

                        log.warn("Exception when uploading content", e);

                        elem.fireSessionErrorEvent(e);
                        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    }
                }
            }
        }

    } finally {
        elem.stopInTimeout();
    }
}

From source file:org.alfresco.repo.web.scripts.bean.BaseRemoteStore.java

/**
 * Execute the webscript based on the request parameters
 *//*w  ww.  ja  v  a  2 s.c o  m*/
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    // NOTE: This web script must be executed in a HTTP Servlet environment

    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);

    if (webScriptServletRequest == null) {
        throw new WebScriptException("Remote Store access must be executed in HTTP Servlet environment");
    }

    HttpServletRequest httpReq = webScriptServletRequest.getHttpServletRequest();

    // the request path for the remote store
    String extPath = req.getExtensionPath();

    // values that we need to determine
    String methodName = null;
    String store = null;
    StringBuilder pathBuilder = new StringBuilder(128);

    // tokenize the path and figure out tokenized values
    StringTokenizer tokenizer = new StringTokenizer(extPath, "/");
    if (tokenizer.hasMoreTokens()) {
        methodName = tokenizer.nextToken();

        if (tokenizer.hasMoreTokens()) {
            String el = tokenizer.nextToken();

            if (TOKEN_STORE.equals(el)) {
                // if the token is TOKEN_STORE, then the next token is the id of the store
                store = tokenizer.nextToken();

                // reset element
                el = (tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null);
            }

            while (el != null) {
                pathBuilder.append('/');
                pathBuilder.append(el);

                el = (tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null);
            }
        }
    } else {
        throw new WebScriptException("Unable to tokenize web path: " + extPath);
    }

    // if we don't have a store, check whether it came in on a request parameter
    if (store == null) {
        store = req.getParameter(REQUEST_PARAM_STORE);
        if (store == null) {
            store = this.defaultStore;
        }
        if (store == null) {
            // not good, we should have a store by this point
            // this means that a store was not passed in and that we also didn't have a configured store
            throw new WebScriptException("Unable to determine which store to operate against."
                    + " A store was not specified and a default was not provided.");
        }
    }

    String path = pathBuilder.toString();

    long start = 0;
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Remote method: " + methodName.toUpperCase() + "   Store Id: " + store + "   Path: " + path);
        start = System.nanoTime();
    }

    try {
        // generate enum from string method name - so we can use a fast switch table lookup
        APIMethod method = APIMethod.valueOf(methodName.toUpperCase());
        switch (method) {
        case LASTMODIFIED:
            validatePath(path);
            lastModified(res, store, path);
            break;

        case HAS:
            validatePath(path);
            hasDocument(res, store, path);
            break;

        case GET:
            validatePath(path);
            getDocument(res, store, path);
            break;

        case LIST:
            listDocuments(res, store, path, false);
            break;

        case LISTALL:
            listDocuments(res, store, path, true);
            break;

        case LISTPATTERN:
            listDocuments(res, store, path, req.getParameter("m"));
            break;

        case CREATE:
            validatePath(path);
            if (logger.isDebugEnabled())
                logger.debug("CREATE: content length=" + httpReq.getContentLength());
            createDocument(res, store, path, httpReq.getInputStream());
            break;

        case CREATEMULTI:
            if (logger.isDebugEnabled())
                logger.debug("CREATEMULTI: content length=" + httpReq.getContentLength());
            createDocuments(res, store, httpReq.getInputStream());
            break;

        case UPDATE:
            validatePath(path);
            if (logger.isDebugEnabled())
                logger.debug("UPDATE: content length=" + httpReq.getContentLength());
            updateDocument(res, store, path, httpReq.getInputStream());
            break;

        case DELETE:
            validatePath(path);
            deleteDocument(res, store, path);
            break;
        }
    } catch (IllegalArgumentException enumErr) {
        throw new WebScriptException("Unknown method specified to remote store API: " + methodName);
    } catch (IOException ioErr) {
        throw new WebScriptException("Error during remote store API: " + ioErr.getMessage());
    }

    if (logger.isDebugEnabled()) {
        long end = System.nanoTime();
        logger.debug("Time to execute method: " + (end - start) / 1000000f + "ms");
    }
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }/*  ww w  .  java2s. c  o m*/
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:fr.inrialpes.exmo.align.service.HTTPTransport.java

/**
 * Starts a HTTP server to given port.//www .j  ava 2s  .  c o  m
 *
 * @param params: the parameters of the connection, including HTTP port and host
 * @param manager: the manager which will deal with connections
 * @param serv: the set of services to be listening on this connection
 * @throws AServException when something goes wrong (e.g., socket already in use)
 */
public void init(Properties params, AServProtocolManager manager, Vector<AlignmentServiceProfile> serv)
        throws AServException {
    this.manager = manager;
    services = serv;
    tcpPort = Integer.parseInt(params.getProperty("http"));
    tcpHost = params.getProperty("host");

    // ********************************************************************
    // JE: Jetty implementation
    server = new Server(tcpPort);

    // The handler deals with the request
    // most of its work is to deal with large content sent in specific ways 
    Handler handler = new AbstractHandler() {
        public void handle(String String, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String method = request.getMethod();
            String uri = request.getPathInfo();
            Properties params = new Properties();
            try {
                decodeParams(request.getQueryString(), params);
            } catch (Exception ex) {
                logger.debug("IGNORED EXCEPTION: {}", ex);
            }
            ;
            // I do not decode them here because it is useless
            // See below how it is done.
            Properties header = new Properties();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                header.setProperty(headerName, request.getHeader(headerName));
            }

            // Get the content if any
            // This is supposed to be only an uploaded file
            // Note that this could be made more uniform 
            // with the text/xml part stored in a file as well.
            String mimetype = request.getContentType();
            // Multi part: the content provided by an upload HTML form
            if (mimetype != null && mimetype.startsWith("multipart/form-data")) {
                try {
                    //if ( !ServletFileUpload.isMultipartContent( request ) ) {
                    //   logger.debug( "Does not detect multipart" );
                    //}
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    File tempDir = new File(System.getProperty("java.io.tmpdir"));
                    factory.setRepository(tempDir);
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    List<FileItem> items = upload.parseRequest(request);
                    for (FileItem fi : items) {
                        if (fi.isFormField()) {
                            logger.trace("  >> {} = {}", fi.getFieldName(), fi.getString());
                            params.setProperty(fi.getFieldName(), fi.getString());
                        } else {
                            logger.trace("  >> {} : {}", fi.getName(), fi.getSize());
                            logger.trace("  Stored at {}", fi.getName(), fi.getSize());
                            try {
                                // FilenameUtils.getName() needed for Internet Explorer problem
                                File uploadedFile = new File(tempDir, FilenameUtils.getName(fi.getName()));
                                fi.write(uploadedFile);
                                params.setProperty("filename", uploadedFile.toString());
                                params.setProperty("todiscard", "true");
                            } catch (Exception ex) {
                                logger.warn("Cannot load file", ex);
                            }
                            // Another solution is to run this in 
                            /*
                              InputStream uploadedStream = item.getInputStream();
                              ...
                              uploadedStream.close();
                            */
                        }
                    }
                    ;
                } catch (FileUploadException fuex) {
                    logger.trace("Upload Error", fuex);
                }
            } else if (mimetype != null && mimetype.startsWith("text/xml")) {
                // Most likely Web service request (REST through POST)
                int length = request.getContentLength();
                if (length > 0) {
                    char[] mess = new char[length + 1];
                    try {
                        new BufferedReader(new InputStreamReader(request.getInputStream())).read(mess, 0,
                                length);
                    } catch (Exception e) {
                        logger.debug("IGNORED Exception", e);
                    }
                    params.setProperty("content", new String(mess));
                }
                // File attached to SOAP messages
            } else if (mimetype != null && mimetype.startsWith("application/octet-stream")) {
                File alignFile = new File(File.separator + "tmp" + File.separator + newId() + "XXX.rdf");
                // check if file already exists - and overwrite if necessary.
                if (alignFile.exists())
                    alignFile.delete();
                FileOutputStream fos = new FileOutputStream(alignFile);
                InputStream is = request.getInputStream();

                try {
                    byte[] buffer = new byte[4096];
                    int bytes = 0;
                    while (true) {
                        bytes = is.read(buffer);
                        if (bytes < 0)
                            break;
                        fos.write(buffer, 0, bytes);
                    }
                } catch (Exception e) {
                } finally {
                    fos.flush();
                    fos.close();
                }
                is.close();
                params.setProperty("content", "");
                params.setProperty("filename", alignFile.getAbsolutePath());
            }

            // Get the answer (HTTP)
            HTTPResponse r = serve(uri, method, header, params);

            // Return it
            response.setContentType(r.getContentType());
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println(r.getData());
            ((Request) request).setHandled(true);
        }
    };
    server.setHandler(handler);

    // Common part
    try {
        server.start();
    } catch (Exception e) {
        throw new AServException("Cannot launch HTTP Server", e);
    }
    //server.join();

    // ********************************************************************
    //if ( params.getProperty( "wsdl" ) != null ){
    //    wsmanager = new WSAServProfile();
    //    if ( wsmanager != null ) wsmanager.init( params, manager );
    //}
    //if ( params.getProperty( "http" ) != null ){
    //    htmanager = new HTMLAServProfile();
    //    if ( htmanager != null ) htmanager.init( params, manager );
    //}
    myId = "LocalHTMLInterface";
    serverId = manager.serverURL();
    logger.info("Launched on {}/html/", serverId);
    localId = 0;
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {/*  w  w  w  .j a va  2 s .c om*/
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:org.openqa.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {//from   w w  w. j  av a  2s.  c  o  m
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * MKCOL Method./*w  w w. j  av  a2  s  .c  om*/
 */
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Is there a body in the response which we don't understand? If so, return error code
    // as per rfc2518 8.3.1

    if (req.getContentLength() > 0) {
        resp.sendError(SakaidavStatus.SC_UNSUPPORTED_MEDIA_TYPE);
        return;
    }

    if (readOnly) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(SakaidavStatus.SC_LOCKED);
        return;
    }

    String path = getRelativePathSAKAI(req);
    if (prohibited(path) || (path.toUpperCase().startsWith("/WEB-INF"))
            || (path.toUpperCase().startsWith("/META-INF"))) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    String name = justName(path);

    if ((name.toUpperCase().startsWith("/WEB-INF")) || (name.toUpperCase().startsWith("/META-INF"))) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    // Check to see if the parent collection exists. ContentHosting will create a parent folder if it 
    // does not exist, but the WebDAV spec requires this operation to fail (rfc2518, 8.3.1).

    String parentId = isolateContainingId(adjustId(path));

    try {
        contentHostingService.getCollection(parentId);
    } catch (IdUnusedException e1) {
        resp.sendError(SakaidavStatus.SC_CONFLICT);
        return;
    } catch (TypeException e1) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    } catch (PermissionException e1) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    String adjustedId = adjustId(path);

    // Check to see if collection with this name already exists
    try {
        contentHostingService.getProperties(adjustedId);

        // return error (litmus: MKCOL on existing collection should fail, RFC2518:8.3.1 / 8.3.2)

        resp.sendError(SakaidavStatus.SC_METHOD_NOT_ALLOWED);
        return;

    } catch (IdUnusedException e) {
        // Resource not found (this is actually the normal case)
    } catch (PermissionException e) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    // Check to see if a resource with this name already exists
    if (adjustedId.endsWith("/") && adjustedId.length() > 1)
        try {
            String idToCheck = adjustedId.substring(0, adjustedId.length() - 1);

            contentHostingService.getProperties(idToCheck);

            // don't allow overwriting an existing resource (litmus: mkcol_over_plain)

            resp.sendError(SakaidavStatus.SC_METHOD_NOT_ALLOWED);
            return;

        } catch (IdUnusedException e) {
            // Resource not found (this is actually the normal case)
        } catch (PermissionException e) {
            resp.sendError(SakaidavStatus.SC_FORBIDDEN);
            return;
        }

    // Add the collection

    try {
        ContentCollectionEdit edit = contentHostingService.addCollection(adjustId(path));
        ResourcePropertiesEdit resourceProperties = edit.getPropertiesEdit();
        resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
        contentHostingService.commitCollection(edit);
    }

    catch (IdUsedException e) {
        // Should not happen because if this esists, we either return or delete above
    } catch (IdInvalidException e) {
        M_log.warn("SAKAIDavServlet.doMkcol() IdInvalid:" + e.getMessage());
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    } catch (PermissionException e) {
        // This is normal
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    } catch (InconsistentException e) {
        M_log.warn("SAKAIDavServlet.doMkcol() InconsistentException:" + e.getMessage());
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    resp.setStatus(HttpServletResponse.SC_CREATED);
    // Removing any lock-null resource which would be present
    lockNullResources.remove(path);

}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * Show HTTP header information.// w w  w  .  j  a  v  a 2  s .c  om
 */
@SuppressWarnings("unchecked")
protected void showRequestInfo(HttpServletRequest req) {

    if (M_log.isDebugEnabled())
        M_log.debug("DefaultServlet Request Info");

    // Show generic info
    if (M_log.isDebugEnabled())
        M_log.debug("Encoding : " + req.getCharacterEncoding());
    if (M_log.isDebugEnabled())
        M_log.debug("Length : " + req.getContentLength());
    if (M_log.isDebugEnabled())
        M_log.debug("Type : " + req.getContentType());

    if (M_log.isDebugEnabled())
        M_log.debug("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] + ", ");
        }
    }

    if (M_log.isDebugEnabled())
        M_log.debug("Protocol : " + req.getProtocol());
    if (M_log.isDebugEnabled())
        M_log.debug("Address : " + req.getRemoteAddr());
    if (M_log.isDebugEnabled())
        M_log.debug("Host : " + req.getRemoteHost());
    if (M_log.isDebugEnabled())
        M_log.debug("Scheme : " + req.getScheme());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Name : " + req.getServerName());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Port : " + req.getServerPort());

    if (M_log.isDebugEnabled())
        M_log.debug("Attributes");

    Enumeration attributes = req.getAttributeNames();

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

    // Show HTTP info
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Header Info");

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

    Enumeration headers = req.getHeaderNames();

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

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

protected InputBundle input(HttpServletRequest req, String objid, String cmpid, String fileid)
        throws IOException, FileUploadException {
    log.info(req.getMethod() + " " + req.getRequestURL());
    InputBundle input = null;/*from  w ww .ja v  a  2 s . com*/
    if (ServletFileUpload.isMultipartContent(req)
            || (req.getContentType() != null && req.getContentType().startsWith("multipart/form-data"))) {
        // process multipart uploads
        input = multipartInput(req, objid, cmpid, fileid);
    } else if (req.getContentLength() > 0) {
        // if there is a POST/PUT body, then use it
        InputStream in = req.getInputStream();
        input = new InputBundle(req.getParameterMap(), in, fedoraDebug);
    } else {
        // check for locally-staged file or source filestore reference
        Map<String, String[]> params = req.getParameterMap();
        InputStream in = alternateStream(params, objid, cmpid, fileid);
        input = new InputBundle(params, in);
    }

    // retrieve the user
    userID = null;
    user = getParamString(input.getParams(), "user", null);
    client = getParamString(input.getParams(), "client", "No client specified");
    return input;
}

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

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

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

    // Update the counters
    numReceivedEvents++;

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

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

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

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

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

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

            servicePath = headerValue;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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