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.roosster.mappers.ApiServletMapper.java

/**
 * /*from  w  w  w. j  av a2s .c o  m*/
 */
protected void processException(int method, HttpServletRequest req, HttpServletResponse resp, Output output,
        String commandName, Exception ex) throws ServletException, IOException {
    if (ex instanceof OperationException) {
        ex = (Exception) ex.getCause();
    }

    if (ex instanceof CommandNotFoundException) {

        LOG.warn(ex.getMessage(), ex);
        resp.sendError(HttpServletResponse.SC_NOT_FOUND,
                "RoossterException: <" + ex.getClass().getName() + "> " + ex.getMessage());

    } else if (ex instanceof ParseException) {

        LOG.warn("Sending HTTP Status Code 400: " + ex.getMessage(), ex);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "RoossterException: <" + ex.getClass().getName() + "> " + ex.getMessage());

    } else if (ex instanceof MethodNotAllowedException) {

        LOG.warn("Sending HTTP Status Code 405: " + ex.getMessage(), ex);
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                "RoossterException: <" + ex.getClass().getName() + "> " + ex.getMessage());

    } else if (ex instanceof IllegalArgumentException) {

        LOG.warn("Sending HTTP Status Code 400: " + ex.getMessage(), ex);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "RoossterException: <" + ex.getClass().getName() + "> " + ex.getMessage());

    } else {

        Throwable t = ex.getCause() == null ? ex : ex.getCause();
        LOG.warn("Sending HTTP Status Code 500: " + t.getMessage(), t);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "RoossterException: <" + t.getClass().getName() + "> " + t.getMessage());
    }

}

From source file:org.sakaiproject.sdata.tool.util.PathSecurityAssertion.java

/**
 * Performs the security assertion based on the resourceLocation, from the
 * original request and the method begin attempted. Will throw a
 * SDataException with Forbidden if the resource location is outside the
 * configured range, or if permission is denied.
 * /*from w  ww  .  j a v  a2  s .c o  m*/
 * @param method
 *          the http method being used
 * @param urlPath
 *          the path of the url, excluding host, protocol, port and query
 *          string, but including everything else.
 * @see org.sakaiproject.sdata.tool.api.SecurityAssertion#check(java.lang.String,java.lang.String,
 *      java.lang.String)
 */
public void check(String method, String resourcePath) throws SDataException {

    if (!(basePath.length() == 0) && (resourcePath == null || !resourcePath.startsWith(basePath))) {
        LOG.info("Denied " + method + " on [" + resourcePath + "] base mismatch [" + basePath + "]");
        throw new SDataException(HttpServletResponse.SC_FORBIDDEN, "Access Forbidden");
    }
    String resourceReference = baseResource + resourcePath.substring(basePath.length());
    PermissionQuery permissionQuery = getResourceLock(method);

    if (permissionQuery == null) {
        throw new SDataException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                "Method " + method + " is not allowed");
    } else {
        authzResolverService.check(resourceReference, permissionQuery);
    }
}

From source file:de.micromata.genome.gwiki.web.GWikiServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (GLog.isTraceEnabled() == true) {
        String lopi = "Req: ctpath: " + req.getContextPath() + "; spath: " + req.getServletPath() + "; pi: "
                + req.getPathInfo();/*from w  ww.  ja v  a2 s .  c o  m*/
        GLog.note(GWikiLogCategory.Wiki, lopi);
    }
    initWiki(req, resp);
    long start = System.currentTimeMillis();
    GWikiWeb wiki = getWikiWeb();
    GWikiContext ctx = new GWikiContext(wiki, this, req, resp);
    try {
        GWikiContext.setCurrent(ctx);
        String page = getWikiPage(ctx);

        final String method = req.getMethod();
        if (StringUtils.equals(method, "GET") == false && StringUtils.equals(method, "POST") == false) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Gwiki Method " + method + " not supported");
            return;
        }
        if (page.startsWith("static/") == true) {
            serveStatic(page, ctx);
            return;
        }
        wiki.serveWiki(page, ctx);
    } catch (RuntimeIOException ex) {
        GLog.info(GWikiLogCategory.Wiki, "IO Error serving: " + ex.getMessage(), new LogExceptionAttribute(ex));
    } catch (Exception ex) {
        if (isIgnorableAppServeIOException(ex) == true) {
            GLog.note(GWikiLogCategory.Wiki, "IO Error serving: " + ex.getMessage());
        } else {
            GLog.error(GWikiLogCategory.Wiki, "GWikiWeb serve error: " + ex.getMessage(),
                    new LogExceptionAttribute(ex));
        }
    } finally {
        LoggingServiceManager.get().getStatsDAO().addPerformance(GWikiLogCategory.Wiki, "GWikiServlet.doPost",
                System.currentTimeMillis() - start, 0);
        GWikiContext.setCurrent(null);
        if (daoContext != null) {
            daoContext.getWikiSelector().deinitWiki(this, req, resp);
        }
    }
}

From source file:com.jaspersoft.jasperserver.rest.RESTAbstractService.java

protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    log.error(//from   www . j  a  va  2 s  . co  m
            "Method DELETE is not supported for this object type - request params: Path: " + req.getPathInfo());
    restUtils.setStatusAndBody(HttpServletResponse.SC_METHOD_NOT_ALLOWED, resp,
            "Method not supported for this object type");
}

From source file:v7db.files.buckets.BucketsServletTest.java

public void testEchoPutPUT() throws IOException, SAXException {

    ServletUnitClient sc = sr.newClient();
    {//ww w  .j  a  v  a2 s  .c o m
        WebRequest request = new PutMethodWebRequest("http://test/myServlet/1",
                new ByteArrayInputStream("testPUT".getBytes()), "text/plain");
        try {
            sc.getResponse(request);
            fail("bucket not found => 404");
        } catch (HttpNotFoundException e) {
            assertEquals("Bucket '1' not found", e.getResponseMessage());
        }

    }

    prepareBucket("1", "EchoPut", null, null);
    {
        WebRequest request = new PutMethodWebRequest("http://test/myServlet/1",
                new ByteArrayInputStream("testPUT".getBytes()), "text/plain");
        request.setParameter("sha", "1234");
        try {
            sc.getResponse(request);
            fail("uploads not allowed => 405");
        } catch (HttpException e) {
            assertEquals(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getResponseCode());
        }
    }

    prepareBucket("2", "EchoPut", null, "EchoPut");

    {
        WebRequest request = new PutMethodWebRequest("http://test/myServlet/2",
                new ByteArrayInputStream("testPUT".getBytes()), "text/plain");
        WebResponse response = sc.getResponse(request);
        assertEquals(DigestUtils.shaHex("testPUT".getBytes()), response.getText());

        assertMockMongoContainsDocument("test.v7files.content", DigestUtils.sha("testPUT".getBytes()));

        WebRequest get = new GetMethodWebRequest("http://test/myServlet/2");
        get.setParameter("sha", response.getText());
        assertEquals("testPUT", sc.getResponse(get).getText());
    }

}

From source file:org.springframework.security.oauth.provider.filter.OAuthProviderProcessingFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (!skipProcessing(request)) {
        if (requiresAuthentication(request, response, chain)) {
            if (!allowMethod(request.getMethod().toUpperCase())) {
                if (log.isDebugEnabled()) {
                    log.debug("Method " + request.getMethod() + " not supported.");
                }//from   w w w  . j  av  a  2s  .c om

                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                return;
            }

            try {
                Map<String, String> oauthParams = getProviderSupport().parseParameters(request);

                if (parametersAreAdequate(oauthParams)) {

                    if (log.isDebugEnabled()) {
                        StringBuilder builder = new StringBuilder("OAuth parameters parsed: ");
                        for (String param : oauthParams.keySet()) {
                            builder.append(param).append('=').append(oauthParams.get(param)).append(' ');
                        }
                        log.debug(builder.toString());
                    }

                    String consumerKey = oauthParams.get(OAuthConsumerParameter.oauth_consumer_key.toString());
                    if (consumerKey == null) {
                        throw new InvalidOAuthParametersException(messages.getMessage(
                                "OAuthProcessingFilter.missingConsumerKey", "Missing consumer key."));
                    }

                    //load the consumer details.
                    ConsumerDetails consumerDetails = getConsumerDetailsService()
                            .loadConsumerByConsumerKey(consumerKey);
                    if (log.isDebugEnabled()) {
                        log.debug("Consumer details loaded for " + consumerKey + ": " + consumerDetails);
                    }

                    //validate the parameters for the consumer.
                    validateOAuthParams(consumerDetails, oauthParams);
                    if (log.isDebugEnabled()) {
                        log.debug("Parameters validated.");
                    }

                    //extract the credentials.
                    String token = oauthParams.get(OAuthConsumerParameter.oauth_token.toString());
                    String signatureMethod = oauthParams
                            .get(OAuthConsumerParameter.oauth_signature_method.toString());
                    String signature = oauthParams.get(OAuthConsumerParameter.oauth_signature.toString());
                    String signatureBaseString = getProviderSupport().getSignatureBaseString(request);
                    ConsumerCredentials credentials = new ConsumerCredentials(consumerKey, signature,
                            signatureMethod, signatureBaseString, token);

                    //create an authentication request.
                    ConsumerAuthentication authentication = new ConsumerAuthentication(consumerDetails,
                            credentials, oauthParams);
                    authentication.setDetails(createDetails(request, consumerDetails));

                    Authentication previousAuthentication = SecurityContextHolder.getContext()
                            .getAuthentication();
                    try {
                        //set the authentication request (unauthenticated) into the context.
                        SecurityContextHolder.getContext().setAuthentication(authentication);

                        //validate the signature.
                        validateSignature(authentication);

                        //mark the authentication request as validated.
                        authentication.setSignatureValidated(true);

                        //mark that processing has been handled.
                        request.setAttribute(OAUTH_PROCESSING_HANDLED, Boolean.TRUE);

                        if (log.isDebugEnabled()) {
                            log.debug("Signature validated.");
                        }

                        //go.
                        onValidSignature(request, response, chain);
                    } finally {
                        //clear out the consumer authentication to make sure it doesn't get cached.
                        resetPreviousAuthentication(previousAuthentication);
                    }
                } else if (!isIgnoreInadequateCredentials()) {
                    throw new InvalidOAuthParametersException(
                            messages.getMessage("OAuthProcessingFilter.missingCredentials",
                                    "Inadequate OAuth consumer credentials."));
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Supplied OAuth parameters are inadequate. Ignoring.");
                    }
                    chain.doFilter(request, response);
                }
            } catch (AuthenticationException ae) {
                fail(request, response, ae);
            } catch (ServletException e) {
                if (e.getRootCause() instanceof AuthenticationException) {
                    fail(request, response, (AuthenticationException) e.getRootCause());
                } else {
                    throw e;
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Request does not require authentication.  OAuth processing skipped.");
            }

            chain.doFilter(servletRequest, servletResponse);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Processing explicitly skipped.");
        }

        chain.doFilter(servletRequest, servletResponse);
    }
}

From source file:com.moss.bdbadmin.jetty.BdbAdminJettyAdapter.java

public void handle(String target, final HttpServletRequest request, final HttpServletResponse response,
        int arg3) throws IOException, ServletException {

    target = request.getRequestURI(); // the target is automatically URLDecoded, we don't want this

    if (!target.startsWith(contextPath)) {
        return;//  w  w  w.j ava2s. c o  m
    }

    final IdProof assertion;
    {
        IdProof a = null;

        String value = request.getHeader(AuthenticationHeader.HEADER_NAME);
        if (value != null && value.length() > 0) {
            try {
                a = AuthenticationHeader.decode(value);
            } catch (Exception ex) {
                ex.printStackTrace();
                a = null;
            }
        } else {
            System.out.println("No assertion included in request header");
            a = null;
        }

        assertion = a;
    }

    final ServiceResource resource;
    {
        String path;
        if (target.length() >= contextPath.length()) {
            path = target.substring(contextPath.length()).trim();
        } else {
            path = target;
        }

        ServiceResource r = null;
        ;
        try {
            r = service.resolve(path);
        } catch (ResourcePathException ex) {
            ex.printStackTrace();
        }

        resource = r;
    }

    if (assertion == null || resource == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        abstract class Handler {
            abstract void handle() throws Exception;
        }

        Handler handler = resource.acceptVisitor(new ServiceResourceVisitor<Handler>() {
            public Handler visit(BdbMapResource map) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod())) {
                            byte[] data = service.map(assertion);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(BdbCategory category) {
                return null;
            }

            public Handler visit(BdbEnv env) {
                return null;
            }

            public Handler visit(final BdbDb db) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("GET".equals(request.getMethod())) {
                            byte[] data = service.dbInfo(assertion, db);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else if ("DELETE".equals(request.getMethod())) {
                            service.clearDb(assertion, db);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(final BdbEntityResource entity) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod())) {
                            byte[] data = service.entryInfo(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("GET".equals(request.getMethod())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("HEAD".equals(request.getMethod())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("PUT".equals(request.getMethod())) {

                            byte[] input;
                            {
                                InputStream in = request.getInputStream();
                                ByteArrayOutputStream out = new ByteArrayOutputStream();

                                byte[] buffer = new byte[1023 * 10]; //10k buffer
                                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                                    out.write(buffer, 0, numRead);
                                }

                                in.close();
                                out.close();

                                input = out.toByteArray();
                            }

                            service.putEntry(assertion, entity, input);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else if ("DELETE".equals(request.getMethod())) {
                            if (service.deleteEntry(assertion, entity)) {
                                response.setStatus(HttpServletResponse.SC_OK);
                            } else {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            }
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }
        });

        if (handler == null) {
            System.out.println("Cannot perform any methods on requested path");
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        } else {
            try {
                handler.handle();
            } catch (IdProovingException ex) {
                ex.printStackTrace();
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            } catch (NotAuthorizedException ex) {
                ex.printStackTrace();
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
    }

    response.getOutputStream().close();

    ((Request) request).setHandled(true);
}

From source file:org.sakaiproject.iclicker.tool.RestServlet.java

@SuppressWarnings("unchecked")
protected void handle(HttpServletRequest req, HttpServletResponse res, String method)
        throws ServletException, IOException {
    // force all response encoding to UTF-8 / XML by default
    res.setCharacterEncoding("UTF-8");
    // get the path
    String path = req.getPathInfo();
    if (path == null) {
        path = "";
    }//  ww  w .  j a  v a 2 s.  c  o  m
    String[] segments = HttpRESTUtils.getPathSegments(path);

    // init the vars to success
    boolean valid = true;
    int status = HttpServletResponse.SC_OK;
    String output = "";

    // check to see if this is one of the paths we understand
    if (path == null || "".equals(path) || segments.length == 0) {
        valid = false;
        output = "Unknown path (" + path + ") specified";
        status = HttpServletResponse.SC_NOT_FOUND;
    }

    // check the method is allowed
    if (valid && !"POST".equals(method) && !"GET".equals(method)) {
        valid = false;
        output = "Only POST and GET methods are supported";
        status = HttpServletResponse.SC_METHOD_NOT_ALLOWED;
    }

    // attempt to handle the request 
    if (valid) {
        // check against the ones we know and process
        String pathSeg0 = HttpRESTUtils.getPathSegment(path, 0);
        String pathSeg1 = HttpRESTUtils.getPathSegment(path, 1);

        boolean restDebug = false;
        if (req.getParameter("_debug") != null || logic.forceRestDebugging) {
            restDebug = true;
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            for (Map.Entry<String, String[]> entry : (Set<Map.Entry<String, String[]>>) req.getParameterMap()
                    .entrySet()) {
                sb.append(entry.getKey()).append("=").append(Arrays.toString(entry.getValue())).append(", ");
            }
            if (sb.length() > 2) {
                sb.setLength(sb.length() - 2); //Removes the last comma
            }
            sb.append("]");
            log.info("iclicker REST debugging: req: " + method + " " + path + ", params=" + sb);
        }
        try {
            if ("verifykey".equals(pathSeg0)) {
                // SPECIAL case handling (no authn handling)
                String ssoKey = req.getParameter(SSO_KEY);
                if (logic.verifyKey(ssoKey)) {
                    status = HttpServletResponse.SC_OK;
                    output = "Verified";
                } else {
                    status = HttpServletResponse.SC_NOT_IMPLEMENTED;
                    output = "Disabled";
                }
                if (restDebug) {
                    log.info("iclicker REST debugging: verifykey (s=" + status + ", o=" + output + ")");
                }
                res.setContentType("text/plain");
                res.setContentLength(output.length());
                res.getWriter().print(output);
                res.setStatus(status);
                return;
            } else {
                // NORMAL case handling
                // handle the request authn
                handleAuthN(req, res);
                // process the REQUEST
                if ("GET".equals(method)) {
                    if ("courses".equals(pathSeg0)) {
                        // handle retrieving the list of courses for an instructor
                        String userId = getAndCheckCurrentUser("access instructor courses listings");
                        String courseId = pathSeg1;
                        if (restDebug) {
                            log.info("iclicker REST debugging: courses (u=" + userId + ", c=" + courseId + ")");
                        }
                        List<Course> courses = logic.getCoursesForInstructorWithStudents(courseId);
                        if (courses.isEmpty()) {
                            throw new SecurityException(
                                    "No courses found, only instructors can access instructor courses listings");
                        }
                        output = logic.encodeCourses(userId, courses);

                    } else if ("students".equals(pathSeg0)) {
                        // handle retrieval of the list of students
                        String courseId = pathSeg1;
                        if (courseId == null) {
                            throw new IllegalArgumentException(
                                    "valid courseId must be included in the URL /students/{courseId}");
                        }
                        if (restDebug) {
                            log.info("iclicker REST debugging: students (c=" + courseId + ")");
                        }
                        getAndCheckCurrentUser("access student enrollment listings");
                        List<Student> students = logic.getStudentsForCourseWithClickerReg(courseId);
                        Course course = new Course(courseId, courseId);
                        course.students = students;
                        output = logic.encodeEnrollments(course);

                    } else {
                        // UNKNOWN
                        valid = false;
                        output = "Unknown path (" + path + ") specified";
                        status = HttpServletResponse.SC_NOT_FOUND;
                    }
                } else {
                    // POST
                    if ("gradebook".equals(pathSeg0)) {
                        // handle retrieval of the list of students
                        String courseId = pathSeg1;
                        if (courseId == null) {
                            throw new IllegalArgumentException(
                                    "valid courseId must be included in the URL /gradebook/{courseId}");
                        }
                        getAndCheckCurrentUser("upload grades into the gradebook");
                        String xml = getXMLData(req);
                        if (restDebug) {
                            log.info(
                                    "iclicker REST debugging: gradebook (c=" + courseId + ", xml=" + xml + ")");
                        }
                        try {
                            Gradebook gradebook = logic.decodeGradebookXML(xml);
                            // process gradebook data
                            List<GradebookItem> results = logic.saveGradebook(gradebook);
                            // generate the output
                            output = logic.encodeSaveGradebookResults(courseId, results);
                            if (output == null) {
                                // special return, non-XML, no failures in save
                                res.setStatus(HttpServletResponse.SC_OK);
                                res.setContentType("text/plain");
                                output = "True";
                                res.setContentLength(output.length());
                                res.getWriter().print(output);
                                return;
                            } else {
                                // failures occurred during save
                                status = HttpServletResponse.SC_OK;
                            }
                        } catch (IllegalArgumentException e) {
                            // invalid XML
                            valid = false;
                            output = "Invalid gradebook XML in request, unable to process: " + xml;
                            log.warn("i>clicker: " + output, e);
                            status = HttpServletResponse.SC_BAD_REQUEST;
                        }

                    } else if ("authenticate".equals(pathSeg0)) {
                        if (restDebug) {
                            log.info("iclicker REST debugging: authenticate");
                        }
                        getAndCheckCurrentUser("authenticate via iclicker");
                        // special return, non-XML
                        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
                        return;

                    } else if ("register".equals(pathSeg0)) {
                        getAndCheckCurrentUser("upload registrations data");
                        String xml = getXMLData(req);
                        if (restDebug) {
                            log.info("iclicker REST debugging: register (xml=" + xml + ")");
                        }
                        ClickerRegistration cr = logic.decodeClickerRegistration(xml);
                        String ownerId = cr.getOwnerId();
                        Locale locale = req.getLocale();
                        String message;
                        boolean regStatus = false;
                        try {
                            logic.createRegistration(cr.getClickerId(), ownerId);
                            // valid registration
                            message = logic.getMessage("reg.registered.below.success", locale,
                                    cr.getClickerId());
                            regStatus = true;
                        } catch (ClickerIdInvalidException e) {
                            // invalid clicker id
                            //log.warn("register: " + e, e);
                            message = logic.getMessage("reg.registered.clickerId.invalid", locale,
                                    cr.getClickerId());
                        } catch (IllegalArgumentException e) {
                            // invalid user id
                            //log.warn("register: invalid user id: " + e, e);
                            message = "Student not found in the CMS";
                        } catch (ClickerRegisteredException e) {
                            // already registered
                            String key;
                            if (e.ownerId.equals(e.registeredOwnerId)) {
                                // already registered to this user
                                key = "reg.registered.below.duplicate";
                            } else {
                                // already registered to another user
                                key = "reg.registered.clickerId.duplicate.notowned";
                            }
                            message = logic.getMessage(key, locale, cr.getClickerId());
                            //log.warn("register: clicker registered: " + e, e);
                        }
                        List<ClickerRegistration> registrations = logic.getClickerRegistrationsForUser(ownerId,
                                true);
                        output = logic.encodeClickerRegistrationResult(registrations, regStatus, message);
                        if (regStatus) {
                            status = HttpServletResponse.SC_OK;
                        } else {
                            status = HttpServletResponse.SC_BAD_REQUEST;
                        }

                    } else {
                        // UNKNOWN
                        valid = false;
                        output = "Unknown path (" + path + ") specified";
                        status = HttpServletResponse.SC_NOT_FOUND;
                    }
                }
            }
        } catch (SecurityException e) {
            valid = false;
            String currentUserId = currentUser();
            if (currentUserId == null) {
                output = "User must be logged in to perform this action: " + e;
                status = HttpServletResponse.SC_UNAUTHORIZED;
            } else {
                output = "User (" + currentUserId + ") is not allowed to perform this action: " + e;
                status = HttpServletResponse.SC_FORBIDDEN;
            }
        } catch (IllegalArgumentException e) {
            valid = false;
            output = "Invalid request: " + e;
            log.warn("i>clicker: " + output, e);
            status = HttpServletResponse.SC_BAD_REQUEST;
        } catch (Exception e) {
            valid = false;
            output = "Failure occurred: " + e;
            log.warn("i>clicker: " + output, e);
            status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
        if (restDebug) {
            String extra = "";
            if (!valid) {
                extra = ", o=" + output;
            }
            log.info("iclicker REST debugging: DONE (s=" + status + ", v=" + valid + extra + ")");
        }
    }
    if (valid) {
        // send the response
        res.setStatus(HttpServletResponse.SC_OK);
        res.setContentType("application/xml");
        output = XML_HEADER + output;
        res.setContentLength(output.length());
        res.getWriter().print(output);
    } else {
        // error with info about how to do it right
        res.setStatus(status);
        res.setContentType("text/plain");
        // add helpful info to the output
        String msg = "ERROR " + status + ": Invalid request (" + req.getMethod() + " " + req.getContextPath()
                + req.getServletPath() + path + ")"
                + "\n\n=INFO========================================================================================\n"
                + output
                + "\n\n-HELP----------------------------------------------------------------------------------------\n"
                + "Valid request paths include the following (without the servlet prefix: "
                + req.getContextPath() + req.getServletPath() + "):\n"
                + "POST /authenticate             - authenticate by sending credentials (" + LOGIN + ","
                + PASSWORD + ") \n" + "                                 return status 204 (valid login) \n"
                + "POST /verifykey                - check the encoded key is valid and matches the shared key \n"
                + "                                 return 200 if valid OR 501 if SSO not enabled OR 400/401 if key is bad \n"
                + "POST /register                 - Add a new clicker registration, return 200 for success or 400 with \n"
                + "                                 registration response (XML) for failure \n"
                + "GET  /courses                  - returns the list of courses for the current user (XML) \n"
                + "GET  /students/{courseId}      - returns the list of student enrollments for the given course (XML) \n"
                + "                                 or 403 if user is not an instructor in the specified course \n"
                + "POST /gradebook/{courseId}     - send the gradebook data into the system, returns errors on failure (XML) \n"
                + "                                 or 'True' if no errors, 400 if the xml is missing or courseid is invalid, \n"
                + "                                 403 if user is not an instructor in the specified course \n"
                + "\n" + " - Authenticate by sending credentials (" + LOGIN + "," + PASSWORD
                + ") or by sending a valid session id (" + SESSION_ID + ") in the request parameters \n"
                + " -- SSO authentication requires an encoded key (" + SSO_KEY
                + ") in the request parameters \n"
                + " -- The response headers will include the sessionId when credentials are valid \n"
                + " -- Invalid credentials or sessionId will result in a 401 (invalid credentials) or 403 (not authorized) status \n"
                + " - Use " + COMPENSATE_METHOD + " to override the http method being used (e.g. POST /courses?"
                + COMPENSATE_METHOD + "=GET will force the method to be a GET despite sending as a POST) \n"
                + " - Send data as the http request BODY or as a form parameter called " + XML_DATA + " \n"
                + " - All endpoints return 403 if user is not an instructor \n";
        res.setContentLength(msg.length());
        res.getWriter().print(msg);
        //res.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
    }
}

From source file:cf.spring.servicebroker.ServiceBrokerHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!authenticator.authenticate(request, response)) {
        return;/*  w ww.j a v a2  s  .c  o m*/
    }
    ApiVersionValidator.validateApiVersion(request);
    try {
        response.setContentType(Constants.JSON_CONTENT_TYPE);
        final Matcher matcher = URI_PATTERN.matcher(request.getRequestURI());
        if (!matcher.matches()) {
            throw new NotFoundException("Resource not found");
        }
        final String instanceId = matcher.group(1);
        final String bindingId = matcher.group(3);
        if ("put".equalsIgnoreCase(request.getMethod())) {
            if (bindingId == null) {
                final ProvisionBody provisionBody = mapper.readValue(request.getInputStream(),
                        ProvisionBody.class);
                final String serviceId = provisionBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
                final ProvisionRequest provisionRequest = new ProvisionRequest(UUID.fromString(instanceId),
                        provisionBody.getPlanId(), provisionBody.getOrganizationGuid(),
                        provisionBody.getSpaceGuid());
                final ProvisionResponse provisionResponse = accessor.provision(provisionRequest);
                if (provisionResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), provisionResponse);
            } else {
                final BindBody bindBody = mapper.readValue(request.getInputStream(), BindBody.class);
                final String serviceId = bindBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);

                final BindRequest bindRequest = new BindRequest(UUID.fromString(instanceId),
                        UUID.fromString(bindingId), bindBody.applicationGuid, bindBody.getPlanId());
                final BindResponse bindResponse = accessor.bind(bindRequest);
                if (bindResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), bindResponse);
            }
        } else if ("delete".equalsIgnoreCase(request.getMethod())) {
            final String serviceId = request.getParameter(SERVICE_ID_PARAM);
            final String planId = request.getParameter(PLAN_ID_PARAM);
            final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
            try {
                if (bindingId == null) {
                    // Deprovision
                    final DeprovisionRequest deprovisionRequest = new DeprovisionRequest(
                            UUID.fromString(instanceId), planId);
                    accessor.deprovision(deprovisionRequest);
                } else {
                    // Unbind
                    final UnbindRequest unbindRequest = new UnbindRequest(UUID.fromString(bindingId),
                            UUID.fromString(instanceId), planId);
                    accessor.unbind(unbindRequest);
                }
            } catch (MissingResourceException e) {
                response.setStatus(HttpServletResponse.SC_GONE);
            }
            response.getWriter().write("{}");
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (ConflictException e) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        response.getWriter().write("{}");
    } catch (ServiceBrokerException e) {
        LOGGER.warn("An error occurred processing a service broker request", e);
        response.setStatus(e.getHttpResponseCode());
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    } catch (Throwable e) {
        LOGGER.error(e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    }
}

From source file:org.jscep.server.ScepServlet.java

/**
 * {@inheritDoc}/* w ww.  j a v a  2s.com*/
 */
@SuppressWarnings("unchecked")
@Override
public final void service(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    byte[] body = getMessageBytes(req);

    final Operation op;
    try {
        op = getOperation(req);
        if (op == null) {
            // The operation parameter must be set.

            res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Writer writer = res.getWriter();
            writer.write("Missing \"operation\" parameter.");
            writer.flush();

            return;
        }
    } catch (IllegalArgumentException e) {
        // The operation was not recognised.

        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        Writer writer = res.getWriter();
        writer.write("Invalid \"operation\" parameter.");
        writer.flush();

        return;
    }

    LOGGER.debug("Incoming Operation: " + op);

    final String reqMethod = req.getMethod();

    if (op == Operation.PKI_OPERATION) {
        if (!reqMethod.equals(POST) && !reqMethod.equals(GET)) {
            // PKIOperation must be sent using GET or POST

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET + ", " + POST);

            return;
        }
    } else {
        if (!reqMethod.equals(GET)) {
            // Operations other than PKIOperation must be sent using GET

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET);

            return;
        }
    }

    LOGGER.debug("Method " + reqMethod + " Allowed for Operation: " + op);

    if (op == Operation.GET_CA_CAPS) {
        try {
            LOGGER.debug("Invoking doGetCaCaps");
            doGetCaCaps(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetCaCert");
            doGetCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_NEXT_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetNextCaCert");
            doGetNextCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.PKI_OPERATION) {
        // PKIOperation

        res.setHeader("Content-Type", "application/x-pki-message");

        CMSSignedData sd;
        try {
            sd = new CMSSignedData(body);
        } catch (CMSException e) {
            throw new ServletException(e);
        }

        Store reqStore = sd.getCertificates();
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        CertificateFactory factory;
        try {
            factory = CertificateFactory.getInstance("X.509");
        } catch (CertificateException e) {
            throw new ServletException(e);
        }
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert;
        try {
            reqCert = (X509Certificate) factory.generateCertificate(bais);
        } catch (CertificateException e) {
            throw new ServletException(e);
        }

        PkiMessage<?> msg;
        try {
            PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(), getRecipientKey());
            PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder);
            msg = decoder.decode(sd);
        } catch (MessageDecodingException e) {
            LOGGER.error("Error decoding request", e);
            throw new ServletException(e);
        }

        LOGGER.debug("Processing message {}", msg);

        MessageType msgType = msg.getMessageType();
        Object msgData = msg.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = msg.getTransactionId();
        Nonce recipientNonce = msg.getSenderNonce();
        CertRep certRep;

        if (msgType == MessageType.GET_CERT) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name principal = iasn.getName();
            final BigInteger serial = iasn.getSerialNumber().getValue();

            try {
                List<X509Certificate> issued = doGetCert(principal, serial);
                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CERT_INITIAL) {
            final IssuerAndSubject ias = (IssuerAndSubject) msgData;
            final X500Name issuer = X500Name.getInstance(ias.getIssuer());
            final X500Name subject = X500Name.getInstance(ias.getSubject());

            try {
                List<X509Certificate> issued = doGetCertInitial(issuer, subject, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CRL) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name issuer = iasn.getName();
            final BigInteger serialNumber = iasn.getSerialNumber().getValue();

            try {
                LOGGER.debug("Invoking doGetCrl");
                CMSSignedData messageData = getMessageData(doGetCrl(issuer, serialNumber));

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            } catch (OperationFailureException e) {
                LOGGER.error("Error executing GetCRL request", e);
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                LOGGER.error("Error executing GetCRL request", e);
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.PKCS_REQ) {
            final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData;

            try {
                LOGGER.debug("Invoking doEnrol");
                List<X509Certificate> issued = doEnrol(certReq, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else {
            throw new ServletException("Unknown Message for Operation");
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede");
        PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(), getSigner(),
                getSignerCertificateChain(), envEncoder);
        CMSSignedData signedData;
        try {
            signedData = encoder.encode(certRep);
        } catch (MessageEncodingException e) {
            LOGGER.error("Error decoding response", e);
            throw new ServletException(e);
        }

        res.getOutputStream().write(signedData.getEncoded());
        res.getOutputStream().close();
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown Operation");
    }
}