Example usage for javax.servlet.http HttpServletResponse SC_NOT_IMPLEMENTED

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

Introduction

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

Prototype

int SC_NOT_IMPLEMENTED

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

Click Source Link

Document

Status code (501) indicating the HTTP server does not support the functionality needed to fulfill the request.

Usage

From source file:org.eclipse.orion.server.cf.servlets.AbstractRESTHandler.java

/**
 * Handles a DELETE request. Note this method is meant to be overridden in descendant classes.
 * @param request The DELETE request being handled.
 * @param response The response associated with the request.
 * @param path Path suffix required to handle the request.
 * @return A {@link JazzJob} which returns the DELETE request result on completion.
 *///from ww  w  .ja v  a 2s .  com
protected CFJob handleDelete(T resource, final HttpServletRequest request, final HttpServletResponse response,
        final String path) {
    return new CFJob(request, false) {
        @Override
        protected IStatus performJob() {
            String msg = NLS.bind("Failed to handle request for {0}", path); //$NON-NLS-1$
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_IMPLEMENTED, msg, null);
        }
    };
}

From source file:org.tsugi.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
protected void doRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("getServiceURL=" + getServiceURL(request));

    String ipAddress = request.getRemoteAddr();
    System.out.println("LTI Service request from IP=" + ipAddress);

    String rpi = request.getPathInfo();
    String uri = request.getRequestURI();
    String[] parts = uri.split("/");
    if (parts.length < 4) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, null, "Incorrect url format", null);
        return;/*from ww w. j  ava  2s.  com*/
    }
    String controller = parts[3];
    if ("register".equals(controller)) {
        doRegister(request, response);
        return;
    } else if ("launch".equals(controller)) {
        doLaunch(request, response);
        return;
    } else if (SVC_tc_profile.equals(controller) && parts.length == 5) {
        String profile_id = parts[4];
        getToolConsumerProfile(request, response, profile_id);
        return;
    } else if (SVC_tc_registration.equals(controller) && parts.length == 5) {
        String profile_id = parts[4];
        registerToolProviderProfile(request, response, profile_id);
        return;
    } else if (SVC_Result.equals(controller) && parts.length == 5) {
        String sourcedid = parts[4];
        handleResultRequest(request, response, sourcedid);
        return;
    } else if (SVC_Settings.equals(controller) && parts.length >= 6) {
        handleSettingsRequest(request, response, parts);
        return;
    }

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);
    if (jsonRequest.valid) {
        System.out.println(jsonRequest.getPostBody());
    }

    response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    M_log.warn("Unknown request=" + uri);
    doErrorJSON(request, response, null, "Unknown request=" + uri, null);
}

From source file:org.imsglobal.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
protected void doRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("getServiceURL=" + getServiceURL(request));

    String ipAddress = request.getRemoteAddr();
    System.out.println("LTI Service request from IP=" + ipAddress);

    String rpi = request.getPathInfo();
    String uri = request.getRequestURI();
    String[] parts = uri.split("/");
    if (parts.length < 4) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, null, "Incorrect url format", null);
        return;//from w w w.  ja v a  2  s .co  m
    }
    String controller = parts[3];
    if ("register".equals(controller)) {
        doRegister(request, response);
        return;
    } else if ("launch".equals(controller)) {
        doLaunch(request, response);
        return;
    } else if (SVC_tc_profile.equals(controller) && parts.length == 5) {
        String profile_id = parts[4];
        getToolConsumerProfile(request, response, profile_id);
        return;
    } else if (SVC_tc_registration.equals(controller) && parts.length == 5) {
        String profile_id = parts[4];
        registerToolProviderProfile(request, response, profile_id);
        return;
    } else if (SVC_Result.equals(controller) && parts.length == 5) {
        String sourcedid = parts[4];
        handleResultRequest(request, response, sourcedid);
        return;
    } else if (SVC_Settings.equals(controller) && parts.length >= 6) {
        handleSettingsRequest(request, response, parts);
        return;
    }

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);
    if (jsonRequest.valid) {
        System.out.println(jsonRequest.getPostBody());
    }

    response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    M_log.log(Level.WARNING, "Unknown request=" + uri);
    doErrorJSON(request, response, null, "Unknown request=" + uri, null);
}

From source file:it.cnr.icar.eric.server.interfaces.rest.RestServlet.java

/** Handles the HTTP <code>GET</code> method.
 * @param request servlet request//w w  w  .  j a  v  a2s.c o m
 * @param response servlet response
 */
@SuppressWarnings("static-access")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String interfase = request.getParameter("interface");

    try {
        if ((interfase == null) || interfase.equals("")) {
            //First check if it is a user defined URL since that is less expensive to match        
            UserDefinedURLHandler udefURLHandler = new UserDefinedURLHandler(request, response);
            try {
                udefURLHandler.processGetRequest();
                response.setStatus(response.SC_OK);
            } catch (ObjectNotFoundException e) {
                FilePathURLHandler filePathURLHandler = new FilePathURLHandler(request, response);
                filePathURLHandler.processGetRequest();
                response.setStatus(response.SC_OK);
            }
        } else if (interfase.equalsIgnoreCase("QueryManager")) {
            QueryManagerURLHandler qmURLHandler = new QueryManagerURLHandler(request, response);
            qmURLHandler.processGetRequest();
            response.setStatus(response.SC_OK);
        } else if (interfase.equalsIgnoreCase("LifeCycleManager")) {
            LifeCycleManagerURLHandler lcmURLHandler = new LifeCycleManagerURLHandler(request, response);
            lcmURLHandler.processGetRequest();
            response.setStatus(response.SC_OK);
        } else if (extendedInterfaces.containsKey(interfase)) {
            String className = extendedInterfaces.get(interfase).toString();
            URLHandler handler = createURLHandlerInstance(className, request, response);
            if (handler != null) {
                handler.processGetRequest();
                response.setStatus(response.SC_OK);
            } else {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Invalid request. Unknown interface: " + interfase);
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Invalid request. Unknown interface: " + interfase);
        }
    } catch (ObjectNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (InvalidRequestException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (UnimplementedException e) {
        response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, e.getMessage());
    } catch (RegistryException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractController.java

/**
 * Handle exception.//from w ww.  j  a  va 2 s  .co  m
 *
 * @param response the response
 * @param request the request
 * @param ex the ex
 * @return the model and view
 */
@ExceptionHandler(UnsupportedOperationException.class)
@ResponseBody
public CTS2Exception handleException(HttpServletResponse response, HttpServletRequest request,
        UnsupportedOperationException ex) {
    int status = HttpServletResponse.SC_NOT_IMPLEMENTED;

    response.setStatus(status);

    return ExceptionFactory.createUnknownException(
            "Method not implemented. " + ex.getMessage() != null ? ex.getMessage() : "", getUrlString(request),
            getParameterString(request));
}

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 = "";
    }//from   w  ww  .  j a va 2s . co  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:org.eclipse.orion.server.git.servlets.GitIndexHandlerV1.java

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, Repository db, IPath path)
        throws ServletException, NoFilepatternException, IOException, JSONException {
    JSONObject toReset = OrionServlet.readJSONRequest(request);
    String resetType = toReset.optString(GitConstants.KEY_RESET_TYPE, null);
    if (resetType != null) {
        JSONArray paths = toReset.optJSONArray(ProtocolConstants.KEY_PATH);
        if (paths != null) {
            String msg = NLS.bind("Mixing {0} and {1} parameters is not allowed.",
                    new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_RESET_TYPE });
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }/* w w w .  j a  v  a 2 s . c o  m*/
        String ref = toReset.optString(GitConstants.KEY_TAG_COMMIT, Constants.HEAD);
        try {
            ResetType type = ResetType.valueOf(resetType);
            switch (type) {
            case MIXED:
            case HARD:
                Git git = new Git(db);
                // "git reset --{type} HEAD ."
                try {
                    git.reset().setMode(type).setRef(ref).call();
                } catch (GitAPIException e) {
                    statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e));
                }
                return true;
            case KEEP:
            case MERGE:
            case SOFT:
                String msg = NLS.bind("The reset type is not yet supported: {0}.", resetType);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_IMPLEMENTED, msg, null));
            }
        } catch (IllegalArgumentException e) {
            String msg = NLS.bind("Unknown or malformed reset type: {0}.", resetType);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
    } else {
        String commit = toReset.optString(GitConstants.KEY_TAG_COMMIT, null);
        if (commit != null) {
            String msg = NLS.bind("Mixing {0} and {1} parameters is not allowed.",
                    new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_TAG_COMMIT });
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        JSONArray paths = toReset.optJSONArray(ProtocolConstants.KEY_PATH);
        Git git = new Git(db);
        ResetCommand reset = git.reset().setRef(Constants.HEAD);
        if (paths != null) {
            for (int i = 0; i < paths.length(); i++) {
                reset.addPath(paths.getString(i));
            }
        } else {
            //path format is /file/{workspaceId}/{projectName}[/{path}]
            String projectRelativePath = path.removeFirstSegments(3).toString();
            if (projectRelativePath.isEmpty()) {
                String msg = "Path cannot be empty.";
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }
            reset.addPath(projectRelativePath);
        }
        try {
            reset.call();
        } catch (GitAPIException e) {
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), e));
        }
        return true;
    }
    return false;
}

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

/**
 * The REST servlet check for the resource type that has been requested.<br>
 * The resource is represented by the url i.e. /rest/<b>resource</b> or /rest/<b>report</b>
 * The resource logic is implemented by extending a RESTService.<br>
 * The RESTService handled for a specific request is configured in the file shared-config\applicationContext-rest-services.xml. It is a map which
 * binds urls to RESTServices. The RESTService implementation is in charge to accept or not the specific method type.
 *
 * @param req  HttpServletRequest//from  w  w w.  j av  a  2  s.co  m
 * @param resp  HttpServletResponse
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("-------------------------------------------------------------------------------- ");
    }

    // This print writer is used only in case of exception, but in general exception should be always
    // handled inside the RESTService implementation, if available.
    PrintWriter pw = null;
    String serviceName = null;
    String path = null;

    try {

        // Get the name of the service requested by the user
        path = req.getPathInfo();
        if (path == null) {
            // error...
            log.error("request params: Path: " + path);
            utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid");
            return;
        }

        serviceName = utils.extractServiceName(path);

        // If the service name is null or empty, return an error.
        if (serviceName == null || serviceName.length() == 0) {
            log.error("request params: Service" + serviceName + " Path: " + path);
            utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid");
            return;
        }

        RESTService service = registry.getService(serviceName);
        if (service == null) {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName);
            utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid");
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("request params: Path: " + path + " Requested Service: " + serviceName
                    + " Service from registry: " + service.getClass());
        }

        resp.setContentType("text/xml; charset=UTF-8");
        service.execute(req, resp);
    } catch (ServiceException ex) {
        if (log.isDebugEnabled())
            log.debug("Error executing a REST service: " + ex.getErrorCode(), ex);
        // The servlet is able to map common ServiceException errors with most appropriate REST (HTTP) error codes...
        // This should be really just the latest case, when a more specific error is not available.
        // In general the service implementation should take care to send to the client the proper response.
        switch (ex.getErrorCode()) {
        case ServiceException.RESOURCE_NOT_FOUND: {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_NOT_FOUND + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "");
            break;
        }
        case ServiceException.RESOURCE_BAD_REQUEST: {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ex.getMessage());
            break;
        }
        case ServiceException.FORBIDDEN: {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, ex.getMessage());
            break;
        }
        default: {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
        }
        }
    }

    catch (UnsupportedOperationException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_NOT_IMPLEMENTED + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_NOT_IMPLEMENTED, resp, "");
    }

    catch (ReportJobNotFoundException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
    }

    catch (JSExceptionWrapper ex) {
        Exception e = ex.getOriginalException();
        if (e instanceof ConstraintViolationException || e instanceof DataIntegrityViolationException) {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, "");
        } else {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
        }
    }

    catch (JSValidationException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
    }

    catch (AccessDeniedException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, ex.getMessage());

    }

    catch (IllegalStateException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");

    }

    catch (IllegalArgumentException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_BAD_REQUEST + " Error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");

    } catch (Exception ex) {
        // This should Never happen. If it does, it's probably an implementation bug, or the remote service
        // implementation did not provide a better or specific error.
        log.error("Error executing a REST service", ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.SparqlQueryServlet.java

private void doNoModelInContext(HttpServletResponse res) {
    try {//from ww  w. java2s. c om
        res.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        ServletOutputStream sos = res.getOutputStream();
        sos.println("<html><body>this service is not supporeted by the current "
                + "webapp configuration. A jena model is required in the servlet context.</body></html>");
    } catch (IOException e) {
        log.error("Could not write to ServletOutputStream");
    }
}

From source file:com.epam.wilma.test.server.ExampleHandler.java

private void generateErrorCode(final String path, final HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    if (PATH_TO_TIMEOUT.equals(path)) {
        try {//from  www  .j a v  a2  s  . c  o m
            Thread.sleep(WAIT_IN_MILLIS);
        } catch (Exception e) {
            throw new ServletException("Thread's wait failed....", e);
        }
    } else if (PATH_INTERNAL_SERVER_ERROR.equals(path)) {
        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } else if (PATH_SERVICE_UNAVAILABLE.equals(path)) {
        httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else if (PATH_BAD_GATWAY.equals(path)) {
        httpServletResponse.sendError(HttpServletResponse.SC_BAD_GATEWAY);
    } else if (PATH_NOT_IMPLEMENTED.equals(path)) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

}