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:net.sf.appstatus.web.StatusWebHandler.java

/**
 * Handle a GET request.//from  ww w. ja v a 2s . c  o  m
 *
 * @param req
 * @param resp
 * @throws IOException
 */
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    if (allowIp != null) {
        if (!req.getRemoteAddr().equals(allowIp)) {
            resp.sendError(401, "IP not authorized");
            return;
        }
    }

    if (req.getParameter("icon") != null || req.getParameter("resource") != null) {
        Resources.doGet(this, req, resp);
        return;
    }

    if (req.getParameter("p") != null && pages.containsKey(req.getParameter("p"))) {
        pages.get(req.getParameter("p")).doGet(this, req, resp);

    } else {
        pages.get("status").doGet(this, req, resp);
    }
}

From source file:org.loklak.api.server.GraphServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RemoteAccess.Post post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;//w  w w .  ja va 2s . c om
    }

    // parameters
    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    boolean minified = post.get("minified", false);
    String[] screen_names = post.get("screen_name", "").split(",");
    String followers = screen_names.length == 1 ? post.get("followers", "0") : "0";
    String following = screen_names.length == 1 ? post.get("following", "0") : "0";
    int maxFollowers = Integer.parseInt(followers);
    int maxFollowing = Integer.parseInt(following);

    List<Map<String, Object>> twitterUserEntries = new ArrayList<>();
    for (String screen_name : screen_names) {
        try {
            Map<String, Object> twitterUserEntry = TwitterAPI.getUser(screen_name, false);
            if (twitterUserEntry != null)
                twitterUserEntries.add(twitterUserEntry);
        } catch (TwitterException e) {
        }
    }
    Map<String, Object> topology = null;
    try {
        topology = TwitterAPI.getNetwork(screen_names[0], maxFollowers, maxFollowing);
    } catch (TwitterException e) {
    }

    post.setResponse(response, "application/javascript");

    // generate json
    Map<String, Object> m = new LinkedHashMap<>();
    m.put("edges", post.getClientHost());

    if (twitterUserEntries.size() == 1)
        m.put("user", twitterUserEntries.iterator().next());
    if (twitterUserEntries.size() > 1)
        m.put("users", twitterUserEntries);
    if (topology != null)
        m.put("topology", topology);

    // write json
    FileHandler.setCaching(response, 10);
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print((minified ? new ObjectMapper().writer() : new ObjectMapper().writerWithDefaultPrettyPrinter())
            .writeValueAsString(m));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:org.craftercms.security.utils.handlers.AbstractRestHandlerBase.java

protected <T> void sendObject(int status, T responseBody, RequestContext context) throws IOException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    response.setStatus(status);//w w w. j a v a 2  s  .com

    try {
        responseWriter.writeWithMessageConverters(responseBody, request, response);
    } catch (HttpMediaTypeNotAcceptableException e) {
        logger.error(e.getMessage(), e);

        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }
}

From source file:org.piraso.server.spring.web.PirasoServlet.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter(SERVICE_PARAMETER) == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request Parameter 'service' is required.");
        return;// w  ww .jav a2s  .  c om
    }

    User user = getRegistry().createOrGetUser(new PirasoHttpServletRequest(request));

    if (SERVICE_GET_REGISTRY_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        retrieveRegistry(response);
    } else if (SERVICE_LOG_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        log(request);
        writeResponse(response, PLAIN_CONTENT_TYPE, "OK");
    } else if (SERVICE_REQUEST_ID_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        writeResponse(response, PLAIN_CONTENT_TYPE, String.valueOf(PirasoContextIDGenerator.INSTANCE.next()));
    } else if (SERVICE_START_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        startLoggerService(request, response, user);
    } else if (SERVICE_STOP_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        stopService(response, user);
        writeResponse(response, PLAIN_CONTENT_TYPE, "OK");
    } else if (SERVICE_TEST_PARAMETER_VALUE.equals(request.getParameter(SERVICE_PARAMETER))) {
        writeResponse(response, JSON_CONTENT_TYPE, String.format(
                "{\"status\":\"%s\", \"version\":\"%s\", \"bridgeSupported\": true}", STATUS_OK, version));
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                String.format("Request Parameter 'service' with value '%s' is invalid.",
                        request.getParameter(SERVICE_PARAMETER)));
    }
}

From source file:eu.trentorise.game.api.rest.MainController.java

@RequestMapping(method = RequestMethod.POST, value = "/execute", consumes = { "application/json" }, produces = {
        "application/json" })
@ApiOperation(value = "Execute an action", notes = "Execute an action in a game")
public void executeAction(@RequestBody ExecutionDataDTO data, HttpServletResponse res) {
    Game game = gameSrv.loadGameDefinitionByAction(data.getActionId());
    if (game != null && game.isTerminated()) {
        try {//from   w w w.j  a  va  2 s  .  co  m
            res.sendError(403, String.format("game %s is expired", game.getId()));
        } catch (IOException e1) {
            LogHub.error(game.getId(), logger, "Exception sendError to client", e1);
        }
    } else {
        if (data.getExecutionMoment() == null) {
            workflow.apply(data.getGameId(), data.getActionId(), data.getPlayerId(), data.getData(), null);
        } else {
            workflow.apply(data.getGameId(), data.getActionId(), data.getPlayerId(),
                    data.getExecutionMoment().getTime(), data.getData(), null);
        }
    }
}

From source file:de.mpg.mpdl.inge.pidcache.web.MainServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    logger.info("PID cache POST request");

    if (req.getParameter("url") == null) {
        resp.sendError(HttpServletResponse.SC_NO_CONTENT, "URL parameter failed.");
    }//from w w w.ja  v a2  s.c  o  m
    try {

        if (!authenticate(req, resp)) {
            logger.warn("Unauthorized request from " + req.getRemoteHost());
            return;
        }

        PidCacheService cacheService = new PidCacheService();
        String xmlOutput = null;

        if (GwdgPidService.GWDG_PIDSERVICE_CREATE.equals(req.getPathInfo())) {
            xmlOutput = cacheService.create(req.getParameter("url"));
        } else if (GwdgPidService.GWDG_PIDSERVICE_EDIT.equals(req.getPathInfo())) {
            if (req.getParameter("pid") == null) {
                resp.sendError(HttpServletResponse.SC_NO_CONTENT, "PID parameter failed.");
            }
            xmlOutput = cacheService.update(req.getParameter("pid"), req.getParameter("url"));
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getPathInfo());
        }

        resp.setStatus(cacheService.getStatus());
        resp.encodeRedirectURL(cacheService.getLocation());
        resp.addHeader("Location", cacheService.getLocation());
        resp.getWriter().append(xmlOutput);
    } catch (Exception e) {
        throw new ServletException("Error processing request", e);
    }
}

From source file:eu.trentorise.game.api.rest.platform.DomainMainController.java

@RequestMapping(method = RequestMethod.POST, value = "/execute", consumes = { "application/json" }, produces = {
        "application/json" })
@ApiOperation(value = "Execute an action", notes = "Execute an action in a game")
public void executeAction(@PathVariable String domain, @RequestBody ExecutionDataDTO data,
        HttpServletResponse res) {
    Game game = gameSrv.loadGameDefinitionByAction(data.getActionId());
    if (game != null && game.isTerminated()) {
        try {/* w w  w.ja v a 2 s  . c  om*/
            res.sendError(403, String.format("game %s is expired", game.getId()));
        } catch (IOException e1) {
            LogHub.error(game.getId(), logger, "Exception sendError to client", e1);
        }
    } else {
        if (data.getExecutionMoment() == null) {
            workflow.apply(data.getGameId(), data.getActionId(), data.getPlayerId(), data.getData(), null);
        } else {
            workflow.apply(data.getGameId(), data.getActionId(), data.getPlayerId(),
                    data.getExecutionMoment().getTime(), data.getData(), null);
        }
    }
}

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

/**
 * Mtodo que se puede overridear en el caso de necesitar otro comportamiento al
 * no encontrarse un mapeo apropiado para la url recibida.
 * /*from  w  ww . j  ava 2  s  .co m*/
 * @param request
 * @param response
 * @throws Exception .
 */
protected void onNoMapping(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    response.sendError(404, "no mapping for this url");
}

From source file:org.tec.security.spring.Http401AuthenticationEntryPoint.java

/**
 * {@inheritDoc}//  w w w .j a v a 2 s. c  o m
 */
@Override()
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    if (mLogger.isDebugEnabled()) {
        mLogger.debug("url requires authentication " + request.getRequestURL().toString());
    }
    //send response code to trip error handler to prompt for login
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication required");
}