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:org.loklak.api.server.UserServlet.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;//from   w  w  w .ja v  a  2  s .  co  m
    }

    // 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) {
                TwitterAPI.enrichLocation(twitterUserEntry);
                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<>();
    Map<String, Object> metadata = new LinkedHashMap<>();
    metadata.put("client", post.getClientHost());
    m.put("search_metadata", metadata);

    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
    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();
    sos.flush();
    sos.close();
    post.finalize();
}

From source file:es.ucm.fdi.storage.web.StorageController.java

@RequestMapping(method = RequestMethod.GET, value = "/storage/**")
public void servirArchivos(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String ctxPath = request.getContextPath();
    String objectId = request.getRequestURI();
    objectId = objectId.substring(ctxPath.length() + "/storage/".length());
    int pos = objectId.indexOf('/');
    if (pos < 0) {
        response.sendError(400, "Upps");
        return;/*  w  w w. ja v  a 2s. c o  m*/
    }
    String bucket = objectId.substring(0, pos);
    String key = objectId.substring(pos + 1);
    StorageObject object = storage.getObject(bucket, key);
    String mimeType = object.getMimeType();
    long length = object.getContentLength();

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) length);

    try {
        object.transferTo(response.getOutputStream());
        response.flushBuffer();
    } catch (IOException ex) {
        logger.error("Error writing file to output stream. bucket=>'{}', key=>'{}'", bucket, key, ex);
        response.sendError(500, "Upps");
    }
}

From source file:se.vgregion.urlservice.controllers.BitlyApiController.java

private void sendUnknownFormatError(HttpServletResponse response) throws IOException {
    response.sendError(500, "INVALID_ARG_FORMAT");
}

From source file:se.vgregion.urlservice.controllers.BitlyApiController.java

private void sendInvalidUriError(HttpServletResponse response) throws IOException {
    response.sendError(500, "INVALID_URI");
}

From source file:se.vgregion.urlservice.controllers.BitlyApiController.java

private void sendAccessDeniedError(HttpServletResponse response) throws IOException {
    response.sendError(500, "ACCESS_DENIED");
}

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

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

    OrderView order = orderDao.get(lic.getOrderRef());
    if (order == null) {
        response.sendError(400, Util.parseError("Invalid Inv No, please select from the list"));
        return null;
    }/*  w  w  w.j av  a 2 s  .  c  o m*/

    if (lic.getIssueDate() == null) {
        response.sendError(400, Util.parseError("Please select issue date"));
        return null;
    }

    lic = setExpireDate(lic);

    lic.setId(null);
    licDAO.saveOrUpdate(lic);

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

}

From source file:org.axonframework.samples.trader.webui.rest.RestController.java

@RequestMapping(value = "/command", method = RequestMethod.POST)
public @ResponseBody String mappedCommand(String command, HttpServletResponse response) throws IOException {
    try {//from   w ww  .j  a  va 2  s .co m
        Object actualCommand = xStream.fromXML(command);
        commandBus.dispatch(new GenericCommandMessage<Object>(actualCommand));
    } catch (StructuralCommandValidationFailedException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This is an invalid request.");
    } catch (Exception e) {
        logger.error("Problem whils deserializing an xml: {}", command, e);
        return "ERROR - " + e.getMessage();
    }

    return "OK";
}

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

private void stopService(HttpServletResponse response, User user) throws IOException {
    ResponseLoggerService service = getRegistry().getLogger(user);

    if (service == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND,
                String.format("Service for user '%s' not found.", user.toString()));
        return;//w ww. j  ava  2 s.  co m
    }

    if (!service.isAlive()) {
        response.sendError(HttpServletResponse.SC_CONFLICT,
                String.format("Service for user '%s' not active.", user.toString()));
        getRegistry().removeUser(user);

        return;
    }

    try {
        // gracefully stop the service
        service.stopAndWait(stopTimeout);

        if (service.isAlive()) {
            response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
                    String.format("Service for user '%s' stop timeout.", user.toString()));
        }
    } catch (InterruptedException ignored) {
    }
}

From source file:io.hops.hopsworks.api.admin.llap.LlapMonitorProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    // Check if the user is logged in
    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;//from  ww w .  ja v a 2s  .c  o m
    }

    // Check that the user is an admin
    boolean isAdmin = servletRequest.isUserInRole("HOPS_ADMIN");
    if (!isAdmin) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this application");
        return;
    }

    // The path we will receive is [host]/llapmonitor/llaphost/
    // We need to extract the llaphost to redirect the request
    String[] pathInfoSplits = servletRequest.getPathInfo().split("/");
    String llapHost = pathInfoSplits[1];

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    if (matcher.find()) {
        matcher.appendReplacement(urlBuf, llapHost);
    }

    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    URI targetUriObj;
    try {
        targetUriObj = new URI(newTargetUri);
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj));

    super.service(servletRequest, servletResponse);
}

From source file:egpi.tes.ahv.servicio.AutenticacionREST.java

public void procesarError(HttpServletResponse response, Exception e) {
    System.out.println("\n\nprocesarError=" + e.getMessage() + "\n\n");
    try {/*from  www .j  av  a  2 s  . co  m*/
        if (status == 0) {
            response.sendError(500, e.getMessage());
        } else {
            response.sendError(status, e.getMessage());
        }
    } catch (IOException ex) {
        Logger.getLogger(AutenticacionREST.class.getName()).log(Level.SEVERE, null, ex);
    }
}