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:com.webtide.jetty.load.generator.web.MonitorServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (_restrictToLocalhost) {
        if (!isLoopbackAddress(req.getRemoteAddr())) {
            resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }/*from  w w w  .  ja va 2 s . co  m*/
    }

    if (Boolean.valueOf(req.getParameter("start"))) {
        start = platformMonitor.start();
        return;
    }

    if (Boolean.valueOf(req.getParameter("stop"))) {
        stop = platformMonitor.stop();
        return;
    }

    if (Boolean.valueOf(req.getParameter("stats"))) {
        if (start == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (stop == null) {
            stop = platformMonitor.stop();
        }
        sendResponse(resp);
    }
}

From source file:uk.org.iay.mdq.server.ResultRawView.java

@Override
public void render(final Map<String, ?> model, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final Result result = (Result) model.get("result");
    log.debug("rendering as {}", getContentType());

    if (result.isNotFound()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from  w ww  .  ja  v  a 2s .c  om*/
    }

    // select the representation to provide
    Representation rep = null;
    final String acceptEncoding = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
    if (acceptEncoding != null) {
        if (acceptEncoding.contains("gzip")) {
            rep = result.getGZIPRepresentation();
        } else if (acceptEncoding.contains("compress")) {
            rep = result.getDeflateRepresentation();
        }
    }

    // default to the normal representation
    if (rep == null) {
        rep = result.getRepresentation();
    }

    // Set response headers
    String contentEncoding = rep.getContentEncoding();
    if (contentEncoding != null) {
        response.setHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding);
    } else {
        // for logging only
        contentEncoding = "normal";
    }
    response.setContentType(getContentType());
    response.setContentLength(rep.getBytes().length);
    response.setHeader(HttpHeaders.ETAG, rep.getETag());

    log.debug("selected ({}) representation is {} bytes", contentEncoding, rep.getBytes().length);

    response.getOutputStream().write(rep.getBytes());
}

From source file:de.mpg.escidoc.services.aa.web.client.BasicAaClient.java

private boolean testLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String auth = request.getHeader("authorization");
    if (auth == null) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"Validation Service\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } else {//from   w w w . ja  v a  2  s.  c  om
        auth = auth.substring(6);
        String cred = new String(Base64.decodeBase64(auth.getBytes()));
        if (cred.contains(":")) {

            String[] userPass = cred.split(":");
            String userName = "admin";
            String password = "nimda";

            if (!userPass[0].equals(userName) || !userPass[1].equals(password)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return false;
            } else {
                return true;
            }
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
    }
}

From source file:com.sesnu.orion.web.controller.DuLicenseController.java

@RequestMapping(value = "/api/user/lic/{state}", method = RequestMethod.PUT)
public @ResponseBody List<DuLicenseView> updateItem(HttpServletResponse response,
        @PathVariable("state") String state, @RequestBody DuLicense lic2) throws Exception {

    if (licDAO.get(lic2.getId()) == null) {
        response.sendError(400);
        return null;
    }//from  w  w  w  . ja va 2s.c om

    lic2 = setExpireDate(lic2);
    licDAO.saveOrUpdate(lic2);
    List<DuLicenseView> licenses = null;

    if (state.equals("all")) {
        licenses = licDAO.listAll();
    } else {
        licenses = licDAO.listByOrderId(lic2.getOrderRef());
    }
    if (licenses.size() > 0) {
        return licenses;
    }
    response.sendError(404);
    return null;

}

From source file:eu.freme.broker.security.SecurityConfig.java

@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return new AuthenticationEntryPoint() {

        @Override//from  w  w  w .j  a v a 2s.  co  m
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    };
}

From source file:com.pureinfo.tgirls.servlet.GetScriptServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String scriptType = request.getParameter("scriptType");
    if (StringUtils.isEmpty(scriptType)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//from   www .  j  ava  2s.  c om
    }

    String location = null;
    String userId = null;
    String photoId = null;
    ScriptType st = null;//

    try {
        st = ScriptType.getScriptType(Integer.parseInt(scriptType));
    } catch (Exception e) {
    }

    switch (st) {
    case UserInfo:
        userId = request.getParameter("utid");
        location = ScriptManager.mapUserInfoScriptLocation(userId);
        break;
    case UserUpload:
        userId = request.getParameter("utid");
        location = ScriptManager.mapUserUploadScriptLocation(userId);
        break;
    case UserBuy:
        userId = request.getParameter("utid");
        location = ScriptManager.mapUserBuyScriptLocation(userId);
        break;
    case Pic:
        photoId = request.getParameter("picId");
        location = ScriptManager.mapPhotoScriptLocation(photoId);
        break;

    default:
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (StringUtils.isEmpty(location)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    location += "?version=" + Math.random();
    logger.debug("return script:" + location);

    response.setHeader("Location", location);
    response.setHeader("Content-Encoding", "gzip");
    response.setStatus(HttpServletResponse.SC_SEE_OTHER);
    response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    response.setHeader("Pragma", "no-cache"); //HTTP 1.0
    response.setDateHeader("Expires", -1);
    response.setDateHeader("max-age", 0);

    return;

}

From source file:uk.urchinly.wabi.expose.DownloadController.java

@RequestMapping(value = "/download/{assetId}", method = RequestMethod.GET)
public void download(HttpServletResponse response, @PathVariable("assetId") String assetId) throws IOException {

    Asset asset = this.assetMongoRepository.findOne(assetId);

    if (asset == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from  w  ww.j a va2  s. c o  m*/
    }

    File file = new File(appSharePath, asset.getFileName());

    if (file.canRead()) {
        this.rabbitTemplate.convertAndSend(MessagingConstants.USAGE_ROUTE,
                new UsageEvent("download asset", asset.toString()));

        response.setContentType(asset.getContentType());
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } else {
        logger.warn("File '{}' not found.", file.getAbsolutePath());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:aiai.ai.launchpad.server.ServerController.java

private HttpEntity<String> returnEmptyStringWithStatus(HttpServletResponse response, int status)
        throws IOException {
    response.sendError(status);
    return new HttpEntity<>("", getHeader(0));
}

From source file:com.googlesource.gerrit.plugins.gitblit.auth.GerritAuthenticationFilter.java

public boolean filterBasicAuth(HttpServletRequest request, HttpServletResponse response, String hdr)
        throws IOException, UnsupportedEncodingException {
    if (!hdr.startsWith(LIT_BASIC)) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }//w ww.j a v a 2  s.  c o  m

    final byte[] decoded = new Base64().decode(hdr.substring(LIT_BASIC.length()).getBytes());
    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }
    String usernamePassword = new String(decoded, encoding);
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }
    request.setAttribute("gerrit-username", usernamePassword.substring(0, splitPos));
    request.setAttribute("gerrit-password", usernamePassword.substring(splitPos + 1));

    return true;
}

From source file:com.googlesource.gerrit.plugins.gitblit.auth.GerritAuthFilter.java

public boolean filterBasicAuth(HttpServletRequest request, HttpServletResponse response, String hdr)
        throws IOException, UnsupportedEncodingException {
    if (!hdr.startsWith(LIT_BASIC)) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }/*from w w  w. j  a  v  a 2s .  c o  m*/

    final byte[] decoded = new Base64().decode(hdr.substring(LIT_BASIC.length()).getBytes());
    String usernamePassword = new String(decoded,
            Objects.firstNonNull(request.getCharacterEncoding(), "UTF-8"));
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }
    request.setAttribute("gerrit-username", usernamePassword.substring(0, splitPos));
    request.setAttribute("gerrit-password", usernamePassword.substring(splitPos + 1));

    return true;
}