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:be.fedict.eid.dss.admin.portal.AccountingExportServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    HttpSession httpSession = request.getSession();
    Identity identity = (Identity) httpSession.getAttribute("org.jboss.seam.security.identity");
    if (false == identity.hasRole("admin")) {
        response.sendError(HttpURLConnection.HTTP_FORBIDDEN, "no admin role");
        return;//from   w ww  . jav a  2s . co  m
    }

    response.setContentType("text/csv");
    PrintWriter printWriter = response.getWriter();
    List<AccountingEntity> accountingEntities = this.accountingService.listAll();
    for (AccountingEntity accountingEntity : accountingEntities) {
        printWriter.print("\"");
        printWriter.print(accountingEntity.getDomain());
        printWriter.print("\",\"");
        printWriter.print(accountingEntity.getRequests());
        printWriter.println("\"");
    }
}

From source file:common.web.servlets.StaticFilesServlet.java

/** 
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request/*from w  ww.  j  a v  a  2 s.c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String name = getResourceName(request.getPathInfo());

    if (name == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
        return;
    }

    File file = new File(realPath, name);

    if (!file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
        return;
    }

    //delete after testing
    //synchronized(semaphore){
    long time = System.nanoTime();
    if (logger.isDebugEnabled()) {
        logger.debug("get resource=" + name);
        logger.debug("get file=" + file.getAbsolutePath());
    }
    OutputStream os = response.getOutputStream();
    //if (useNew){
    //   FileUtils.loadFromFileNew(file, os);
    //} else {
    FileUtils.loadFromFileOld(file, os);
    //}
    os.flush();
    os.close();

    time = System.nanoTime() - time;
    //if (useNew){
    //logger.info("proceed time new = "+time+"; avg = "+(servTimeNew/servQuantityNew)+"; count="+servQuantityNew+"; size = "+servSizeNew);
    //   newStat.increaseCount();
    //   newStat.increaseSize(file.length());
    //   newStat.increaseTime(time);
    //   useNew = false;
    //} else {
    //logger.info("proceed time old = "+time+"; avg = "+(servTimeOld/servQuantityOld)+"; count="+servQuantityOld+"; size = "+servSizeOld);
    oldStat.increaseCount();
    oldStat.increaseSize(file.length());
    oldStat.increaseTime(time);
    //   useNew = true;
    //}
    //}
}

From source file:com.ppcxy.cyfm.showcase.demos.web.RemoteContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?URL/*from  w w w.j  a  v a2  s  .c  o  m*/
    String contentUrl = request.getParameter("contentUrl");
    if (StringUtils.isBlank(contentUrl)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "contentUrl parameter is required.");
    }

    // ?HttpClientJDK ??URL
    String client = request.getParameter("client");
    if ("apache".equals(client)) {
        fetchContentByApacheHttpClient(response, contentUrl);
    } else {
        fetchContentByJDKConnection(response, contentUrl);
    }
}

From source file:com.sampullara.findmyiphone.FindMyDevice.java

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    String username = httpServletRequest.getParameter("username");
    String password = httpServletRequest.getParameter("password");
    if (username == null || password == null) {
        httpServletResponse.sendError(400, "You must specify a MobileMe username and password");
        return;/*from   w w  w  .jav  a 2 s .  c om*/
    }

    httpServletResponse.setContentType("application/json");
    writeDeviceLocations(httpServletResponse.getWriter(), username, password);
}

From source file:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public void getFile(@PathVariable("id") int id, HttpServletResponse response) throws IOException {
    Files f = fileService.get(id);
    if (f == null) {
        response.sendError(HttpServletResponse.SC_GONE, "O arquivo solicitado no foi encontrado.");
    } else {// w ww.  ja v  a  2s .  co m
        String fileName = f.getLocation();

        try {
            // get your file as InputStream
            InputStream is = new FileInputStream(new File(fileName));

            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
            response.setContentType(f.getContentType());
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());

            response.flushBuffer();

        } catch (FileNotFoundException fe) {
            response.sendError(HttpServletResponse.SC_GONE, "O arquivo solicitado no foi encontrado.");
            LOG.error("O arquivo solicitado no foi encontrado.", fe);
        } catch (IOException ex) {
            LOG.error("Error writing file to output stream. Filename was '" + fileName + "'");
            throw ex;
        }
    }
}

From source file:org.tangram.components.spring.DefaultController.java

@RequestMapping(value = "/id_{id}/view_{view}")
public ModelAndView render(@PathVariable("id") String id, @PathVariable("view") String view,
        HttpServletRequest request, HttpServletResponse response) {
    try {/*from   www.  j  a  va2  s  .co  m*/
        Utils.setPrimaryBrowserLanguageForJstl(request);
        LOG.debug("render() id={} view={}", id, view);
        Content content = beanFactory.getBean(id);
        LOG.debug("render() content={}", content);
        if (content == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "no content with id " + id + " in repository.");
            return null;
        } // if
        Map<String, Object> model = createModel(new TargetDescriptor(content, view, null), request, response);
        ViewContext viewContext = viewContextFactory.createViewContext(model, view);
        return SpringViewUtilities.createModelAndView(viewContext);
    } catch (Exception e) {
        ViewContext viewContext = viewContextFactory.createViewContext(e, request, response);
        return SpringViewUtilities.createModelAndView(viewContext);
    } // try/catch
}

From source file:com.bigdata.rockstor.console.UploadServlet.java

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

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.error("It is not a MultipartContent, return error.");
        resp.sendError(500, "It is not a MultipartContent, return error.");
        return;// w  ww .j a  va2  s  .  c o  m
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(1024 * 1024 * 512);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(req);
        LOG.info("parse requeset success : items num : " + fileItems.size());
    } catch (FileUploadException e) {
        LOG.error("parse requeset failed !");
        resp.sendError(500, "parse requeset failed !");
        return;
    }

    HashMap<String, String> headMap = new HashMap<String, String>();
    FileItem theFile = null;
    long size = -1;
    URI uri = null;

    Iterator<FileItem> iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = null;
            try {
                value = item.getString("UTF-8").trim();
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            LOG.info("Parse head info : " + name + " -- " + value);
            if (name.equals("ObjName")) {
                try {
                    uri = new URI(value);
                } catch (URISyntaxException e) {
                    LOG.info("Parse uri info error : " + value);
                    uri = null;
                }
            } else if (name.equals("ObjSize")) {
                try {
                    size = Long.parseLong(value);
                } catch (Exception e) {
                    LOG.error("Parse objSize error : " + value);
                }
            } else {
                headMap.put(name, value);
            }
        } else {
            theFile = item;
        }
    }

    if (size == -1 || uri == null || theFile == null || headMap.size() == 0) {
        LOG.error("Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0");
        resp.sendError(500,
                "Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0");
        return;
    }

    HttpPut put = new HttpPut();
    put.setURI(uri);
    for (Map.Entry<String, String> e : headMap.entrySet()) {
        if ("Filename".equals(e.getKey()))
            continue;
        put.setHeader(e.getKey(), e.getValue());
    }
    put.setEntity(new InputStreamEntity(theFile.getInputStream(), size));
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(put);
    if (200 != response.getStatusLine().getStatusCode()) {
        LOG.error("Put object error : " + response.getStatusLine().getStatusCode() + " : "
                + response.getStatusLine().getReasonPhrase());
        resp.sendError(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        return;
    }
    LOG.info("Put object OK : " + uri);
    response.setStatusCode(200);
}

From source file:fr.treeptik.cloudunit.config.Http401EntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg)
        throws IOException, ServletException {

    // Maybe change the log level...
    log.warn("Access Denied [ " + request.getRequestURL().toString() + "] : " + arg.getMessage());

    // Trace message to ban intruders with fail2ban
    //generateLogTraceForFail2ban();

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access unauthorized");
}

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

@SuppressWarnings("unchecked")
@Override/*from w ww .  j  ava2  s  .c  o m*/
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;
    }

    // parameters
    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    boolean minified = post.get("minified", false);
    String data = post.get("data", "");
    String places = post.get("places", "");
    if (places.length() == 0 && data.length() == 0) {
        response.sendError(503,
                "you must submit a data attribut with a json containing the property 'places' with a list of place names");
        return;
    }

    String[] place = new String[0];
    if (places.length() > 0) {
        place = places.split(",");
    } else {
        // parse the json data
        try {
            Map<String, Object> map = DAO.jsonMapper.readValue(data, DAO.jsonTypeRef);
            Object places_obj = map.get("places");
            if (places_obj instanceof List<?>) {
                List<Object> p = (List<Object>) places_obj;
                place = new String[p.size()];
                int i = 0;
                for (Object o : p)
                    place[i++] = (String) o;
            } else {
                response.sendError(400, "submitted data is not well-formed: expected a list of strings");
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // find locations for places
    Map<String, Object> locations = new LinkedHashMap<>();
    for (String p : place) {
        GeoMark loc = DAO.geoNames.analyse(p, null, 5, Long.toString(System.currentTimeMillis()));
        Map<String, Object> location = new LinkedHashMap<>();
        if (loc != null) {
            location.put("place",
                    minified ? new String[] { loc.getNames().iterator().next() } : loc.getNames());
            location.put("population", loc.getPopulation());
            location.put("country_code", loc.getISO3166cc());
            location.put("country", DAO.geoNames.getCountryName(loc.getISO3166cc()));
            location.put("location", new double[] { loc.lon(), loc.lat() });
            location.put("mark", new double[] { loc.mlon(), loc.mlat() });
        }
        locations.put(p, location);
    }

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

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

    // 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();
    post.finalize();
}

From source file:com.matthewcasperson.validation.filter.ParameterValidationFilter.java

/**
 * Return with a status code of 400//from ww w  . java 2  s .co  m
 * @param response The servlet request
 */
private void respondWithBadRequest(final ServletResponse response) {
    checkNotNull(response);

    /*
     * This is thrown when one of the validation rules determined that a parameter was
     * sent with invalid data and could not, or should not, be sanitised.
     */
    if (response instanceof HttpServletResponse) {
        try {
            final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameter data");
        } catch (final IOException ex) {
            /*
             * This shouldn't happen, but log it if it does
             */
            LOGGER.log(Level.SEVERE, ExceptionUtils.getFullStackTrace(ex));
        }
    }
}