List of usage examples for javax.servlet.http HttpServletRequest getServletContext
public ServletContext getServletContext();
From source file:com.yoshio3.azuread.graph.GraphAPIImpl.java
public void init(HttpServletRequest request) { AzureADUserPrincipal userPrincipal = (AzureADUserPrincipal) request.getSession() .getAttribute(PRINCIPAL_SESSION_NAME); authString = "Bearer " + userPrincipal.getAuthenticationResult().getAccessToken(); tenant = request.getServletContext().getInitParameter("tenant"); jaxrsClient = ClientBuilder.newClient().register( (new JacksonJaxbJsonProvider(new ObjectMapper(), JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS))) .register(JacksonFeature.class); System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); }
From source file:paquete.producto.Main.java
/** * Almacena la imagen indicada en el input "imagen" del formulario * dentro de la carpeta indicada en la constante SAVE_DIR, generando un * nombre nuevo para el archivo en funcin de una codificacin MD5 * //from w w w . j av a 2s . co m * @param request * @return Nombre generado para la imagen o null si no se ha enviado ningn * archivo */ private String saveImagen(HttpServletRequest request) { //Crear la ruta completa donde se guardarn las imgenes String appPath = request.getServletContext().getRealPath(""); String savePath = appPath + File.separator + SAVE_DIR; logger.fine("Save path = " + savePath); //Crear la carpeta si no existe File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } //Crear un nombre para la imagen utilizando un cdigo MD5 en funcin // del tiempo y una palabra secreta. // Se utiliza una codificacin de este tipo para que se dificulte la // localizacin no permitida de las imgenes String secret = "W8fQAP9X"; long time = Calendar.getInstance().getTimeInMillis(); //Para generar el cdigo MD5 se usa la clase DigestUtils de la librera // org.apache.commons.codec (se incluye en la carpeta 'libs' del proyecto) String fileName = DigestUtils.md5Hex(secret + time); try { //Obtener los datos enviados desde el input "photoFileName" del formulario Part filePart = request.getPart("imagen"); String fullPathFile = savePath + File.separator + fileName; //Guardar la imagen en la ruta y nombre indicados if (filePart.getSize() > 0) { filePart.write(fullPathFile); logger.fine("Saved file: " + fullPathFile); return fileName; } else { return null; } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalStateException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (ServletException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:mvc.PaymentController.java
private String getErrors(BindingResult result, HttpServletRequest req) { String errorString = ""; ApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(req.getServletContext()); ResourceBundleMessageSource rbms = applicationContext.getBean(ResourceBundleMessageSource.class); for (FieldError error : result.getFieldErrors()) { errorString += rbms.getMessage(error.getCode(), null, Locale.US); }//w ww. j av a 2 s . co m return errorString; }
From source file:com.arcadian.loginservlet.LecturesServlet.java
/** * Handles the HTTP//from www . j a v a 2 s.com * <code>GET</code> method. * * @param request servlet request * @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 { if (request.getParameter("filename") != null) { String fileName = request.getParameter("filename"); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName); System.out.println("File location on server::" + file.getAbsolutePath()); ServletContext ctx = getServletContext(); InputStream fis = new FileInputStream(file); String mimeType = ctx.getMimeType(file.getAbsolutePath()); System.out.println("mime type=" + mimeType); response.setContentType(mimeType != null ? mimeType : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); ServletOutputStream os = response.getOutputStream(); byte[] bufferData = new byte[102400]; int read = 0; while ((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); } os.flush(); os.close(); fis.close(); System.out.println("File downloaded at client successfully"); } processRequest(request, response); }
From source file:catalogo.Main.java
/** * Almacena la imagen indicada en el input "photoFileName" del formulario * dentro de la carpeta indicada en la constante SAVE_DIR, generando un * nombre nuevo para el archivo en funcin de una codificacin MD5 * /* www . j ava 2 s. c om*/ * @param request * @return Nombre generado para la imagen o null si no se ha enviado ningn * archivo */ private String savePhotoFile(HttpServletRequest request) { //Crear la ruta completa donde se guardarn las imgenes String appPath = request.getServletContext().getRealPath(""); String savePath = appPath + File.separator + SAVE_DIR; logger.fine("Save path = " + savePath); //Crear la carpeta si no existe File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } //Crear un nombre para la imagen utilizando un cdigo MD5 en funcin // del tiempo y una palabra secreta. // Se utiliza una codificacin de este tipo para que se dificulte la // localizacin no permitida de las imgenes String secret = "W8fQAP9X"; long time = Calendar.getInstance().getTimeInMillis(); //Para generar el cdigo MD5 se usa la clase DigestUtils de la librera // org.apache.commons.codec (se incluye en la carpeta 'libs' del proyecto) String fileName = DigestUtils.md5Hex(secret + time); try { //Obtener los datos enviados desde el input "photoFileName" del formulario Part filePart = request.getPart("photoFileName"); String fullPathFile = savePath + File.separator + fileName; //Guardar la imagen en la ruta y nombre indicados if (filePart.getSize() > 0) { filePart.write(fullPathFile); logger.fine("Saved file: " + fullPathFile); return fileName; } else { return null; } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalStateException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (ServletException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:gumga.framework.presentation.api.AbstractReportAPI.java
public void generateAndExportHTMLReport(String reportName, String destFile, List data, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws JRException, IOException { InputStream is = getResourceAsInputStream(request, reportName); setContentType(response, reportName, ReportType.HTML); reportService.exportReportToHtmlFile(is, data, params, destFile); //Set the output content InputStream generatedIs = request.getServletContext().getResourceAsStream(destFile); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead;/*from www. j a va2 s . com*/ byte[] bytes = new byte[16384]; while ((nRead = generatedIs.read(bytes, 0, bytes.length)) != -1) { buffer.write(bytes, 0, nRead); } buffer.flush(); bytes = buffer.toByteArray(); response.setContentLength(bytes.length); response.getOutputStream().write(bytes, 0, bytes.length); }
From source file:org.siphon.db2js.DbjsRunner.java
public void run(HttpServletRequest request, HttpServletResponse response, String method) throws ServletException, IOException { String jsfile = request.getServletContext().getRealPath(request.getServletPath()); if (!new File(jsfile).exists()) { response.setStatus(404);//from w w w. j a va 2s . c om PrintWriter out = response.getWriter(); out.print(request.getServletPath() + " not found"); out.flush(); return; } JsEngineHandlerContext engineContext = null; try { engineContext = dbjsManager.getEngineContext(jsfile, request.getServletPath(), dataSource, otherArgs); } catch (Exception e3) { logger.error("", e3); engineContext.free(); throw new ServletException(e3); } JsspRequest jsspRequest = new JsspRequest(request, engineContext); ScriptObjectMirror params; try { params = getParams(engineContext, jsspRequest); } catch (Exception e3) { response.setStatus(500); PrintWriter out = response.getWriter(); out.print("params must be json"); out.flush(); engineContext.free(); return; } formatter.writeHttpHeader(response, engineContext); JsspWriter out = null; try { initEngineContext(engineContext, jsspRequest, response); out = (JsspWriter) engineContext.getScriptEngine().get("out"); Object res = run(engineContext, jsspRequest, response, method, params); formatter.formatQueryResult(res, null, engineContext); } catch (Exception e) { try { this.completeTask(engineContext.getScriptEngine(), e); } catch (Exception e2) { logger.error("", e2); } Object ex = JsEngineUtil.parseJsException(e); if (ex instanceof Throwable == false) { boolean ignore = false; if (ex instanceof ScriptObjectMirror) { ScriptObjectMirror mex = (ScriptObjectMirror) ex; if (mex.containsKey("name") && "ValidationError".equals(mex.get("name"))) { ignore = true; } } else if (ex instanceof ScriptObject) { ScriptObject oex = (ScriptObject) ex; if (oex.containsKey("name") && "ValidationError".equals(oex.get("name"))) { ignore = true; } } if (!ignore) logger.error(engineContext.getJson().tryStringify(ex), e); } else { logger.error("", (Throwable) ex); } try { out.print(formatter.formatException(ex, engineContext)); out.flush(); } catch (Exception e1) { logger.error("", e1); } } finally { if (engineContext != null) engineContext.free(); out.flush(); } }
From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java
@Path("store/{path:.*}") @GET// ww w . j a va2 s. c o m public Response storeInfo(@PathParam("path") String path, @Context HttpServletRequest request) throws Exception { File file = new File(request.getServletContext().getRealPath("data/" + path)); if (file.exists()) { if (file.isDirectory()) { return listfile(path, file); } else { String mt = new MimetypesFileTypeMap().getContentType(file); //????,?download2 return Response.ok(file, mt) .header("Content-disposition", "attachment;filename=" + file.getName() + ";filename*=UTF-8''" + URLEncoder.encode(file.getName(), "UTF-8")) .header("ragma", "No-cache").header("Cache-Control", "no-cache").build(); } } StringBuilder sb = new StringBuilder(); sb.append("<html>").append("\r\n").append("<head><title>404 Not Found</title></head>").append("\r\n") .append("<body bgcolor=\"white\">").append("\r\n").append("<center><h1>404 Not Found</h1></center>") .append("\r\n").append("</body>").append("\r\n").append("</html>"); return Response.ok(sb.toString()).header("Content-Type", "text/html;charset=utf-8").build(); }
From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java
@Path("show") @GET/* ww w . j av a 2 s . c om*/ public Response show(@Context HttpServletRequest request) throws FileNotFoundException { final File file = new File(request.getServletContext().getRealPath("index.html")); final InputStream responseStream = new FileInputStream(file); StreamingOutput output = new StreamingOutput() { @Override public void write(OutputStream out) throws IOException, WebApplicationException { try { int length; byte[] buffer = new byte[1024 * 10]; while ((length = responseStream.read(buffer)) != -1) { out.write(buffer, 0, length); out.flush(); } } finally { responseStream.close(); } } }; return Response.ok(output).header("Content-Type", "text/plain").build(); }
From source file:com.dlshouwen.tdjs.content.controller.TdjsArtCheckController.java
/** * ?/*from w w w . ja va 2 s . c o m*/ * * @param articleId ? * @param request * @return base + 'editAnnouncement' * @throws Exception */ @RequestMapping(value = "/{articleId}/check", method = RequestMethod.GET) public ModelAndView checkArticle(@PathVariable String articleId, HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView view = new ModelAndView("/tdjs/content/articleDetail.btl"); String sourcePath = AttributeUtils.getAttributeContent(request.getServletContext(), "source_webapp_file_postion"); // ?? Article article = dao.getArticleById(articleId); String channel_id = article.getChannel_id(); Channel channelNow = channelDao.getChannelById(channel_id); String teamId = article.getTeam_id(); Team teamNow = teamDao.getTeamById(teamId); List<Map<String, Object>> allChannel = channelDao.getChannelListByTeamId(teamId); List<Picture> pictureList = pictureDao.getPictureByAlbumId(articleId); if (null == pictureList || pictureList.size() == 0) { pictureList = null; } view.addObject("teamNow", teamNow); view.addObject("allChannel", allChannel); view.addObject("article", article); view.addObject("channelNow", channelNow); view.addObject("pictureList", pictureList); view.addObject("SOURCEPATH", sourcePath); // ? LogUtils.updateOperationLog(request, OperationType.VISIT, "?"); return view; }