List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:org.apache.coyote.tomcat5.CoyoteRequest.java
/** * Return the real path of the specified virtual path. * * @param path Path to be translated//from www.j a v a 2s.c o m * * @deprecated As of version 2.1 of the Java Servlet API, use * <code>ServletContext.getRealPath()</code>. */ public String getRealPath(String path) { if (context == null) return (null); ServletContext servletContext = context.getServletContext(); if (servletContext == null) return (null); else { try { return (servletContext.getRealPath(path)); } catch (IllegalArgumentException e) { return (null); } } }
From source file:org.openspaces.pu.container.jee.context.BootstrapWebApplicationContextListener.java
public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); Boolean bootstraped = (Boolean) servletContext.getAttribute(BOOTSTRAP_CONTEXT_KEY); if (bootstraped != null && bootstraped) { logger.debug("Already performed bootstrap, ignoring"); return;/* w ww.ja v a2 s. c o m*/ } servletContext.setAttribute(BOOTSTRAP_CONTEXT_KEY, true); logger.info("Booting OpenSpaces Web Application Support"); logger.info(ClassLoaderUtils.getCurrentClassPathString("Web Class Loader")); final ProcessingUnitContainerConfig config = new ProcessingUnitContainerConfig(); InputStream is = servletContext.getResourceAsStream(MARSHALLED_CLUSTER_INFO); if (is != null) { try { config.setClusterInfo((ClusterInfo) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is))); servletContext.setAttribute(JeeProcessingUnitContainerProvider.CLUSTER_INFO_CONTEXT, config.getClusterInfo()); } catch (Exception e) { logger.warn("Failed to read cluster info from " + MARSHALLED_CLUSTER_INFO, e); } } else { logger.debug("No cluster info found at " + MARSHALLED_CLUSTER_INFO); } is = servletContext.getResourceAsStream(MARSHALLED_BEAN_LEVEL_PROPERTIES); if (is != null) { try { config.setBeanLevelProperties( (BeanLevelProperties) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is))); servletContext.setAttribute(JeeProcessingUnitContainerProvider.BEAN_LEVEL_PROPERTIES_CONTEXT, config.getBeanLevelProperties()); } catch (Exception e) { logger.warn("Failed to read bean level properties from " + MARSHALLED_BEAN_LEVEL_PROPERTIES, e); } } else { logger.debug("No bean level properties found at " + MARSHALLED_BEAN_LEVEL_PROPERTIES); } Resource resource = null; String realPath = servletContext.getRealPath("/META-INF/spring/pu.xml"); if (realPath != null) { resource = new FileSystemResource(realPath); } if (resource != null && resource.exists()) { logger.debug("Loading [" + resource + "]"); // create the Spring application context final ResourceApplicationContext applicationContext = new ResourceApplicationContext( new Resource[] { resource }, null, config); // "start" the application context applicationContext.refresh(); servletContext.setAttribute(JeeProcessingUnitContainerProvider.APPLICATION_CONTEXT_CONTEXT, applicationContext); String[] beanNames = applicationContext.getBeanDefinitionNames(); for (String beanName : beanNames) { if (applicationContext.getType(beanName) != null) servletContext.setAttribute(beanName, applicationContext.getBean(beanName)); } if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) { final String key = config.getClusterInfo().getUniqueName(); SharedServiceData.addServiceDetails(key, new Callable() { public Object call() throws Exception { ArrayList<ServiceDetails> serviceDetails = new ArrayList<ServiceDetails>(); Map map = applicationContext.getBeansOfType(ServiceDetailsProvider.class); for (Iterator it = map.values().iterator(); it.hasNext();) { ServiceDetails[] details = ((ServiceDetailsProvider) it.next()).getServicesDetails(); if (details != null) { for (ServiceDetails detail : details) { serviceDetails.add(detail); } } } return serviceDetails.toArray(new Object[serviceDetails.size()]); } }); SharedServiceData.addServiceMonitors(key, new Callable() { public Object call() throws Exception { ArrayList<ServiceMonitors> serviceMonitors = new ArrayList<ServiceMonitors>(); Map map = applicationContext.getBeansOfType(ServiceMonitorsProvider.class); for (Iterator it = map.values().iterator(); it.hasNext();) { ServiceMonitors[] monitors = ((ServiceMonitorsProvider) it.next()) .getServicesMonitors(); if (monitors != null) { for (ServiceMonitors monitor : monitors) { serviceMonitors.add(monitor); } } } return serviceMonitors.toArray(new Object[serviceMonitors.size()]); } }); Map map = applicationContext.getBeansOfType(MemberAliveIndicator.class); for (Iterator it = map.values().iterator(); it.hasNext();) { final MemberAliveIndicator memberAliveIndicator = (MemberAliveIndicator) it.next(); if (memberAliveIndicator.isMemberAliveEnabled()) { SharedServiceData.addMemberAliveIndicator(key, new Callable<Boolean>() { public Boolean call() throws Exception { return memberAliveIndicator.isAlive(); } }); } } map = applicationContext.getBeansOfType(ProcessingUnitUndeployingListener.class); for (Iterator it = map.values().iterator(); it.hasNext();) { final ProcessingUnitUndeployingListener listener = (ProcessingUnitUndeployingListener) it .next(); SharedServiceData.addUndeployingEventListener(key, new Callable() { public Object call() throws Exception { listener.processingUnitUndeploying(); return null; } }); } map = applicationContext.getBeansOfType(InternalDumpProcessor.class); for (Iterator it = map.values().iterator(); it.hasNext();) { SharedServiceData.addDumpProcessors(key, it.next()); } } } else { logger.debug("No [" + ApplicationContextProcessingUnitContainerProvider.DEFAULT_PU_CONTEXT_LOCATION + "] to load"); } // load jee specific context listener if (config.getBeanLevelProperties() != null) { String jeeContainer = JeeProcessingUnitContainerProvider .getJeeContainer(config.getBeanLevelProperties()); String className = "org.openspaces.pu.container.jee." + jeeContainer + "." + StringUtils.capitalize(jeeContainer) + "WebApplicationContextListener"; Class clazz = null; try { clazz = Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { // no class, ignore } if (clazz != null) { try { jeeContainerContextListener = (ServletContextListener) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException( "Failed to create JEE specific context listener [" + clazz.getName() + "]", e); } jeeContainerContextListener.contextInitialized(servletContextEvent); } } // set the class loader used so the service bean can use it if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) { SharedServiceData.putWebAppClassLoader(config.getClusterInfo().getUniqueName(), Thread.currentThread().getContextClassLoader()); } }
From source file:org.apache.click.util.ClickUtils.java
/** * Deploy the specified classpath resource to the given target directory * under the web application root directory. * <p/>// w w w . ja v a2s . c o m * This method will <b>not</b> override any existing resources found in the * target directory. * <p/> * If an IOException or SecurityException occurs this method will log a * warning message. * * @param servletContext the web applications servlet context * @param resource the classpath resource name * @param targetDir the target directory to deploy the resource to */ public static void deployFile(ServletContext servletContext, String resource, String targetDir) { if (servletContext == null) { throw new IllegalArgumentException("Null servletContext parameter"); } if (StringUtils.isBlank(resource)) { String msg = "Null resource parameter not defined"; throw new IllegalArgumentException(msg); } String realTargetDir = servletContext.getRealPath("/") + File.separator; if (StringUtils.isNotBlank(targetDir)) { realTargetDir = realTargetDir + targetDir; } LogService logger = getConfigService(servletContext).getLogService(); try { // Create files deployment directory File directory = new File(realTargetDir); if (!directory.exists()) { if (!directory.mkdirs()) { String msg = "could not create deployment directory: " + directory; throw new IOException(msg); } } String destination = resource; int index = resource.lastIndexOf('/'); if (index != -1) { destination = resource.substring(index + 1); } destination = realTargetDir + File.separator + destination; File destinationFile = new File(destination); if (!destinationFile.exists()) { InputStream inputStream = getResourceAsStream(resource, ClickUtils.class); if (inputStream != null) { FileOutputStream fos = null; try { fos = new FileOutputStream(destinationFile); byte[] buffer = new byte[1024]; while (true) { int length = inputStream.read(buffer); if (length < 0) { break; } fos.write(buffer, 0, length); } if (logger.isTraceEnabled()) { int lastIndex = destination.lastIndexOf(File.separatorChar); if (lastIndex != -1) { destination = destination.substring(lastIndex + 1); } String msg = "deployed " + targetDir + "/" + destination; logger.trace(msg); } } finally { close(fos); close(inputStream); } } else { String msg = "could not locate classpath resource: " + resource; throw new IOException(msg); } } } catch (IOException ioe) { String msg = "error occurred deploying resource " + resource + ", error " + ioe; logger.warn(msg); } catch (SecurityException se) { String msg = "error occurred deploying resource " + resource + ", error " + se; logger.warn(msg); } }
From source file:tw.edu.chit.struts.action.course.ReportPrintAction.java
/** * //from ww w. j a v a 2 s . co m * * @param mapping * @param form * @param request * @param response * @param sterm * @throws Exception */ @SuppressWarnings("unchecked") private void printStayTimePrint(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(); String term = form.getString("sterm"); 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/TeachSchedAll.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFFont fontSize12 = workbook.createFont(); fontSize12.setFontHeightInPoints((short) 12); fontSize12.setFontName("Arial Unicode MS"); HSSFSheet sheet = null; int sheetIndex = 0, colOffset = 1, col = 0; boolean isLocationNull = false; String departClass = null; Dtime dtime = null; Empl empl = null; Set<String> idnoSet = new HashSet<String>(); Short colorForStayTime = HSSFColor.AUTOMATIC.index; Short colorForLifeCounseling = HSSFColor.LIGHT_GREEN.index; List<TeacherStayTime> tsts = null; List<LifeCounseling> lcs = null; List<Dtime> dtimes = null; List<Map> map = null; Map content = null; for (Clazz clazz : clazzes) { departClass = clazz.getClassNo(); dtime = new Dtime(); dtime.setDepartClass(departClass); dtime.setSterm(sterm); dtimes = cm.findDtimeBy(dtime, "cscode"); if (!dtimes.isEmpty()) { for (Dtime d : dtimes) { if (StringUtils.isNotBlank(d.getTechid())) idnoSet.add(d.getTechid()); } } } for (String idno : idnoSet) { empl = mm.findEmplByIdno(idno); if (empl != null && "1".equalsIgnoreCase(empl.getCategory())) { sheet = workbook.getSheetAt(sheetIndex); workbook.setSheetName(sheetIndex++, empl.getCname()); isLocationNull = empl.getLocation() == null; Toolket.setCellValue(sheet, 0, 1, year + "" + term + "" + empl.getCname() + "?" + " (:" + (isLocationNull ? "" : StringUtils.defaultIfEmpty(empl.getLocation().getExtension(), "")) + " ?:" + (isLocationNull ? "" : StringUtils.defaultIfEmpty(empl.getLocation().getRoomId(), "")) + ")"); map = cm.findCourseByTeacherTermWeekdaySched(empl.getIdno(), term.toString()); for (int i = 0; i < 14; i++) { for (int j = 0; j < 7; j++) { content = map.get(j * 15 + i); if (!CollectionUtils.isEmpty(content)) { Toolket.setCellValue(sheet, i + 2, j + 2, (String) content.get("ClassName") + "\n" + (String) content.get("chi_name") + "\n" + (String) content.get("place")); } } } List<TeacherStayTime> myTsts = cm.ezGetBy( " Select Week, Node1, Node2, Node3, Node4, Node5, Node6, Node7, Node8, Node9, Node10, " + " Node11, Node12, Node13, Node14 " + " From TeacherStayTime " + " Where SchoolYear='" + year + "'" + " And SchoolTerm='" + term + "' " + " And parentOid='" + empl.getOid() + "'"); List myTsts2 = new ArrayList(); //int colOffset = 1, col = 0; for (int i = 0; i < myTsts.size(); i++) { //for (TeacherStayTime tst : tsts) { myTsts2.add(myTsts.get(i)); String s = myTsts2.get(i).toString(); col = Integer.parseInt(s.substring(6, 7)) + colOffset; //Week //if (tst.getNode1() != null && tst.getNode1() == 1) { if (Integer.parseInt(s.substring(15, 16)) == 1) { //Node1 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 2, col))) Toolket.setCellValue(workbook, sheet, 2, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(24, 25)) == 1) { //Node2 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 3, col))) Toolket.setCellValue(workbook, sheet, 3, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(33, 34)) == 1) { //Node3 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 4, col))) Toolket.setCellValue(workbook, sheet, 4, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(42, 43)) == 1) { //Node4 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 5, col))) Toolket.setCellValue(workbook, sheet, 5, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(51, 52)) == 1) { //Node5 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 6, col))) Toolket.setCellValue(workbook, sheet, 6, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(60, 61)) == 1) { //Node6 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 7, col))) Toolket.setCellValue(workbook, sheet, 7, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(69, 70)) == 1) { //Node7 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 8, col))) Toolket.setCellValue(workbook, sheet, 8, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(78, 79)) == 1) { //Node8 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 9, col))) Toolket.setCellValue(workbook, sheet, 9, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(87, 88)) == 1) { //Node9 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 10, col))) Toolket.setCellValue(workbook, sheet, 10, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(97, 98)) == 1) { //Node10 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 11, col))) Toolket.setCellValue(workbook, sheet, 11, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(107, 108)) == 1) { //Node11 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 12, col))) Toolket.setCellValue(workbook, sheet, 12, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(117, 118)) == 1) { //Node12 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 13, col))) Toolket.setCellValue(workbook, sheet, 13, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(127, 128)) == 1) { //Node13 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 14, col))) Toolket.setCellValue(workbook, sheet, 14, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (Integer.parseInt(s.substring(137, 138)) == 1) { //Node14 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 15, col))) Toolket.setCellValue(workbook, sheet, 15, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } } //List<LifeCounseling> lcs = empl.getLifeCounseling(); List<LifeCounseling> myLcs = cm.ezGetBy( " Select Week, Node1, Node2, Node3, Node4, Node5, Node6, Node7, Node8, Node9, Node10, " + " Node11, Node12, Node13, Node14 " + " From LifeCounseling Where ParentOid='" + empl.getOid() + "'"); List myLcs2 = new ArrayList(); colOffset = 1; col = 0; //for (LifeCounseling lc : lcs) { for (int y = 0; y < myLcs.size(); y++) { myLcs2.add(myLcs.get(y)); String st = myLcs2.get(y).toString(); col = Integer.parseInt(st.substring(6, 7)) + colOffset; //col = lc.getWeek() + colOffset; //if (lc.getNode1() != null && lc.getNode1() == 1) { if (Integer.parseInt(st.substring(15, 16)) == 1) { //Node1 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 2, col))) Toolket.setCellValue(workbook, sheet, 2, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode2() != null && lc.getNode2() == 1) { if (Integer.parseInt(st.substring(24, 25)) == 1) { //Node2 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 3, col))) Toolket.setCellValue(workbook, sheet, 3, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode3() != null && lc.getNode3() == 1) { if (Integer.parseInt(st.substring(33, 34)) == 1) { //Node3 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 4, col))) Toolket.setCellValue(workbook, sheet, 4, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode4() != null && lc.getNode4() == 1) { if (Integer.parseInt(st.substring(42, 43)) == 1) { //Node4 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 5, col))) Toolket.setCellValue(workbook, sheet, 5, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode5() != null && lc.getNode5() == 1) { if (Integer.parseInt(st.substring(51, 52)) == 1) { //Node5 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 6, col))) Toolket.setCellValue(workbook, sheet, 6, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode6() != null && lc.getNode6() == 1) { if (Integer.parseInt(st.substring(60, 61)) == 1) { //Node6 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 7, col))) Toolket.setCellValue(workbook, sheet, 7, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode7() != null && lc.getNode7() == 1) { if (Integer.parseInt(st.substring(69, 70)) == 1) { //Node7 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 8, col))) Toolket.setCellValue(workbook, sheet, 8, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode8() != null && lc.getNode8() == 1) { if (Integer.parseInt(st.substring(78, 79)) == 1) { //Node8 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 9, col))) Toolket.setCellValue(workbook, sheet, 9, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode9() != null && lc.getNode9() == 1) { if (Integer.parseInt(st.substring(87, 88)) == 1) { //Node9 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 10, col))) Toolket.setCellValue(workbook, sheet, 10, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode10() != null && lc.getNode10() == 1) { if (Integer.parseInt(st.substring(97, 98)) == 1) { //Node10 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 11, col))) Toolket.setCellValue(workbook, sheet, 11, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode11() != null && lc.getNode11() == 1) { if (Integer.parseInt(st.substring(107, 108)) == 1) { //Node11 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 12, col))) Toolket.setCellValue(workbook, sheet, 12, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode12() != null && lc.getNode12() == 1) { if (Integer.parseInt(st.substring(117, 118)) == 1) { //Node12 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 13, col))) Toolket.setCellValue(workbook, sheet, 13, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode13() != null && lc.getNode13() == 1) { if (Integer.parseInt(st.substring(127, 128)) == 1) { //Node13 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 14, col))) Toolket.setCellValue(workbook, sheet, 14, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } //if (lc.getNode14() != null && lc.getNode14() == 1) { if (Integer.parseInt(st.substring(137, 138)) == 1) { //Node14 if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 15, col))) Toolket.setCellValue(workbook, sheet, 15, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } } } } //===================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /* tsts = empl.getStayTime(); for (TeacherStayTime tst : tsts) { col = tst.getWeek() + colOffset; if (tst.getNode1() != null && tst.getNode1() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 2, col))) Toolket.setCellValue(workbook, sheet, 2, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode2() != null && tst.getNode2() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 3, col))) Toolket.setCellValue(workbook, sheet, 3, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode3() != null && tst.getNode3() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 4, col))) Toolket.setCellValue(workbook, sheet, 4, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode4() != null && tst.getNode4() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 5, col))) Toolket.setCellValue(workbook, sheet, 5, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode5() != null && tst.getNode5() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 6, col))) Toolket.setCellValue(workbook, sheet, 6, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode6() != null && tst.getNode6() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 7, col))) Toolket.setCellValue(workbook, sheet, 7, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode7() != null && tst.getNode7() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 8, col))) Toolket.setCellValue(workbook, sheet, 8, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode8() != null && tst.getNode8() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 9, col))) Toolket.setCellValue(workbook, sheet, 9, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode9() != null && tst.getNode9() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 10, col))) Toolket.setCellValue(workbook, sheet, 10, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode10() != null && tst.getNode10() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 11, col))) Toolket.setCellValue(workbook, sheet, 11, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode11() != null && tst.getNode11() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 12, col))) Toolket.setCellValue(workbook, sheet, 12, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode12() != null && tst.getNode12() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 13, col))) Toolket.setCellValue(workbook, sheet, 13, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode13() != null && tst.getNode13() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 14, col))) Toolket.setCellValue(workbook, sheet, 14, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } if (tst.getNode14() != null && tst.getNode14() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 15, col))) Toolket.setCellValue(workbook, sheet, 15, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForStayTime); } } lcs = empl.getLifeCounseling(); colOffset = 1; col = 0; for (LifeCounseling lc : lcs) { col = lc.getWeek() + colOffset; if (lc.getNode1() != null && lc.getNode1() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 2, col))) Toolket.setCellValue(workbook, sheet, 2, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode2() != null && lc.getNode2() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 3, col))) Toolket.setCellValue(workbook, sheet, 3, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode3() != null && lc.getNode3() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 4, col))) Toolket.setCellValue(workbook, sheet, 4, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode4() != null && lc.getNode4() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 5, col))) Toolket.setCellValue(workbook, sheet, 5, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode5() != null && lc.getNode5() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 6, col))) Toolket.setCellValue(workbook, sheet, 6, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode6() != null && lc.getNode6() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 7, col))) Toolket.setCellValue(workbook, sheet, 7, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode7() != null && lc.getNode7() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 8, col))) Toolket.setCellValue(workbook, sheet, 8, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode8() != null && lc.getNode8() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 9, col))) Toolket.setCellValue(workbook, sheet, 9, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode9() != null && lc.getNode9() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 10, col))) Toolket.setCellValue(workbook, sheet, 10, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode10() != null && lc.getNode10() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 11, col))) Toolket.setCellValue(workbook, sheet, 11, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode11() != null && lc.getNode11() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 12, col))) Toolket.setCellValue(workbook, sheet, 12, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode12() != null && lc.getNode12() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 13, col))) Toolket.setCellValue(workbook, sheet, 13, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode13() != null && lc.getNode13() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 14, col))) Toolket.setCellValue(workbook, sheet, 14, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } if (lc.getNode14() != null && lc.getNode14() == 1) { if (StringUtils.isEmpty(Toolket.getCellValue(sheet, 15, col))) Toolket.setCellValue(workbook, sheet, 15, col, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, colorForLifeCounseling); } } } */ //=================================>>>>>>>>>>>>>>>>>>>>> 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, "StayTimeList.xls"); FileOutputStream fos = new FileOutputStream(output); workbook.write(fos); fos.close(); JasperReportUtils.printXlsToFrontEnd(response, output); output.delete(); tempDir.delete(); } }
From source file:org.openmeetings.servlet.outputhandler.BackupExport.java
public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, ServletContext servletCtx) throws ServletException, IOException { String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; }/*w w w . ja v a2s .c om*/ log.debug("sid: " + sid); Long users_id = sessionManagement.checkSession(sid); Long user_level = userManagement.getUserLevelByID(users_id); log.debug("users_id: " + users_id); log.debug("user_level: " + user_level); if (authLevelManagement.checkAdminLevel(user_level)) { // if (true) { String includeFileOption = httpServletRequest.getParameter("includeFileOption"); boolean includeFiles = includeFileOption == null || "yes".equals(includeFileOption); String moduleName = httpServletRequest.getParameter("moduleName"); if (moduleName == null) { moduleName = "moduleName"; } log.debug("moduleName: " + moduleName); if (moduleName.equals("backup")) { /* * ##################### Create Base Folder structure */ String current_dir = servletCtx.getRealPath("/"); File working_dir = new File(new File(current_dir, OpenmeetingsVariables.UPLOAD_DIR), "backup"); if (!working_dir.exists()) { working_dir.mkdir(); } String dateString = "backup_" + CalendarPatterns.getTimeForStreamId(new Date()); File backup_dir = new File(working_dir, dateString); String requestedFile = dateString + ".zip"; File backupFile = new File(backup_dir, requestedFile); String full_path = backupFile.getAbsolutePath(); try { performExport(full_path, backup_dir, includeFiles, current_dir); RandomAccessFile rf = new RandomAccessFile(full_path, "r"); httpServletResponse.reset(); httpServletResponse.resetBuffer(); httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + requestedFile + "\""); httpServletResponse.setHeader("Content-Length", "" + rf.length()); OutputStream out = httpServletResponse.getOutputStream(); byte[] buffer = new byte[1024]; int readed = -1; while ((readed = rf.read(buffer, 0, buffer.length)) > -1) { out.write(buffer, 0, readed); } rf.close(); out.flush(); out.close(); } catch (Exception er) { log.error("Error exporting: ", er); } if (backupFile.exists()) { // log.debug("DELETE :1: "+backupFile.getAbsolutePath()); backupFile.delete(); } deleteDirectory(backup_dir); } } else { log.debug("ERROR LangExport: not authorized FileDownload " + (new Date())); } }
From source file:org.openbravo.client.kernel.StaticResourceComponent.java
/** * @return all static resources needed by the application and placed in the top of the application * page, in order based on module dependencies and using an unique version string to force * client side reload or caching. */// w ww . ja v a 2 s . c om public String getStaticResourceFileName() { final List<Module> modules = KernelUtils.getInstance().getModulesOrderedByDependency(); final ServletContext context = (ServletContext) getParameters().get(KernelConstants.SERVLET_CONTEXT); final StringBuffer sb = new StringBuffer(); final String skinParam; if (getParameters().containsKey(KernelConstants.SKIN_PARAMETER)) { skinParam = (String) getParameters().get(KernelConstants.SKIN_PARAMETER); } else { skinParam = KernelConstants.SKIN_DEFAULT; } int cntDynamicScripts = 0; final String appName = getApplicationName(); for (Module module : modules) { for (ComponentProvider provider : componentProviders) { final List<ComponentResource> resources = provider.getGlobalComponentResources(); if (resources == null || resources.size() == 0) { continue; } if (provider.getModule().getId().equals(module.getId())) { for (ComponentResource resource : resources) { if (!resource.isValidForApp(appName)) { continue; } log.debug("Processing resource: " + resource); String resourcePath = resource.getPath(); if (resource.getType() == ComponentResourceType.Stylesheet) { // do these differently... } else if (resource.getType() == ComponentResourceType.Static) { if (resourcePath.startsWith(KernelConstants.KERNEL_JAVA_PACKAGE)) { final String[] pathParts = WebServiceUtil.getInstance().getSegments( resourcePath.substring(KernelConstants.KERNEL_JAVA_PACKAGE.length())); final Component component = provider.getComponent(pathParts[1], getParameters()); sb.append(ComponentGenerator.getInstance().generate(component)).append("\n"); } else { // Skin version handling if (resourcePath.contains(KernelConstants.SKIN_PARAMETER)) { resourcePath = resourcePath.replaceAll(KernelConstants.SKIN_PARAMETER, skinParam); } try { final File file = new File(context.getRealPath(resourcePath)); if (!file.exists() || !file.canRead()) { log.error(file.getAbsolutePath() + " cannot be read"); continue; } String resourceContents = FileUtils.readFileToString(file, "UTF-8"); sb.append(resourceContents).append("\n"); } catch (Exception e) { log.error("Error reading file: " + resource, e); } } } else if (resource.getType() == ComponentResourceType.Dynamic) { if (resourcePath.startsWith("/") && getContextUrl().length() > 0) { resourcePath = getContextUrl() + resourcePath.substring(1); } else { resourcePath = getContextUrl() + resourcePath; } sb.append("$LAB.script('" + resourcePath + "').wait(function(){var _exception; try{\n"); cntDynamicScripts++; } else { log.error("Resource " + resource + " not supported"); } } } } } if (!"".equals(sb.toString())) { /* * If a module is in development or the application is running the tests, add the isDebug * variable to the generated javascript file. * * If the isDebug variable is present in the javascript files, the code that calls * OB.UTIL.Debug will not be executed * * This option is intended to run additional code (checks, etc) that will not be run while in * production. * * This improves performance at the same time that the developer have a tool to improve * stability. * * TODO: add an algorithm to remove the OB.UTIL.Debug code and calls from the generated * javacript file * * TODO: don't load the ob-debug.js file if not in use */ if (isInDevelopment() || OBPropertiesProvider.getInstance().getBooleanProperty("test.environment")) { // append a global isDebug var and the causes that provoked the application to enter Debug mode sb.insert(0, String.format( "var isDebug = true;\nvar debugCauses = {\n isInDevelopment: %s,\n isTestEnvironment: %s\n};\n\n", isInDevelopment(), OBPropertiesProvider.getInstance().getBooleanProperty("test.environment"))); } sb.append("if (window.onerror && window.onerror.name === '" + KernelConstants.BOOTSTRAP_ERROR_HANDLER_NAME + "') { window.onerror = null; }"); sb.append( "if (typeof OBStartApplication !== 'undefined' && Object.prototype.toString.call(OBStartApplication) === '[object Function]') { OBStartApplication(); }"); } for (int i = 0; i < cntDynamicScripts; i++) { // add extra exception handling code otherwise exceptions occuring in // the Labs wait function are not visible. sb.append("\n} catch (_exception) {"); sb.append( "if (isc) { isc.Log.logError(_exception + ' ' + _exception.message + ' ' + _exception.stack); }"); sb.append("if (console && console.trace) { console.trace();}"); sb.append("}\n});"); } // note compress, note that modules are cached in memory // when changing development status, system needs to be restarted. final String output; // in classicmode the isc combined is included, compressing that gives errors if (!isInDevelopment() && !isClassicMode() && !OBPropertiesProvider.getInstance().getBooleanProperty("test.environment")) { output = JSCompressor.getInstance().compress(sb.toString()); } else { output = sb.toString(); } final String md5 = DigestUtils.md5Hex(output); final File dir = new File(context.getRealPath(GEN_TARGET_LOCATION)); if (!dir.exists()) { dir.mkdir(); } File outFile = new File(context.getRealPath(GEN_TARGET_LOCATION + "/" + md5 + ".js")); if (!outFile.exists()) { try { log.debug("Writing file: " + outFile.getAbsolutePath()); FileUtils.writeStringToFile(outFile, output, "UTF-8"); } catch (Exception e) { log.error("Error writing file: " + e.getMessage(), e); } } return md5; }
From source file:Admin_Thesaurus.ImportData.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (SystemIsLockedForAdministrativeJobs(request, response)) { return;/*from ww w . j a va 2s. co m*/ } String basePath = request.getSession().getServletContext().getRealPath(""); // ---------------------- LOCK SYSTEM ---------------------- ConfigDBadmin config = new ConfigDBadmin(basePath); DBAdminUtilities dbAdminUtils = new DBAdminUtilities(); dbAdminUtils.LockSystemForAdministrativeJobs(config); response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); ServletContext context = session.getServletContext(); SessionWrapperClass sessionInstance = new SessionWrapperClass(); init(request, response, sessionInstance); PrintWriter out = response.getWriter(); OutputStreamWriter logFileWriter = null; try { // check for previous logon but because of ajax usage respond with Session Invalidate str UserInfoClass SessionUserInfo = (UserInfoClass) sessionInstance.getAttribute("SessionUser"); if (SessionUserInfo == null || !SessionUserInfo.servletAccessControl(this.getClass().getName())) { out.println("Session Invalidate"); response.sendRedirect("Index"); return; } //tools Utilities u = new Utilities(); DBGeneral dbGen = new DBGeneral(); DBImportData dbImport = new DBImportData(); DBMergeThesauri dbMerge = new DBMergeThesauri(); StringObject translatedMsgObj = new StringObject(""); Vector<String> thesauriNames = new Vector<String>(); CommonUtilsDBadmin common_utils = new CommonUtilsDBadmin(config); StringObject resultObj = new StringObject(""); String initiallySelectedThesaurus = SessionUserInfo.selectedThesaurus; //Parameters String xmlFilePath = request.getParameter("importXMLfilename"); //String importSchemaName = request.getParameter("schematype"); String importSchemaName = ConstantParameters.xmlschematype_THEMAS; String importThesaurusName = request.getParameter("Import_Thesaurus_NewName_NAME"); String importMethodChoice = request.getParameter("ImportThesaurusMode");//thesaurusImport or bulkImport String importHierarchyName = u .getDecodedParameterValue(request.getParameter("Import_Thesaurus_HierarchyName")); String pathToErrorsXML = context.getRealPath("/translations/Consistencies_Error_Codes.xml"); String language = context.getInitParameter("LocaleLanguage"); String country = context.getInitParameter("LocaleCountry"); String WebAppUsersFileName = request.getSession().getServletContext() .getRealPath("/" + UsersClass.WebAppUsersXMLFilePath); String logPath = context.getRealPath("/" + ConstantParameters.LogFilesFolderName); String logFileNamePath = logPath; String webAppSaveResults_Folder = Parameters.Save_Results_Folder; String pathToSaveScriptingAndLocale = context .getRealPath("/translations/SaveAll_Locale_And_Scripting.xml"); Locale targetLocale = new Locale(language, country); if ((importMethodChoice.equals("thesaurusImport") && (importThesaurusName != null)) || (importMethodChoice.equals("bulkImport") && importHierarchyName != null)) { UpDownFiles fup = new UpDownFiles(); String[] formData = new String[10]; FileItem[] dom = fup.prepareToUpBinary(request, formData); //Hashtable initParams = UpDownFiles.uploadParams; if (dom[0] != null) { String filename = xmlFilePath; ///String caption = (String) initParams.get("caption"); filename = filename.substring(filename.lastIndexOf(File.separator) + 1); String fileType = filename.substring(filename.lastIndexOf(".") + 1); String userFileName = filename.substring(0, filename.lastIndexOf(".")); filename = userFileName + "(" + getDate() + " " + getTime() + ")." + fileType; String fullPath = getServletContext().getRealPath("/Uploads") + "/" + filename; xmlFilePath = fullPath; if (fup.writeBinary(dom[0], fullPath)) { //mode = 1; } else { //mode = -1; } } else { //mode = -1; } } QClass Q = new QClass(); TMSAPIClass TA = new TMSAPIClass(); IntegerObject sis_session = new IntegerObject(); IntegerObject tms_session = new IntegerObject(); //open connection and start transaction if (dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, null, null, true) == QClass.APIFail) { Utils.StaticClass .webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName()); return; } dbGen.GetExistingThesaurus(false, thesauriNames, Q, sis_session); if (importMethodChoice.equals("thesaurusImport")) { //Format Name Of import Thesaurus importThesaurusName = importThesaurusName.trim(); importThesaurusName = importThesaurusName.replaceAll(" ", "_"); importThesaurusName = importThesaurusName.toUpperCase(); if (thesauriNames.contains(importThesaurusName)) { resultObj.setValue(u.translateFromMessagesXML("root/ImportData/importThesaurusNameFailure", new String[] { importThesaurusName })); //resultObj.setValue("Thesaurus '" + importThesaurusName + "' already exists in database. Please choose a different name for the Thesaurus."); Vector<String> allHierarchies = new Vector<String>(); Vector<String> allGuideTerms = new Vector<String>(); dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session, allHierarchies, allGuideTerms); //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); //Q.TEST_abort_transaction(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); StringBuffer xml = new StringBuffer(); xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI)); xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms, targetLocale)); xml.append(getXMLMiddle(thesauriNames, u.translateFromMessagesXML("root/ImportData/ImportFunctionFailure", null) + resultObj.getValue(), importMethodChoice)); xml.append(u.getXMLUserInfo(SessionUserInfo)); xml.append(u.getXMLEnd()); u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl"); // ---------------------- UNLOCK SYSTEM ---------------------- dbAdminUtils.UnlockSystemForAdministrativeJobs(); return; } } else if (importMethodChoice.equals("bulkImport")) { importThesaurusName = SessionUserInfo.selectedThesaurus; if (thesauriNames.contains(importThesaurusName) == false) { //String pathToMessagesXML = context.getRealPath("/translations/Messages.xml"); //StringObject resultMessageObj = new StringObject(); StringObject resultMessageObj_2 = new StringObject(); //Vector<String> errorArgs = new Vector<String>(); resultObj.setValue(u.translateFromMessagesXML("root/ImportData/ThesaurusDoesNotExist", new String[] { importThesaurusName })); //resultObj.setValue("Thesaurus '" + importThesaurusName + "' does not exist in database. Please choose a different thesaurus if this one still exists."); Vector<String> allHierarchies = new Vector<String>(); Vector<String> allGuideTerms = new Vector<String>(); dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session, allHierarchies, allGuideTerms); //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); //Q.TEST_abort_transaction(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); StringBuffer xml = new StringBuffer(); xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI)); xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms, targetLocale)); resultMessageObj_2 .setValue(u.translateFromMessagesXML("root/ImportData/InsertionFailure", null)); xml.append(getXMLMiddle(thesauriNames, resultMessageObj_2.getValue() + resultObj.getValue(), importMethodChoice)); //xml.append(getXMLMiddle(thesauriNames, "Data insertion failure. " + resultObj.getValue(),importMethodChoice)); xml.append(u.getXMLUserInfo(SessionUserInfo)); xml.append(u.getXMLEnd()); u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl"); // ---------------------- UNLOCK SYSTEM ---------------------- dbAdminUtils.UnlockSystemForAdministrativeJobs(); return; } } //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); Utils.StaticClass.closeDb(); StringObject DBbackupFileNameCreated = new StringObject(""); long startTime = Utilities.startTimer(); String time = Utilities.GetNow(); String Filename = "Import_Thesaurus_" + importThesaurusName + "_" + time; logFileNamePath += "/" + Filename + ".xml"; try { OutputStream fout = new FileOutputStream(logFileNamePath); OutputStream bout = new BufferedOutputStream(fout); logFileWriter = new OutputStreamWriter(bout, "UTF-8"); logFileWriter.append(ConstantParameters.xmlHeader);//+ "\r\n" //logFileWriter.append("<?xml-stylesheet type=\"text/xsl\" href=\"../" + webAppSaveResults_Folder + "/ImportCopyMergeThesaurus_Report.xsl" + "\"?>\r\n"); logFileWriter.append("<page language=\"" + Parameters.UILang + "\" primarylanguage=\"" + Parameters.PrimaryLang.toLowerCase() + "\">\r\n"); logFileWriter.append("<title>" + u.translateFromMessagesXML("root/ImportData/ReportTitle", new String[] { importThesaurusName, time }) + "</title>\r\n" + "<pathToSaveScriptingAndLocale>" + pathToSaveScriptingAndLocale + "</pathToSaveScriptingAndLocale>\r\n"); //logFileWriter.append("<!--"+time + " LogFile for data import in thesaurus: " + importThesaurusName +".-->\r\n"); Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + time + " LogFile for data import in thesaurus: " + importThesaurusName + "."); } catch (Exception exc) { Utils.StaticClass.webAppSystemOutPrintln( Parameters.LogFilePrefix + "Error in opening file: " + exc.getMessage()); Utils.StaticClass.handleException(exc); } if (importMethodChoice.equals("thesaurusImport")) { if (dbImport.thesaurusImportActions(SessionUserInfo, common_utils, config, targetLocale, pathToErrorsXML, xmlFilePath, importSchemaName, importThesaurusName, "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated, resultObj, logFileWriter) == false) { abortActions(request, sessionInstance, context, targetLocale, common_utils, initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj, out); return; } } else if (importMethodChoice.equals("bulkImport")) { /* //open connection and start Transaction if(dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, tms_session, SessionUserInfo.selectedThesaurus, false)==QClass.APIFail) { Utils.StaticClass.webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName()); return; } */ if (dbImport.bulkImportActions(sessionInstance, context, common_utils, config, targetLocale, pathToErrorsXML, xmlFilePath, importThesaurusName, importHierarchyName, "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated, resultObj, logFileWriter) == false) { abortActions(request, sessionInstance, context, targetLocale, common_utils, initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj, out); return; } } commitActions(request, WebAppUsersFileName, sessionInstance, context, targetLocale, importThesaurusName, out, Filename.concat(".html")); //ReportSuccessMessage logFileWriter .append("\r\n<creationInfo>" + u.translateFromMessagesXML("root/ImportData/ReportSuccessMessage", new String[] { importThesaurusName, xmlFilePath, ((Utilities.stopTimer(startTime)) / 60) + "" }) + "</creationInfo>\r\n"); if (logFileWriter != null) { logFileWriter.append("</page>"); logFileWriter.flush(); logFileWriter.close(); } //Now XSL should be found and java xsl transformation should be performed String XSL = context.getRealPath("/" + webAppSaveResults_Folder) + "/ImportCopyMergeThesaurus_Report.xsl"; u.XmlFileTransform(logFileNamePath, XSL, logPath + "/" + Filename.concat(".html")); } catch (Exception e) { Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + ".Exception catched in servlet " + getServletName() + ". Message:" + e.getMessage()); Utils.StaticClass.handleException(e); if (logFileWriter != null) { logFileWriter.append("</page>"); logFileWriter.flush(); logFileWriter.close(); } } finally { out.flush(); out.close(); sessionInstance.writeBackToSession(session); } }
From source file:org.mifos.framework.ApplicationInitializer.java
private void copyResources(ServletContext sc) throws IOException { URL protocol = ETLReportDWHelper.class.getClassLoader().getResource("sql/release-upgrades.txt"); ConfigurationLocator configurationLocator = new ConfigurationLocator(); String configPath = configurationLocator.getConfigurationDirectory(); try {/*ww w. j av a 2s.c o m*/ if (protocol.getProtocol().equals("jar")) { String destinationDirectoryForJobs = configPath + "/ETL/MifosDataWarehouseETL"; String destinationDirectoryForJar = configPath + "/ETL/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar"; String pathFromJar = "/WEB-INF/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar"; String pathFromJobs = "/WEB-INF/MifosDataWarehouseETL/"; if (File.separatorChar == '\\') { destinationDirectoryForJobs = destinationDirectoryForJobs.replaceAll("/", "\\\\"); destinationDirectoryForJar = destinationDirectoryForJar.replaceAll("/", "\\\\"); } File directory = new File(destinationDirectoryForJobs); directory.mkdirs(); FileUtils.cleanDirectory(directory); File jarDest = new File(destinationDirectoryForJar); URL fullPath = sc.getResource(pathFromJar); File f = new File(sc.getResource(pathFromJobs).toString().replace("file:", "")); for (File fileEntry : f.listFiles()) { FileUtils.copyFileToDirectory(fileEntry, directory); logger.info("Copy file: " + fileEntry.getName() + " to: " + directory); } FileUtils.copyURLToFile(fullPath, jarDest); logger.info("Copy file: " + fullPath + " to: " + directory); } } catch (NullPointerException e) { String destinationDirectoryForJobs = configPath + "/ETL/MifosDataWarehouseETL"; String destinationDirectoryForJar = configPath + "/ETL/"; String pathFromJar = sc.getRealPath("/") + "/WEB-INF/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar"; String pathFromJobs = sc.getRealPath("/") + "/WEB-INF/MifosDataWarehouseETL/"; if (File.separatorChar == '\\') { destinationDirectoryForJobs = destinationDirectoryForJobs.replaceAll("/", "\\\\"); destinationDirectoryForJar = destinationDirectoryForJar.replaceAll("/", "\\\\"); } File directory = new File(destinationDirectoryForJobs); directory.mkdirs(); FileUtils.cleanDirectory(directory); logger.info(System.getProperty("user.dir")); File jarDest = new File(destinationDirectoryForJar); URL fullPath = sc.getResource(pathFromJar); File f = new File(pathFromJobs); for (File fileEntry : f.listFiles()) { FileUtils.copyFileToDirectory(fileEntry, directory); logger.info("Copy file: " + fileEntry.getName() + " to: " + directory); } FileUtils.copyFileToDirectory(new File(pathFromJar), jarDest); logger.info("Copy file: " + fullPath + " to: " + directory); } }
From source file:org.apache.catalina.loader.WebappLoader.java
/** * Set the appropriate context attribute for our class path. This * is required only because Jasper depends on it. *///from w ww .j a va 2 s . c o m private void setClassPath() { // Validate our current state information if (!(container instanceof Context)) return; ServletContext servletContext = ((Context) container).getServletContext(); if (servletContext == null) return; if (container instanceof StandardContext) { String baseClasspath = ((StandardContext) container).getCompilerClasspath(); if (baseClasspath != null) { servletContext.setAttribute(Globals.CLASS_PATH_ATTR, baseClasspath); return; } } StringBuffer classpath = new StringBuffer(); // Assemble the class path information from our class loader chain ClassLoader loader = getClassLoader(); int layers = 0; int n = 0; while (loader != null) { if (!(loader instanceof URLClassLoader)) { String cp = getClasspath(loader); if (cp == null) { log.info("Unknown loader " + loader + " " + loader.getClass()); break; } else { if (n > 0) classpath.append(File.pathSeparator); classpath.append(cp); n++; } break; //continue; } URL repositories[] = ((URLClassLoader) loader).getURLs(); for (int i = 0; i < repositories.length; i++) { String repository = repositories[i].toString(); if (repository.startsWith("file://")) repository = repository.substring(7); else if (repository.startsWith("file:")) repository = repository.substring(5); else if (repository.startsWith("jndi:")) repository = servletContext.getRealPath(repository.substring(5)); else continue; if (repository == null) continue; if (n > 0) classpath.append(File.pathSeparator); classpath.append(repository); n++; } loader = loader.getParent(); layers++; } this.classpath = classpath.toString(); // Store the assembled class path as a servlet context attribute servletContext.setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString()); }
From source file:jp.or.openid.eiwg.scim.operation.Operation.java
/** * ??//from w w w. j a v a 2s . c o m * * @param context * @param request */ public boolean Authentication(ServletContext context, HttpServletRequest request) throws IOException { boolean result = false; // Authorization? String authorization = request.getHeader("Authorization"); if (authorization == null || StringUtils.isEmpty(authorization)) { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_UNAUTHORIZED); //return false; return true; } String[] values = authorization.split(" "); // ? setError(0, null, null); if (values.length < 2) { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_UNAUTHORIZED); } else { // ???????? if ("Basic".equalsIgnoreCase(values[0])) { // HTTP Basic ? String userID; String password; String[] loginInfo = SCIMUtil.decodeBase64(values[1]).split(":"); if (loginInfo.length < 2) { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS); } else { // ?? userID = loginInfo[0]; // password = loginInfo[1]; if (StringUtils.isEmpty(userID) || StringUtils.isEmpty(password)) { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS); } else { // ???? // ??? ObjectMapper mapper = new ObjectMapper(); ArrayList<LinkedHashMap<String, Object>> adminInfoList = null; try { adminInfoList = mapper.readValue(new File(context.getRealPath("/WEB-INF/Admin.json")), new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() { }); } catch (IOException e) { // setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, MessageConstants.ERROR_UNKNOWN); e.printStackTrace(); return result; } if (adminInfoList != null && !adminInfoList.isEmpty()) { Iterator<LinkedHashMap<String, Object>> adminInfoIt = adminInfoList.iterator(); while (adminInfoIt.hasNext()) { LinkedHashMap<String, Object> adminInfo = adminInfoIt.next(); Object adminID = SCIMUtil.getAttribute(adminInfo, "id"); Object adminPassword = SCIMUtil.getAttribute(adminInfo, "password"); // id???? if (adminID != null && adminID instanceof String) { if (userID.equals(adminID.toString())) { // password???? if (adminID != null && adminID instanceof String) { if (password.equals(adminPassword.toString())) { // ?? result = true; } } break; } } } if (result != true) { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS); } } else { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS); } } } } else if ("Bearer".equalsIgnoreCase(values[0])) { // OAuth2 Bearer String token = values[1]; if (StringUtils.isEmpty(token)) { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS); } else { // ?? // ??? ObjectMapper mapper = new ObjectMapper(); ArrayList<LinkedHashMap<String, Object>> adminInfoList = null; try { adminInfoList = mapper.readValue(new File(context.getRealPath("/WEB-INF/Admin.json")), new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() { }); } catch (IOException e) { // setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, MessageConstants.ERROR_UNKNOWN); e.printStackTrace(); return result; } if (adminInfoList != null && !adminInfoList.isEmpty()) { Iterator<LinkedHashMap<String, Object>> adminInfoIt = adminInfoList.iterator(); while (adminInfoIt.hasNext()) { LinkedHashMap<String, Object> adminInfo = adminInfoIt.next(); Object adminToken = SCIMUtil.getAttribute(adminInfo, "bearer"); // token???? if (adminToken != null && adminToken instanceof String) { if (token.equals(adminToken.toString())) { // ?? result = true; break; } } } if (result != true) { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS); } } else { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS); } } } else { // setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS); } } return result; }