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:io.mapzone.arena.geocode.GeocodeServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//ww  w  . jav a 2s.c  o m

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));

        if (req.getParameterMap().isEmpty()) {
            resp.sendError(400, "No parameters found! Please specify at least 'text'.");
            return;
        }

        GeocodeQuery query = extractQuery(req);

        // perform search
        List<Address> addresses = service.geocode(query);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("application/json;charset=utf-8");
        handleCors(req, resp);

        // convert addresses to result json
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream());
        JSONWriter writer = new JSONWriter(outputStreamWriter);
        writer.object();
        writer.key("results");
        writer.array();
        for (Address address : addresses) {
            writer.value(toJSON(address));
        }
        writer.endArray();
        writer.endObject();
        outputStreamWriter.flush();
        outputStreamWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:gsn.http.OutputStructureHandler.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;
    }/*from   ww w .  j  ava  2  s  . com*/
    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 (user != null) // meaning, that a login session is active, otherwise we couldn't get there
        if (Main.getContainerConfig().isAcEnabled() == true) {
            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.rockagen.gnext.service.spring.security.extension.ExAuthenticationHandler.java

/**
 * Authentication failure handler//from   w  w w. j  a  v a 2  s  .  co m
 *
 * @param request  request
 * @param response response
 */
public void failureHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uid = request.getParameter(username);
    try {
        failureRegister(uid, request);
    } catch (AuthenticationException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
    }
}

From source file:org.terasoluna.gfw.functionaltest.app.redirect.WhiteListRedirectStrategy.java

public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
    if (checkWhiteList(url)) {
        String redirectUrl = response.encodeRedirectURL(url);

        if (logger.isDebugEnabled()) {
            logger.debug("Redirecting to '" + redirectUrl + "'");
        }/*from   www  .j ava  2  s  .  c  om*/

        response.sendRedirect(redirectUrl);

    } else {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, url);
    }
}

From source file:de.mpg.imeji.presentation.servlet.ImageServlet.java

/**
 * {@inheritDoc}//from w ww  .  ja v a2 s . com
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String imageUrl = req.getParameter("imageUrl");
    GetMethod method = null;
    try {
        if (imageUrl == null) {
            resp.sendError(404, "URL null");
        } else {
            method = new GetMethod(imageUrl);
            method.setFollowRedirects(false);
            if (userHandle == null) {
                userHandle = LoginHelper.login(PropertyReader.getProperty("imeji.escidoc.user"),
                        PropertyReader.getProperty("imeji.escidoc.password"));
            }
            method.addRequestHeader("Cookie", "escidocCookie=" + userHandle);
            method.addRequestHeader("Cache-Control", "public");
            method.setRequestHeader("Connection", "close");
            // Execute the method with HttpClient.
            HttpClient client = new HttpClient();
            ProxyHelper.setProxy(client, frameworkUrl);
            client.executeMethod(method);
            // byte[] input;
            InputStream input;
            if (method.getStatusCode() == 302) {
                // try again
                logger.info("try load image again");
                method.releaseConnection();
                userHandle = LoginHelper.login(
                        de.mpg.imeji.presentation.util.PropertyReader.getProperty("imeji.escidoc.user"),
                        PropertyReader.getProperty("imeji.escidoc.password"));
                method = new GetMethod(imageUrl);
                method.setFollowRedirects(true);
                method.addRequestHeader("Cookie", "escidocCookie=" + userHandle);
                client.executeMethod(method);
            }
            if (method.getStatusCode() != 200) {
                ProxyHelper.setProxy(client, PropertyReader.getProperty("escidoc.imeji.instance.url"));
                method = new GetMethod(PropertyReader.getProperty("escidoc.imeji.instance.url")
                        + "/resources/icon/defaultThumb.gif");
                client.executeMethod(method);
                // out = resp.getOutputStream();
                if (method.getStatusCode() == 302) {
                    method.releaseConnection();
                    throw new RuntimeException("error code " + method.getStatusCode());
                }
                input = method.getResponseBodyAsStream();
            } else {
                for (Header header : method.getResponseHeaders()) {
                    resp.setHeader(header.getName(), header.getValue());
                }
                input = method.getResponseBodyAsStream();
            }
            OutputStream out = resp.getOutputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            while ((numRead = input.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                // out.flush();
                numWritten += numRead;
            }
            input.close();
            method.releaseConnection();
            out.flush();
            out.close();
            // ReadableByteChannel inputChannel = Channels.newChannel(input);
            // WritableByteChannel outputChannel = Channels.newChannel(out);
            // fastChannelCopy(inputChannel, outputChannel);
            // inputChannel.close();
            // outputChannel.close();
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (method != null)
            method.releaseConnection();
    }
}

From source file:au.org.ala.biocache.web.DownloadController.java

/**
 * Add a download to the offline queue//from w w w.ja  v  a2 s .  co  m
 * @param requestParams
 * @param ip
 * @param apiKey
 * @param type
 * @param response
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value = "occurrences/offline/{type}/download*", method = RequestMethod.GET)
public String occurrenceDownload(DownloadRequestParams requestParams,
        @RequestParam(value = "ip", required = false) String ip,
        @RequestParam(value = "apiKey", required = false) String apiKey, @PathVariable("type") String type,
        HttpServletResponse response, HttpServletRequest request) throws Exception {

    boolean sensitive = false;
    if (apiKey != null) {
        if (shouldPerformOperation(apiKey, response, false)) {
            sensitive = true;
        }
    } else if (StringUtils.isEmpty(requestParams.getEmail())) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED,
                "Unable to perform an offline download without an email address");
    }

    ip = ip == null ? request.getRemoteAddr() : ip;
    DownloadType downloadType = "index".equals(type.toLowerCase()) ? DownloadType.RECORDS_INDEX
            : DownloadType.RECORDS_DB;
    //create a new task
    DownloadDetailsDTO dd = new DownloadDetailsDTO(requestParams, ip, downloadType);
    dd.setIncludeSensitive(sensitive);

    persistentQueueDAO.addDownloadToQueue(dd);
    return null;
}

From source file:io.robusta.rra.controller.SpringController.java

@Override
public boolean validate(HttpServletRequest request, HttpServletResponse response, String... keys) {
    Representation representation = getRepresentation(request);
    throwIfNull(representation);/*from  w ww. j a v a  2s.c o  m*/
    boolean valid = representation.has(keys);

    if (!valid) {
        try {
            response.sendError(406, "Json not valid ! it hasn't at least one of these keys: "
                    + java.util.Arrays.toString(keys));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return valid;
}

From source file:com.streamsets.pipeline.lib.http.HttpReceiverServlet.java

protected void processRequest(HttpServletRequest req, InputStream is, HttpServletResponse resp)
        throws IOException {
    if (getReceiver().process(req, is, resp)) {
        resp.setStatus(HttpServletResponse.SC_OK);
        requestMeter.mark();//from   w  w  w  .j a va2 s . c o  m
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Record(s) didn't reach all destinations");
        errorRequestMeter.mark();
    }
}

From source file:com.controlj.addon.weather.servlets.AjaxController.java

private void handleError(HttpServletResponse resp, Throwable th) throws IOException {
    resp.sendError(500, th.getMessage());
    Logging.println(th);/*from   ww  w .ja  va  2s  .c o  m*/
}

From source file:org.dspace.app.webui.cris.controller.ProjectDetailsController.java

@Override
public ModelAndView handleDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    Project grant = extractProject(request);

    if (grant == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Grant page not found");
        return null;
    }//from   ww  w.  j a  v a  2 s  .  c  o  m

    Context context = UIUtil.obtainContext(request);

    EPerson currentUser = context.getCurrentUser();

    if ((grant.getStatus() == null || grant.getStatus().booleanValue() == false)
            && !AuthorizeManager.isAdmin(context)) {

        if (currentUser != null || Authenticate.startAuthentication(context, request, response)) {
            // Log the error
            log.info(LogManager.getHeader(context, "authorize_error",
                    "Only system administrator can access to disabled researcher page"));

            JSPManager.showAuthorizeError(request, response,
                    new AuthorizeException("Only system administrator can access to disabled researcher page"));
        }
        return null;
    }

    if (AuthorizeManager.isAdmin(context)) {
        model.put("grant_page_menu", new Boolean(true));
    }

    ModelAndView mvc = null;

    try {
        mvc = super.handleDetails(request, response);
    } catch (RuntimeException e) {
        return null;
    }

    if (subscribeService != null) {
        boolean subscribed = subscribeService.isSubscribed(currentUser, grant);
        model.put("subscribed", subscribed);

    }

    request.setAttribute("sectionid", StatsConfig.DETAILS_SECTION);
    new DSpace().getEventService().fireEvent(new UsageEvent(UsageEvent.Action.VIEW, request, context, grant));

    mvc.getModel().putAll(model);
    mvc.getModel().put("project", grant);
    return mvc;
}