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.haulmont.cuba.web.controllers.StaticContentController.java

@RequestMapping(method = RequestMethod.HEAD)
public String handleHeadRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/* ww  w .  jav  a  2s .c  o  m*/
        lookup(request).respondHead(request, response);
    } catch (UnsupportedOperationException e) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }
    return null;
}

From source file:com.bosch.cr.integration.helloworld.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*  w w w.j  a  v a 2s  .co m*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.commercehub.dropwizard.BuildInfoServlet.java

private void writeValueForKey(String requestedKey, HttpServletResponse response) throws IOException {
    String value = manifestAttributes.getProperty(requestedKey);
    if (StringUtils.isNotBlank(value)) {
        response.setContentType(MediaType.TEXT_PLAIN);
        response.getWriter().print(value);
    } else {//from  w ww  .ja v a 2  s .  c  om
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for CR\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*from  w w  w  . j  a v a2 s.c  om*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

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

@RequestMapping(value = "/video/{id}/data", method = RequestMethod.GET)
HttpServletResponse getData(@PathVariable(value = "id") long id, HttpServletResponse response)
        throws IOException {
    //don't have the data: response.state == 404 
    videoFileManager = (null == videoFileManager) ? VideoFileManager.get() : videoFileManager;
    if (!videos.containsKey(id) || !videoFileManager.hasVideoData(videos.get(id))) {
        response.sendError(404);
        return response;
    }/* w  ww.  j a va  2s .c o  m*/

    //successful: response.state == 200
    videoFileManager.copyVideoData(videos.get(id), response.getOutputStream());
    response.setStatus(200);
    return response;
}

From source file:com.bosch.cr.examples.inventorybrowser.server.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*from w  w  w  .  ja  v  a 2  s.  c  o  m*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", props.getProperty("apiToken"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());

    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

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

/**
 * Handle a PROPPATCH request.//from ww w .  j  a v a 2 s.c o m
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).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 (object.exists()) {
        SAXReader saxReader = new SAXReader();
        try {
            Document propDoc = saxReader.read(request.getInputStream());
            logXml(propDoc);

            Element propUpdateEl = propDoc.getRootElement();
            List<Element> requestedProperties = new ArrayList<Element>();
            for (Object elObject : propUpdateEl.elements()) {
                Element el = (Element) elObject;
                String command = el.getName();
                if (AbstractDavResource.TAG_PROP_SET.equals(command)
                        || AbstractDavResource.TAG_PROP_REMOVE.equals(command)) {
                    for (Object propElObject : el.elements()) {
                        for (Object propNameElObject : ((Element) propElObject).elements()) {
                            Element propNameEl = (Element) propNameElObject;
                            requestedProperties.add(propNameEl);
                        }
                    }
                }
            }

            // respond as XML encoded multi status
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(SC_MULTI_STATUS);

            Document multiStatusResponse = getMultiStatusResponse(object, requestedProperties,
                    getBaseUrl(request));

            logXml(multiStatusResponse);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(multiStatusResponse);
            writer.flush();
            writer.close();

        } catch (DocumentException e) {
            LOG.error("invalid request: " + e.getMessage());
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        LOG.error(object.getName().getPath() + " NOT FOUND");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:cz.incad.kramerius.client.CacheServlet.java

private void proccesRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String action = req.getParameter("action");
    resp.setContentType("text/plain;charset=utf-8");
    if ("save".equals(action)) {
        saveToFile(req, resp);//from   w  w  w . ja  va 2 s .c  om
    } else if ("get".equals(action)) {
        loadFromFile(req, resp);
    } else {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.haulmont.cuba.restapi.FileUploadController.java

protected FileDescriptor getFileDescriptor(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String name = request.getParameter("name");
    if (name == null) {
        log.error("'name' request parameter is not specified");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }/*  w w  w.j  a va  2 s  .c  om*/

    String ext = request.getParameter("ext");
    if (ext == null) {
        log.error("'ext' request parameter is not specified");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    String size = request.getParameter("size");

    FileDescriptor fd = metadata.create(FileDescriptor.class);
    fd.setName(name);
    fd.setExtension(ext);
    fd.setCreateDate(timeSource.currentTimestamp());
    if (size != null) {
        fd.setSize(Long.parseLong(size));
    }

    return fd;
}

From source file:fr.univlille2.ecm.drive.BasicDriveAuthenticator.java

public Boolean handleLoginPrompt(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        String baseURL) {//from ww w  .  j  a  v a 2 s . c  o  m
    logger.debug(BasicDriveAuthenticator.class.getSimpleName() + " : handleLoginPrompt");
    try {
        String baHeader = "Basic realm=\"" + realmName + '\"';
        httpResponse.addHeader(BA_HEADER_NAME, baHeader);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return true;
    } catch (IOException e) {
        return false;
    }
}