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, String msg) throws IOException;

Source Link

Document

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

Usage

From source file:com.cradiator.TeamCityStatusPlugin.BuildMonitorController.java

protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (requestHasParameter(request, PROJECT_ID))
        return showProject(request.getParameter(PROJECT_ID), response);
    else if (requestHasParameter(request, BUILD_TYPE_ID))
        return showBuild(request.getParameter(BUILD_TYPE_ID), response);
    else {// w w  w  .  j  a  v  a 2s  .  c  om
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no project id or buildTypeId specified");
        return null;
    }
}

From source file:gsn.http.AddressingReqHandler.java

public boolean isValid(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String vsName = request.getParameter("name");

    //Added by Behnaz
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");

    if (vsName == null || vsName.trim().length() == 0) {
        response.sendError(WebConstants.MISSING_VSNAME_ERROR, "The virtual sensor name is missing");
        return false;
    }// w ww . ja  v  a  2  s .co m
    VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName);
    if (sensorConfig == null) {
        response.sendError(WebConstants.ERROR_INVALID_VSNAME, "The specified virtual sensor doesn't exist.");
        return false;
    }

    //Added by Behnaz.
    if (Main.getContainerConfig().isAcEnabled() == true) {
        if (user != null) // meaning, that a login session is active, otherwise we couldn't get there
            if (user.hasReadAccessRight(vsName) == false && user.isAdmin() == false) // ACCESS_DENIED
            {
                response.sendError(WebConstants.ACCESS_DENIED,
                        "Access denied to the specified virtual sensor .");
                return false;
            }

    }
    return true;
}

From source file:com.gst.infrastructure.security.service.CustomAuthenticationFailureHandler.java

/**
 * Performs the redirect or forward to the {@code defaultFailureUrl} if set,
 * otherwise returns a 401 error code.// www.  j a  v  a  2 s .  com
 * <p>
 * If redirecting or forwarding, {@code saveException} will be called to
 * cache the exception for use in the target view.
 */
@Override
public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException exception) throws IOException, ServletException {

    if (this.defaultFailureUrl == null) {
        this.logger.debug("No failure URL set, sending 401 Unauthorized error");

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Authentication Failed: " + exception.getMessage());
    } else {
        saveException(request, exception);

        if (this.forwardToDestination) {
            this.logger.debug("Forwarding to " + this.defaultFailureUrl);

            request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);
        } else {
            this.logger.debug("Redirecting to " + this.defaultFailureUrl);

            final String oauthToken = request.getParameter("oauth_token");
            request.setAttribute("oauth_token", oauthToken);
            final String url = this.defaultFailureUrl + "?oauth_token=" + oauthToken;
            this.redirectStrategy.sendRedirect(request, response, url);
        }
    }
}

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

/**
 * POST /video/*from  ww  w.  j a  v  a  2  s.c  o m*/
 * 
 * The video metadata is provided as an application/json request
 * body. The JSON should generate a valid instance of the 
 * Video class when deserialized by Spring's default 
 * Jackson library.
 * 
 * Returns the JSON representation of the Video object that
 * was stored along with any updates to that object made by the server.
 * @param video
 * @return
 * @throws IOException 
 */
@RequestMapping(value = VIDEO_SVC_PATH, method = RequestMethod.POST)
public @ResponseBody Video addVideo(@RequestBody Video v, HttpServletResponse response) throws IOException {

    try {
        save(v);
        v.setDataUrl(getDataUrl(v.getId()));
        return v;
    } catch (Throwable e) {
        response.sendError(404, ERROR_MSG);
        return v;
    }

}

From source file:com.lushapp.common.web.servlet.RemoteContentServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ??// www  .  ja  va 2s.c o  m
    String contentUrl = request.getParameter("contentUrl");
    if (StringUtils.isBlank(contentUrl)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "contentUrl parameter is required.");
    }

    // ??
    String client = request.getParameter("client");

    InputStream input = null;
    if ("apache".equals(client)) {
        // Apache HttpClient
        fetchContentByApacheHttpClient(response, contentUrl);
    } else {
        // JDK HttpUrlConnection
        fetchContentByJDKConnection(response, contentUrl);
    }
}

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

private void loadFromFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    try {//w  ww. java 2 s  .c o  m
        String filename = getPath() + req.getParameter("f");
        File f = new File(filename);
        resp.getWriter().write(FileUtils.readFileToString(f, "UTF-8"));
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not load file: " + e.toString());
    }
}

From source file:annis.gui.servlets.ResourceServlet.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream outStream = response.getOutputStream();

    String completePath = request.getPathInfo();

    if (completePath == null) {
        response.sendError(404, "must provide a valid and existing path with a vistype");
        return;//  w w  w .j a  v a 2s  .c  om
    }

    // remove trailing /
    completePath = completePath.substring(1);

    String[] pathComponents = completePath.split("/");

    String vistype = pathComponents[0];

    if (pathComponents.length < 2) {
        response.sendError(404, "must provide a valid and existing path");
        return;
    }

    String path = StringUtils.join(Arrays.copyOfRange(pathComponents, 1, pathComponents.length), "/");

    // get the visualizer for this vistype
    ResourcePlugin vis = resourceRegistry.get(vistype);
    if (vis == null) {
        response.sendError(500, "There is no resource with the short name " + vistype);
    } else if (path.endsWith(".class")) {
        response.sendError(403, "illegal class path access");
    } else {
        URL resource = vis.getClass().getResource(path);
        if (resource == null) {
            response.sendError(404, path + " not found");
        } else {
            // check if it is new
            URLConnection resourceConnection = resource.openConnection();
            long resourceLastModified = resourceConnection.getLastModified();
            long requestLastModified = request.getDateHeader("If-Modified-Since");
            if (requestLastModified != -1 && resourceLastModified <= requestLastModified) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            } else {
                response.addDateHeader("Last-Modified", resourceLastModified);
                if ("localhost".equals(request.getServerName())) {
                    // does always expire right now
                    response.addDateHeader("Expires", new Date().getTime());
                } else {
                    // expires in one minute per default
                    response.addDateHeader("Expires", new Date().getTime() + 60000);
                }
                // not in cache, stream out
                String mimeType = getServletContext().getMimeType(path);
                response.setContentType(mimeType);
                if (mimeType.startsWith("text/")) {
                    response.setCharacterEncoding("UTF-8");
                }
                OutputStream bufferedOut = new BufferedOutputStream(outStream);
                InputStream resourceInStream = new BufferedInputStream(resource.openStream());

                try {
                    int v = -1;
                    while ((v = resourceInStream.read()) != -1) {
                        bufferedOut.write(v);
                    }
                } finally {
                    resourceInStream.close();
                    bufferedOut.flush();
                    outStream.flush();
                }
            }
        }
    }

}

From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java

/**
 * Mtodo que se puede overridear en el caso de necesitar otro comportamiento al
 * producirse un error de conexin./*from www .  j a v  a2 s  .c  o  m*/
 * 
 * @param request
 * @param response
 * @param method
 * @param e
 * @throws Exception .
 */
protected void onConnectionException(final HttpServletRequest request, final HttpServletResponse response,
        final HttpMethod method, final ConnectException e) throws Exception {
    response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
}

From source file:com.netflix.spinnaker.fiat.controllers.RolesController.java

@RequestMapping(value = "/sync", method = RequestMethod.POST)
public long sync(HttpServletResponse response, @RequestBody(required = false) List<String> specificRoles)
        throws IOException {
    if (specificRoles == null) {
        log.info("Full role sync invoked by web request.");
        long count = syncer.syncAndReturn();
        if (count == 0) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "Error occurred syncing permissions. See Fiat Logs.");
        }/* ww  w . j  a  va  2  s.  co m*/
        return count;
    }

    log.info("Web request role sync of roles: " + String.join(",", specificRoles));
    Map<String, UserPermission> affectedUsers = permissionsRepository.getAllByRoles(specificRoles);
    if (affectedUsers.size() == 0) {
        log.info("No users found with specified roles");
        return 0;
    }
    return syncer.updateUserPermissions(affectedUsers);
}

From source file:com.xyxy.platform.examples.showcase.demos.web.StaticContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ??//from  w  w  w. ja  v a2 s. co  m
    String contentPath = request.getParameter("contentPath");
    if (StringUtils.isBlank(contentPath)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "contentPath parameter is required.");
        return;
    }

    // ??.
    ContentInfo contentInfo = getContentInfo(contentPath);

    // ?EtagModifiedSince Header?, ??304,.
    if (!Servlets.checkIfModifiedSince(request, response, contentInfo.lastModified)
            || !Servlets.checkIfNoneMatchEtag(request, response, contentInfo.etag)) {
        return;
    }

    // Etag/
    Servlets.setExpiresHeader(response, Servlets.ONE_YEAR_SECONDS);
    Servlets.setLastModifiedHeader(response, contentInfo.lastModified);
    Servlets.setEtag(response, contentInfo.etag);

    // MIME
    response.setContentType(contentInfo.mimeType);

    // ?Header
    if (request.getParameter("download") != null) {
        Servlets.setFileDownloadHeader(request, response, contentInfo.fileName);
    }

    // OutputStream
    OutputStream output;
    if (checkAccetptGzip(request) && contentInfo.needGzip) {
        // outputstream, http1.1 trunked??content-length.
        output = buildGzipOutputStream(response);
    } else {
        // outputstream, content-length.
        response.setContentLength(contentInfo.length);
        output = response.getOutputStream();
    }

    // ?,?input file
    FileUtils.copyFile(contentInfo.file, output);
    output.flush();
}