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.apache.sling.servlets.get.impl.helpers.HtmlRendererServlet.java

@Override
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp)
        throws ServletException, IOException {
    final Resource r = req.getResource();

    if (ResourceUtil.isNonExistingResource(r)) {
        throw new ResourceNotFoundException("No data to render.");
    }//w  w  w . j  a  v a 2 s.  c  om

    resp.setContentType(req.getResponseContentType());
    resp.setCharacterEncoding("UTF-8");

    final PrintWriter pw = resp.getWriter();

    final boolean isIncluded = req.getAttribute(SlingConstants.ATTR_REQUEST_SERVLET) != null;

    @SuppressWarnings("unchecked")
    final Map map = r.adaptTo(Map.class);
    if (map != null) {
        printProlog(pw, isIncluded);
        printResourceInfo(pw, r);
        render(pw, r, map);
        printEpilog(pw, isIncluded);
    } else if (r.adaptTo(String.class) != null) {
        printProlog(pw, isIncluded);
        printResourceInfo(pw, r);
        render(pw, r, r.adaptTo(String.class));
        printEpilog(pw, isIncluded);
    } else if (r.adaptTo(String[].class) != null) {
        printProlog(pw, isIncluded);
        printResourceInfo(pw, r);
        render(pw, r, r.adaptTo(String[].class));
        printEpilog(pw, isIncluded);
    } else {
        if (!isIncluded) {
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT); // NO Content
        }
    }
}

From source file:org.apache.hadoop.hdfsproxy.ProxyForwardServlet.java

/** {@inheritDoc} */
public void forwardRequest(HttpServletRequest request, HttpServletResponse response, ServletContext context,
        String pathInfo) throws IOException, ServletException {
    String path = buildForwardPath(request, pathInfo);
    RequestDispatcher dispatcher = context.getRequestDispatcher(path);
    if (dispatcher == null) {
        LOG.info("There was no such dispatcher: " + path);
        response.sendError(HttpServletResponse.SC_NO_CONTENT);
        return;// w ww. ja  v  a 2  s.  c  o  m
    }
    dispatcher.forward(request, response);
}

From source file:com.basetechnology.s0.agentserver.appserver.HandlePut.java

public boolean handlePut() throws Exception {
    // Extract out commonly used info
    String path = httpInfo.path;//  www  . ja va 2 s. c o m
    String[] pathParts = httpInfo.pathParts;
    Request request = httpInfo.request;
    HttpServletResponse response = httpInfo.response;
    AgentServer agentServer = httpInfo.agentServer;
    String lcPath = path.toLowerCase();

    if (path.equalsIgnoreCase("/config")) {
        checkAdminAccess();
        JSONObject configJson = getInputJson();
        log.info("Updating configuration settings");

        // Update the config settings as requested
        agentServer.config.update(configJson);

        // Update was successful
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (path.equalsIgnoreCase("/config/reset")) {
        checkAdminAccess();

        log.info("Resetting to original configuration settings");

        // Reset config settings to original defaults
        agentServer.config.restoreDefaults();

        // Update was successful
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.equals("/shutdown")) {
        checkAdminAccess();

        // Request the agent app server to shutdown
        // TODO: Can we really do this here and still return a response?
        // Or do we need to set a timer, return, and shutdown independent of current request

        // Spin up a separate thread to gracefully shutdown the server in a timely manner
        AgentAppServerShutdown agentAppServerShutdown = new AgentAppServerShutdown(agentServer);
        shutdownThread = new Thread(agentAppServerShutdown);
        shutdownThread.start();

        // Done
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return true;
    } else if (lcPath.equals("/status/pause")) {
        checkAdminAccess();
        // Request the agent scheduler to pause
        AgentScheduler.singleton.pause();
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.equals("/status/restart")) {
        checkAdminAccess();
        // Request the agent scheduler to shutdown
        AgentScheduler.singleton.shutdown();

        // Sleep a little to wait for shutdown to complete
        Thread.sleep(250);

        // Make sure scheduler is no longer running
        if (AgentScheduler.singleton != null)
            // Sleep a little longer to wait for shutdown
            Thread.sleep(250);

        // Force the scheduler to start
        AgentScheduler agentScheduler = new AgentScheduler(agentServer);

        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.equals("/status/resume")) {
        checkAdminAccess();
        // Request the agent scheduler to resume
        AgentScheduler.singleton.resume();
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.equals("/status/shutdown")) {
        checkAdminAccess();
        // Request the agent scheduler to shutdown
        log.info("Shutting down agent server");
        AgentScheduler.singleton.shutdown();
        log.info("Agent server shut down");
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.equals("/status/start")) {
        checkAdminAccess();
        // Make sure scheduler is not already running
        if (AgentScheduler.singleton == null) {
            // Force the scheduler to start
            AgentScheduler agentScheduler = new AgentScheduler(agentServer);
        }
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.equals("/status/stop")) {
        checkAdminAccess();
        // Request the agent scheduler to shutdown
        log.info("Shutting down agent server");
        AgentScheduler.singleton.shutdown();
        log.info("Agent server shut down");
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(true);

        // Parse the user info JSON from posted entity
        JSONObject userJson = getInputJson();

        log.info("Updating existing user: " + user.id);

        // Parse the updated user info
        User newUser = User.fromJson(userJson, true);

        // Update the user info
        user.update(agentServer, newUser);

        // Update was successful
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/disable$")) {
        User user = checkAdminUserAccess();
        String allActivityString = request.getParameter("all_activity");
        boolean disableAllActivity = allActivityString == null || (allActivityString.equalsIgnoreCase("true")
                || allActivityString.equalsIgnoreCase("yes") || allActivityString.equalsIgnoreCase("on"));
        String newActivityString = request.getParameter("new_activity");
        boolean disableNewActivity = newActivityString == null || (newActivityString.equalsIgnoreCase("true")
                || newActivityString.equalsIgnoreCase("yes") || newActivityString.equalsIgnoreCase("on"));
        log.info("Disabling user: " + user.id + " diable all activity: " + disableAllActivity
                + " disable new activity: " + disableNewActivity);

        // Disable user as directed
        user.enabled = !disableAllActivity;
        user.newActivityEnabled = !disableNewActivity;

        // Update was successful
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/enable$")) {
        User user = checkAdminUserAccess();
        String allActivityString = request.getParameter("all_activity");
        boolean enableAllActivity = allActivityString == null || (allActivityString.equalsIgnoreCase("true")
                || allActivityString.equalsIgnoreCase("yes") || allActivityString.equalsIgnoreCase("on"));
        String newActivityString = request.getParameter("new_activity");
        boolean enableNewActivity = newActivityString == null || (newActivityString.equalsIgnoreCase("true")
                || newActivityString.equalsIgnoreCase("yes") || newActivityString.equalsIgnoreCase("on"));
        log.info("Enabling user: " + user.id + " enable new activity: " + enableNewActivity);

        // Enable user as directed
        user.enabled = enableAllActivity;
        user.newActivityEnabled = enableNewActivity;

        // Update was successful
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agent_definitions/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        JSONObject agentJson = getInputJson();

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent definition name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent definition name path parameter");
        if (!agentServer.users.containsKey(user.id))
            throw new AgentAppServerBadRequestException("Unknown user id");

        AgentDefinition agent = agentServer.agentDefinitions.get(user.id).get(agentName);
        log.info("Updating agent definition named: " + agentName + " for user: " + user.id);

        // Parse the updated agent definition info
        AgentDefinition newAgentDefinition = AgentDefinition.fromJson(agentServer, user, agentJson, true);

        // Update the agent definition info
        agent.update(agentServer, newAgentDefinition);

        // Update was successful
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        JSONObject agentJson = getInputJson();

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        AgentInstance agent = agentServer.agentInstances.get(user.id).get(agentName);
        String agentDefinitionName = agent.agentDefinition.name;
        log.info("Updating agent instance named: " + agentName + " with definition: " + agentDefinitionName
                + " for user: " + user.id);

        // Parse the updated agent instance info
        AgentInstance newAgentInstance = AgentInstance.fromJson(agentServer, user, agentJson,
                agent.agentDefinition, true);

        // Update the agent instance info
        agent.update(agentServer, newAgentInstance);

        // Update was successful
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/dismiss_exceptions$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        log.info("Dismissing exceptions for agent instance " + agentName + " for user: " + user.id);
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agent = agentMap.get(agentName);

        // Set the time of dismissal for exceptions
        agent.lastDismissedExceptionTime = System.currentTimeMillis();

        // Done
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches(
            "^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/notifications/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        String notificationName = pathParts.length >= 7 ? pathParts[6] : null;
        String responseParam = request.getParameter("response");
        String responseChoice = request.getParameter("response_choice");
        String comment = request.getParameter("comment");

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");
        if (notificationName == null)
            throw new AgentAppServerBadRequestException("Missing notification name path parameter");
        if (notificationName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty notification name path parameter");
        if (responseParam == null)
            throw new AgentAppServerBadRequestException("Missing response query parameter");
        if (responseParam.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty response query parameter");
        if (!NotificationInstance.responses.contains(responseParam))
            throw new AgentAppServerBadRequestException("Unknown response keyword query parameter");

        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agent = agentMap.get(agentName);

        NotificationInstance notificationInstance = agent.notifications.get(notificationName);
        if (notificationInstance == null)
            throw new AgentAppServerBadRequestException(
                    "Undefined notification name for agent instance '" + agentName + "': " + notificationName);
        if (!notificationInstance.pending)
            throw new AgentAppServerBadRequestException("Cannot respond to notification '" + notificationName
                    + "' for agent instance '" + agentName + "' since it is not pending");

        log.info("Respond to a pending notification '" + notificationName + "' for agent instance " + agentName
                + " for user: " + user.id);

        agent.respondToNotification(notificationInstance, responseParam, responseChoice, comment);

        // Done
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/(pause|disable)$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        log.info("Disabling/pausing agent instance " + agentName + " for user: " + user.id);
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agent = agentMap.get(agentName);

        // Disable/pause the agent
        agent.disable();

        // Done
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/(resume|enable)$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        log.info("Enabling/resuming agent instance " + agentName + " for user: " + user.id);
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agent = agentMap.get(agentName);

        // Enable/resume the agent
        agent.enable();

        // Done
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (lcPath
            .matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/run_script/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        String scriptName = pathParts[6];

        // Capture and convert the arguments to be passed to the script
        List<Value> arguments = new ArrayList<Value>();
        String[] argumentStrings = request.getParameterValues("arg");
        if (argumentStrings != null) {
            int numArgs = argumentStrings.length;
            for (int i = 0; i < numArgs; i++) {
                String argumentString = argumentStrings[i];
                Value argumentValue = JsonUtils.parseJson(argumentString);
                arguments.add(argumentValue);
            }
        }

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");
        if (scriptName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance script name path parameter");
        if (scriptName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance script name path parameter");

        ScriptDefinition scriptDefinition = agentServer.agentInstances.get(user.id)
                .get(agentName).agentDefinition.scripts.get(scriptName);
        if (scriptDefinition == null)
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "Undefined public agent script for that user: " + scriptName);
        if (!scriptDefinition.publicAccess)
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "Undefined public agent script for that user: " + scriptName);

        log.info("Call a public script for agent instance " + agentName + " for user: " + user.id);
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agent = agentMap.get(agentName);

        // Call the script
        List<ExceptionInfo> exceptions = agent.exceptionHistory;
        int numExceptions = exceptions.size();
        Value returnValue = agent.runScript(scriptName, arguments);

        // Check for exceptions
        int numExceptionsAfter = exceptions.size();
        if (numExceptions != numExceptionsAfter)
            handleException(400, exceptions.get(numExceptions).exception);
        else {
            // Done; successful
            JSONObject returnValueObject = new JSONObject();
            returnValueObject.put("return_value", returnValue.toJsonObject());
            setOutput(returnValueObject);
        }
    } else {
        throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                "Path does not address any existing object");
    }

    return true;

}

From source file:com.thinkberg.webdav.CopyMoveBase.java

/**
 * Handle a COPY or MOVE request.//from  w  w w  .ja  va 2s  .  co m
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error executing this request
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean overwrite = getOverwrite(request);
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());
    FileObject targetObject = getDestination(request);

    try {
        final LockManager lockManager = LockManager.getInstance();
        LockManager.EvaluationResult evaluation = lockManager.evaluateCondition(targetObject, getIf(request));
        if (!evaluation.result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        if ("MOVE".equals(request.getMethod())) {
            evaluation = lockManager.evaluateCondition(object, getIf(request));
            if (!evaluation.result) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return;
            }
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (null == targetObject) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (object.equals(targetObject)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (targetObject.exists()) {
        if (!overwrite) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        FileObject targetParent = targetObject.getParent();
        if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) {
            response.sendError(HttpServletResponse.SC_CONFLICT);
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
    }

    // delegate the actual execution to a sub class
    copyOrMove(object, targetObject, getDepth(request));
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.ClobDatatypeStorageController.java

@RequestMapping(method = RequestMethod.DELETE, value = "/{uuid}")
public void delete(@PathVariable("uuid") String uuid, HttpServletRequest request,
        HttpServletResponse response) {/*from   w  w w  .  j a  v a2 s  .co  m*/
    ClobDatatypeStorage clobData = datatypeService.getClobDatatypeStorageByUuid(uuid);
    if (clobData != null) {
        datatypeService.deleteClobDatatypeStorage(clobData);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}

From source file:edu.slu.tpen.servlet.LoginServlet.java

/**
 * Handles the HTTP <code>POST</code> method by logging in using the given credentials.  Credentials
 * should be specified as a JSON object in the request body.  There is also a deprecated way of passing
 * the credentials as query parameters./*w w w .  j  a va2 s.c o m*/
 *
 * @param req servlet request
 * @param resp servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String mail = null, password = null;
        if (req.getContentLength() > 0) {
            String contentType = getBaseContentType(req);
            if (contentType.equals("application/json")) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, String> creds = mapper.readValue(req.getInputStream(),
                        new TypeReference<Map<String, String>>() {
                        });
                mail = creds.get("mail");
                password = creds.get("password");
            }
        } else {
            // Deprecated approach where user-name and password are passed on the query string.
            mail = req.getParameter("uname");
            password = req.getParameter("password");
        }
        if (mail != null && password != null) {
            User u = new User(mail, password);
            if (u.getUID() > 0) {
                HttpSession sess = req.getSession(true);
                sess.setAttribute("UID", u.getUID());
            } else {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        } else if (mail == null && password == null) {
            // Passing null data indicates a logout.
            HttpSession sess = req.getSession(true);
            sess.removeAttribute("UID");
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            // Only supplied one of user-id and password.
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (NoSuchAlgorithmException ex) {
        reportInternalError(resp, ex);
    }
}

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

/**
 * Return the files and folders that are in the trash can.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
 * @throws IOException if the response cannot be sent
 * @throws ServletException//ww w.j  av  a 2 s.  com
 */
void serveTrash(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String path = getInnerPath(req, PATH_TRASH);
    if (path.equals(""))
        path = "/";

    if (!path.equals("/")) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    List<FileHeader> files = null;
    List<Folder> folders = null;
    User user = getUser(req);
    User owner = getOwner(req);
    if (!owner.equals(user)) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    try {
        files = getService().getDeletedFiles(user.getId());
        folders = getService().getDeletedRootFolders(user.getId());
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    if (files.isEmpty() && folders.isEmpty()) {
        resp.sendError(HttpServletResponse.SC_NO_CONTENT);
        return;
    }

    JSONObject json = new JSONObject();
    try {
        List<JSONObject> trashFolders = new ArrayList<JSONObject>();
        for (Folder f : folders) {
            JSONObject j = new JSONObject();
            j.put("name", f.getName()).put("uri", getApiRoot() + f.getURI());
            if (f.getParent() != null)
                j.put("parent", getApiRoot() + f.getParent().getURI());
            trashFolders.add(j);
        }
        json.put("folders", trashFolders);
        List<JSONObject> trashFiles = new ArrayList<JSONObject>();
        for (FileHeader f : files) {
            JSONObject j = new JSONObject();
            j.put("name", f.getName()).put("owner", f.getOwner().getUsername()).put("deleted", f.isDeleted())
                    .put("version", f.getCurrentBody().getVersion())
                    .put("size", f.getCurrentBody().getFileSize())
                    .put("content", f.getCurrentBody().getMimeType()).put("shared", f.getShared())
                    .put("versioned", f.isVersioned()).put("path", f.getFolder().getPath())
                    .put("creationDate", f.getAuditInfo().getCreationDate().getTime())
                    .put("modificationDate", f.getAuditInfo().getModificationDate().getTime())
                    .put("uri", getApiRoot() + f.getURI());
            JSONObject p = new JSONObject();
            p.put("uri", getApiRoot() + f.getFolder().getURI()).put("name",
                    URLEncoder.encode(f.getFolder().getName(), "UTF-8"));
            j.put("folder", p);
            trashFiles.add(j);
        }
        json.put("files", trashFiles);
    } catch (JSONException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Workaround for IE's broken caching behavior.
    resp.setHeader("Expires", "-1");
    sendJson(req, resp, json.toString());
}

From source file:com.google.api.server.spi.EndpointsServletTest.java

@Test
public void empty() throws IOException {
    req.setRequestURI("/_ah/api/test/v2/empty");
    req.setMethod("GET");

    servlet.service(req, resp);/*from w  w w .j  av  a  2s . c o m*/

    assertThat(resp.getStatus()).isEqualTo(HttpServletResponse.SC_NO_CONTENT);
}

From source file:org.opentestsystem.delivery.testreg.rest.StudentPackageController.java

@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/studentpackage", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
@Secured({ "ROLE_Entity Read" })
@ResponseBody/*w w  w. j ava2s . c om*/
public void extractStudentPackage(@RequestParam(value = "ssid", required = false) final String studentId,
        @RequestParam(value = "externalId", required = false) final String externalSsid,
        @RequestParam("stateabbreviation") final String stateAbbreviation, final HttpServletResponse response)
        throws IOException {
    StopWatch sw = new StopWatch();
    sw.start();
    Student student = null;

    if (hasText(studentId) && hasText(externalSsid)) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
    } else if (hasText(studentId)) {
        student = studentService.findByStudentIdAndStateAbbreviation(studentId, stateAbbreviation);
    } else if (hasText(externalSsid)) {
        student = studentService.findByExternalSsidAndStateAbbreviation(externalSsid, stateAbbreviation);
    }

    if (student != null) {
        String studentPackage = studentPackageService.exportStudentPackage(student);
        response.setContentType(MediaType.APPLICATION_XML_VALUE);
        ServletOutputStream out = response.getOutputStream();
        IOUtils.copy(new ByteArrayInputStream(studentPackage.getBytes()), out);
        out.flush();
    } else {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
    sw.stop();
    this.metricClient.sendPerformanceMetricToMna("StudentPackage for " + externalSsid + " (ms) ", sw.getTime());
}

From source file:org.efaps.webdav4vfs.handler.AbstractCopyMoveBaseHandler.java

/**
 * Handle a COPY or MOVE request./*from  w  w  w.  j  ava 2  s. co m*/
 *
 * @param _request      HTTP servlet request
 * @param _response     HTTP servlet response
 * @throws IOException if there is an error executing this request
 */
@Override
public void service(final HttpServletRequest _request, final HttpServletResponse _response) throws IOException {
    boolean overwrite = getOverwrite(_request);
    FileObject object = VFSBackend.resolveFile(_request.getPathInfo());
    FileObject targetObject = getDestination(_request);

    try {
        final LockManager lockManager = LockManager.getInstance();
        LockManager.EvaluationResult evaluation = lockManager.evaluateCondition(targetObject, getIf(_request));
        if (!evaluation.result) {
            _response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        if ("MOVE".equals(_request.getMethod())) {
            evaluation = lockManager.evaluateCondition(object, getIf(_request));
            if (!evaluation.result) {
                _response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return;
            }
        }
    } catch (LockException e) {
        _response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        _response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (null == targetObject) {
        _response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (object.equals(targetObject)) {
        _response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (targetObject.exists()) {
        if (!overwrite) {
            _response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        _response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        FileObject targetParent = targetObject.getParent();
        if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) {
            _response.sendError(HttpServletResponse.SC_CONFLICT);
        }
        _response.setStatus(HttpServletResponse.SC_CREATED);
    }

    // delegate the actual execution to a sub class
    this.copyOrMove(object, targetObject, getDepth(_request));
}