List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:com.liferay.portal.lar.LayoutExporter.java
protected void exportTheme(LayoutSet layoutSet, ZipWriter zipWriter) throws Exception { Theme theme = layoutSet.getTheme();//from w w w .j a v a 2 s . com String lookAndFeelXML = ContentUtil.get("com/liferay/portal/dependencies/liferay-look-and-feel.xml.tmpl"); lookAndFeelXML = StringUtil.replace(lookAndFeelXML, new String[] { "[$TEMPLATE_EXTENSION$]", "[$VIRTUAL_PATH$]" }, new String[] { theme.getTemplateExtension(), theme.getVirtualPath() }); String servletContextName = theme.getServletContextName(); ServletContext servletContext = ServletContextPool.get(servletContextName); if (servletContext == null) { if (_log.isWarnEnabled()) { _log.warn("Servlet context not found for theme " + theme.getThemeId()); } return; } File themeZip = new File(zipWriter.getPath() + "/theme.zip"); ZipWriter themeZipWriter = ZipWriterFactoryUtil.getZipWriter(themeZip); themeZipWriter.addEntry("liferay-look-and-feel.xml", lookAndFeelXML); File cssPath = null; File imagesPath = null; File javaScriptPath = null; File templatesPath = null; if (!theme.isLoadFromServletContext()) { ThemeLoader themeLoader = ThemeLoaderFactory.getThemeLoader(servletContextName); if (themeLoader == null) { _log.error(servletContextName + " does not map to a theme loader"); } else { String realPath = themeLoader.getFileStorage().getPath() + StringPool.SLASH + theme.getName(); cssPath = new File(realPath + "/css"); imagesPath = new File(realPath + "/images"); javaScriptPath = new File(realPath + "/javascript"); templatesPath = new File(realPath + "/templates"); } } else { cssPath = new File(servletContext.getRealPath(theme.getCssPath())); imagesPath = new File(servletContext.getRealPath(theme.getImagesPath())); javaScriptPath = new File(servletContext.getRealPath(theme.getJavaScriptPath())); templatesPath = new File(servletContext.getRealPath(theme.getTemplatesPath())); } exportThemeFiles("css", cssPath, themeZipWriter); exportThemeFiles("images", imagesPath, themeZipWriter); exportThemeFiles("javascript", javaScriptPath, themeZipWriter); exportThemeFiles("templates", templatesPath, themeZipWriter); }
From source file:ec.sirec.web.base.CatastroControlador.java
public String generarReporteFichaCatastral() throws Exception { //Conexion con local datasource UtilitariosCod util = new UtilitariosCod(); Connection conexion = util.getConexion(); byte[] fichero = null; JasperReport jasperReport = null;//from w w w. j ava 2 s. co m Map parameters = new HashMap(); try { copiarImagenDePredio(); FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) context.getExternalContext().getSession(false); ServletContext servletContext = (ServletContext) context.getExternalContext().getContext(); session.removeAttribute("reporteInforme"); parameters.put("catpre_codigo", catastroPredialActual.getCatpreCodigo()); parameters.put("logo_gad", servletContext.getRealPath("/imagenes/icons/gadPedroMoncayo.jpg")); parameters.put("imagen_predio", servletContext.getRealPath("/imagenes/" + catastroPredialActual.getClaveCatastral() + ".jpg")); //-----------Sub reportes---------------- String subrep1 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR1", subrep1); String subrep2 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2", subrep2); String subrep3 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR3", subrep3); //---------Sub sub reportes pagina 1 String subrep1_1 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR1_1", subrep1_1); String subrep1_2 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR1_2", subrep1_2); String subrep1_3 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR1_3", subrep1_3); // ------------------ //---------Sub sub reportes pagina 2 String subrep2_1 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1", subrep2_1); String subrep2_2 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_2", subrep2_2); // ------------------ //---------Sub sub reporte detalles pagina 2 String subrep2_1_a = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_a", subrep2_1_a); String subrep2_1_b = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_b", subrep2_1_b); String subrep2_1_c = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_c", subrep2_1_c); String subrep2_1_d = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_d", subrep2_1_d); String subrep2_1_e = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_e", subrep2_1_e); String subrep2_1_f = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_f", subrep2_1_f); String subrep2_1_g = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_g", subrep2_1_g); String subrep2_1_h = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_h", subrep2_1_h); String subrep2_1_i = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR2_1_i", subrep2_1_i); //---------Sub sub reportes pagina 3 String subrep3_1 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR3_1", subrep3_1); String subrep3_2 = servletContext.getRealPath("/reportes/fichaCatastral"); parameters.put("SUBREPORT_DIR3_2", subrep3_2); jasperReport = (JasperReport) JRLoader .loadObject(servletContext.getRealPath("/reportes/fichaCatastral/repFichaCatastral.jasper")); fichero = JasperRunManager.runReportToPdf(jasperReport, parameters, conexion); session.setAttribute("reporteInforme", fichero); } catch (JRException ex) { LOGGER.log(Level.SEVERE, null, ex); } catch (Exception e) { LOGGER.log(Level.SEVERE, null, e); } finally { if (conexion != null) { conexion.close(); } } return null; }
From source file:tw.edu.chit.struts.action.course.ReportPrintAction.java
/** * ?/*w w w. j av a2s.c o m*/ * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request request javax.servlet.http.HttpServletRequest object * @param response response javax.servlet.http.HttpServletResponse object * @param sterm */ private void printIntroduction(ActionMapping mapping, DynaActionForm form, HttpServletRequest request, HttpServletResponse response, String sterm) throws Exception { HttpSession session = request.getSession(false); MemberManager mm = (MemberManager) getBean(IConstants.MEMBER_MANAGER_BEAN_NAME); CourseManager cm = (CourseManager) getBean(IConstants.COURSE_MANAGER_BEAN_NAME); ScoreManager sm = (ScoreManager) getBean(IConstants.SCORE_MANAGER_BEAN_NAME); ServletContext context = request.getSession().getServletContext(); Integer year = cm.getSchoolYear(); List<Clazz> clazzes = sm.findClassBy(new Clazz(processClassInfo(form)), getUserCredential(session).getClassInChargeAry(), true); if (!clazzes.isEmpty()) { File templateXLS = new File(context.getRealPath("/WEB-INF/reports/CourseIntrosListPrint.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFSheet sheet = null; int sheetIndex = 0; String departClass = null, emplName = null; Dtime dtime = null; DEmpl de = null; Csno csno = null; CourseIntroduction ci = null; Employee employee = null; List<Dtime> dtimes = null; List<CourseIntroduction> cis = null; for (Clazz clazz : clazzes) { departClass = clazz.getClassNo(); if (Toolket.isDelayClass(departClass)) continue; dtime = new Dtime(); dtime.setDepartClass(departClass); dtime.setSterm(sterm); dtimes = cm.findDtimeBy(dtime, "cscode"); if (!dtimes.isEmpty()) { for (Dtime d : dtimes) { cis = cm.getCourseIntroByDtimeOid(d.getOid(), year, Integer.valueOf(sterm)); if (cis.isEmpty()) continue; ci = cis.get(0); csno = cm.findCourseInfoByCscode(d.getCscode()); employee = mm.findEmployeeByIdno(d.getTechid()); if (employee == null) { if (StringUtils.isBlank(d.getTechid())) { emplName = ""; } else { if (StringUtils.isBlank(d.getTechid())) { emplName = ""; } else { de = mm.findDEmplBy(new DEmpl(d.getTechid())).get(0); emplName = de.getCname(); } } } else emplName = employee.getName(); sheet = workbook.getSheetAt(sheetIndex); workbook.setSheetName(sheetIndex++, departClass + " " + StringUtils.replace(csno.getChiName().replaceAll("/", " "), "", "")); Toolket.setCellValue(sheet, 2, 0, Toolket.getCellValue(sheet, 2, 0).replaceAll("TECH", emplName).replaceAll("DEPT", Toolket.getClassFullName(d.getDepartClass()))); Toolket.setCellValue(sheet, 3, 0, Toolket.getCellValue(sheet, 3, 0).replaceAll("TITLE", csno.getChiName())); Toolket.setCellValue(sheet, 4, 0, Toolket.getCellValue(sheet, 4, 0).replaceAll("ENG", StringUtils.isBlank(csno.getEngName()) ? "" : csno.getEngName())); Toolket.setCellValue(sheet, 5, 0, Toolket.getCellValue(sheet, 5, 0).replaceAll("YEAR", ci.getSchoolYear().toString()) .replaceAll("TERM", d.getSterm()) .replaceAll("CREDIT", d.getCredit().toString())); Toolket.setCellValue(sheet, 7, 0, Toolket.getCellValue(sheet, 7, 0).replaceAll("CHIINTRO", StringUtils.isBlank(ci.getChiIntro()) ? "" : ci.getChiIntro())); Toolket.setCellValue(sheet, 20, 0, Toolket.getCellValue(sheet, 20, 0).replaceAll("ENGINTRO", StringUtils.isBlank(ci.getEngIntro()) ? "" : ci.getEngIntro())); } } } File tempDir = new File( context.getRealPath("/WEB-INF/reports/temp/" + getUserCredential(session).getMember().getIdno() + (new SimpleDateFormat("yyyyMMdd").format(new Date())))); if (!tempDir.exists()) tempDir.mkdirs(); File output = new File(tempDir, "CourseIntros.xls"); FileOutputStream fos = new FileOutputStream(output); workbook.write(fos); fos.close(); JasperReportUtils.printXlsToFrontEnd(response, output); output.delete(); tempDir.delete(); } }
From source file:tw.edu.chit.struts.action.course.ReportPrintAction.java
/** * ??/*w w w.ja va 2 s. co m*/ * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request request javax.servlet.http.HttpServletRequest object * @param response response javax.servlet.http.HttpServletResponse object * @param sterm */ private void printSyllabus(ActionMapping mapping, DynaActionForm form, HttpServletRequest request, HttpServletResponse response, String sterm) throws Exception { HttpSession session = request.getSession(false); MemberManager mm = (MemberManager) getBean(IConstants.MEMBER_MANAGER_BEAN_NAME); CourseManager cm = (CourseManager) getBean(IConstants.COURSE_MANAGER_BEAN_NAME); ScoreManager sm = (ScoreManager) getBean(IConstants.SCORE_MANAGER_BEAN_NAME); ServletContext context = request.getSession().getServletContext(); Integer year = cm.getSchoolYear(); List<Clazz> clazzes = sm.findClassBy(new Clazz(processClassInfo(form)), getUserCredential(session).getClassInChargeAry(), true); if (!clazzes.isEmpty()) { File templateXLS = new File(context.getRealPath("/WEB-INF/reports/CourseSyllabusListPrint.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFSheet sheet = null; int sheetIndex = 0; String departClass = null, emplName = null; Dtime dtime = null; DEmpl de = null; Csno csno = null; CourseSyllabus cs = null; Employee employee = null; List<Dtime> dtimes = null; List<Syllabus> syllabus = null; for (Clazz clazz : clazzes) { departClass = clazz.getClassNo(); if (Toolket.isDelayClass(departClass)) continue; dtime = new Dtime(); dtime.setDepartClass(departClass); dtime.setSterm(sterm); dtimes = cm.findDtimeBy(dtime, "cscode"); if (!dtimes.isEmpty()) { for (Dtime d : dtimes) { cs = cm.getCourseSyllabusByDtimeOid(d.getOid(), year, Integer.valueOf(sterm)); if (cs == null) continue; csno = cm.findCourseInfoByCscode(d.getCscode()); employee = mm.findEmployeeByIdno(d.getTechid()); if (employee == null) { if (StringUtils.isBlank(d.getTechid())) { emplName = ""; } else { if (StringUtils.isBlank(d.getTechid())) { emplName = ""; } else { de = mm.findDEmplBy(new DEmpl(d.getTechid())).get(0); emplName = de.getCname(); } } } else emplName = employee.getName(); sheet = workbook.getSheetAt(sheetIndex); workbook.setSheetName(sheetIndex++, departClass + " " + csno.getChiName().replaceAll("/", " ").replaceAll("", " ")); Toolket.setCellValue(sheet, 2, 0, Toolket.getCellValue(sheet, 2, 0).replaceAll("TECH", emplName).replaceAll("DEPT", Toolket.getClassFullName(d.getDepartClass()))); Toolket.setCellValue(sheet, 3, 0, Toolket.getCellValue(sheet, 3, 0).replaceAll("HOUR", cs.getOfficeHours())); Toolket.setCellValue(sheet, 4, 0, Toolket.getCellValue(sheet, 4, 0).replaceAll("TITLE", csno.getChiName())); Toolket.setCellValue(sheet, 5, 0, Toolket.getCellValue(sheet, 5, 0).replaceAll("ENG", StringUtils.isBlank(csno.getEngName()) ? "" : csno.getEngName())); Toolket.setCellValue(sheet, 6, 0, Toolket.getCellValue(sheet, 6, 0).replaceAll("YEAR", cs.getSchoolYear().toString()) .replaceAll("TERM", d.getSterm()) .replaceAll("CREDIT", d.getCredit().toString())); Toolket.setCellValue(sheet, 7, 0, Toolket.getCellValue(sheet, 7, 0).replaceAll("PRE", cs.getPrerequisites().trim())); Toolket.setCellValue(sheet, 9, 0, Toolket.getCellValue(sheet, 9, 0).replaceAll("OBJ", cs.getObjectives().trim())); syllabus = cs.getSyllabuses(); if (!syllabus.isEmpty()) { int index = 12; for (Syllabus s : syllabus) { Toolket.setCellValue(sheet, index, 0, (s == null || s.getTopic() == null ? "" : s.getTopic().trim())); Toolket.setCellValue(sheet, index, 1, (s == null || s.getContent() == null ? "" : s.getContent().trim())); Toolket.setCellValue(sheet, index, 2, (s == null || s.getHours() == null ? "" : s.getHours().trim())); Toolket.setCellValue(sheet, index, 3, (s == null || s.getWeek() == null ? "" : s.getWeek().trim())); Toolket.setCellValue(sheet, index++, 4, (s == null || s.getRemarks() == null ? "" : s.getRemarks().trim())); } } } } } File tempDir = new File( context.getRealPath("/WEB-INF/reports/temp/" + getUserCredential(session).getMember().getIdno() + (new SimpleDateFormat("yyyyMMdd").format(new Date())))); if (!tempDir.exists()) tempDir.mkdirs(); File output = new File(tempDir, "CourseSyllabus.xls"); FileOutputStream fos = new FileOutputStream(output); workbook.write(fos); fos.close(); JasperReportUtils.printXlsToFrontEnd(response, output); output.delete(); tempDir.delete(); } }
From source file:org.apache.click.util.ClickUtils.java
/** * Returns true if Click resources (JavaScript, CSS, images etc) packaged * in jars can be deployed to the root directory of the webapp, false * otherwise./*from w w w . ja v a2s .c o m*/ * <p/> * This method will return false in restricted environments where write * access to the underlying file system is disallowed. Examples where * write access is not allowed include the WebLogic JEE server (this can be * changed though) and Google App Engine. * * @param servletContext the application servlet context * @return true if writes are allowed, false otherwise */ public static boolean isResourcesDeployable(ServletContext servletContext) { try { boolean canWrite = (servletContext.getRealPath("/") != null); if (!canWrite) { return false; } // Since Google App Engine returns a value for getRealPath, check // SecurityManager if writes are allowed SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite("/click"); } return true; } catch (Throwable e) { return false; } }
From source file:tw.edu.chit.struts.action.course.ReportPrintAction.java
/** * ?/*from w w w . j ava 2s . c o m*/ * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request request javax.servlet.http.HttpServletRequest object * @param response response javax.servlet.http.HttpServletResponse object * @param sterm */ @SuppressWarnings("unchecked") private void printCourseDataPrint(ActionMapping mapping, DynaActionForm form, HttpServletRequest request, HttpServletResponse response, String sterm) throws Exception { HttpSession session = request.getSession(false); AdminManager am = (AdminManager) getBean(IConstants.ADMIN_MANAGER_BEAN_NAME); MemberManager mm = (MemberManager) getBean(IConstants.MEMBER_MANAGER_BEAN_NAME); CourseManager cm = (CourseManager) getBean(IConstants.COURSE_MANAGER_BEAN_NAME); ScoreManager sm = (ScoreManager) getBean(IConstants.SCORE_MANAGER_BEAN_NAME); ServletContext context = request.getSession().getServletContext(); Integer year = cm.getSchoolYear(); List<Clazz> clazzes = sm.findClassBy(new Clazz(processClassInfo(form)), getUserCredential(session).getClassInChargeAry(), true); if (!clazzes.isEmpty()) { File templateXLS = new File(context.getRealPath("/WEB-INF/reports/CourseDataPrint.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFFont fontSize12 = workbook.createFont(); fontSize12.setFontHeightInPoints((short) 12); fontSize12.setFontName("Arial Unicode MS"); HSSFSheet sheet = workbook.getSheetAt(0); Toolket.setCellValue(sheet, 0, 0, "?" + year + "?"); Toolket.setCellValue(sheet, 0, 30, "" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())); int index = 2, boys = 0, girls = 0; boolean flag = false; String departClass = null, optValue = null; Dtime dtime = null; Empl empl = null; Csno csno = null; List<Object> objs = null; List<DtimeTeacher> dtimeTeachers = null; List<String> csGroups = null; List<Student> stmds = null; Object[] data = null; String[] no = { "50000", "T0001", "T0002" }; String[] no1 = { "", "", "", "", "()", "()", "()", "()", "()", "()" }; String[] no2 = { "", "" }; String[] english = { "S0351", "S0352", "S0353", "S0391", "T0090", "T0350", "T0351", "T0352", "T0360", "T0B20", "TD890", "TG321", "TH821", "THQ20", "TP3W0", "TQ090" }; String[] japan = { "T0161" }; StringBuffer buffer = new StringBuffer(); String hql = "SELECT d, cs FROM Dtime d, Csno cs " + "WHERE d.cscode = cs.cscode " + "AND d.sterm = ? AND d.departClass = ?"; String hql1 = "SELECT DISTINCT cg.cname FROM CsGroup cg, CsGroupSet cs " + "WHERE cg.oid = cs.groupOid AND cs.cscode = ? ORDER BY cg.oid"; for (Clazz clazz : clazzes) { departClass = clazz.getClassNo(); if (Toolket.isDelayClass(departClass)) continue; objs = am.find(hql, new Object[] { sterm, departClass }, -1); for (Object o : objs) { data = (Object[]) o; dtime = (Dtime) data[0]; csno = (Csno) data[1]; stmds = cm.findSeldStudentByDtimeOid(dtime.getOid()); if (!ArrayUtils.contains(no, dtime.getCscode()) && !stmds.isEmpty()) { csGroups = am.find(hql1, new Object[] { dtime.getCscode() }, -1); if (csGroups.isEmpty()) Toolket.setCellValue(sheet, index, 0, ""); else { buffer = new StringBuffer(); for (String cg : csGroups) buffer.append(cg).append(","); Toolket.setCellValue(sheet, index, 0, StringUtils.substring(buffer.toString(), 0, buffer.toString().length() - 1)); // ?? } Toolket.setCellValue(sheet, index, 1, ""); // Toolket.setCellValue(sheet, index, 2, "D".equalsIgnoreCase(clazz.getSchoolType()) ? "0" : ("N".equalsIgnoreCase(clazz.getSchoolType()) ? "1" : "2")); // Toolket.setCellValue(sheet, index, 3, Toolket.getSchoolNoBy(clazz)); // / Toolket.setCellValue(sheet, index, 4, StringUtils.abbreviate(csno.getChiName(), 64)); // ?? Toolket.setCellValue(sheet, index, 5, StringUtils.abbreviate(Toolket.getDepartName(departClass), 25)); // Toolket.setCellValue(sheet, index, 6, ""); // Toolket.setCellValue(sheet, index, 7, "1"); // flag = false; for (String noValue : no1) { if (csno.getChiName().endsWith(noValue)) { flag = true; break; } } if (!flag) { for (String noValue : no2) { if (StringUtils.contains(csno.getChiName(), noValue)) { flag = true; break; } } } Toolket.setCellValue(sheet, index, 8, flag ? "1" : "0"); // ? optValue = "1".equals(dtime.getOpt()) ? "0" : ("2".equals(dtime.getOpt()) ? "1" : "3"); Toolket.setCellValue(sheet, index, 9, optValue); // ? Toolket.setCellValue(sheet, index, 10, dtime.getCredit().toString()); // Toolket.setCellValue(sheet, index, 11, dtime.getThour().toString()); // ? Toolket.setCellValue(sheet, index, 12, ""); // ? Toolket.setCellValue(sheet, index, 13, clazz.getGrade()); // Toolket.setCellValue(sheet, index, 14, clazz.getClassName()); // ? Toolket.setCellValue(sheet, index, 15, "http://www.cust.edu.tw/www/info/intro_en.php?coursenum=" + dtime.getOid()); // ? Toolket.setCellValue(sheet, index, 16, "http://www.cust.edu.tw/www/info/intro_obj.php?coursenum=" + dtime.getOid()); // Toolket.setCellValue(sheet, index, 17, ""); // ? buffer = new StringBuffer(); empl = mm.findEmplByIdno(dtime.getTechid()); if (empl != null) buffer.append(empl.getCname()).append(","); dtimeTeachers = cm.getDtimeTeacherBy(dtime.getOid().toString()); for (DtimeTeacher dt : dtimeTeachers) buffer.append(dt.getChiName2()).append(","); Toolket.setCellValue(sheet, index, 18, StringUtils.substring(buffer.toString(), 0, buffer.toString().length() - 1)); // ? Toolket.setCellValue(sheet, index, 19, ""); // Toolket.setCellValue(sheet, index, 20, ""); // if (ArrayUtils.contains(english, csno.getCscode())) { Toolket.setCellValue(sheet, index, 21, ""); // 1 Toolket.setCellValue(sheet, index, 22, ""); // 2 } else if (ArrayUtils.contains(japan, csno.getCscode())) { Toolket.setCellValue(sheet, index, 21, ""); // 1 Toolket.setCellValue(sheet, index, 22, ""); // 2 } else { Toolket.setCellValue(sheet, index, 21, ""); // 1 Toolket.setCellValue(sheet, index, 22, ""); // 2 } Toolket.setCellValue(sheet, index, 23, ""); // Toolket.setCellValue(sheet, index, 24, ""); // 1 Toolket.setCellValue(sheet, index, 25, ""); // 2 Toolket.setCellValue(sheet, index, 26, StringUtils.abbreviate(csno.getEngName(), 255)); // ?? Toolket.setCellValue(sheet, index, 27, "0"); // Toolket.setCellValue(sheet, index, 28, StringUtils.contains(csno.getChiName(), "") ? "2" : Toolket.getCourseStyleBy(dtime.getElearning())); // Toolket.setCellValue(sheet, index, 29, empl == null ? "" : Toolket.getTeacherSourceBy(empl.getUnit())); // ? boys = 0; girls = 0; for (Student student : stmds) { if ("1".equals(student.getSex())) boys++; else if ("2".equals(student.getSex())) girls++; } Toolket.setCellValue(sheet, index, 30, String.valueOf(boys)); // Toolket.setCellValue(sheet, index++, 31, String.valueOf(girls)); // } } } File tempDir = new File( context.getRealPath("/WEB-INF/reports/temp/" + getUserCredential(session).getMember().getIdno() + (new SimpleDateFormat("yyyyMMdd").format(new Date())))); if (!tempDir.exists()) tempDir.mkdirs(); File output = new File(tempDir, "CourseDataPrint.xls"); FileOutputStream fos = new FileOutputStream(output); workbook.write(fos); fos.close(); JasperReportUtils.printXlsToFrontEnd(response, output); output.delete(); tempDir.delete(); } else { Map<String, String> param = new HashMap<String, String>(); File image = new File(context.getRealPath("/pages/images/2002chitS.jpg")); param.put("IMAGE", image.getAbsolutePath()); byte[] bytes = JasperRunManager.runReportToPdf(JasperReportUtils.getNoResultReport(context), param, new JREmptyDataSource()); JasperReportUtils.printPdfToFrontEnd(response, bytes); } }
From source file:org.eclipse.birt.report.utility.ParameterAccessor.java
/** * Returns real path relative to context * //from ww w . j a va2 s. com * @param path * @param context * @return */ private static String getRealPath(String path, ServletContext context) { assert path != null; String realPath = null; try { String orginalPath = path; if (!path.startsWith("/")) //$NON-NLS-1$ { path = "/" + path; //$NON-NLS-1$ } realPath = context.getRealPath(path); if (realPath == null) { // try to get root path from system properties String rootPath = System.getProperty(IBirtConstants.SYS_PROP_ROOT_PATH); if (rootPath != null && isUniversalPath(rootPath)) { path = path.substring(1); realPath = DataUtil.trimSepEnd(rootPath) + "/" + path; //$NON-NLS-1$ } else { URL url = context.getResource("/"); //$NON-NLS-1$ if (url != null) { String urlRoot = null; // for file urls if ("file".equalsIgnoreCase(url.getProtocol())) //$NON-NLS-1$ { urlRoot = DataUtil.trimString(url.getPath()); } // for other url protocals, e.g. path in an unpacked // war, or other global urls else { urlRoot = DataUtil.trimString(url.toExternalForm()); } if (orginalPath.startsWith(urlRoot)) { realPath = orginalPath; } else { if (urlRoot.endsWith("/") //$NON-NLS-1$ || orginalPath.startsWith("/")) //$NON-NLS-1$ { realPath = urlRoot + orginalPath; } else { realPath = urlRoot + "/" + orginalPath; //$NON-NLS-1$ } } } } } } catch (Exception e) { realPath = path; } return realPath; }
From source file:org.apache.ofbiz.content.data.DataEvents.java
/** Streams ImageDataResource data to the output. */ // TODO: remove this method in favor of serveObjectData public static String serveImage(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); ServletContext application = session.getServletContext(); Delegator delegator = (Delegator) request.getAttribute("delegator"); Map<String, Object> parameters = UtilHttp.getParameterMap(request); Debug.logInfo("Img UserAgent - " + request.getHeader("User-Agent"), module); String dataResourceId = (String) parameters.get("imgId"); if (UtilValidate.isEmpty(dataResourceId)) { String errorMsg = "Error getting image record from db: " + " dataResourceId is empty"; Debug.logError(errorMsg, module); request.setAttribute("_ERROR_MESSAGE_", errorMsg); return "error"; }/*from ww w .jav a2s.c om*/ try { GenericValue dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", dataResourceId).cache().queryOne(); if (!"Y".equals(dataResource.getString("isPublic"))) { // now require login... GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); if (userLogin == null) { String errorMsg = "You must be logged in to download the Data Resource with ID [" + dataResourceId + "]"; Debug.logError(errorMsg, module); request.setAttribute("_ERROR_MESSAGE_", errorMsg); return "error"; } // make sure the logged in user can download this content; otherwise is a pretty big security hole for DataResource records... // TODO: should we restrict the roleTypeId? long contentAndRoleCount = EntityQuery.use(delegator).from("ContentAndRole") .where("partyId", userLogin.get("partyId"), "dataResourceId", dataResourceId).queryCount(); if (contentAndRoleCount == 0) { String errorMsg = "You do not have permission to download the Data Resource with ID [" + dataResourceId + "], ie you are not associated with it."; Debug.logError(errorMsg, module); request.setAttribute("_ERROR_MESSAGE_", errorMsg); return "error"; } } String mimeType = DataResourceWorker.getMimeType(dataResource); // hack for IE and mime types String userAgent = request.getHeader("User-Agent"); if (userAgent.indexOf("MSIE") > -1) { Debug.logInfo("Found MSIE changing mime type from - " + mimeType, module); mimeType = "application/octet-stream"; } if (mimeType != null) { response.setContentType(mimeType); } OutputStream os = response.getOutputStream(); Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "", application.getInitParameter("webSiteId"), UtilHttp.getLocale(request), application.getRealPath("/"), false); os.write(IOUtils.toByteArray((ByteArrayInputStream) resourceData.get("stream"))); os.flush(); } catch (GenericEntityException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } catch (GeneralException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } catch (IOException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } return "success"; }
From source file:org.epics.archiverappliance.config.DefaultConfigService.java
@Override public void initialize(ServletContext sce) throws ConfigException { this.servletContext = sce; String contextPath = sce.getContextPath(); logger.info("DefaultConfigService was created with a servlet context " + contextPath); try {/* ww w. jav a 2 s .co m*/ String pathToVersionTxt = sce.getRealPath("ui/comm/version.txt"); logger.debug("The full path to the version.txt is " + pathToVersionTxt); List<String> lines = Files.readAllLines(Paths.get(pathToVersionTxt), Charset.forName("UTF-8")); for (String line : lines) { configlogger.info(line); } } catch (Throwable t) { logger.fatal("Unable to determine appliance version", t); } try { // We first try Java system properties for this appliance's identity // If a property is not defined, then we check the environment. // This gives us the ability to cater to unit tests as well as running using buildAndDeploy scripts without touching the server.xml file. // Probably not the most standard way but suited to this need. // Finally, we use the local machine's hostname as the myidentity. myIdentity = System.getProperty(ARCHAPPL_MYIDENTITY); if (myIdentity == null) { myIdentity = System.getenv(ARCHAPPL_MYIDENTITY); if (myIdentity != null) { logger.info("Obtained my identity from environment variable " + myIdentity); } else { logger.info("Using the local machine's hostname " + myIdentity + " as my identity"); myIdentity = InetAddress.getLocalHost().getCanonicalHostName(); } if (myIdentity == null) { throw new ConfigException("Unable to determine identity of this appliance"); } } else { logger.info("Obtained my identity from Java system properties " + myIdentity); } logger.info("My identity is " + myIdentity); } catch (Exception ex) { String msg = "Cannot determine this appliance's identity using either the environment variable " + ARCHAPPL_MYIDENTITY + " or the java system property " + ARCHAPPL_MYIDENTITY; configlogger.fatal(msg); throw new ConfigException(msg, ex); } // Appliances should be local and come straight from persistence. try { appliances = AppliancesList.loadAppliancesXML(servletContext); } catch (Exception ex) { throw new ConfigException("Exception loading appliances.xml", ex); } myApplianceInfo = appliances.get(myIdentity); if (myApplianceInfo == null) throw new ConfigException("Unable to determine applianceinfo using identity " + myIdentity); configlogger.info("My identity is " + myApplianceInfo.getIdentity() + " and my mgmt URL is " + myApplianceInfo.getMgmtURL()); // To make sure we are not starting multiple appliance with the same identity, we make sure that the hostnames match try { String machineHostName = InetAddress.getLocalHost().getCanonicalHostName(); String[] myAddrParts = myApplianceInfo.getClusterInetPort().split(":"); String myHostNameFromInfo = myAddrParts[0]; if (myHostNameFromInfo.equals("localhost")) { logger.debug( "Using localhost for the cluster inet port. If you are indeed running a cluster, the cluster members will not join the cluster."); } else if (myHostNameFromInfo.equals(machineHostName)) { logger.debug( "Hostname from config and hostname from InetAddress match exactly; we are correctly configured " + machineHostName); } else if (InetAddressValidator.getInstance().isValid(myHostNameFromInfo)) { logger.debug("Using ipAddress for cluster config " + myHostNameFromInfo); } else { String msg = "The hostname from appliances.xml is " + myHostNameFromInfo + " and from a call to InetAddress.getLocalHost().getCanonicalHostName() (typially FQDN) is " + machineHostName + ". These are not identical. They are probably equivalent but to prevent multiple appliances binding to the same identity we enforce this equality."; configlogger.fatal(msg); throw new ConfigException(msg); } } catch (UnknownHostException ex) { configlogger.error( "Got an UnknownHostException when trying to determine the hostname. This happens when DNS is not set correctly on this machine (for example, when using VM's. See the documentation for InetAddress.getLocalHost().getCanonicalHostName()"); } try { String archApplPropertiesFileName = System.getProperty(ARCHAPPL_PROPERTIES_FILENAME); if (archApplPropertiesFileName == null) { archApplPropertiesFileName = System.getenv(ARCHAPPL_PROPERTIES_FILENAME); } if (archApplPropertiesFileName == null) { archApplPropertiesFileName = new URL(this.getClass().getClassLoader() .getResource(DEFAULT_ARCHAPPL_PROPERTIES_FILENAME).toString()).getPath(); configlogger.info( "Loading archappl.properties from the webapp classpath " + archApplPropertiesFileName); } else { configlogger.info("Loading archappl.properties using the environment/JVM property from " + archApplPropertiesFileName); } try (InputStream is = new FileInputStream(new File(archApplPropertiesFileName))) { archapplproperties.load(is); configlogger.info( "Done loading installation specific properties file from " + archApplPropertiesFileName); } catch (Exception ex) { throw new ConfigException( "Exception loading installation specific properties file " + archApplPropertiesFileName, ex); } } catch (ConfigException cex) { throw cex; } catch (Exception ex) { configlogger.fatal("Exception loading the appliance properties file", ex); } switch (contextPath) { case "/mgmt": warFile = WAR_FILE.MGMT; this.mgmtRuntime = new MgmtRuntimeState(this); break; case "/engine": warFile = WAR_FILE.ENGINE; this.engineContext = new EngineContext(this); break; case "/retrieval": warFile = WAR_FILE.RETRIEVAL; this.retrievalState = new RetrievalState(this); break; case "/etl": this.etlPVLookup = new PBThreeTierETLPVLookup(this); warFile = WAR_FILE.ETL; break; default: logger.error("We seem to have introduced a new component into the system " + contextPath); } String pvName2KeyMappingClass = this.getInstallationProperties() .getProperty(ARCHAPPL_PVNAME_TO_KEY_MAPPING_CLASSNAME); if (pvName2KeyMappingClass == null || pvName2KeyMappingClass.equals("") || pvName2KeyMappingClass.length() < 1) { logger.info("Using the default key mapping class"); pvName2KeyConverter = new ConvertPVNameToKey(); pvName2KeyConverter.initialize(this); } else { try { logger.info("Using " + pvName2KeyMappingClass + " as the name to key mapping class"); pvName2KeyConverter = (PVNameToKeyMapping) Class.forName(pvName2KeyMappingClass).newInstance(); pvName2KeyConverter.initialize(this); } catch (Exception ex) { logger.fatal("Cannot initialize pv name to key mapping class " + pvName2KeyMappingClass, ex); throw new ConfigException( "Cannot initialize pv name to key mapping class " + pvName2KeyMappingClass, ex); } } String runtimeFieldsListStr = this.getInstallationProperties() .getProperty("org.epics.archiverappliance.config.RuntimeKeys"); if (runtimeFieldsListStr != null && !runtimeFieldsListStr.isEmpty()) { logger.debug("Got runtime fields from the properties file " + runtimeFieldsListStr); String[] runTimeFieldsArr = runtimeFieldsListStr.split(","); for (String rf : runTimeFieldsArr) { this.runTimeFields.add(rf.trim()); } } startupExecutor = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("Startup executor"); return t; } }); this.addShutdownHook(new Runnable() { @Override public void run() { logger.info("Shutting down startup scheduled executor..."); startupExecutor.shutdown(); } }); this.startupState = STARTUP_SEQUENCE.READY_TO_JOIN_APPLIANCE; if (this.warFile == WAR_FILE.MGMT) { logger.info("Scheduling webappReady's for the mgmt webapp "); MgmtPostStartup mgmtPostStartup = new MgmtPostStartup(this); ScheduledFuture<?> postStartupFuture = startupExecutor.scheduleAtFixedRate(mgmtPostStartup, 10, 20, TimeUnit.SECONDS); mgmtPostStartup.setCancellingFuture(postStartupFuture); } else { logger.info("Scheduling webappReady's for the non-mgmt webapp " + this.warFile.toString()); NonMgmtPostStartup nonMgmtPostStartup = new NonMgmtPostStartup(this, this.warFile.toString()); ScheduledFuture<?> postStartupFuture = startupExecutor.scheduleAtFixedRate(nonMgmtPostStartup, 10, 20, TimeUnit.SECONDS); nonMgmtPostStartup.setCancellingFuture(postStartupFuture); } // Measure some JMX metrics once a minute startupExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { processMetrics.takeMeasurement(); } }, 60, 60, TimeUnit.SECONDS); }
From source file:com.ecyrd.jspwiki.WikiEngine.java
/** * Instantiate using this method when you're running as a servlet and * WikiEngine will figure out where to look for the property * file.//w w w . j a va 2 s . c o m * Do not use this method - use WikiEngine.getInstance() instead. * * @param context A ServletContext. * @param appid An Application ID. This application is an unique random string which * is used to recognize this WikiEngine. * @param props The WikiEngine configuration. * @throws WikiException If the WikiEngine construction fails. */ protected WikiEngine(ServletContext context, String appid, Properties props) throws WikiException { super(); m_servletContext = context; m_appid = appid; // Stash the WikiEngine in the servlet context if (context != null) { context.setAttribute(ATTR_WIKIENGINE, this); m_rootPath = context.getRealPath("/"); } try { // // Note: May be null, if JSPWiki has been deployed in a WAR file. // initialize(props); log.info("Root path for this Wiki is: '" + m_rootPath + "'"); } catch (Exception e) { String msg = Release.APPNAME + ": Unable to load and setup properties from jspwiki.properties. " + e.getMessage(); if (context != null) { context.log(msg); } throw new WikiException(msg, e); } }