Example usage for javax.servlet.http HttpServletResponse sendError

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

Introduction

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

Prototype

public void sendError(int sc) throws IOException;

Source Link

Document

Sends an error response to the client using the specified status code and clears the buffer.

Usage

From source file:org.magnum.dataup.CopyOfMyVideoController.java

@RequestMapping(value = "/video/{id}/data", method = RequestMethod.POST)
public VideoStatus setVideoData(Long id, TypedFile videoData, HttpServletResponse response) throws IOException {

    System.out.println("setVideoData() id - " + id);
    if (id < 1 || id > no_ids || videoData.length() < 1) {
        response.sendError(404);
        return (new VideoStatus(VideoState.READY));
    }/*from   w ww .  j a va  2  s.co  m*/

    Video v = videos.get((int) (id - 1));

    if (v == null) {
        response.sendError(404);
        return (new VideoStatus(VideoState.READY));
    }

    VideoFileManager vfm = VideoFileManager.get();
    vfm.saveVideoData(v, videoData.in());

    return (new VideoStatus(VideoState.READY));
}

From source file:com.attribyte.essem.BasicAuth.java

@Override
public void sendUnauthorized(final String index, final HttpServletResponse response) throws IOException {
    response.setHeader(WWW_AUTHENTICATE_HEADER, "Basic realm=" + "\"" + index + "\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

From source file:info.magnolia.cms.servlets.Spool.java

/**
 * All static resource requests are handled here.
 *
 * @param request  HttpServletRequest//  w w  w. jav  a2  s  . co m
 * @param response HttpServletResponse
 * @throws IOException for error in accessing the resource or the servlet output stream
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    File resource = new File(getServletContext().getRealPath(Path.getURI(request)));
    if (!resource.exists() || resource.isDirectory()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    this.setResponseHeaders(resource, response);
    boolean success = this.spool(resource, response);
    if (!success && !response.isCommitted()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:fr.aliasource.webmail.server.DownloadAttachmentsImpl.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*from w  ww  .  java 2  s.  c  o  m*/
    }

    String[] items = req.getRequestURI().split("/");
    String atId = null;

    boolean dl = false;
    boolean preview = false;
    for (String s : items) {
        if (s.startsWith("at_")) {
            atId = s;
        } else if (s.equals("download")) {
            dl = true;
        } else if (s.equals("preview")) {
            dl = false;
            preview = true;
        }
    }
    logger.info("[" + account.getLogin() + "] " + (dl ? "download" : "view") + " of attachment id: " + atId
            + " uri: " + req.getRequestURI().split("/"));

    AttachmentMetadata[] metas = account.getAttachementsMetadata(new String[] { atId });

    if (!preview) {
        resp.setHeader("Content-Type", (dl ? "application/octet-stream" : metas[0].getMime()));
    } else {
        resp.setHeader("Content-Type", metas[0].getPreviewMime());
    }
    if (!preview) {
        resp.setHeader("Content-Length", "" + metas[0].getSize());
    }

    OutputStream out = resp.getOutputStream();
    InputStream in = account.downloadAttachement(atId + (preview ? ".preview" : ""));
    transfer(in, out, true);
}

From source file:cz.fi.muni.xkremser.editor.server.AuthenticationServlet.java

private void requrireAuthentication(HttpServletResponse resp) throws IOException {
    resp.setHeader("WWW-Authenticate", "BASIC realm=\"users\"");
    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

From source file:org.simbasecurity.core.service.http.DBViewer.java

@Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    if (enabled == null || !Boolean.valueOf(enabled)) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }//from  w  w  w.  j  a  v  a 2s . co  m

    resp.setContentType("text/html");

    String table = req.getParameter("table");
    String query = req.getParameter("query");
    boolean asSQL = req.getParameter("asSQL") != null;
    PrintWriter out = resp.getWriter();
    printHeader(out);
    printForm(out, req.getRequestURI(), table, asSQL, query);

    if (!StringUtil.isEmpty(table)) {
        if (asSQL) {
            printRecordsAsSQL(out, table);
        } else {
            printRecords(out, "SELECT * FROM " + table);
        }
    } else if (!StringUtil.isEmpty(query)) {
        printRecords(out, query);
    }
    printFooter(out);
    out.close();

    return null;
}

From source file:jetbrains.buildServer.projectPush.PostProjectToSandboxController.java

@Nullable
@Override/*from w  w w  .j a va2  s  .  co m*/
protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
        throws Exception {
    if (!isPost(request)) {
        response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value());
        return null;
    }

    final StringBuilder stringBuffer = new StringBuilder();
    try {
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            stringBuffer.append(line);
    } catch (Exception e) {
        response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
        return null;
    }

    final String projectName = stringBuffer.toString();
    if (projectName.isEmpty()) {
        response.sendError(HttpStatus.BAD_REQUEST.value(), "Project name is empty.");
        return null;
    }

    if (mySettings.isDisabled()) {
        response.sendError(HttpStatus.FORBIDDEN.value(), "Sandbox disabled.");
        return null;
    }

    SUser user;
    user = SessionUser.getUser(request);
    if (user == null) {
        user = myAuthHelper.getAuthenticatedUser(request, response);
    }
    if (user == null)
        return null;

    final Role projectAdminRole = myRolesHelper.findProjectAdminRole();
    if (projectAdminRole == null) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "Failed to locate Project Admin role on the server.");
        return null;
    }

    final SProject project;
    try {
        final String sandboxProjectId = mySettings.getSandboxProjectId();
        final SProject sandboxProject = myProjectManager.findProjectByExternalId(sandboxProjectId);
        if (sandboxProject == null) {
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                    "Failed to locate sandbox project by ID " + sandboxProjectId);
            return null;
        }

        if (sandboxProject.findProjectByName(projectName) != null) {
            response.sendError(HttpStatus.CONFLICT.value(),
                    "Project with name " + projectName + " already exists.");
            return null;
        }

        project = sandboxProject.createProject(
                myProjectIdentifiersManager.generateNewExternalId(null, projectName, null), projectName);
        project.persist();
    } catch (Exception e) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        return null;
    }

    try {
        myRolesHelper.addRole(user, RoleScope.projectScope(project.getProjectId()), projectAdminRole);
    } catch (Throwable throwable) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), throwable.getMessage());
        return null;
    }

    response.setStatus(HttpStatus.CREATED.value());
    response.setHeader(HttpHeaders.LOCATION, RESTApiHelper.getProjectURI(project));

    return null;
}

From source file:com.mirth.connect.server.servlets.CodeTemplateServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {/*from w  w  w .  ja  va2s .c om*/
        try {
            CodeTemplateController codeTemplateController = ControllerFactory.getFactory()
                    .createCodeTemplateController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (operation.equals(Operations.CODE_TEMPLATE_GET)) {
                CodeTemplate codeTemplate = (CodeTemplate) serializer
                        .fromXML(request.getParameter("codeTemplate"));
                parameterMap.put("codeTemplate", codeTemplate);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(codeTemplateController.getCodeTemplate(codeTemplate), out);
                }
            } else if (operation.equals(Operations.CODE_TEMPLATE_UPDATE)) {
                List<CodeTemplate> codeTemplates = (List<CodeTemplate>) serializer
                        .fromXML(request.getParameter("codeTemplates"));
                parameterMap.put("codeTemplates", codeTemplates);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    codeTemplateController.updateCodeTemplates(codeTemplates);
                }
            } else if (operation.equals(Operations.CODE_TEMPLATE_REMOVE)) {
                CodeTemplate codeTemplate = (CodeTemplate) serializer
                        .fromXML(request.getParameter("codeTemplate"));
                parameterMap.put("codeTemplate", codeTemplate);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    codeTemplateController.removeCodeTemplate(codeTemplate);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:com.ocpsoft.pretty.faces.beans.ParameterValidator.java

private void handleValidationFailure(final FacesContext context, final FacesMessage message, String onError) {
    boolean continueToFaces = false;
    if ((onError != null) && !"".equals(onError.trim())) {
        if (elUtils.isEl(onError)) {
            Object result = elUtils.invokeMethod(context, onError);
            if (result == null) {
                continueToFaces = true;/*from w  w  w.  j  av  a  2s  . c o m*/
            } else {
                onError = result.toString();
            }
        }

        if (onError != null) {
            String viewId = context.getViewRoot().getViewId();
            context.getApplication().getNavigationHandler().handleNavigation(context, viewId, onError);
        }
    }

    if (!context.getResponseComplete() && !continueToFaces) {
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            context.responseComplete();
        } catch (IOException e1) {
            throw new PrettyException(e1);
        }
    }
}

From source file:com.mirth.connect.server.servlets.DatabaseTaskServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {//from   www  .  j  a va 2 s  .  c o  m
        try {
            DatabaseTaskController databaseTaskController = ControllerFactory.getFactory()
                    .createDatabaseTaskController();
            ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            ServerEventContext context = new ServerEventContext();
            context.setUserId(getCurrentUserId(request));

            if (operation.equals(Operations.DATABASE_TASKS_GET)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    serializer.serialize(databaseTaskController.getDatabaseTasks(), out);
                }
            } else if (operation.equals(Operations.DATABASE_TASK_RUN)) {
                DatabaseTask databaseTask = serializer
                        .deserialize((String) request.getParameter("databaseTask"), DatabaseTask.class);
                parameterMap.put("databaseTask", databaseTask);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    String result = databaseTaskController.runDatabaseTask(databaseTask);
                    if (StringUtils.isNotBlank(result)) {
                        out.write(result);
                    }
                }
            } else if (operation.equals(Operations.DATABASE_TASK_CANCEL)) {
                DatabaseTask databaseTask = serializer
                        .deserialize((String) request.getParameter("databaseTask"), DatabaseTask.class);
                parameterMap.put("databaseTask", databaseTask);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    databaseTaskController.cancelDatabaseTask(databaseTask);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}