Example usage for javax.servlet.http HttpServletRequest getContentType

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

Introduction

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

Prototype

public String getContentType();

Source Link

Document

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

Usage

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * HTTP PUT implementation.//from  w w  w.  j  a  v  a  2 s  .  co  m
 */
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO: Reuse code doPost resp. share code with doPut

    String value = request.getParameter(YANEL_RESOURCE_USECASE);

    if (value != null && value.equals("save")) {
        log.debug("Save data ...");
        save(request, response, false);
        return;
    } else if (value != null && value.equals("checkin")) {
        log.debug("Checkin data ...");
        save(request, response, true);

        log.warn("Release lock has not been implemented yet ...!");
        // releaseLock();
        return;
    } else {
        log.warn("No parameter " + YANEL_RESOURCE_USECASE + "!");

        String contentType = request.getContentType();
        if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) {
            InputStream in = intercept(request.getInputStream());
            // Overwrite existing atom entry
            try {
                String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>";
                Realm realm = yanelInstance.getMap().getRealm(request.getServletPath());
                String entryPath = yanelInstance.getMap().getPath(realm, request.getServletPath());

                log.debug("Realm and Path of new Atom entry: " + realm + " " + entryPath);

                Resource atomEntryResource = yanelInstance.getResourceManager().getResource(
                        getEnvironment(request, response), realm, entryPath,
                        new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName),
                        new ResourceTypeIdentifier(atomEntryUniversalName, null));

                // TODO: There seems to be a problem ...
                ((ModifiableV2) atomEntryResource).write(in);

                // NOTE: This method does not update updated date
                /*
                                    OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath);
                                    byte buffer[] = new byte[8192];
                                    int bytesRead;
                                    while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
                                    }
                */

                log.info("Atom entry has been saved: " + entryPath);

                response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
                return;
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else {
            Resource resource = getResource(request, response);
            log.warn("DEBUG: Client (" + request.getHeader("User-Agent") + ") requests to save a resource: "
                    + resource.getRealm() + ", " + resource.getPath());
            save(request, response, false);
            return;
        }
    }
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
 *//*from w ww  .  j  a v a2s. co  m*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String transition = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION);
    if (transition != null) {
        executeWorkflowTransition(request, response, request.getParameter(YANEL_RESOURCE_REVISION), transition);
        return;
    }

    String value = request.getParameter(YANEL_RESOURCE_USECASE);

    if (value != null && value.equals("save")) {
        log.debug("Save data ...");
        save(request, response, false);
        return;
    } else if (value != null && value.equals("checkin")) {
        log.debug("Checkin data ...");
        save(request, response, true);

        log.warn("Release lock has not been implemented yet ...");
        // releaseLock();
        return;
    } else {
        log.info("No parameter " + YANEL_RESOURCE_USECASE + "!");

        String contentType = request.getContentType();
        // TODO: Check for type (see section 9.2 of APP spec (e.g. draft 16)
        if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) {
            InputStream in = intercept(request.getInputStream());
            // Create new Atom entry
            try {
                String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>";
                Realm realm = yanelInstance.getMap().getRealm(request.getServletPath());
                String newEntryPath = yanelInstance.getMap().getPath(realm,
                        request.getServletPath() + "/" + new Date().getTime() + ".xml");

                log.debug("Realm and Path of new Atom entry: " + realm + " " + newEntryPath);
                Resource atomEntryResource = yanelInstance.getResourceManager().getResource(
                        getEnvironment(request, response), realm, newEntryPath,
                        new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName),
                        new ResourceTypeIdentifier(atomEntryUniversalName, null));

                ((ModifiableV2) atomEntryResource).write(in);

                byte buffer[] = new byte[8192];
                int bytesRead;
                InputStream resourceIn = ((ModifiableV2) atomEntryResource).getInputStream();
                OutputStream responseOut = response.getOutputStream();
                while ((bytesRead = resourceIn.read(buffer)) != -1) {
                    responseOut.write(buffer, 0, bytesRead);
                }
                resourceIn.close();
                //responseOut.close();

                // TODO: Fix Location ...
                response.setHeader("Location", "http://ulysses.wyona.org" + newEntryPath);
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED);
                return;
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        }

        // Enable or disable toolbar
        yanelUI.switchToolbar(request);

        getContent(request, response);
    }
}

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;//  www. j  av a2  s.co m
    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: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 {//from  www.  j  a v  a 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:com.funambol.transport.http.server.Sync4jServlet.java

/**
 * Processes the request//from   ww w. ja  v a 2 s .c o m
 * @param httpRequest the request
 * @param httpResponse the response
 * @throws javax.servlet.ServletException if an error occurs
 * @throws java.io.IOException if an error occurs
 */
@Override
public void doPost(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    if (log.isInfoEnabled()) {
        log.info("Handling incoming request");
    }

    String requestURL = getRequestURL(httpRequest);
    String sessionId = getSessionId(httpRequest);
    String requestedSessionId = httpRequest.getRequestedSessionId();
    if (log.isInfoEnabled()) {
        log.info("Request URL: " + requestURL);
        log.info("Requested sessionId: " + requestedSessionId);
    }

    if (log.isTraceEnabled()) {
        showHeaders(httpRequest);
    }

    httpResponse.setHeader(HEADER_X_FUNAMBOL_DS_SERVER, getServerHeader());

    if (httpRequest.getSession().isNew()) {
        httpRequest.getSession().setMaxInactiveInterval(sessionTimeout);
        if (requestedSessionId != null && !requestedSessionId.equals("")) {
            if (!sessionId.equalsIgnoreCase(requestedSessionId)) {
                //
                // The client requires a session that maybe is already expired...
                // returing a 408
                //
                if (log.isInfoEnabled()) {
                    log.info("Session '" + requestedSessionId + "' not found");
                }
                httpResponse.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
                return;
            }
        }
    }

    long requestTime = System.currentTimeMillis();

    //
    // Setting the header 'Set-Cookie' in order to avoid the session tracking
    // using cookies.
    //
    // The web container adds a cookie JSESSIONID in order to
    // track the session, and to do that, it adds (transparently) in the response
    // header:
    // Set-Cookie: JSESSIONID=xxxxxxxxxx
    // In order not to use the cookie, the header "Set-Cookie" is set to an empty value
    // In this way, the session tracking is based on the jsessionid parameter
    // specified in the url (url rewriting).
    // The cookie is dangerous because a client could use:
    // http://xxxxxx:yyy/funambol/ds
    // but with a jsessionid specified as cookie. In this way, the server
    // search a previous session with the same id. And if a previous session
    // was interrupted and not expired, the server reuses this one and this
    // can cause an exception because the client sends the msg 1 and maybe
    // the previous session was in the mapping state.
    //
    // Unfortunatelly on Nokia S60 3Ed feature pack 1, the JAM is not able to
    // handle the response from the server if it contains an empty header Set-Cookie.
    // This means that to make the JAM working, we must avoid:
    //     httpResponse.setHeader("Set-Cookie", "");
    // and add a dummy cookie.
    // In order to do this in a generic way, we avoid empty Set-Cookie if in
    // the request is specified x-funambol-force-cookies header with value
    // 1 or yes or true
    //
    String x_funambol_force_cookies = httpRequest.getHeader(HEADER_X_FUNAMBOL_FORCE_COOKIES);
    if (!getBooleanValue(x_funambol_force_cookies)) {
        httpResponse.setHeader("Set-Cookie", "");
    } else {
        //
        // Setting a dummy cookie
        //
        Cookie cookie = new Cookie("funambol-dummy-cookie", "");
        httpResponse.addCookie(cookie);
    }

    final String contentType = httpRequest.getContentType().split(";")[0];

    final String contentEncoding = (String) httpRequest.getHeader(HEADER_CONTENT_ENCODING);
    final String sizeThreshold = (String) httpRequest.getHeader(HEADER_SIZE_THRESHOLD);

    String acceptEncoding = (String) httpRequest.getHeader(HEADER_ACCEPT_ENCODING);

    if (!enableCompression) {
        //
        // In this way it's like the client doesn't support any encoding
        //
        if (acceptEncoding != null && acceptEncoding.length() != 0) {
            if (log.isTraceEnabled()) {
                log.trace("Forcing no compression (enable-compression is set to false)");
            }
            acceptEncoding = null;
        }
    }

    Map params = getRequestParameters(httpRequest);
    Map headers = getRequestHeaders(httpRequest);

    byte[] requestData = null;
    try {
        requestData = getRequestContent(httpRequest, contentEncoding, requestTime, sessionId);

        if (requestData == null || requestData.length == 0) {
            handleError(httpRequest, httpResponse,
                    "Received empty content. Returning a BAD REQUEST code to the client.", null);
            return;
        }
    } catch (Exception e) {
        handleError(httpRequest, httpResponse, "Error reading the request", e);
        return;
    }

    //
    // If the session id is not specified in the URL, a new remote object
    // will be created. Otherwise the session id specifies which remote
    // object shall handles the request.
    //
    SyncHolder holder = null;

    try {
        holder = createHolder(httpRequest.getSession());

    } catch (Exception e) {
        handleError(httpRequest, httpResponse, "Error creating SyncBean", e);
        return;
    }

    String remoteAddress = httpRequest.getRemoteAddr();
    //
    // We put the remote address in the header map so that we can pass it to
    // the adapted.
    //
    headers.put(HEADER_X_FUNAMBOL_CLIENT_REMOTE_ADDRESS, remoteAddress);

    SyncResponse resp = null;
    try {
        if (com.funambol.framework.core.Constants.MIMETYPE_SYNCMLDS_WBXML.equals(contentType)) {
            resp = holder.processWBXMLMessage(requestURL, requestData, params, headers);
        } else if (com.funambol.framework.core.Constants.MIMETYPE_SYNCMLDS_XML.equals(contentType)) {
            resp = holder.processXMLMessage(requestURL, requestData, params, headers);
        } else {
            throw new ProtocolException("Mime type " + contentType + " not supported or unknown");
        }
    } catch (Exception e) {
        log.error("Error processing the request", e);

        Throwable cause = e.getCause();

        if ((cause != null) && ((cause instanceof ProtocolException) || (cause instanceof Sync4jException))) {

            handleError(httpRequest, httpResponse, "Protocol error", cause);
            return;
        } else {
            throw new ServletException(e);
        }
    }

    httpResponse.setContentType(contentType);
    setResponseContent(httpResponse, acceptEncoding, sizeThreshold, resp, requestTime, sessionId);

    if (log.isInfoEnabled()) {
        log.info("Request processed.");
    }

    //
    // If the message completed the SyncML communication, the session
    // must be closed and discarded.
    //
    if (resp.isCompleted()) {
        httpRequest.setAttribute(ATTRIBUTE_LAST_REQUEST, "true");
        closeSession(httpRequest.getSession());
    }

}

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 ww.ja  va  2 s  .  com*/
            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.craftercms.cstudio.share.forms.impl.submission.endpoint.WebscriptEndpointImpl.java

/**
 * post content to url/*w ww.jav  a  2s .c o  m*/
 */
protected Response call(String op, String url, InputStream model, Map<String, Object> parameters) {

    Response response = null;

    try {

        String endpointId = "alfresco";

        SeamlessAppContext appContext = SeamlessAppContext.currentApplicationContext();
        HttpServletRequest req = appContext.getRequest();
        HttpServletResponse res = appContext.getResponse();

        res = new BufferedResponseWrapper(res);

        /* dont need to do this every time, can cache config */
        ApplicationContext alfAppContext = WebApplicationContextUtils
                .getRequiredWebApplicationContext(appContext.getServletContext());
        ConfigService configService = (ConfigService) alfAppContext.getBean("web.config");
        RemoteConfigElement config = (RemoteConfigElement) configService.getConfig("Remote")
                .getConfigElement("remote");

        try {
            // retrieve the endpoint descriptor - do not allow proxy access
            // to
            // unsecure endpoints
            EndpointDescriptor descriptor = config.getEndpointDescriptor(endpointId);

            if (descriptor == null || descriptor.getUnsecure()) {
                // throw an exception if endpoint ID is does not exist or
                // invalid
                throw new AlfrescoRuntimeException("Invalid EndPoint Id: " + endpointId);
            }

            String ticket = req.getParameter(PARAM_ALF_TICKET);

            if (ticket == null) {
                ticket = appContext.getTicket();
            }

            // user id from session NOTE: @see
            // org.alfresco.web.site.UserFactory
            Connector connector = null;

            String userId = (String) req.getSession().getAttribute(UserFactory.SESSION_ATTRIBUTE_KEY_USER_ID);

            if (userId != null) {
                // build an authenticated connector - as we have a userId
                connector = _connectorService.getConnector(endpointId, userId, req.getSession());
            } else if (ticket != null || descriptor.getIdentity() == IdentityType.NONE
                    || descriptor.getIdentity() == IdentityType.DECLARED || descriptor.getExternalAuth()) {

                connector = _connectorService.getConnector(endpointId, req.getSession());
            } else if (descriptor.getBasicAuth()) {

                String authorization = req.getHeader("Authorization");
                if (authorization == null || authorization.length() == 0) {
                    res.setStatus(HttpServletResponse.SC_UNAUTHORIZED,
                            "No user id found in session and requested endpoint requires authentication.");
                    res.setHeader("WWW-Authenticate", "Basic realm=\"Alfresco\"");
                } else {

                    String[] authParts = authorization.split(" ");
                    if (!authParts[0].equalsIgnoreCase("basic")) {
                        throw new AlfrescoRuntimeException(
                                "Authorization '" + authParts[0] + "' not supported.");
                    }

                    String[] values = new String(Base64.decode(authParts[1])).split(":");
                    if (values.length == 2) {
                        if (logger.isDebugEnabled())
                            logger.debug("Authenticating (BASIC HTTP) user " + values[0]);

                        connector = _connectorService.getConnector(endpointId, values[0], req.getSession());
                        Credentials credentials = new CredentialsImpl(endpointId);
                        credentials.setProperty(Credentials.CREDENTIAL_USERNAME, values[0]);
                        credentials.setProperty(Credentials.CREDENTIAL_PASSWORD, values[1]);
                        connector.setCredentials(credentials);
                    } else {

                        throw new AlfrescoRuntimeException("Authorization request did not provide user/pass.");
                    }
                }
            } else {
                res.setStatus(HttpServletResponse.SC_UNAUTHORIZED,
                        "No user id found in session and requested endpoint requires authentication.");
            }

            ConnectorContext context;

            if (ticket == null) {
                context = new ConnectorContext();
            } else {
                // special case for some Flash apps - see above
                Map<String, String> params = new HashMap<String, String>(1, 1.0f);
                params.put(PARAM_ALF_TICKET, ticket);
                context = new ConnectorContext(params, null);
            }
            context.setContentType(req.getContentType());

            HttpMethod httpMethod = HttpMethod.valueOf(op);
            context.setMethod(httpMethod);

            if (url.indexOf("?") != -1) {
                url += "&" + PARAM_ALF_TICKET + "=" + ticket;
            } else {
                url += "?" + PARAM_ALF_TICKET + "=" + ticket;
            }

            if (logger.isDebugEnabled()) {
                logger.debug("EndPointProxyServlet preparing to proxy:");
                logger.debug(" - endpointId: " + endpointId);
                logger.debug(" - userId: " + userId);
                logger.debug(" - connector: " + connector);
                logger.debug(" - method: " + context.getMethod());
                logger.debug(" - url: " + url);
            }

            if (model != null && "POST".equals(op)) {
                // set default content type for post if not provided
                if (StringUtils.isEmpty(context.getContentType())) {
                    context.setContentType(POST_REQUEST_DEFAULT_CONTENT_TYPE);
                }
                response = connector.call(url, context, model);
            } else {
                response = connector.call(url, context);
            }

            String statusCode = "" + response.getStatus().getCode();
            int statusCodeAsInt = Integer.parseInt(statusCode);

            if (statusCodeAsInt >= 400) {
                System.out.println("Submission handler: End point Return code: '" + statusCode + "'");
                System.out.println(" - message: " + response.getStatus().getMessage());
                System.out.println(" - message: " + response.getStatus().getException());
                System.out.println(((BufferedResponseWrapper) res).getString());
                System.out.println(" - endpointId: " + endpointId);
                System.out.println(" - userId: " + userId);
                System.out.println(" - connector: " + connector);
                System.out.println(" - method: " + context.getMethod());
                System.out.println(" - url: " + url);

            }
        } catch (Throwable err) {
            System.out.println("error during proxy:" + err);
            throw new AlfrescoRuntimeException("Error during endpoint proxy processing: " + err.getMessage(),
                    err);
        }
    } catch (Throwable err) {
        System.out.println("error during proxy:" + err);
        err.printStackTrace();
        throw new AlfrescoRuntimeException("Error during endpoint proxy processing: " + err.getMessage(), err);
    }

    return response;
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Save data/*from   w w  w  . ja v  a2  s.com*/
 * @param request TODO
 * @param response TODO
 */
private void save(HttpServletRequest request, HttpServletResponse response, boolean doCheckin)
        throws ServletException, IOException {
    log.debug("Save data ...");

    Resource resource = getResource(request, response);
    /* NOTE: Commented because the current default repo implementation does not support versioning yet.
    if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
    try {
        // check the resource state:
        Identity identity = getIdentity(request);
        String userID = identity.getUser().getID();
        VersionableV2 versionable  = (VersionableV2)resource;
        if (versionable.isCheckedOut()) {
            String checkoutUserID = versionable.getCheckoutUserID(); 
            if (!checkoutUserID.equals(userID)) {
                throw new Exception("Resource is checked out by another user: " + checkoutUserID);
            }
        } else {
            throw new Exception("Resource is not checked out.");
        }
            
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }
    }
    */

    InputStream in = request.getInputStream();

    // TODO: Should be delegated to resource type, e.g. <{http://...}xml/>!
    // Check on well-formedness ...
    String contentType = request.getContentType();
    log.debug("Content-Type: " + contentType);
    if (contentType != null && (contentType.indexOf("application/xml") >= 0
            || contentType.indexOf("application/xhtml+xml") >= 0)) {
        try {
            in = XMLHelper.isWellFormed(in);
        } catch (Exception e) {
            log.error(e, e);
            response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
            response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            PrintWriter w = response.getWriter();
            w.print(XMLExceptionV1.getDefaultException(XMLExceptionV1.DATA_NOT_WELL_FORMED, e.getMessage()));
            return;
        }
    } else {
        log.info("No well-formedness check required for content type: " + contentType);
    }

    // IMPORTANT TODO: Use ModifiableV2.write(InputStream in) such that resource can modify data during saving resp. check if getOutputStream is equals null and then use write ....
    OutputStream out = null;
    Resource res = getResource(request, response);
    if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) {
        out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath()));
        write(in, out, request, response);
    } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
        try {
            out = ((ModifiableV2) res).getOutputStream();
            if (out != null) {
                write(in, out, request, response);
            } else {
                log.warn("getOutputStream() returned null, hence fallback to write()");
                ((ModifiableV2) res).write(in);
            }
        } catch (Exception e) {
            throw new ServletException(e.getMessage(), e);
        }
    } else {
        String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!";
        log.warn(message);

        // TODO: Differentiate between Neutron based and other clients ... (Use method isClientSupportingNeutron())
        response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
        response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        PrintWriter w = response.getWriter();
        // TODO: This is not really a 'checkin' problem, but rather a general 'save-data' problem, but the Neutron spec does not support such a type: http://neutron.wyona.org/draft-neutron-protocol-v0.html#rfc.section.8
        w.print(XMLExceptionV1.getDefaultException(XMLExceptionV1.CHECKIN, message));
    }

    if (doCheckin) {
        if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
            VersionableV2 versionable = (VersionableV2) resource;
            try {
                versionable.checkin("updated");
            } catch (Exception e) {
                throw new ServletException(
                        "Could not check in resource <" + resource.getPath() + ">: " + e.getMessage(), e);
            }
        }
    }
}

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

/**
 * Show HTTP header information./*  w  ww  . ja va  2  s.c  o  m*/
 */
@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:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Get usecase. Maps query strings, etc. to usecases, which then can be used for example within access control policies
 *///from   w  w w .  ja  v  a2  s.c o  m
private Usecase getUsecase(HttpServletRequest request) {
    // TODO: Replace hardcoded roles by mapping between roles amd query strings ...
    Usecase usecase = new Usecase("view");

    String yanelResUsecaseValue = request.getParameter(YANEL_RESOURCE_USECASE);
    if (yanelResUsecaseValue != null) {
        if (yanelResUsecaseValue.equals("save")) {
            log.debug("Save data ...");
            usecase = new Usecase("write");
        } else if (yanelResUsecaseValue.equals("checkin")) {
            log.debug("Checkin data ...");
            usecase = new Usecase("write");
        } else if (yanelResUsecaseValue.equals("roll-back")) {
            log.debug("Roll back to previous revision ...");
            usecase = new Usecase("write");
        } else if (yanelResUsecaseValue.equals("introspection")) {
            if (log.isDebugEnabled())
                log.debug("Dynamically generated introspection ...");
            usecase = new Usecase("introspection");
        } else if (yanelResUsecaseValue.equals("checkout")) {
            log.debug("Checkout data ...");
            usecase = new Usecase("open");
        } else if (yanelResUsecaseValue.equals("delete")) {
            log.info("Delete resource (yanel resource usecase delete)");
            usecase = new Usecase("delete");
        } else {
            log.warn("No such generic Yanel resource usecase: " + yanelResUsecaseValue
                    + " (maybe some custom resource usecase)");
        }
    }

    String yanelUsecaseValue = request.getParameter(YANEL_USECASE);
    if (yanelUsecaseValue != null) {
        if (yanelUsecaseValue.equals("create")) {
            log.debug("Create new resource ...");
            usecase = new Usecase("resource.create");
        } else if (yanelUsecaseValue.equals("policy.read")) {
            usecase = new Usecase("policy.read");
        } else {
            log.warn("No such generic Yanel usecase: " + yanelUsecaseValue + " (maybe some custom usecase)");
        }
    }

    String contentType = request.getContentType();
    String method = request.getMethod();
    if (contentType != null && contentType.indexOf("application/atom+xml") >= 0
            && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) {
        // TODO: Is posting atom entries different from a general post (see below)?!
        log.warn("Write/Checkin Atom entry ...");
        usecase = new Usecase("write");
        // TODO: METHOD_POST is not generally protected, but save, checkin, application/atom+xml are being protected. See doPost(.... 
    } else if (method.equals(METHOD_PUT)) {
        log.warn("Upload data ...");
        usecase = new Usecase("write");
    } else if (method.equals(METHOD_DELETE)) {
        log.warn("Delete resource (HTTP method delete)");
        usecase = new Usecase("delete");
    }

    String workflowTransitionValue = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION);
    if (workflowTransitionValue != null) {
        // TODO: At the moment the authorization of workflow transitions are checked within executeWorkflowTransition or rather workflowable.doTransition(transition, revision)
        log.warn("Workflow transition is currently handled as view usecase: " + workflowTransitionValue);
        usecase = new Usecase("view");
        // TODO: Return workflow transition ID
        //usecase = new Usecase(transitionID);
    }

    String toolbarValue = request.getParameter("yanel.toolbar");
    if (toolbarValue != null && toolbarValue.equals("on")) {
        log.debug("Turn on toolbar ...");
        usecase = new Usecase(TOOLBAR_USECASE);
    }

    String yanelPolicyValue = request.getParameter(YANEL_ACCESS_POLICY_USECASE);
    if (yanelPolicyValue != null) {
        if (yanelPolicyValue.equals("create")) {
            usecase = new Usecase("policy.create");
        } else if (yanelPolicyValue.equals("read")) {
            usecase = new Usecase("policy.read");
        } else if (yanelPolicyValue.equals("update")) {
            usecase = new Usecase("policy.update");
        } else if (yanelPolicyValue.equals("delete")) {
            usecase = new Usecase("policy.delete");
        } else {
            log.warn("No such policy usecase: " + yanelPolicyValue);
        }
    }

    String showResourceMeta = request.getParameter(RESOURCE_META_ID_PARAM_NAME);
    if (showResourceMeta != null) {
        usecase = new Usecase(RESOURCE_META_ID_PARAM_NAME);
    }

    return usecase;
}