Example usage for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED

List of usage examples for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED.

Prototype

int SC_METHOD_NOT_ALLOWED

To view the source code for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED.

Click Source Link

Document

Status code (405) indicating that the method specified in the Request-Line is not allowed for the resource identified by the Request-URI.

Usage

From source file:org.apache.servicemix.http.processors.ConsumerProcessor.java

public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Receiving HTTP request: " + request);
    }/*from   w  ww .ja  v a  2s .  c  o m*/
    if ("GET".equals(request.getMethod())) {
        processGetRequest(request, response);
        return;
    }
    if (!started) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Endpoint is stopped");
        return;
    }
    if (!"POST".equals(request.getMethod())) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request.getMethod() + " not supported");
        return;
    }
    // Not giving a specific mutex will synchronize on the contination itself
    Continuation cont = ContinuationSupport.getContinuation(request, null);
    MessageExchange exchange;
    // If the continuation is not a retry
    if (!cont.isPending()) {
        try {
            Context ctx = createContext(request);
            request.setAttribute(Context.class.getName(), ctx);
            exchange = soapHelper.onReceive(ctx);
            exchanges.put(exchange.getExchangeId(), exchange);
            NormalizedMessage inMessage = exchange.getMessage("in");

            Map<String, String> protocolHeaders = new HashMap();
            if (getConfiguration().isWantHeadersFromHttpIntoExchange()) {
                protocolHeaders.putAll(getHeaders(request));
            }
            protocolHeaders.put(AbstractProcessor.HEADER_X_REMOTE_HOST, getClientIp(request));
            inMessage.setProperty(JbiConstants.PROTOCOL_HEADERS, protocolHeaders);
            if (request.getHeader(HEADER_X_CORRELATION_ID) != null) {
                response.addHeader(HEADER_X_CORRELATION_ID, request.getHeader(HEADER_X_CORRELATION_ID));
            }
            String smxInstanceName = System.getProperty(SMX_INSTANCE_NAME_PROPERTY);
            if (smxInstanceName != null) {
                response.addHeader(HEADER_X_POWERED_BY, smxInstanceName);
            } else {
                log.warn(SMX_INSTANCE_NAME_PROPERTY + " property was not set in servicemix.xml file");
            }

            locks.put(exchange.getExchangeId(), cont);
            request.setAttribute(MessageExchange.class.getName(), exchange.getExchangeId());
            synchronized (cont) {
                channel.send(exchange);
                if (log.isDebugEnabled()) {
                    log.debug("Suspending continuation for exchange: " + exchange.getExchangeId());
                }
                boolean result = cont.suspend(suspentionTime);
                exchange = exchanges.remove(exchange.getExchangeId());
                request.removeAttribute(MessageExchange.class.getName());
                if (!result) {
                    locks.remove(exchange.getExchangeId());
                    throw new Exception("Exchange timed out");
                }
            }
        } catch (RetryRequest retry) {
            throw retry;
        } catch (SoapFault fault) {
            sendFault(fault, request, response);
            return;
        } catch (Exception e) {
            sendFault(new SoapFault(e), request, response);
            return;
        }
    } else {
        synchronized (cont) {
            String id = (String) request.getAttribute(MessageExchange.class.getName());
            locks.remove(id);
            exchange = exchanges.remove(id);
            request.removeAttribute(MessageExchange.class.getName());
            // Check if this is a timeout
            if (exchange == null) {
                throw new IllegalStateException("Exchange not found");
            }
            if (log.isDebugEnabled() && request.getHeader(HEADER_X_CORRELATION_ID) != null) {
                String externalCorrelationId = request.getHeader(HEADER_X_CORRELATION_ID);
                String exchangeCorrelationId = (String) exchange.getProperty(JbiConstants.CORRELATION_ID);
                log.debug("Message exchange with correlationId='" + exchangeCorrelationId
                        + "' is correlated with external message exchange with correlationId='"
                        + externalCorrelationId + "'");
            }
            if (!cont.isResumed()) {
                Exception e = new Exception("Exchange timed out: " + exchange.getExchangeId());
                sendFault(new SoapFault(e), request, response);
                return;
            }
        }
    }
    if (exchange.getStatus() == ExchangeStatus.ERROR) {
        if (exchange.getError() != null) {
            throw new Exception(exchange.getError());
        } else {
            throw new Exception("Unknown Error");
        }
    } else if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
        try {
            if (exchange.getFault() != null) {
                processFault(exchange, request, response);
            } else {
                processResponse(exchange, request, response);
            }
        } finally {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    } else if (exchange.getStatus() == ExchangeStatus.DONE) {
        // This happens when there is no response to send back
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
    }
}

From source file:org.xwiki.platform.patchservice.web.PatchServiceServlet.java

protected void handleRequest(HttpServletRequest req, HttpServletResponse resp, List<String> acceptedCommands) {
    XWikiContext context = null;/*from w w w. j  a v  a  2s  . c om*/
    try {
        // Get the command, between the first and the second /
        String command = req.getPathInfo();
        if (command != null) {
            command = command.substring(1);
            if (command.indexOf('/') > 0) {
                command = command.substring(0, command.indexOf('/'));
            }
            // Check that this is something supported
            if (!this.allVerbs.contains(command)) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print("Unknown command: " + command);
                return;
            }
            // Check that the HTTP method was correct
            if (!acceptedCommands.contains(command)) {
                resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                resp.getWriter().print("Bad HTTP method for command: " + command);
                return;
            }
            context = initializeXWikiContext(command, req, resp);

            XWiki.getXWiki(context);
            execute(command, context);
        }
    } catch (Exception ex) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        try {
            resp.getWriter().print("Unhandled server error: " + ex.getMessage());
        } catch (IOException ex1) {
            // Cannot send message, ignore.
        }
        ex.printStackTrace();
    } finally {
        if (context != null) {
            cleanupComponents();
        }
    }
}

From source file:org.springframework.extensions.webscripts.AbstractRuntime.java

/**
 * Execute the Web Script encapsulated by this Web Script Runtime
 *//*from   www .  jav  a2 s  .com*/
final public void executeScript() {
    final boolean debug = logger.isDebugEnabled();
    long startRuntime = 0L;
    if (debug)
        startRuntime = System.nanoTime();

    final String method = getScriptMethod();
    String scriptUrl = null;
    Match match = null;

    try {
        // extract script url
        scriptUrl = getScriptUrl();
        if (scriptUrl == null || scriptUrl.length() == 0) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Script URL not specified");
        }

        if (debug)
            logger.debug("(Runtime=" + getName() + ", Container=" + container.getName()
                    + ") Processing script url (" + method + ") " + scriptUrl);

        WebScriptRequest scriptReq = null;
        WebScriptResponse scriptRes = null;
        Authenticator auth = null;

        RequiredAuthentication containerRequiredAuth = container.getRequiredAuthentication();

        if (!containerRequiredAuth.equals(RequiredAuthentication.none)) {
            // Create initial request & response
            scriptReq = createRequest(null);
            scriptRes = createResponse();
            auth = createAuthenticator();

            if (debug)
                logger.debug("(Runtime=" + getName() + ", Container=" + container.getName()
                        + ") Container requires pre-auth: " + containerRequiredAuth);

            boolean preAuth = true;

            if (auth != null && auth.emptyCredentials()) {
                // check default (unauthenticated) domain
                match = container.getRegistry().findWebScript(method, scriptUrl);
                if ((match != null) && (match.getWebScript().getDescription().getRequiredAuthentication()
                        .equals(RequiredAuthentication.none))) {
                    preAuth = false;
                }
            }

            if (preAuth && (!container.authenticate(auth, containerRequiredAuth))) {
                return; // return response (eg. prompt for un/pw if status is 401 or redirect)
            }
        }

        if (match == null) {
            match = container.getRegistry().findWebScript(method, scriptUrl);
        }

        if (match == null || match.getKind() == Match.Kind.URI) {
            if (match == null) {
                String msg = "Script url " + scriptUrl + " does not map to a Web Script.";
                if (debug)
                    logger.debug(msg);
                throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, msg);
            } else {
                String msg = "Script url " + scriptUrl + " does not support the method " + method;
                if (debug)
                    logger.debug(msg);
                throw new WebScriptException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
            }
        }

        // create web script request & response
        scriptReq = createRequest(match);
        scriptRes = createResponse();

        if (auth == null) {
            // not pre-authenticated
            auth = createAuthenticator();
        }

        if (debug)
            logger.debug("Agent: " + scriptReq.getAgent());

        long startScript = System.nanoTime();
        final WebScript script = match.getWebScript();
        final Description description = script.getDescription();

        try {
            if (debug) {
                String reqFormat = scriptReq.getFormat();
                String format = (reqFormat == null || reqFormat.length() == 0) ? "[undefined]" : reqFormat;
                Description desc = scriptReq.getServiceMatch().getWebScript().getDescription();
                logger.debug("Invoking Web Script " + description.getId() + " (format " + format + ", style: "
                        + desc.getFormatStyle() + ", default: " + desc.getDefaultFormat() + ")");
            }

            executeScript(scriptReq, scriptRes, auth);
        } finally {
            if (debug) {
                long endScript = System.nanoTime();
                logger.debug("Web Script " + description.getId() + " executed in "
                        + (endScript - startScript) / 1000000f + "ms");
            }
        }
    } catch (Throwable e) {
        if (beforeProcessError(match, e)) {
            if (e instanceof WebScriptException
                    && (((WebScriptException) e).getStatus() == HttpServletResponse.SC_NOT_FOUND
                            || ((WebScriptException) e).getStatus() == HttpServletResponse.SC_UNAUTHORIZED)) {
                // debug level output for "missing" WebScripts and API URLs entered incorrectly
                String errorCode = ((WebScriptException) e).getStatus() == HttpServletResponse.SC_NOT_FOUND
                        ? "NOT FOUND"
                        : "UNAUTHORIZED";
                logger.debug("Webscript did not execute. (" + errorCode + "): " + e.getMessage());
            }
            // log error on server so its not swallowed and lost
            else if (logger.isErrorEnabled()) {
                logger.error("Exception from executeScript - redirecting to status template error: "
                        + e.getMessage(), e);
            }

            // setup context
            WebScriptRequest req = createRequest(match);
            WebScriptResponse res = createResponse();
            String format = req.getFormat();

            // extract status code, if specified
            int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
            StatusTemplate statusTemplate = null;
            Map<String, Object> statusModel = null;
            if (e instanceof WebScriptException) {
                WebScriptException we = (WebScriptException) e;
                statusCode = we.getStatus();
                statusTemplate = we.getStatusTemplate();
                statusModel = we.getStatusModel();
            }

            // retrieve status template for response rendering
            if (statusTemplate == null) {
                // locate status template
                // NOTE: search order...
                //   1) root located <status>.ftl
                //   2) root located <format>.status.ftl
                //   3) root located status.ftl
                statusTemplate = getStatusCodeTemplate(statusCode);

                String validTemplatePath = container.getTemplateProcessorRegistry()
                        .findValidTemplatePath(statusTemplate.getPath());
                if (validTemplatePath == null) {
                    if (format != null && format.length() > 0) {
                        // if we have a format try and get the format specific status template
                        statusTemplate = getFormatStatusTemplate(format);
                        validTemplatePath = container.getTemplateProcessorRegistry()
                                .findValidTemplatePath(statusTemplate.getPath());
                    }

                    // if we don't have a valid template path get the default status template
                    if (validTemplatePath == null) {
                        statusTemplate = getStatusTemplate();
                        validTemplatePath = container.getTemplateProcessorRegistry()
                                .findValidTemplatePath(statusTemplate.getPath());
                    }

                    // throw error if a status template could not be found
                    if (validTemplatePath == null) {
                        throw new WebScriptException("Failed to find status template "
                                + statusTemplate.getPath() + " (format: " + statusTemplate.getFormat() + ")");
                    }
                }
            }

            // create basic model for all information known at this point, if one hasn't been pre-provided
            if (statusModel == null || statusModel.equals(Collections.EMPTY_MAP)) {
                statusModel = new HashMap<String, Object>(8, 1.0f);
                statusModel.putAll(container.getTemplateParameters());
                statusModel.put("url", createURLModel(req));
                if (match != null && match.getWebScript() != null) {
                    statusModel.put("webscript", match.getWebScript().getDescription());
                }
            }

            // add status to model
            Status status = new Status();
            status.setCode(statusCode);
            status.setMessage(e.getMessage() != null ? e.getMessage() : e.toString());
            if (exceptionLogger.isDebugEnabled()) {
                status.setException(e);
            }
            statusModel.put("status", status);

            // render output
            String mimetype = container.getFormatRegistry().getMimeType(req.getAgent(),
                    statusTemplate.getFormat());
            if (mimetype == null) {
                throw new WebScriptException(
                        "Web Script format '" + statusTemplate.getFormat() + "' is not registered");
            }

            if (debug) {
                logger.debug("Force success status header in response: " + req.forceSuccessStatus());
                logger.debug("Sending status " + statusCode + " (Template: " + statusTemplate.getPath() + ")");
                logger.debug("Rendering response: content type=" + mimetype);
            }

            Cache cache = new Cache();
            cache.setNeverCache(true);
            res.setCache(cache);
            res.setStatus(req.forceSuccessStatus() ? HttpServletResponse.SC_OK : statusCode);
            res.setContentType(mimetype + ";charset=UTF-8");
            try {
                String validTemplatePath = container.getTemplateProcessorRegistry()
                        .findValidTemplatePath(statusTemplate.getPath());
                TemplateProcessor statusProcessor = container.getTemplateProcessorRegistry()
                        .getTemplateProcessor(validTemplatePath);
                statusProcessor.process(validTemplatePath, statusModel, res.getWriter());
            } catch (Exception e1) {
                logger.error("Internal error", e1);
                throw new WebScriptException("Internal error", e1);
            }
        }
    } finally {
        if (debug) {
            long endRuntime = System.nanoTime();
            logger.debug("Processed script url (" + method + ") " + scriptUrl + " in "
                    + (endRuntime - startRuntime) / 1000000f + "ms");
        }
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.oauth.NuxeoOAuthFilter.java

protected void process(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String uri = httpRequest.getRequestURI();

    // process OAuth 3 legged calls
    if (uri.contains("/oauth/")) {
        String call = uri.split("/oauth/")[1];

        if (call.equals("authorize")) {
            processAuthorize(httpRequest, httpResponse);
        } else if (call.equals("request-token")) {
            processRequestToken(httpRequest, httpResponse);
        } else if (call.equals("access-token")) {
            processAccessToken(httpRequest, httpResponse);

        } else {/*from  w  w w  .j  a v a2 s . c o m*/
            httpResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "OAuth call not supported");
        }
        return;
    }
    // Signed request (simple 2 legged OAuth call or signed request
    // after a 3 legged nego)
    else if (isOAuthSignedRequest(httpRequest)) {

        LoginContext loginContext = processSignedRequest(httpRequest, httpResponse);
        // forward the call if authenticated
        if (loginContext != null) {
            Principal principal = (Principal) loginContext.getSubject().getPrincipals().toArray()[0];
            try {
                chain.doFilter(new NuxeoSecuredRequestWrapper(httpRequest, principal), response);
            } finally {
                try {
                    loginContext.logout();
                } catch (LoginException e) {
                    log.warn("Error when loging out", e);
                }
            }
        } else {
            if (!httpResponse.isCommitted()) {
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
            return;
        }
    }
    // Non OAuth calls can pass through
    else {
        throw new RuntimeException("request is not a outh request");
    }
}

From source file:org.eclipse.rdf4j.http.server.repository.statements.StatementsController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ModelAndView result;//from  w ww  .j  a  va 2 s  .  co  m

    Repository repository = RepositoryInterceptor.getRepository(request);

    String reqMethod = request.getMethod();

    if (METHOD_GET.equals(reqMethod)) {
        logger.info("GET statements");
        result = getExportStatementsResult(repository, request, response);
    } else if (METHOD_HEAD.equals(reqMethod)) {
        logger.info("HEAD statements");
        result = getExportStatementsResult(repository, request, response);
    } else if (METHOD_POST.equals(reqMethod)) {
        String mimeType = HttpServerUtil.getMIMEType(request.getContentType());

        if (Protocol.TXN_MIME_TYPE.equals(mimeType)) {
            logger.info("POST transaction to repository");
            result = getTransactionResultResult(repository, request, response);
        } else if (Protocol.SPARQL_UPDATE_MIME_TYPE.equals(mimeType)
                || request.getParameterMap().containsKey(Protocol.UPDATE_PARAM_NAME)) {
            logger.info("POST SPARQL update request to repository");
            result = getSparqlUpdateResult(repository, request, response);
        } else {
            logger.info("POST data to repository");
            result = getAddDataResult(repository, request, response, false);
        }
    } else if ("PUT".equals(reqMethod)) {
        logger.info("PUT data in repository");
        result = getAddDataResult(repository, request, response, true);
    } else if ("DELETE".equals(reqMethod)) {
        logger.info("DELETE data from repository");
        result = getDeleteDataResult(repository, request, response);
    } else {
        throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                "Method not allowed: " + reqMethod);
    }

    return result;
}

From source file:com.imaginary.home.cloud.api.RestApi.java

@Override
public void doDelete(@Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp)
        throws IOException, ServletException {
    String requestId = request(req);

    try {/* w ww .  j ava2 s . co  m*/
        Map<String, Object> headers = parseHeaders(req);
        String[] path = getPath(req);

        if (path.length < 1) {
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No DELETE is allowed against /");
        } else if (apiCalls.containsKey(path[0])) {
            Map<String, Object> parameters = parseParameters(req);
            APICall call = apiCalls.get(path[0]);

            String userId = authenticate("DELETE", req, headers);

            call.delete(requestId, userId, path, req, resp, headers, parameters);
        } else {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_RESOURCE,
                    "No " + path[0] + " resource exists in this API");
        }
    } catch (RestException e) {
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", e.getStatus());
        error.put("message", e.getMessage());
        error.put("description", e.getDescription());
        resp.setStatus(e.getStatus());
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    } catch (Throwable t) {
        t.printStackTrace();
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        error.put("message", RestException.INTERNAL_ERROR);
        error.put("description", t.getMessage());
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    }
}

From source file:org.apache.wookie.controller.WidgetInstancesController.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (!WidgetKeyManager.isValidRequest(request)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {/*  w w  w . jav a  2 s . c  o m*/
        try {
            String requestId = request.getParameter("requestid"); //$NON-NLS-1$
            if (requestId == null || requestId.equals("")) {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            } else {
                if (requestId.equals("getwidget")) { //$NON-NLS-1$
                    doGetWidget(request, response);
                } else if (requestId.equals("stopwidget")) { //$NON-NLS-1$
                    doStopWidget(request, response);
                } else if (requestId.equals("resumewidget")) { //$NON-NLS-1$
                    doResumeWidget(request, response);
                } else if (requestId.equals("clone")) { //$NON-NLS-1$
                    cloneSharedData(request, response);
                } else {
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                }
            }
        } catch (Exception ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:org.sakaiproject.kernel.rest.RestUserProvider.java

/**
 * {@inheritDoc}/*  w ww  .  j  av a2s  .c  o m*/
 *
 * @see org.sakaiproject.kernel.api.rest.RestProvider#dispatch(java.lang.String[],
 *      javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public void dispatch(String[] elements, HttpServletRequest request, HttpServletResponse response) {
    try {
        if ("POST".equals(request.getMethod())) {
            // Security is managed by the JCR
            Map<String, Object> map = null;
            if ("new".equals(elements[1])) {
                map = createUser(request, response);
            } else if ("changepassword".equals(elements[1])) {
                map = changePassword(request, response, elements.length > 2 ? elements[2] : null);
            }

            if (map != null) {
                String responseBody = beanConverter.convertToString(map);
                response.setContentType(RestProvider.CONTENT_TYPE);
                response.getOutputStream().print(responseBody);
            }

        } else {
            if ("GET".equals(request.getMethod()) && elements.length == 3 && getKey().equals(elements[0])
                    && EXISTS.equals(elements[2]) && elements[1].trim().length() > 0) {
                handleUserExists(elements[1].trim(), response);
            } else {
                throw new RestServiceFaultException(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
    } catch (SecurityException ex) {
        throw ex;
    } catch (RestServiceFaultException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RestServiceFaultException(ex.getMessage(), ex);
    }
}

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

/**
 * Empties the trash can from any currently stored resource,
 * making all trashed files and folders permanently deleted.
 *
  * @param req The HTTP request we are processing
  * @param resp The HTTP response we are processing
 * @throws IOException//from www.j  ava2 s.com
  * @throws IOException if an input/output error occurs
 */
public void emptyTrash(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String path = getInnerPath(req, PATH_TRASH);
    if (path.equals(""))
        path = "/";

    if (!path.equals("/")) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    try {
        User user = getUser(req);
        final User owner = getOwner(req);
        if (!owner.equals(user))
            throw new InsufficientPermissionsException("User " + user.getUsername()
                    + " does not have permission to empty the trash can owned by " + owner.getUsername());
        if (logger.isDebugEnabled())
            logger.debug("Emptying trash for user " + owner.getUsername());
        new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                getService().emptyTrash(owner.getId());
                return null;
            }
        });
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
    } catch (Exception e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

/**
 * Handle POST requests in the users namespace.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
  * @throws IOException if an input/output error occurs
 *//*  w w  w.j  a  v  a  2s. co  m*/
void postUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        final User user = getUser(req);
        User owner = getOwner(req);
        if (!owner.equals(user))
            throw new InsufficientPermissionsException("User " + user.getUsername()
                    + " does not have permission to modify " + owner.getUsername());
        boolean hasResetWebDAVParam = req.getParameterMap().containsKey(RESET_WEBDAV_PARAMETER);
        if (hasResetWebDAVParam) {
            String newPassword = new TransactionHelper<String>().tryExecute(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return getService().resetWebDAVPassword(user.getId());
                }
            });

            // Set the cookie again to send new value
            Cookie cookie = new Cookie(Login.WEBDAV_COOKIE, newPassword);
            cookie.setMaxAge(-1);
            String domain = req.getRemoteHost();
            String path = req.getContextPath();
            cookie.setDomain(domain);
            cookie.setPath(path);
            resp.addCookie(cookie);
        }
        // Workaround for IE's broken caching behavior.
        resp.setHeader("Expires", "-1");
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
    } catch (Exception e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}