List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:org.gliderwiki.admin.PatchController.java
/** * ? ? ?? . //from www .ja v a 2 s . co m * @param request * @param response * @return * @throws Throwable */ @RequestMapping(value = "/admin/getPatch", method = RequestMethod.POST) @ResponseBody public JsonResponse getPatch(HttpServletRequest request, HttpServletResponse response) throws Throwable { JsonResponse res = new JsonResponse(); String functionIdx = request.getParameter("idx"); String callUrl = request.getParameter("url"); logger.debug("#### functionIdx : " + functionIdx); logger.debug("#### callUrl : " + callUrl); // Call URL RestClient . - ? we_patch WePatch restVo = new WePatch(); restVo.setWe_function_idx(Integer.parseInt(functionIdx)); HttpEntity<WePatch> entity = new HttpEntity<WePatch>(restVo); String restUrl = REST_SERVER_URL + callUrl; ResponseEntity<WePatch> entityResponse = restTemplate.postForEntity(restUrl, entity, WePatch.class); // ? ? WePatch . // ? , ?, , ?? . WePatch patchVo = entityResponse.getBody(); String filePath = patchVo.getWe_file_path(); String fileName = patchVo.getWe_file_name(); String localPath = patchVo.getWe_patch_path(); String patchType = patchVo.getWe_patch_type(); // ? ? ? Biz Logic ? . String fullPath = filePath + "/" + fileName; // ? String listUrl = REST_SERVER_URL + fullPath; HttpClient httpClient = new DefaultHttpClient(); // ? (jar? WEB-INF / lib ?. ?, jsp? ? ServletContext context = request.getServletContext(); String destination = context.getRealPath(localPath) + "/" + fileName; logger.debug("##destination : " + destination); logger.debug("##listUrl : " + listUrl); // GliderWiki ? ? HttpClient Stream ?. HttpGet httpGet = new HttpGet(listUrl); HttpResponse httpResponse = httpClient.execute(httpGet); // httpEntity Spring ?? full import . org.apache.http.HttpEntity httpEntity = httpResponse.getEntity(); // ? ? ?. if (httpEntity != null) { try { FileOutputStream fos = new FileOutputStream(destination); httpEntity.writeTo(fos); fos.close(); res.setResult(fileName); res.setStatus(ResponseStatus.SUCCESS); } catch (Exception e) { res.setResult(fileName); res.setStatus(ResponseStatus.FAIL); e.printStackTrace(); } } logger.debug("#### res : " + res.toString()); return res; }
From source file:com.kahlon.guard.controller.PersonImageManager.java
/** * Crop Image//from w w w. ja v a 2 s .co m * @return */ public String crop() { if (croppedImage == null) { return null; } setNewImageName(getRandomImageName()); ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "image" + File.separator + "temp" + File.separator + getNewImageName() + ".png"; if (fileNames == null) { fileNames = new ArrayList<>(); } fileNames.add(newFileName); FileImageOutputStream imageOutput; try { imageOutput = new FileImageOutputStream(new File(newFileName)); imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length); imageOutput.close(); } catch (FileNotFoundException e) { throw new FacesException("File not found.", e.getCause()); } catch (IOException e) { throw new FacesException("IO Exception found.", e.getCause()); } return null; }
From source file:com.kahlon.guard.controller.PersonImageManager.java
/** * Upload person image file/*from ww w .ja v a 2s . c o m*/ * * @param event * @throws java.io.IOException */ public void onUpload(FileUploadEvent event) throws IOException { photo = getRandomImageName(); byte[] data = IOUtils.toByteArray(event.getFile().getInputstream()); ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "image" + File.separator + "temp" + File.separator + photo + ".png"; if (fileNames == null) { fileNames = new ArrayList<>(); } fileNames.add(newFileName); FileImageOutputStream imageOutput; try { imageOutput = new FileImageOutputStream(new File(newFileName)); imageOutput.write(data, 0, data.length); imageOutput.close(); BufferedImage originalImage = ImageIO.read(new File(newFileName)); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImagePng = resizeImageWithHint(originalImage, type); ImageIO.write(resizeImagePng, "png", new File(newFileName)); } catch (Exception e) { throw new FacesException("Error in writing captured image."); } FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, msg); imageUpload = false; }
From source file:acoli.controller.Controller.java
/** * * @param request//from ww w . j a v a 2 s . co m * @param response * @throws ServletException * @throws IOException * @throws FileNotFoundException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileNotFoundException { // Get servlet context. ServletContext servletContext = this.getServletConfig().getServletContext(); String path = servletContext.getRealPath("/"); //System.out.println(path); // Previously used way to obtain servlet context doesn't work. //ServletContext context = request.getServletContext(); //String path = context.getRealPath("/"); //System.out.println("ServletContext.getRealPath():" + path + "<--"); String forward = ""; // Get a map of the request parameters @SuppressWarnings("unchecked") Map parameters = request.getParameterMap(); if (parameters.containsKey("grammar")) { HttpSession session = request.getSession(false); String absoluteUnzippedGrammarDir = (String) session.getAttribute("absoluteUnzippedGrammarDir"); //System.out.println("Uploaded file to analyze: " + absoluteUnzippedGrammarDir); // User-selected port. String javaport = (String) request.getParameter("javaport"); System.out.println("User selected port: " + javaport); String traleport = String.valueOf((Integer.parseInt(javaport) - 1000)); // Check if these ports are already in use // if so, kill the grammar in the corresponding directory and start a new one. if (portAvailable(Integer.parseInt(javaport)) && portAvailable(Integer.parseInt(traleport))) { System.out.println("Both javaport/traleport: " + javaport + "/" + traleport + " available!"); } else { // Java port not free. if (!portAvailable(Integer.parseInt(javaport))) { System.out.println("Port: " + javaport + " not available!"); // Get the grammar directory that is running on this port and kill it. if (portToGrammarFolderMappings.containsKey(javaport)) { String grammarDirToKill = portToGrammarFolderMappings.get(javaport); // Stop grammar. runBashScript(path, "./single_grammar_stop.sh", grammarDirToKill, ""); } else { killProcessID(path, "./free_java_port.sh", javaport); } } // Trale port not free. if (!portAvailable(Integer.parseInt(traleport))) { killProcessID(path, "./free_sicstus_port.sh", traleport); } } // Generate port-specific files // which will be redirected by the script later. PrintWriter w = new PrintWriter(new File(absoluteUnzippedGrammarDir + "/" + "javaserverport.txt")); w.write(javaport); w.flush(); w.close(); w = new PrintWriter(new File(absoluteUnzippedGrammarDir + "/" + "traleserverstart.pl")); w.write("trale_server_start(" + traleport + ").\n"); // 1000 port ids less than the java id. w.flush(); w.close(); // Copy wtx.pl and tokenization.pl into the grammar directory. File tokenizationFile = new File(path + "/resources/servertrale_files/tokenization.pl"); File wtxFile = new File(path + "/resources/servertrale_files/wtx.pl"); //System.out.println("tokenizationFile: " + tokenizationFile.getAbsolutePath()); //System.out.println("wtxFile: " + wtxFile.getAbsolutePath()); File destinationDir = new File(absoluteUnzippedGrammarDir + "/"); //System.out.println("destinationDir: " + absoluteUnzippedGrammarDir); FileUtils.copyFileToDirectory(tokenizationFile, destinationDir); FileUtils.copyFileToDirectory(wtxFile, destinationDir); // Start grammar. // Check webtrale version from user selection. String labelVersion = (String) request.getParameter("webtraleVersion"); System.out.println("User selected label version: " + labelVersion); switch (labelVersion) { case "webtralePS94": runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir, "webtrale_green_labels.jar"); break; case "webtraleAprilLabels": // April labels. runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir, "webtrale_green_aprillabels.jar"); break; case "webtraleMayLabels": // May labels. runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir, "webtrale_green_maylabels.jar"); break; case "webtraleJuneLabels": // June labels. runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir, "webtrale_green_junelabels.jar"); break; default: // Standard labels. runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir, "webtrale_green_nolabels.jar"); break; } portToGrammarFolderMappings.put(javaport, absoluteUnzippedGrammarDir); session.setAttribute("javaport", javaport); System.out.println("Used ports and grammar directories: " + portToGrammarFolderMappings + "\n"); forward = GRAMMAR_JSP; } else if (parameters.containsKey("run")) { forward = RUN_JSP; } else if (parameters.containsKey("admin")) { System.out.println("Accessing grammar admin."); // Check which ports are still non-available. TreeMap<String, String> tmpMap = new TreeMap<>(); for (String aJavaPort : portToGrammarFolderMappings.keySet()) { if (!portAvailable(Integer.parseInt(aJavaPort))) { tmpMap.put(aJavaPort, portToGrammarFolderMappings.get(aJavaPort)); } } portToGrammarFolderMappings.clear(); portToGrammarFolderMappings = tmpMap; System.out .println("Used ports and grammar directories in admin: " + portToGrammarFolderMappings + "\n"); // only testing. //portToGrammarFolderMappings.put("7001", "/var/lib/tomcat7/webapps/servertrale/resources/uploads/BEBFECC89/posval"); //portToGrammarFolderMappings.put("7002", "/var/lib/tomcat7/webapps/servertrale/resources/uploads/B02CA6BAA/4_Semantics_Raising"); // Save all used ports and directories in this session attribute. HttpSession session = request.getSession(false); String portToGrammarFolderMappingsString = portToGrammarFolderMappings.toString().substring(1, portToGrammarFolderMappings.toString().length() - 1); session.setAttribute("runningGrammars", portToGrammarFolderMappingsString.split("\\, ")); forward = ADMIN_JSP; } // Upload (START PAGE) else { // HttpSession session = request.getSession(false); // String absoluteUnzippedGrammarDir = (String) session.getAttribute("absoluteUnzippedGrammarDir"); // if (absoluteUnzippedGrammarDir != null) { // // Stop grammar. // runBashScript(path, "./single_grammar_stop.sh", absoluteUnzippedGrammarDir); // // Remove this java port from the list of occupied ports. // TreeMap<String, String> tmpMap = new TreeMap<>(); // for(String aJavaPort : portToGrammarFolderMappings.keySet()) { // String aGrammarDir = portToGrammarFolderMappings.get(aJavaPort); // if(aGrammarDir.equals(absoluteUnzippedGrammarDir)) { // // Java port should be removed. So ignore it. // } // else { // tmpMap.put(aJavaPort, absoluteUnzippedGrammarDir); // } // } // portToGrammarFolderMappings.clear(); // portToGrammarFolderMappings = tmpMap; // System.out.println("Used ports and grammar directories: " + portToGrammarFolderMappings + "\n\n"); // // } else { // System.out.println("No grammar to kill."); // } forward = UPLOAD_JSP; } RequestDispatcher view = request.getRequestDispatcher(forward); view.forward(request, response); }
From source file:Servlet.ServletFOP.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w.j ava 2 s . c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext webApp = this.getServletContext(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); FopFactory fopFactory = FopFactory.newInstance(); //Setup a buffer to obtain the content length ByteArrayOutputStream out = new ByteArrayOutputStream(); Templates templates = tFactory.newTemplates(new StreamSource(webApp.getRealPath(XSLT_PATH))); // Create a transformer Transformer transformer = templates.newTransformer(); // Get concrete implementation DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); // Need a parser that support namespaces dFactory.setNamespaceAware(true); // Create the parser DocumentBuilder parser = dFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(new Query().chartFOP())); // Parse the XML document Document doc = parser.parse(is); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Setup input Source src = new DOMSource(doc); //Start the transformation and rendering process transformer.transform(src, res); //Prepare response response.setContentType("application/pdf"); response.setContentLength(out.size()); //Send content to Browser response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:authorize.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Logger logger = LogManager.getLogger(authorize.class); logger.trace("START"); PrintWriter out = response.getWriter(); Connection conn = null;// ww w .jav a 2 s. com Statement stmt = null; ResultSet rs = null; HttpSession session = request.getSession(false); String response_type = request.getParameter("response_type"); String username = request.getParameter("username"); String password = request.getParameter("password"); String prompt = request.getParameter("prompt"); String login_hint = request.getParameter("login_hint"); String max_age = request.getParameter("max_age"); String client_id = request.getParameter("client_id"); String redirect_uri = request.getParameter("redirect_uri"); String scope = request.getParameter("scope"); String state = request.getParameter("state"); String nonce = request.getParameter("nonce"); String consent = request.getParameter("consent"); String client_scope = null; String access_token = null; String id_token = null; String passwd = null; String db_redirect_uri = null; String path = null; String sql = null; String uri = null; String issuer = null; String keyname = null; String kit = "public.key"; boolean redirect_uri_check = true; int access_token_time = 60; if (scope == null) { scope = "openid"; } else if (scope.equals("consent")) { scope = null; if (null != request.getParameter("openid")) { scope = "openid"; if (null != request.getParameter("profile")) scope += " profile"; if (null != request.getParameter("email")) scope += " email"; if (null != request.getParameter("phone")) scope += " phone"; if (null != request.getParameter("address")) scope += " address"; } } logger.trace(scope); if (prompt != null && prompt.contains("login") && consent == null && session != null) session.invalidate(); try { ServletContext context = this.getServletContext(); path = context.getRealPath("/WEB-INF/oauth2"); Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); conn = DriverManager.getConnection("jdbc:derby:" + path); stmt = conn.createStatement(); logger.trace("connect()"); sql = "SELECT scope,redirect_uri FROM client WHERE client_id='" + client_id + "'"; rs = stmt.executeQuery(sql); while (rs.next()) { client_scope = rs.getString("scope"); db_redirect_uri = rs.getString("redirect_uri"); } logger.trace(sql); if (redirect_uri == null) redirect_uri = db_redirect_uri; sql = "SELECT passwd FROM profile WHERE uid='" + username + "'"; rs = stmt.executeQuery(sql); while (rs.next()) { passwd = rs.getString("passwd"); } logger.trace(sql); path = context.getRealPath("/WEB-INF/config.json"); InputStream input = new FileInputStream(path); JsonParser parser = Json.createParser(input); while (parser.hasNext()) { JsonParser.Event event = parser.next(); switch (event) { case KEY_NAME: keyname = parser.getString(); break; case VALUE_NUMBER: access_token_time = parser.getInt(); break; case VALUE_TRUE: redirect_uri_check = true; break; case VALUE_FALSE: redirect_uri_check = false; break; case VALUE_STRING: if (keyname.equals("issuer")) issuer = parser.getString(); if (keyname.equals("kit")) kit = parser.getString(); break; default: break; } } java.util.Date dt = new java.util.Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentTime = sdf.format(dt); if (client_scope != null && passwd != null) { byte[] cipher_byte; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); cipher_byte = md.digest(); String sha256_password = Base64.getEncoder().withoutPadding().encodeToString(cipher_byte); StringTokenizer strToken = new StringTokenizer(scope, " "); while (strToken.hasMoreTokens()) { String token = strToken.nextToken().toString(); logger.trace(token); if (!client_scope.contains(token)) throw new Exception("out of scope"); } if (passwd.contains(sha256_password) && (!redirect_uri_check || db_redirect_uri.equals(redirect_uri))) { if (prompt != null && prompt.contains("consent") && !consent.equals("false")) { username = "null"; password = "null"; consent = "true"; throw new Exception("consent is true"); } access_token = RandomStringUtils.randomAlphanumeric(32); logger.trace(access_token); sql = "insert into session(uid,access_token,issued_in,scope,client_id) values ('" + username + "','" + access_token + "','" + currentTime + "','" + scope + "','" + client_id + "')"; stmt.executeUpdate(sql); md.update(access_token.getBytes()); cipher_byte = md.digest(); byte[] half_cipher_byte = Arrays.copyOf(cipher_byte, (cipher_byte.length / 2)); String at_hash = Base64.getEncoder().withoutPadding().encodeToString(half_cipher_byte); path = context.getRealPath("/WEB-INF/private.der"); File filePrivateKey = new File(path); FileInputStream fis = new FileInputStream(path); byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()]; fis.read(encodedPrivateKey); fis.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); Calendar exp = Calendar.getInstance(); exp.add(Calendar.SECOND, access_token_time); if (nonce == null || nonce.equals("null")) { if (response_type.contains("id_token")) { uri = redirect_uri; uri += "#error=invalid_request&error_description=nonce%20is%20not%20valid."; response.sendRedirect(uri); logger.info(uri); return; } } else { id_token = Jwts.builder().setHeaderParam("alg", "RS256").setHeaderParam("typ", "JWT") .setHeaderParam("kid", kit).setIssuer(issuer).claim("at_hash", at_hash) .setSubject(username).setAudience(client_id).claim("nonce", nonce) .setSubject(username).setExpiration(exp.getTime()) .setIssuedAt(Calendar.getInstance().getTime()) .claim("auth_time", String.valueOf(Calendar.getInstance().getTime().getTime()).substring(0, 10)) .signWith(SignatureAlgorithm.RS256, privateKey).compact(); logger.trace(id_token); } uri = redirect_uri; if (response_type.equals("token")) uri += "#access_token=" + access_token + "&token_type=bearer&expires_in=" + access_token_time; if (response_type.equals("id_token")) uri += "#id_token=" + id_token; if (response_type.equals("token id_token") || response_type.equals("id_token token")) uri += "#access_token=" + access_token + "&token_type=bearer&expires_in=" + access_token_time + "&id_token=" + id_token; if (state != null && !state.equals("null")) uri += "&state=" + state; response.sendRedirect(uri); logger.info(uri); return; } } } catch (Exception e) { logger.trace(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); logger.trace("close()"); } catch (SQLException e) { logger.trace(e.getMessage()); } } if (redirect_uri != null || redirect_uri.equals("null")) uri = redirect_uri; else uri = "/myop/error"; if (username != null && !username.equals("null") && password != null && !password.equals("null")) { uri += "#error=access_denied&error_description=User%20authentication%20failed."; session = request.getSession(false); if (session != null) session.invalidate(); } else if (scope == null) { uri += "#error=invalid_scope&error_description=The%20scope%20value%20is%20not%20supported."; } else if (client_scope == null || client_scope.equals("null")) { uri += "#error=unauthorized_clienti&error_description=Client%20authentication%20failed."; } else if (response_type == null || response_type.equals("null") || !(response_type.equals("token") || response_type.equals("id_token") || response_type.equals("token id_token") || response_type.equals("id_token token"))) { uri += "#error=unsupported_response_type&error_description==The%20response_type%20value%20%22" + response_type + "%22%20is%20not%20supported."; } else if (redirect_uri_check && !db_redirect_uri.equals(redirect_uri)) { uri += "#error=invalid_request&error_description=redirect_uri%20is%20not%20valid."; } else { uri = "/myop/login?response_type=" + URLEncoder.encode(response_type, "UTF-8") + "&client_id=" + client_id + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") + "&scope=" + URLEncoder.encode(scope, "UTF-8"); if (nonce != null && !nonce.equals("null")) uri += "&nonce=" + nonce; if (prompt != null && !prompt.equals("null")) uri += "&prompt=" + prompt; if (login_hint != null && !login_hint.equals("null")) uri += "&login_hint=" + login_hint; if (max_age != null && !max_age.equals("null")) uri += "&max_age=" + max_age; if (consent != null && consent.equals("true")) uri += "&consent=" + consent; } if (state != null && !state.equals("null")) uri += "&state=" + state; response.sendRedirect(uri); logger.info(uri); logger.trace("END"); }
From source file:servlet.PdfServlet1.java
/** * Processes requests for both HTTP//from ww w. j a va 2s. c o m * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MyQuery mq = new MyQuery(); ServletContext webApp = this.getServletContext(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); FopFactory fopFactory = FopFactory.newInstance(); //Setup a buffer to obtain the content length ByteArrayOutputStream out = new ByteArrayOutputStream(); Templates templates = tFactory.newTemplates(new StreamSource(webApp.getRealPath(XSLT_PATH))); // Create a transformer Transformer transformer = templates.newTransformer(); // Get concrete implementation DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); // Need a parser that support namespaces dFactory.setNamespaceAware(true); // Create the parser DocumentBuilder parser = dFactory.newDocumentBuilder(); // Parse the XML document InputSource is = new InputSource(new StringReader(mq.getStarsBis())); // Parse the XML document Document doc = parser.parse(is); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Setup input Source src = new DOMSource(doc); //Start the transformation and rendering process transformer.transform(src, res); //Prepare response response.setContentType("application/pdf"); response.setContentLength(out.size()); //Send content to Browser response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:servlet.PdfServlet2.java
/** * Processes requests for both HTTP/*from w ww .j ava 2s .co m*/ * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MyQuery mq = new MyQuery(); ServletContext webApp = this.getServletContext(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); FopFactory fopFactory = FopFactory.newInstance(); //Setup a buffer to obtain the content length ByteArrayOutputStream out = new ByteArrayOutputStream(); Templates templates = tFactory.newTemplates(new StreamSource(webApp.getRealPath(XSLT_PATH))); // Create a transformer Transformer transformer = templates.newTransformer(); // Get concrete implementation DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); // Need a parser that support namespaces dFactory.setNamespaceAware(true); // Create the parser DocumentBuilder parser = dFactory.newDocumentBuilder(); // Parse the XML document InputSource is = new InputSource(new StringReader(mq.getPayments())); // Parse the XML document Document doc = parser.parse(is); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Setup input Source src = new DOMSource(doc); //Start the transformation and rendering process transformer.transform(src, res); //Prepare response response.setContentType("application/pdf"); response.setContentLength(out.size()); //Send content to Browser response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:org.glimpse.server.manager.xml.XmlUserManager.java
public void setServletContext(ServletContext servletContext) { this.usersDirectory = new File( configuration.getString("users.directory", servletContext.getRealPath("/WEB-INF/users"))); passwordsFile = new File(usersDirectory, "passwords"); }
From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); if (repo != null) { return;/*from ww w .j a v a 2 s .c o m*/ } try { // load properties file ServletContext context = config.getServletContext(); String propsDir = context.getRealPath("/WEB-INF"); String propsFileName = config.getInitParameter(SAIL_PROPERTIES); File propsFile = new File(propsDir, propsFileName); Properties sailProps = new Properties(); sailProps.load(new FileInputStream(propsFile)); BigdataSail sail = new BigdataSail(sailProps); repo = new BigdataSailRepository(sail); repo.initialize(); } catch (Exception ex) { ex.printStackTrace(); throw new ServletException(ex); } }