Example usage for javax.servlet.http HttpServletResponse SC_NO_CONTENT

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

Introduction

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

Prototype

int SC_NO_CONTENT

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

Click Source Link

Document

Status code (204) indicating that the request succeeded but that there was no new information to return.

Usage

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  ava 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:org.gss_project.gss.server.rest.GroupsHandler.java

/**
 * Handle DELETE requests in the groups 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  ww.  j av a  2 s  . co  m*/
void deleteGroup(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String path = getInnerPath(req, PATH_GROUPS);
    if (path.equals(""))
        path = "/";

    if (path.equals("/"))
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, METHOD_GET + ", " + METHOD_POST);
    else {
        // Chop any trailing slash
        path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
        // Chop any leading slash
        path = path.startsWith("/") ? path.substring(1) : path;
        int slash = path.indexOf('/');
        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 modify the groups owned by " + owner.getUsername());
            if (slash != -1) {
                // Request to delete group member
                if (logger.isDebugEnabled())
                    logger.debug("Removing member " + path.substring(slash + 1) + " from group "
                            + path.substring(0, slash));
                final Group group = getService().getGroup(owner.getId(),
                        URLDecoder.decode(path.substring(0, slash), "UTF-8"));
                for (final User u : group.getMembers())
                    if (u.getUsername().equals(path.substring(slash + 1)))
                        new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                            @Override
                            public Void call() throws Exception {
                                getService().removeMemberFromGroup(owner.getId(), group.getId(), u.getId());
                                return null;
                            }
                        });
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("Removing group " + path);
                final Group group = getService().getGroup(owner.getId(), URLDecoder.decode(path, "UTF-8"));
                new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        getService().deleteGroup(owner.getId(), group.getId());
                        return null;
                    }
                });
            }
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
            // Workaround for IE's broken caching behavior.
            resp.setHeader("Expires", "-1");
        } 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:com.twinsoft.convertigo.engine.servlets.GenericServlet.java

protected void doRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    HttpServletRequestTwsWrapper wrapped_request = new HttpServletRequestTwsWrapper(request);
    request = wrapped_request;/*ww  w  .ja  va  2 s .  c om*/

    String baseUrl = getServletBaseUrl(request);

    if ((baseUrl.indexOf("/projects/") != -1) || (baseUrl.indexOf("/webclipper/") != -1)) {
        long t0 = System.currentTimeMillis();
        try {
            String encoded = request.getParameter(Parameter.RsaEncoded.getName());
            if (encoded != null) {
                String query = Engine.theApp.rsaManager.decrypt(encoded, request.getSession());
                wrapped_request.clearParameters();
                wrapped_request.addQuery(query);
            }

            Object result = processRequest(request);

            response.addHeader("Expires", "-1");

            if (getCacheControl(request).equals("false"))
                HeaderName.CacheControl.addHeader(response,
                        "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");

            /**
             * Disabled since #253 : Too much HTML Connector cookies in
             * response header make a tomcat exception
             * http://sourceus.twinsoft.fr/ticket/253 cookies must be in xml
             * if wanted, not in headers
             * 
             * Vector cookies = (Vector)
             * request.getAttribute("convertigo.cookies"); for (int i=0;
             * i<cookies.size(); i++) { String sCookie =
             * (String)cookies.elementAt(i);
             * response.addHeader("Set-Cookie", sCookie);
             * Engine.logContext.trace("[GenericServlet] Set-Cookie: " +
             * sCookie); }
             */

            String trSessionId = (String) request.getAttribute("sequence.transaction.sessionid");
            if ((trSessionId != null) && (!trSessionId.equals(""))) {
                response.setHeader("Transaction-JSessionId", trSessionId);
            }

            String requested_content_type = request.getParameter(Parameter.ContentType.getName());
            String content_type = getContentType(request);
            if (requested_content_type != null && !requested_content_type.equals(content_type)) {
                Engine.logEngine.debug("(GenericServlet) Override Content-Type requested to change : "
                        + content_type + " to " + requested_content_type);
                content_type = requested_content_type;
            } else {
                requested_content_type = null;
            }

            response.setContentType(content_type);
            if (content_type.startsWith("text")) {
                String charset = (String) request.getAttribute("convertigo.charset");
                if (charset != null && charset.length() > 0) {
                    response.setCharacterEncoding(charset);
                }
            }

            try {

                if (result != null) {

                    Boolean b = (Boolean) request.getAttribute("convertigo.isErrorDocument");
                    if (b.booleanValue()) {
                        Requester requester = getRequester();
                        boolean bThrowHTTP500 = false;

                        if (requester instanceof WebServiceServletRequester) {
                            bThrowHTTP500 = Boolean.parseBoolean(EnginePropertiesManager.getProperty(
                                    EnginePropertiesManager.PropertyName.THROW_HTTP_500_SOAP_FAULT));
                        } else if (requester instanceof ServletRequester) {
                            bThrowHTTP500 = Boolean.parseBoolean(EnginePropertiesManager
                                    .getProperty(EnginePropertiesManager.PropertyName.THROW_HTTP_500));
                        }

                        if (bThrowHTTP500) {
                            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            Engine.logEngine.debug("(GenericServlet) Requested HTTP 500 status code");
                        }
                    } else {
                        applyCustomStatus(request, response);
                    }

                    if (result instanceof AttachmentDetails) {
                        AttachmentDetails attachment = (AttachmentDetails) result;
                        byte[] data = attachment.getData();
                        String contentType = attachment.getContentType();

                        if (requested_content_type != null) {
                            contentType = requested_content_type;
                        }

                        String name = attachment.getName();

                        HeaderName.ContentType.setHeader(response, contentType);
                        HeaderName.ContentLength.setHeader(response, "" + data.length);
                        HeaderName.ContentDisposition.setHeader(response, "attachment; filename=" + name);

                        applyCustomHeaders(request, response);

                        OutputStream out = response.getOutputStream();
                        out.write(data);
                        out.flush();
                    } else if (result instanceof byte[]) {
                        if (requested_content_type != null) {
                            response.setContentType(requested_content_type);
                        } else {
                            response.setContentType(getContentType(request));
                            response.setCharacterEncoding((String) request.getAttribute("convertigo.charset"));
                        }
                        HeaderName.ContentLength.addHeader(response, "" + ((byte[]) result).length);

                        applyCustomHeaders(request, response);

                        OutputStream out = response.getOutputStream();
                        out.write((byte[]) result);
                        out.flush();
                    } else {
                        String sResult = "";
                        if (result instanceof String) {
                            sResult = (String) result;
                        } else if (result instanceof Document) {
                            sResult = XMLUtils.prettyPrintDOM((Document) result);
                        } else if (result instanceof SOAPMessage) {
                            sResult = SOAPUtils.toString((SOAPMessage) result,
                                    (String) request.getAttribute("convertigo.charset"));
                        }

                        applyCustomHeaders(request, response);

                        Writer writer = response.getWriter();
                        writer.write(sResult);
                        writer.flush();
                    }
                } else {
                    applyCustomHeaders(request, response);

                    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                }
            } catch (IOException e) {
                // The connection has probably been reset by peer
                Engine.logContext
                        .warn("[GenericServlet] The connection has probably been reset by peer (IOException): "
                                + e.getMessage());
            } finally {
                // Supervision mode
                String supervision = request.getParameter(Parameter.Supervision.getName());
                if (supervision != null) {
                    Engine.logContext
                            .debug("[GenericServlet] Supervision mode => invalidating HTTP session in 30s.");
                    removeSession(request, 30);
                }

                // Removes context and session when finished
                // Note: case of context.requireEndOfContext has been set in
                // scope
                if (request.getAttribute("convertigo.requireEndOfContext") != null) {
                    removeContext(request);
                    removeSession(request, 1);
                }

                // Removes context when finished
                String removeContextParam = request.getParameter(Parameter.RemoveContext.getName());
                if (removeContextParam == null) {
                    // case of a mother sequence (context is removed by
                    // default)
                    Boolean removeContextAttr = (Boolean) request
                            .getAttribute("convertigo.context.removalRequired");
                    if ((removeContextAttr != null) && removeContextAttr.booleanValue()) {
                        removeContext(request);
                    }
                } else {
                    // other cases (remove context if exist __removeContext
                    // or __removeContext=true/false)
                    if (!("false".equals(removeContextParam))) {
                        removeContext(request);
                    }
                }

                // Removes session when finished
                String removeSessionParam = request.getParameter(Parameter.RemoveSession.getName());
                if (removeSessionParam != null) {
                    // __removeSession or __removeSession=true/false
                    // or __removeSession=xx (where xx is a number of seconds)
                    if (!("false".equals(removeSessionParam))) {
                        int interval = 1;
                        try {
                            interval = Integer.parseInt(removeSessionParam, 10);
                        } catch (Exception e) {
                        }
                        removeSession(request, interval);
                    }
                }

            }
        } catch (Exception e) {
            Engine.logContext.error("Unable to process the request!", e);
            processException(request, response, e);
        } finally {
            long t1 = System.currentTimeMillis();
            Engine.theApp.pluginsManager.fireHttpServletRequestEnd(request, t0, t1);
        }
    } else {
        // Not a valid Convertigo invocation URL, use retrieve as static
        // resource
        handleStaticData(request, response);
        return;
    }
}

From source file:org.alfresco.repo.webdav.PutMethodTest.java

@Test
public void testPutContentToAnExistingFile() throws Exception {
    FileInfo testFileInfo = fileFolderService.create(companyHomeNodeRef, "file-" + GUID.generate(),
            ContentModel.TYPE_CONTENT);
    try {//from  w w  w.jav a  2 s.c o  m
        executeMethod(WebDAV.METHOD_PUT, testFileInfo.getName(), testDataFile, null);

        assertTrue("File does not exist.", nodeService.exists(testFileInfo.getNodeRef()));
        assertEquals("Filename is not correct.", testFileInfo.getName(),
                nodeService.getProperty(testFileInfo.getNodeRef(), ContentModel.PROP_NAME));
        assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is "
                + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());
        InputStream updatedFileIS = fileFolderService.getReader(testFileInfo.getNodeRef())
                .getContentInputStream();
        byte[] updatedFile = IOUtils.toByteArray(updatedFileIS);
        updatedFileIS.close();
        assertTrue("The content has to be equal", ArrayUtils.isEquals(testDataFile, updatedFile));
    } catch (Exception e) {
        fail("Failed to upload a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    } finally {
        nodeService.deleteNode(testFileInfo.getNodeRef());
    }
}

From source file:com.rsginer.spring.controllers.RestaurantesController.java

@RequestMapping(value = { "/upload-file" }, method = RequestMethod.POST, produces = "application/json")
public void uploadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestParam("file") MultipartFile file) {
    try {//from w w w. ja v  a2 s.  c o  m
        String rutaRelativa = "/uploads";
        String rutaAbsoluta = httpServletRequest.getServletContext().getVirtualServerName();
        String jsonSalida = jsonTransformer
                .toJson("http://" + rutaAbsoluta + ":" + httpServletRequest.getLocalPort()
                        + httpServletRequest.getContextPath() + "/uploads/" + file.getOriginalFilename());
        if (!file.isEmpty()) {
            int res = fileSaveService.saveFile(file, httpServletRequest);
            if (res == 200) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                httpServletResponse.setContentType("application/json; charset=UTF-8");
                try {
                    httpServletResponse.getWriter().println(jsonSalida);
                } catch (IOException ex) {
                    Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } catch (BussinessException ex) {
        List<BussinessMessage> bussinessMessages = ex.getBussinessMessages();
        String jsonSalida = jsonTransformer.toJson(bussinessMessages);
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }

    }

}

From source file:org.osaf.cosmo.mc.MorseCodeServlet.java

/**
 * Handles update requests./* w ww. j  av a  2  s  .c  o  m*/
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled())
        log.debug("handling POST for " + req.getPathInfo());

    CollectionPath cp = CollectionPath.parse(req.getPathInfo());
    if (cp != null) {
        String tokenStr = req.getHeader(HEADER_SYNC_TOKEN);
        if (StringUtils.isBlank(tokenStr)) {
            String msg = "Missing sync token";
            handleGeneralException(new BadRequestException(msg), resp);
            return;
        }

        if (!checkWritePreconditions(req, resp))
            return;

        EimmlStreamReader reader = null;
        try {
            SyncToken token = SyncToken.deserialize(tokenStr);

            reader = new EimmlStreamReader(req.getReader());
            if (!reader.getCollectionUuid().equals(cp.getUid())) {
                String msg = "EIMML collection uid " + reader.getCollectionUuid()
                        + " does not match target collection uid " + cp.getUid();
                handleGeneralException(new BadRequestException(msg), resp);
                return;
            }

            EimmlStreamReaderIterator i = new EimmlStreamReaderIterator(reader);
            PubRecords records = new PubRecords(i, reader.getCollectionName(), reader.getCollectionHue());

            PubCollection pubCollection = controller.updateCollection(cp.getUid(), token, records);

            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
            resp.addHeader(HEADER_SYNC_TOKEN, pubCollection.getToken().serialize());
            return;
        } catch (CosmoSecurityException e) {
            if (e instanceof ItemSecurityException) {
                InsufficientPrivilegesException ipe = new InsufficientPrivilegesException(
                        (ItemSecurityException) e);
                handleGeneralException(ipe, resp);
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
            }
            return;
        } catch (EimmlStreamException e) {
            Throwable cause = e.getCause();
            String msg = "Unable to read EIM stream: " + e.getMessage();
            msg += cause != null ? ": " + cause.getMessage() : "";
            handleGeneralException(new BadRequestException(msg, e), resp);
            return;
        } catch (CollectionLockedException e) {
            resp.sendError(SC_LOCKED, "Collection is locked for update");
            return;
        } catch (StaleCollectionException e) {
            resp.sendError(HttpServletResponse.SC_RESET_CONTENT,
                    "Collection contains more recently updated items");
            return;
        } catch (MorseCodeException e) {
            Throwable root = e.getCause();
            if (root != null && root instanceof EimmlStreamException) {
                String msg = "Unable to read EIM stream: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }
            if (root != null && root instanceof EimSchemaException) {
                String msg = "Unable to process EIM records: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }

            handleGeneralException(e, resp);
            return;
        } catch (RuntimeException e) {
            handleGeneralException(new MorseCodeException(e), resp);
            return;
        } finally {
            if (reader != null)
                reader.close();
        }
    }
    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * DELETE?/*from w ww .jav  a  2 s.  c  om*/
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId != null && !targetId.isEmpty()) {

            // 
            boolean deleteResult = op.deleteUserInfo(context, request, targetId);
            if (deleteResult) {
                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:com.aaasec.sigserv.csspserver.SpServlet.java

private static void nullResponse(HttpServletResponse response) {
    try {/*w ww .  j  a va 2  s  .com*/
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        response.getWriter().write("");
        response.getWriter().close();
    } catch (IOException ex) {
        Logger.getLogger(SpServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.alfresco.rest.api.tests.TestDownloads.java

/**
 * Tests deleting a download node using the /nodes API:
 *
 * <p>DELETE:</p>/*from ww w  . j  a  v a2s .c o m*/
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>}
 * 
 */
@Test
public void test005DeleteDownloadNode() throws Exception {

    //test deleting a download node
    Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    assertDoneDownload(download, 1, 13);

    deleteNode(download.getId(), true, HttpServletResponse.SC_NO_CONTENT);

    getDownload(download.getId(), HttpServletResponse.SC_NOT_FOUND);

    //test user2 deleting a download node created by user1
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    assertDoneDownload(download, 1, 13);

    setRequestContext(user2);

    deleteNode(download.getId(), true, HttpServletResponse.SC_FORBIDDEN);

    assertDoneDownload(download, 1, 13);
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

protected @Nullable String getString(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource) throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".getString(" + authToken + "," + endpoint + ","
                + resource + ")");
    }/*from w  w w  .  ja va2  s .co m*/
    if (wire.isDebugEnabled()) {
        wire.debug("--------------------------------------------------------> " + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpGet get = new HttpGet(endpoint + resource);

        get.addHeader("Content-Type", "application/json");
        get.addHeader("X-Auth-Token", authToken);

        if (wire.isDebugEnabled()) {
            wire.debug(get.getRequestLine().toString());
            for (Header header : get.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            response = client.execute(get);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);

        if (code == HttpServletResponse.SC_NOT_FOUND) {
            return null;
        }
        if (code != HttpServletResponse.SC_NO_CONTENT && code != HttpServletResponse.SC_OK
                && code != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) {
            std.error("getString(): Expected OK for GET request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }

            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                return null;
            }
            std.error("getString(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            return json;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".getString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + endpoint + resource);
        }
    }
}