List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:com.liferay.portal.servlet.PortletContextListener.java
public void contextInitialized(ServletContextEvent sce) { try {//www.ja v a 2 s.com // Servlet context ServletContext ctx = sce.getServletContext(); _servletContextName = StringUtil.replace(ctx.getServletContextName(), StringPool.SPACE, StringPool.UNDERLINE); // Company ids _companyIds = StringUtil.split(ctx.getInitParameter("company_id")); // Class loader ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // Initialize portlets String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")), Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")) }; _portlets = PortletManagerUtil.initWAR(_servletContextName, xmls); // Portlet context wrapper Iterator itr1 = _portlets.iterator(); while (itr1.hasNext()) { Portlet portlet = (Portlet) itr1.next(); javax.portlet.Portlet portletInstance = (javax.portlet.Portlet) contextClassLoader .loadClass(portlet.getPortletClass()).newInstance(); Indexer indexerInstance = null; if (Validator.isNotNull(portlet.getIndexerClass())) { indexerInstance = (Indexer) contextClassLoader.loadClass(portlet.getIndexerClass()) .newInstance(); } Scheduler schedulerInstance = null; if (Validator.isNotNull(portlet.getSchedulerClass())) { schedulerInstance = (Scheduler) contextClassLoader.loadClass(portlet.getSchedulerClass()) .newInstance(); } PreferencesValidator prefsValidator = null; if (Validator.isNotNull(portlet.getPreferencesValidator())) { prefsValidator = (PreferencesValidator) contextClassLoader .loadClass(portlet.getPreferencesValidator()).newInstance(); try { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) { prefsValidator.validate( PortletPreferencesSerializer.fromDefaultXML(portlet.getDefaultPreferences())); } } catch (Exception e1) { _log.warn("Portlet with the name " + portlet.getPortletId() + " does not have valid default preferences"); } } Map resourceBundles = null; if (Validator.isNotNull(portlet.getResourceBundle())) { resourceBundles = CollectionFactory.getHashMap(); Iterator itr2 = portlet.getSupportedLocales().iterator(); while (itr2.hasNext()) { String supportedLocale = (String) itr2.next(); Locale locale = new Locale(supportedLocale); try { ResourceBundle resourceBundle = ResourceBundle.getBundle(portlet.getResourceBundle(), locale, contextClassLoader); resourceBundles.put(locale.getLanguage(), resourceBundle); } catch (MissingResourceException mre) { _log.warn(mre.getMessage()); } } } Map customUserAttributes = CollectionFactory.getHashMap(); Iterator itr2 = portlet.getCustomUserAttributes().entrySet().iterator(); while (itr2.hasNext()) { Map.Entry entry = (Map.Entry) itr2.next(); String attrName = (String) entry.getKey(); String attrCustomClass = (String) entry.getValue(); customUserAttributes.put(attrCustomClass, contextClassLoader.loadClass(attrCustomClass).newInstance()); } PortletContextWrapper pcw = new PortletContextWrapper(portlet.getPortletId(), ctx, portletInstance, indexerInstance, schedulerInstance, prefsValidator, resourceBundles, customUserAttributes); PortletContextPool.put(portlet.getPortletId(), pcw); } // Portlet class loader String servletPath = ctx.getRealPath("/"); if (!servletPath.endsWith("/") && !servletPath.endsWith("\\")) { servletPath += "/"; } File servletClasses = new File(servletPath + "WEB-INF/classes"); File servletLib = new File(servletPath + "WEB-INF/lib"); List urls = new ArrayList(); if (servletClasses.exists()) { urls.add(new URL("file:" + servletClasses + "/")); } if (servletLib.exists()) { String[] jars = FileUtil.listFiles(servletLib); for (int i = 0; i < jars.length; i++) { urls.add(new URL("file:" + servletLib + "/" + jars[i])); } } URLClassLoader portletClassLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0]), contextClassLoader); ctx.setAttribute(WebKeys.PORTLET_CLASS_LOADER, portletClassLoader); // Portlet display String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml")); Map newCategories = PortletManagerUtil.getWARDisplay(_servletContextName, xml); for (int i = 0; i < _companyIds.length; i++) { String companyId = _companyIds[i]; Map oldCategories = (Map) WebAppPool.get(companyId, WebKeys.PORTLET_DISPLAY); Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories); WebAppPool.put(companyId, WebKeys.PORTLET_DISPLAY, mergedCategories); } // Reinitialize portal properties PropsUtil.init(); } catch (Exception e2) { Logger.error(this, e2.getMessage(), e2); } }
From source file:tw.edu.chit.struts.action.course.ReportPrintAction.java
/** * /* www .ja v a 2 s. 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 printIdnoCheckErrorStudentsList(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); ScoreManager sm = (ScoreManager) getBean(IConstants.SCORE_MANAGER_BEAN_NAME); ServletContext context = request.getSession().getServletContext(); List<Clazz> clazzes = sm.findClassBy(new Clazz(processClassInfo(form)), getUserCredential(session).getClassInChargeAry(), false); if (!clazzes.isEmpty()) { List<Student> students = null; HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("?"); sheet.setColumnWidth(0, 3000); sheet.setColumnWidth(1, 3000); sheet.setColumnWidth(2, 5000); sheet.setColumnWidth(3, 3500); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3)); HSSFFont fontSize16 = workbook.createFont(); fontSize16.setFontHeightInPoints((short) 16); fontSize16.setFontName("Arial Unicode MS"); HSSFFont fontSize12 = workbook.createFont(); fontSize12.setFontHeightInPoints((short) 12); fontSize12.setFontName("Arial Unicode MS"); // Header Toolket.setCellValue(workbook, sheet, 0, 0, "?", fontSize16, HSSFCellStyle.ALIGN_CENTER, false, 35.0F, null); // Column Header Toolket.setCellValue(workbook, sheet, 1, 0, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, 1, 1, "??", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, 1, 2, "?", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, 1, 3, "", fontSize12, HSSFCellStyle.ALIGN_CENTER, true, null); int index = 2; for (Clazz clazz : clazzes) { if (Toolket.isDelayClass(clazz.getClassNo())) continue; students = mm.findStudentsByClassNo(clazz.getClassNo()); if (!students.isEmpty()) { for (Student student : students) { if (!Toolket.checkIdno(student.getIdno())) { Toolket.setCellValue(workbook, sheet, index, 0, student.getStudentNo(), fontSize12, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, index, 1, student.getStudentName(), fontSize12, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, index, 2, Toolket.getClassFullName(student.getDepartClass()), null, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, index++, 3, student.getIdno(), null, HSSFCellStyle.ALIGN_CENTER, true, null); } } } } 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, "RegisterList.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:com.siberhus.web.ckeditor.CkeditorConfigurationHolder.java
public void init(ServletContext servletContext) throws Exception { InputStream inStream = this.getClass().getResourceAsStream("/ckeditor.properties"); if (inStream == null) { log.info("Could not locate ckeditor.properties in classpath."); inStream = CkeditorConfigurationHolder.class .getResourceAsStream("/com/siberhus/web/ckeditor/ckeditor.properties"); }//from w w w.ja v a2s. c om properties.load(inStream); ckeditor = new CkeditorConfig(); String prop = null; prop = getProperty("ckeditor.config"); if (prop != null) ckeditor.config = prop; prop = getProperty("ckeditor.skipAllowedItemsCheck"); if (prop != null) ckeditor.skipAllowedItemsCheck = Boolean.valueOf(prop); prop = getProperty("ckeditor.defaulFileBrowser"); if (prop != null) ckeditor.defaultFileBrowser = prop; prop = getProperty("ckeditor.connectors.prefix"); if (prop != null) ckeditor.connectors.prefix = PathUtils.checkSlashes(prop, "L- R-", true); prop = getProperty("ckeditor.upload.basedir"); if (prop != null) ckeditor.upload.basedir = prop; prop = getProperty("ckeditor.upload.baseurl"); if (prop != null) { ckeditor.upload.baseurl = prop; if (!prop.toUpperCase().startsWith("HTTP")) { ckeditor.upload.isBaseurlVar = true; } } prop = getProperty("ckeditor.upload.enableContentController"); if (prop != null) ckeditor.upload.enableContentController = Boolean.valueOf(prop); prop = getProperty("ckeditor.upload.overwrite"); if (prop != null) ckeditor.upload.overwrite = Boolean.valueOf(prop); // LINK prop = getProperty("ckeditor.upload.link.browser"); if (prop != null) ckeditor.upload.link.browser = Boolean.valueOf(prop); prop = getProperty("ckeditor.upload.link.upload"); if (prop != null) ckeditor.upload.link.upload = Boolean.valueOf(prop); prop = getProperty("ckeditor.upload.link.allowed"); if (prop != null) { for (String p : prop.split(",")) ckeditor.upload.link.allowed.add(p); ckeditor.upload.link.allowed = Collections.unmodifiableList(ckeditor.upload.link.allowed); } prop = getProperty("ckeditor.upload.link.denied"); if (prop != null) { for (String p : prop.split(",")) ckeditor.upload.link.denied.add(p); ckeditor.upload.link.denied = Collections.unmodifiableList(ckeditor.upload.link.denied); } // IMAGE prop = getProperty("ckeditor.upload.image.browser"); if (prop != null) ckeditor.upload.image.browser = Boolean.valueOf(prop); prop = getProperty("ckeditor.upload.image.upload"); if (prop != null) ckeditor.upload.image.upload = Boolean.valueOf(prop); prop = getProperty("ckeditor.upload.image.allowed"); if (prop != null) { for (String p : prop.split(",")) ckeditor.upload.image.allowed.add(p); ckeditor.upload.image.allowed = Collections.unmodifiableList(ckeditor.upload.image.allowed); } prop = getProperty("ckeditor.upload.image.denied"); if (prop != null) { for (String p : prop.split(",")) ckeditor.upload.image.denied.add(p); ckeditor.upload.image.denied = Collections.unmodifiableList(ckeditor.upload.image.denied); } // FLASH prop = getProperty("ckeditor.upload.flash.browser"); if (prop != null) ckeditor.upload.flash.browser = Boolean.valueOf(prop); prop = getProperty("ckeditor.upload.flash.upload"); if (prop != null) ckeditor.upload.flash.upload = Boolean.valueOf(prop); prop = getProperty("ckeditor.upload.flash.allowed"); if (prop != null) { for (String p : prop.split(",")) ckeditor.upload.flash.allowed.add(p); ckeditor.upload.flash.allowed = Collections.unmodifiableList(ckeditor.upload.flash.allowed); } prop = getProperty("ckeditor.upload.flash.denied"); if (prop != null) { for (String p : prop.split(",")) ckeditor.upload.flash.denied.add(p); ckeditor.upload.flash.denied = Collections.unmodifiableList(ckeditor.upload.flash.denied); } prop = getProperty("ckeditor.fileupload.sizeThreshold"); if (prop != null) ckeditor.fileupload.sizeThreshold = Integer.valueOf(prop); prop = getProperty("ckeditor.fileupload.repository"); if (prop != null) { if (prop.startsWith("ctx:")) { prop = servletContext.getRealPath(prop.substring(4)); } File repository = new File(prop); if (!repository.exists()) { throw new IllegalArgumentException("ckeditor.fileupload.repository=file not found"); } ckeditor.fileupload.repository = repository; } prop = getProperty("ckeditor.fileupload.sizeMax"); if (prop != null) ckeditor.fileupload.sizeMax = Long.valueOf(prop); prop = getProperty("ckeditor.fileupload.fileSizeMax"); if (prop != null) ckeditor.fileupload.fileSizeMax = Long.valueOf(prop); }
From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java
protected synchronized String config(ServletContext context) { String error = null;//ww w .ja va2 s .c om try { props = loadConfig(); // default output format formatDefault = props.getProperty("format.default"); // editor backup save dir backupDir = props.getProperty("edit.backupDir"); // identifiers/namespaces minterDefault = props.getProperty("minters.default"); idMinters = new HashMap<String, String>(); String minterList = props.getProperty("minters.list"); String[] minterNames = minterList.split(","); for (int i = 0; i < minterNames.length; i++) { idMinters.put(minterNames[i], props.getProperty("minters." + minterNames[i])); } nsmap = TripleStoreUtil.namespaceMap(props); idNS = nsmap.get("damsid"); prNS = nsmap.get("dams"); rdfNS = nsmap.get("rdf"); madsNS = nsmap.get("mads"); // load valid class/predicate lists validClasses = loadSet(context, "/WEB-INF/valid-classes.txt"); validProperties = loadSet(context, "/WEB-INF/valid-properties.txt"); // xslt config encodingDefault = props.getProperty("solr.encoding"); xslBase = context.getRealPath("/WEB-INF/xsl") + File.separatorChar; log.info("Fedora xsl files directory: " + xslBase); // access control localCopyright = props.getProperty("role.localCopyright"); roleDefault = props.getProperty("role.default"); roleLocal = props.getProperty("role.local"); roleAdmin = props.getProperty("role.admin"); roleAdmin2 = props.getProperty("role.admin2"); roleSuper = props.getProperty("role.super"); String roleList = props.getProperty("role.list"); String[] roles = roleList.split(","); roleMap = new TreeMap<String, String[]>(); try { for (int i = 0; i < roles.length; i++) { String ipList = props.getProperty("role." + roles[i] + ".iplist"); String[] ipArray = ipList.split(","); roleMap.put(roles[i], ipArray); } } catch (Exception ex) { log.error("Error parsing roles: " + ex.toString(), ex); } // triplestores tsDefault = props.getProperty("ts.default"); tsEvents = props.getProperty("ts.events"); // files fsDefault = props.getProperty("fs.default"); fsStaging = props.getProperty("fs.staging"); maxUploadCount = getPropInt(props, "fs.maxUploadCount", -1); maxUploadSize = getPropLong(props, "fs.maxUploadSize", -1L); fsUseMap = new HashMap<String, String>(); for (Enumeration e = props.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); if (key != null && key.startsWith("fs.usemap.")) { String ext = key.substring(10); String use = props.getProperty(key); if (use != null) { fsUseMap.put(ext, use); } } } // fedora compat fedoraObjectDS = props.getProperty("fedora.objectDS"); fedoraRightsDS = props.getProperty("fedora.rightsDS"); fedoraLinksDS = props.getProperty("fedora.linksDS"); fedoraSystemDS = props.getProperty("fedora.systemDS"); sampleObject = props.getProperty("fedora.samplePID"); adminEmail = props.getProperty("fedora.adminEmail"); fedoraCompat = props.getProperty("fedora.compatVersion"); if (props.getProperty("fedora.debug") != null) { fedoraDebug = props.getProperty("fedora.debug").equals("true"); } // derivative list derivativesExt = props.getProperty("derivatives.ext"); String derList = props.getProperty("derivatives.list"); derivativesRes = new HashMap<String, String>(); derivativesUse = new HashMap<String, String>(); loadDerivativesConfig(derList, derivativesRes, derivativesUse); // video derivative list String derVideoList = props.getProperty("derivatives.video.list"); videoDerivativesRes = new HashMap<String, String>(); videoDerivativesUse = new HashMap<String, String>(); loadDerivativesConfig(derVideoList, videoDerivativesRes, videoDerivativesUse); // ImageMagick convert command magickCommand = props.getProperty("magick.convert"); if (magickCommand == null) magickCommand = "convert"; // Ffmpeg convert command ffmpegCommand = props.getProperty("ffmpeg"); if (ffmpegCommand == null) ffmpegCommand = "ffmpeg"; // Jhove configuration String jhoveConf = props.getProperty("jhove.conf"); if (jhoveConf != null) MyJhoveBase.setJhoveConfig(jhoveConf); // Jhove zip model configuration String jhoveZipModelCommand = props.getProperty("jhove.zipModel.command"); if (StringUtils.isNotBlank(jhoveZipModelCommand)) MyJhoveBase.setZipModelCommand(jhoveZipModelCommand); // Jhove gzip model configuration String jhoveGzipModelCommand = props.getProperty("jhove.gzipModel.command"); if (StringUtils.isNotBlank(jhoveGzipModelCommand)) MyJhoveBase.setGzipModelCommand(jhoveGzipModelCommand); jhoveMaxSize = getPropLong(props, "jhove.maxSize", -1L); // ldap for group lookup ldaputil = new LDAPUtil(props); // cache size cacheSize = getPropInt(props, "ts.cacheSize", 0); cacheClear(); // clear cache // queue queueUrl = props.getProperty("queue.url"); queueName = props.getProperty("queue.name"); if (queueEnabled && queueUrl != null) { try { queueConnectionFactory = new ActiveMQConnectionFactory(queueUrl); queueConnection = queueConnectionFactory.createConnection(); queueConnection.start(); queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); queueProducer = queueSession.createProducer(queueSession.createTopic(queueName)); queueProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); log.info("JMS Queue: " + queueUrl + "/" + queueName); } catch (Exception ex) { log.error("Error initializing JMS queue: " + ex.toString(), ex); } } // doi minter ezidTargetUrl = props.getProperty("ezid.target.url"); String ezidHost = props.getProperty("ezid.host"); String ezidShoulder = props.getProperty("ezid.shoulder"); String ezidUser = props.getProperty("ezid.user"); String ezidPass = props.getProperty("ezid.pass"); if (ezidHost != null && ezidShoulder != null && ezidUser != null && ezidPass != null) { ezid = new Ezid(ezidHost, ezidShoulder, ezidUser, ezidPass); } else { ezid = null; } // ffmpeg codec params for derivative creation ffmpegCodecParamsMap = new HashMap<String, String>(); String ffmpegCodecParams = props.getProperty("ffmpeg.codec.params"); if (StringUtils.isNotBlank(ffmpegCodecParams)) { String[] codecParams = ffmpegCodecParams.split("\\;"); for (String codecParam : codecParams) { String[] keyValPair = codecParam.trim().split("\\|"); ffmpegCodecParamsMap.put(keyValPair[0].trim(), keyValPair[1]); } } } catch (Exception ex) { log.error("Error initializing", ex); error = ex.toString(); } return error; }
From source file:edu.lternet.pasta.portal.HarvesterServlet.java
/** * The doPost method of the servlet. <br> * //from w ww. j a va2 s . co m * This method is called when a form has its tag value method equals to post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); ServletContext servletContext = httpSession.getServletContext(); ArrayList<String> documentURLs = null; File emlFile = null; String emlTextArea = null; Harvester harvester = null; String harvestId = null; String harvestListURL = null; String harvestReportId = null; boolean isDesktopUpload = false; boolean isEvaluate = false; String uid = (String) httpSession.getAttribute("uid"); String urlTextArea = null; String warningMessage = ""; try { if (uid == null) { throw new PastaAuthenticationException(LOGIN_WARNING); } else { /* * The "metadataSource" request parameter can have a value of * "emlText", "emlFile", "urlList", "harvestList", or * "desktopHarvester". It is set as a hidden input field in * each of the harvester forms. */ String metadataSource = request.getParameter("metadataSource"); /* * "mode" can have a value of "evaluate" or "upgrade". It is set * as the value of the submit button in each of the harvester * forms. */ String mode = request.getParameter("submit"); if ((mode != null) && (mode.equalsIgnoreCase("evaluate"))) { isEvaluate = true; } if ((metadataSource != null) && (!metadataSource.equals("desktopHarvester"))) { harvestId = generateHarvestId(); if (isEvaluate) { harvestReportId = uid + "-evaluate-" + harvestId; } else { harvestReportId = uid + "-upload-" + harvestId; } } if (metadataSource != null) { if (metadataSource.equals("emlText")) { emlTextArea = request.getParameter("emlTextArea"); if (emlTextArea == null || emlTextArea.trim().isEmpty()) { warningMessage = "<p class=\"warning\">Please enter the text of an EML document into the text area.</p>"; } } else if (metadataSource.equals("emlFile")) { Collection<Part> parts = request.getParts(); for (Part part : parts) { if (part.getContentType() != null) { // save EML file to disk emlFile = processUploadedFile(part); } else { /* * Parse the request parameters. */ String fieldName = part.getName(); String fieldValue = request.getParameter(fieldName); if (fieldName != null && fieldValue != null) { if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) { isEvaluate = true; } else if (fieldName.equals("desktopUpload") && fieldValue.equalsIgnoreCase("1")) { isDesktopUpload = true; } } } } } else if (metadataSource.equals("urlList")) { urlTextArea = request.getParameter("urlTextArea"); if (urlTextArea == null || urlTextArea.trim().isEmpty()) { warningMessage = "<p class=\"warning\">Please enter one or more EML document URLs into the text area.</p>"; } else { documentURLs = parseDocumentURLsFromTextArea(urlTextArea); warningMessage = CHECK_BACK_LATER; } } else if (metadataSource.equals("harvestList")) { harvestListURL = request.getParameter("harvestListURL"); if (harvestListURL == null || harvestListURL.trim().isEmpty()) { warningMessage = "<p class=\"warning\">Please enter the URL to a Metacat Harvest List.</p>"; } else { documentURLs = parseDocumentURLsFromHarvestList(harvestListURL); warningMessage = CHECK_BACK_LATER; } } /* * If the metadata source is "desktopHarvester", we already have the * EML file stored in a session attribute. Now we need to retrieve * the data files from the brower's form fields and write the * data files to a URL accessible location. */ else if (metadataSource.equals("desktopHarvester")) { emlFile = (File) httpSession.getAttribute("emlFile"); ArrayList<Entity> entityList = parseEntityList(emlFile); harvestReportId = (String) httpSession.getAttribute("harvestReportId"); String dataPath = servletContext.getRealPath(DESKTOP_DATA_DIR); String harvestPath = String.format("%s/%s", dataPath, harvestReportId); Collection<Part> parts = request.getParts(); String objectName = null; Part filePart = null; for (Part part : parts) { if (part.getContentType() != null) { // save data file to disk //processDataFile(part, harvestPath); filePart = part; } else { /* * Parse the request parameters. */ String fieldName = part.getName(); String fieldValue = request.getParameter(fieldName); if (fieldName != null && fieldValue != null) { if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) { isEvaluate = true; } else if (fieldName.startsWith("object-name-")) { objectName = fieldValue; } } } if (filePart != null && objectName != null) { processDataFile(filePart, harvestPath, objectName); objectName = null; filePart = null; } } emlFile = transformDesktopEML(harvestPath, emlFile, harvestReportId, entityList); } } else { throw new IllegalStateException("No value specified for request parameter 'metadataSource'"); } if (harvester == null) { harvester = new Harvester(harvesterPath, harvestReportId, uid, isEvaluate); } if (emlTextArea != null) { harvester.processSingleDocument(emlTextArea); } else if (emlFile != null) { if (isDesktopUpload) { ArrayList<Entity> entityList = parseEntityList(emlFile); httpSession.setAttribute("entityList", entityList); httpSession.setAttribute("emlFile", emlFile); httpSession.setAttribute("harvestReportId", harvestReportId); httpSession.setAttribute("isEvaluate", new Boolean(isEvaluate)); } else { harvester.processSingleDocument(emlFile); } } else if (documentURLs != null) { harvester.setDocumentURLs(documentURLs); ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(harvester); executorService.shutdown(); } } } catch (Exception e) { handleDataPortalError(logger, e); } request.setAttribute("message", warningMessage); /* * If we have a new reportId, and either there is no warning message or * it's the "Check back later" message, set the harvestReportID session * attribute to the new reportId value. */ if (harvestReportId != null && harvestReportId.length() > 0 && (warningMessage.length() == 0 || warningMessage.equals(CHECK_BACK_LATER))) { httpSession.setAttribute("harvestReportID", harvestReportId); } if (isDesktopUpload) { RequestDispatcher requestDispatcher = request.getRequestDispatcher("./desktopHarvester.jsp"); requestDispatcher.forward(request, response); } else if (warningMessage.length() == 0) { response.sendRedirect("./harvestReport.jsp"); } else { RequestDispatcher requestDispatcher = request.getRequestDispatcher("./harvester.jsp"); requestDispatcher.forward(request, response); } }
From source file:tw.edu.chit.struts.action.deptassist.ReportPrintAction.java
/** * ?/*from w ww. j a v a2s . c om*/ * * @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 DeptStdSkill4EnglishList(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); CourseManager cm = (CourseManager) getBean(IConstants.COURSE_MANAGER_BEAN_NAME); MemberManager mm = (MemberManager) getBean(MEMBER_MANAGER_BEAN_NAME); Member member = (Member) getUserCredential(session).getMember(); Empl empl = mm.findEmplByOid(member.getOid()); ServletContext context = request.getSession().getServletContext(); CodeEmpl codeEmpl = new CodeEmpl(); codeEmpl.setIdno(empl.getUnit()); Example example4CodeEmpl = Example.create(codeEmpl).ignoreCase().enableLike(MatchMode.START); List<CodeEmpl> codeEmpls = (List<CodeEmpl>) am.findSQLWithCriteria(CodeEmpl.class, example4CodeEmpl, null, null); List<Object> ret = null; DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); if (StringUtils.isNotBlank(form.getString("licenseValidDateStart")) || StringUtils.isNotBlank(form.getString("licenseValidDateEnd"))) { String hql = "SELECT ss, s FROM StdSkill ss, Student s " + "WHERE ss.deptNo = '0' AND ss.studentNo = s.studentNo " + "AND s.departClass LIKE ? AND ss.licenseValidDate BETWEEN ? AND ? " + "ORDER BY s.departClass"; Calendar cal = Calendar.getInstance(); Calendar cal1 = (Calendar) cal.clone(); Calendar cal2 = (Calendar) cal.clone(); Date from = StringUtils.isBlank(form.getString("licenseValidDateStart")) ? null : Toolket.parseNativeDate(form.getString("licenseValidDateStart")); // ??? Date to = StringUtils.isBlank(form.getString("licenseValidDateEnd")) ? Calendar.getInstance().getTime() : Toolket.parseNativeDate(form.getString("licenseValidDateEnd")); cal1.setTime(from); cal1.set(Calendar.HOUR_OF_DAY, 0); cal1.set(Calendar.MINUTE, 0); cal1.set(Calendar.SECOND, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.setTime(to); cal2.set(Calendar.HOUR_OF_DAY, 23); cal2.set(Calendar.MINUTE, 59); cal2.set(Calendar.SECOND, 59); cal2.set(Calendar.MILLISECOND, 999); ret = (List<Object>) am.find(hql, new Object[] { "___" + codeEmpls.get(0).getIdno2().trim() + "__", from, to }); } else { String hql = "SELECT ss, s FROM StdSkill ss, Student s " + "WHERE ss.deptNo = '0' AND ss.studentNo = s.studentNo " + "AND s.departClass LIKE ? ORDER BY s.departClass"; ret = (List<Object>) am.find(hql, new Object[] { "___" + codeEmpls.get(0).getIdno2().trim() + "__", }); } File templateXLS = new File(context.getRealPath("/WEB-INF/reports/DeptStdSkillList.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFSheet sheet = workbook.getSheetAt(0); Toolket.setCellValue(sheet, 0, 0, "?"); int index = 2; List<LicenseCode> codes = null; Student student = null; Graduate graduate = null; DEmpl dempl = null; Csno csno = null; DateFormat df1 = new SimpleDateFormat("yyyy/MM"); Object[] o = null; StdSkill ss = null; if (!ret.isEmpty()) { for (Object obj : ret) { o = (Object[]) obj; ss = (StdSkill) o[0]; student = (Student) o[1]; codes = (List<LicenseCode>) am .findLicenseCodesBy(new LicenseCode(String.valueOf(ss.getLicenseCode()))); if (!codes.isEmpty()) ss.setLicense(codes.get(0)); if (student == null) { graduate = mm.findGraduateByStudentNo(ss.getStudentNo().trim()); if (graduate != null) { ss.setStudentName(graduate.getStudentName().trim()); ss.setDepartClass(Toolket.getClassFullName(graduate.getDepartClass())); } } else { ss.setStudentName(student.getStudentName().trim()); ss.setDepartClass(Toolket.getClassFullName(student.getDepartClass())); } Toolket.setCellValue(sheet, index, 0, ss.getSchoolYear() + "." + ss.getSchoolTerm()); Toolket.setCellValue(sheet, index, 1, ss.getStudentNo().toUpperCase()); Toolket.setCellValue(sheet, index, 2, ss.getStudentName()); Toolket.setCellValue(sheet, index, 3, ss.getDepartClass()); Toolket.setCellValue(sheet, index, 4, ss.getLicense().getCode().trim()); Toolket.setCellValue(sheet, index, 5, ss.getLicense().getDeptName().trim()); Toolket.setCellValue(sheet, index, 6, ss.getLicense().getName().trim()); Toolket.setCellValue(sheet, index, 7, ss.getLicense().getLocale().toString()); Toolket.setCellValue(sheet, index, 8, ss.getLicense().getLevel().trim()); Toolket.setCellValue(sheet, index, 9, ss.getLicense().getType().toString()); Toolket.setCellValue(sheet, index, 10, ss.getAmount().toString()); Toolket.setCellValue(sheet, index, 11, Toolket.getAmountType(ss.getAmountType())); Toolket.setCellValue(sheet, index, 12, ss.getAmountDate() == null ? "" : df1.format(ss.getAmountDate())); Toolket.setCellValue(sheet, index, 13, ss.getLicenseNo()); Toolket.setCellValue(sheet, index, 14, df.format(ss.getLicenseValidDate())); if (StringUtils.isNotBlank(ss.getCscode())) { csno = cm.findCourseInfoByCscode(ss.getCscode()); if (csno != null) Toolket.setCellValue(sheet, index, 15, csno.getChiName().trim()); } else Toolket.setCellValue(sheet, index, 15, ""); if (StringUtils.isNotBlank(ss.getTechIdno())) { empl = mm.findEmplByIdno(ss.getTechIdno()); if (empl != null) Toolket.setCellValue(sheet, index, 16, empl.getCname().trim()); else { dempl = mm.findDEmplByIdno(ss.getTechIdno()); if (dempl != null) Toolket.setCellValue(sheet, index, 16, dempl.getCname().trim()); } } else Toolket.setCellValue(sheet, index, 16, ""); Toolket.setCellValue(sheet, index, 17, ss.getSerialNo()); Toolket.setCellValue(sheet, index, 18, Toolket.getCustomNo(ss.getCustomNo())); Toolket.setCellValue(sheet, index, 19, Toolket.getPass(ss.getPass())); Toolket.setCellValue(sheet, index++, 20, Toolket.getApplyType(ss.getApplyType())); } } 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, "DeptStdSkill4EnglishList.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.deptassist.ReportPrintAction.java
/** * ?/*from w w w . j a va2s . 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 printDeptGStdSkillList(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); CourseManager cm = (CourseManager) getBean(IConstants.COURSE_MANAGER_BEAN_NAME); MemberManager mm = (MemberManager) getBean(MEMBER_MANAGER_BEAN_NAME); Member member = (Member) getUserCredential(session).getMember(); Empl empl = mm.findEmplByOid(member.getOid()); ServletContext context = request.getSession().getServletContext(); CodeEmpl codeEmpl = new CodeEmpl(); codeEmpl.setIdno(empl.getUnit()); Example example4CodeEmpl = Example.create(codeEmpl).ignoreCase().enableLike(MatchMode.START); List<CodeEmpl> codeEmpls = (List<CodeEmpl>) am.findSQLWithCriteria(CodeEmpl.class, example4CodeEmpl, null, null); List<StdSkill> skills = null; StdSkill skill = new StdSkill(); skill.setAmount(null); // ?? Example example = Example.create(skill).ignoreCase().enableLike(MatchMode.ANYWHERE); List<Order> orders = new LinkedList<Order>(); orders.add(Order.asc("schoolYear")); orders.add(Order.asc("schoolTerm")); orders.add(Order.asc("studentNo")); Criterion deptNo = Restrictions.eq("deptNo", codeEmpls.get(0).getIdno2().trim()); // DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); if (StringUtils.isNotBlank(form.getString("licenseValidDateStart")) || StringUtils.isNotBlank(form.getString("licenseValidDateEnd"))) { Calendar cal = Calendar.getInstance(); Calendar cal1 = (Calendar) cal.clone(); Calendar cal2 = (Calendar) cal.clone(); Date from = StringUtils.isBlank(form.getString("licenseValidDateStart")) ? null : Toolket.parseNativeDate(form.getString("licenseValidDateStart")); // ??? Date to = StringUtils.isBlank(form.getString("licenseValidDateEnd")) ? Calendar.getInstance().getTime() : Toolket.parseNativeDate(form.getString("licenseValidDateEnd")); cal1.setTime(from); cal1.set(Calendar.HOUR_OF_DAY, 0); cal1.set(Calendar.MINUTE, 0); cal1.set(Calendar.SECOND, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.setTime(to); cal2.set(Calendar.HOUR_OF_DAY, 23); cal2.set(Calendar.MINUTE, 59); cal2.set(Calendar.SECOND, 59); cal2.set(Calendar.MILLISECOND, 999); Criterion licenseValidDate = Restrictions.between("licenseValidDate", cal1.getTime(), cal2.getTime()); skills = (List<StdSkill>) am.findSQLWithCriteria(StdSkill.class, example, null, orders, deptNo, licenseValidDate); } else skills = (List<StdSkill>) am.findSQLWithCriteria(StdSkill.class, example, null, orders, deptNo); File templateXLS = new File(context.getRealPath("/WEB-INF/reports/DeptStdSkillList.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFSheet sheet = workbook.getSheetAt(0); Toolket.setCellValue(sheet, 0, 0, "?"); int index = 2; List<LicenseCode> codes = null; Student student = null; Graduate graduate = null; DEmpl dempl = null; Csno csno = null; DateFormat df1 = new SimpleDateFormat("yyyy/MM"); for (StdSkill ss : skills) { codes = (List<LicenseCode>) am.findLicenseCodesBy(new LicenseCode(String.valueOf(ss.getLicenseCode()))); if (!codes.isEmpty()) ss.setLicense(codes.get(0)); student = mm.findStudentByNo(ss.getStudentNo().trim()); if (student == null) { graduate = mm.findGraduateByStudentNo(ss.getStudentNo().trim()); if (graduate != null) { ss.setStudentName(graduate.getStudentName().trim()); ss.setDepartClass(Toolket.getClassFullName(graduate.getDepartClass())); } } else { ss.setStudentName(student.getStudentName().trim()); ss.setDepartClass(Toolket.getClassFullName(student.getDepartClass())); } Toolket.setCellValue(sheet, index, 0, ss.getSchoolYear() + "." + ss.getSchoolTerm()); Toolket.setCellValue(sheet, index, 1, ss.getStudentNo().toUpperCase()); Toolket.setCellValue(sheet, index, 2, ss.getStudentName()); Toolket.setCellValue(sheet, index, 3, ss.getDepartClass()); Toolket.setCellValue(sheet, index, 4, ss.getLicense().getCode().trim()); Toolket.setCellValue(sheet, index, 5, ss.getLicense().getDeptName().trim()); Toolket.setCellValue(sheet, index, 6, ss.getLicense().getName().trim()); Toolket.setCellValue(sheet, index, 7, ss.getLicense().getLocale().toString()); Toolket.setCellValue(sheet, index, 8, ss.getLicense().getLevel().trim()); Toolket.setCellValue(sheet, index, 9, ss.getLicense().getType().toString()); Toolket.setCellValue(sheet, index, 10, ss.getAmount().toString()); Toolket.setCellValue(sheet, index, 11, Toolket.getAmountType(ss.getAmountType())); Toolket.setCellValue(sheet, index, 12, ss.getAmountDate() == null ? "" : df1.format(ss.getAmountDate())); Toolket.setCellValue(sheet, index, 13, ss.getLicenseNo()); Toolket.setCellValue(sheet, index, 14, df.format(ss.getLicenseValidDate())); if (StringUtils.isNotBlank(ss.getCscode())) { csno = cm.findCourseInfoByCscode(ss.getCscode()); if (csno != null) Toolket.setCellValue(sheet, index, 15, csno.getChiName().trim()); } else Toolket.setCellValue(sheet, index, 15, ""); if (StringUtils.isNotBlank(ss.getTechIdno())) { empl = mm.findEmplByIdno(ss.getTechIdno()); if (empl != null) Toolket.setCellValue(sheet, index, 16, empl.getCname().trim()); else { dempl = mm.findDEmplByIdno(ss.getTechIdno()); if (dempl != null) Toolket.setCellValue(sheet, index, 16, dempl.getCname().trim()); } } else Toolket.setCellValue(sheet, index, 16, ""); Toolket.setCellValue(sheet, index, 17, ss.getSerialNo()); Toolket.setCellValue(sheet, index, 18, Toolket.getCustomNo(ss.getCustomNo())); Toolket.setCellValue(sheet, index, 19, Toolket.getPass(ss.getPass())); Toolket.setCellValue(sheet, index++, 20, Toolket.getApplyType(ss.getApplyType())); } 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, "DeptStdSkillList.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.deptassist.ReportPrintAction.java
/** * ???/*from ww w . j a v a2s. c om*/ * * @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 printDeptStdSkillList2(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(MEMBER_MANAGER_BEAN_NAME); Member member = (Member) getUserCredential(session).getMember(); Empl empl = mm.findEmplByOid(member.getOid()); ServletContext context = request.getSession().getServletContext(); CodeEmpl codeEmpl = new CodeEmpl(); codeEmpl.setIdno(empl.getUnit()); Example example4CodeEmpl = Example.create(codeEmpl).ignoreCase().enableLike(MatchMode.START); List<CodeEmpl> codeEmpls = (List<CodeEmpl>) am.findSQLWithCriteria(CodeEmpl.class, example4CodeEmpl, null, null); DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); Calendar cal = Calendar.getInstance(); Calendar cal1 = (Calendar) cal.clone(); Calendar cal2 = (Calendar) cal.clone(); if (StringUtils.isNotBlank(form.getString("licenseValidDateStart")) || StringUtils.isNotBlank(form.getString("licenseValidDateEnd"))) { Date from = StringUtils.isBlank(form.getString("licenseValidDateStart")) ? null : Toolket.parseNativeDate(form.getString("licenseValidDateStart")); // ??? Date to = StringUtils.isBlank(form.getString("licenseValidDateEnd")) ? Calendar.getInstance().getTime() : Toolket.parseNativeDate(form.getString("licenseValidDateEnd")); cal1.setTime(from); cal1.set(Calendar.HOUR_OF_DAY, 0); cal1.set(Calendar.MINUTE, 0); cal1.set(Calendar.SECOND, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.setTime(to); cal2.set(Calendar.HOUR_OF_DAY, 23); cal2.set(Calendar.MINUTE, 59); cal2.set(Calendar.SECOND, 59); cal2.set(Calendar.MILLISECOND, 999); } // Y boolean flag = form.getString("amountDateType").equalsIgnoreCase("y"); String hql = ""; if (flag) hql = "FROM StdSkill s WHERE s.amountDate IS NOT NULL AND s.deptNo = ? " + "AND s.licenseValidDate BETWEEN ? AND ? ORDER BY s.studentNo"; else // ? hql = "FROM StdSkill s WHERE s.amountDate IS NULL AND s.deptNo = ? " + "AND s.licenseValidDate BETWEEN ? AND ? ORDER BY s.studentNo"; /* List<StdSkill> skills = (List<StdSkill>) am.find(hql, new Object[] { codeEmpls.get(0).getIdno2().trim(), cal1.getTime(), cal2.getTime() }); */ codeEmpl.setIdno(empl.getUnit()); List<StdSkill> skills = (List<StdSkill>) am.find(hql, new Object[] { codeEmpl.getIdno().trim(), cal1.getTime(), cal2.getTime() }); File templateXLS = new File(context.getRealPath("/WEB-INF/reports/DeptStdSkillList2.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFSheet sheet = workbook.getSheetAt(0); // Header Toolket.setCellValue(sheet, 0, 0, "?" + Toolket.getEmpUnit(empl.getUnit()) + "??? (" + df.format(cal1.getTime()) + "~" + df.format(cal2.getTime()) + ") - " + (flag ? "" : "")); int index = 2; Student student = null; Graduate graduate = null; List<LicenseCode> codes = null; List<LicenseCode961> code961s = null; LicenseCode code = null; LicenseCode961 code961 = null; String checkStr1 = "???\n?\n???"; String checkStr2 = "?\n?"; for (StdSkill skill : skills) { student = mm.findStudentByNo(skill.getStudentNo()); if (student == null) { graduate = mm.findGraduateByStudentNo(skill.getStudentNo()); if (graduate != null) { Toolket.setCellValue(sheet, index, 13, Toolket.getStatus(graduate.getOccurStatus(), true)); Toolket.setCellValue(sheet, index, 14, df.format(graduate.getOccurDate())); student = new Student(); BeanUtils.copyProperties(graduate, student); } } if (student != null || graduate != null) { Toolket.setCellValue(sheet, index, 0, String.valueOf(index - 1)); Toolket.setCellValue(sheet, index, 1, StringUtils.isBlank(student.getDepartClass()) ? "" : Toolket.getSchoolName(student.getDepartClass())); Toolket.setCellValue(sheet, index, 2, Toolket.getClassFullName(student.getDepartClass())); Toolket.setCellValue(sheet, index, 3, student.getStudentNo()); Toolket.setCellValue(sheet, index, 4, student.getStudentName()); Toolket.setCellValue(sheet, index, 5, student.getIdno()); Toolket.setCellValue(sheet, index, 9, String.valueOf(skill.getAmount())); Toolket.setCellValue(sheet, index, 10, ""); Toolket.setCellValue(sheet, index, 11, checkStr1); Toolket.setCellValue(sheet, index, 12, checkStr2); codes = (List<LicenseCode>) am .findLicenseCodesBy(new LicenseCode(String.valueOf(skill.getLicenseCode()))); if (!codes.isEmpty()) { code = codes.get(0); Toolket.setCellValue(sheet, index, 6, code.getName()); Toolket.setCellValue(sheet, index, 7, code.getDeptName()); Toolket.setCellValue(sheet, index, 8, code.getLevel()); } else { code961s = (List<LicenseCode961>) am .findLicenseCode961sBy(new LicenseCode961(String.valueOf(skill.getLicenseCode()))); if (!code961s.isEmpty()) { code961 = code961s.get(0); Toolket.setCellValue(sheet, index, 6, code961.getName()); Toolket.setCellValue(sheet, index, 7, code961.getDeptName()); Toolket.setCellValue(sheet, index, 8, code961.getLevel()); } } index++; } } 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, "DeptStdSkillList2.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.deptassist.ReportPrintAction.java
/** * ?()/*from ww w .j a v a2 s.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 printDeptStdSkillList(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); CourseManager cm = (CourseManager) getBean(IConstants.COURSE_MANAGER_BEAN_NAME); MemberManager mm = (MemberManager) getBean(MEMBER_MANAGER_BEAN_NAME); CourseManager manager = (CourseManager) getBean("courseManager"); Member member = (Member) getUserCredential(session).getMember(); Empl empl = mm.findEmplByOid(member.getOid()); ServletContext context = request.getSession().getServletContext(); CodeEmpl codeEmpl = new CodeEmpl(); codeEmpl.setIdno(empl.getUnit()); Example example4CodeEmpl = Example.create(codeEmpl).ignoreCase().enableLike(MatchMode.START); List<CodeEmpl> codeEmpls = (List<CodeEmpl>) am.findSQLWithCriteria(CodeEmpl.class, example4CodeEmpl, null, null); List<StdSkill> skills = null; StdSkill skill = new StdSkill(); skill.setAmount(null); // ?? Example example = Example.create(skill).ignoreCase().enableLike(MatchMode.ANYWHERE); List<Order> orders = new LinkedList<Order>(); orders.add(Order.asc("schoolYear")); orders.add(Order.asc("schoolTerm")); orders.add(Order.asc("studentNo")); Criterion deptNo = Restrictions.eq("deptNo", codeEmpls.get(0).getIdno2().trim()); // DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); if (StringUtils.isNotBlank(form.getString("licenseValidDateStart")) || StringUtils.isNotBlank(form.getString("licenseValidDateEnd"))) { Calendar cal = Calendar.getInstance(); Calendar cal1 = (Calendar) cal.clone(); Calendar cal2 = (Calendar) cal.clone(); Date from = StringUtils.isBlank(form.getString("licenseValidDateStart")) ? null : Toolket.parseNativeDate(form.getString("licenseValidDateStart")); // ??? Date to = StringUtils.isBlank(form.getString("licenseValidDateEnd")) ? Calendar.getInstance().getTime() : Toolket.parseNativeDate(form.getString("licenseValidDateEnd")); cal1.setTime(from); cal1.set(Calendar.HOUR_OF_DAY, 0); cal1.set(Calendar.MINUTE, 0); cal1.set(Calendar.SECOND, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.setTime(to); cal2.set(Calendar.HOUR_OF_DAY, 23); cal2.set(Calendar.MINUTE, 59); cal2.set(Calendar.SECOND, 59); cal2.set(Calendar.MILLISECOND, 999); Criterion licenseValidDate = Restrictions.between("licenseValidDate", cal1.getTime(), cal2.getTime()); skills = (List<StdSkill>) am.findSQLWithCriteria(StdSkill.class, example, null, orders, deptNo, licenseValidDate); } else skills = (List<StdSkill>) am.findSQLWithCriteria(StdSkill.class, example, null, orders, deptNo); File templateXLS = new File(context.getRealPath("/WEB-INF/reports/DeptStdSkillList.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFSheet sheet = workbook.getSheetAt(0); Toolket.setCellValue(sheet, 0, 0, "?()"); int index = 2; List<LicenseCode> codes = null; Student student = null; Graduate graduate = null; DEmpl dempl = null; Csno csno = null; DateFormat df1 = new SimpleDateFormat("yyyy/MM"); for (StdSkill ss : skills) { codes = (List<LicenseCode>) am.findLicenseCodesBy(new LicenseCode(String.valueOf(ss.getLicenseCode()))); if (!codes.isEmpty()) ss.setLicense(codes.get(0)); student = mm.findStudentByNo(ss.getStudentNo().trim()); if (student == null) { graduate = mm.findGraduateByStudentNo(ss.getStudentNo().trim()); if (graduate != null) { ss.setStudentName(graduate.getStudentName().trim()); ss.setDepartClass(Toolket.getClassFullName(graduate.getDepartClass())); } } else { ss.setStudentName(student.getStudentName().trim()); ss.setDepartClass(Toolket.getClassFullName(student.getDepartClass())); } Toolket.setCellValue(sheet, index, 0, ss.getSchoolYear() + "." + ss.getSchoolTerm()); Toolket.setCellValue(sheet, index, 1, ss.getStudentNo().toUpperCase()); Toolket.setCellValue(sheet, index, 2, ss.getStudentName()); Toolket.setCellValue(sheet, index, 3, ss.getDepartClass()); Toolket.setCellValue(sheet, index, 4, ss.getLicense().getCode().trim()); Toolket.setCellValue(sheet, index, 5, ss.getLicense().getDeptName().trim()); Toolket.setCellValue(sheet, index, 6, ss.getLicense().getName().trim()); //Toolket.setCellValue(sheet, index, 7, ss.getLicense().getLocale() // .toString()); String locale = manager .ezGetString("SELECT Locale FROM LicenseCode WHERE Code='" + ss.getLicenseCode() + "'"); String localename = ""; if (locale.equals("1")) localename = ""; if (locale.equals("2")) localename = ""; if (locale.equals("3")) localename = "??"; Toolket.setCellValue(sheet, index, 7, localename); Toolket.setCellValue(sheet, index, 8, ss.getLicense().getLevel().trim()); //Toolket.setCellValue(sheet, index, 9, ss.getLicense().getType() // .toString()); String Type = manager .ezGetString("SELECT Type FROM LicenseCode WHERE Code='" + ss.getLicenseCode() + "'"); String Typename = ""; if (Type.equals("1")) Typename = "?"; if (Type.equals("2")) Typename = ""; if (Type.equals("3")) Typename = ""; if (Type.equals("4")) Typename = ""; Toolket.setCellValue(sheet, index, 9, Typename); Toolket.setCellValue(sheet, index, 10, ss.getAmount().toString()); Toolket.setCellValue(sheet, index, 11, Toolket.getAmountType(ss.getAmountType())); Toolket.setCellValue(sheet, index, 12, ss.getAmountDate() == null ? "" : df1.format(ss.getAmountDate())); Toolket.setCellValue(sheet, index, 13, ss.getLicenseNo()); Toolket.setCellValue(sheet, index, 14, df.format(ss.getLicenseValidDate())); if (StringUtils.isNotBlank(ss.getCscode())) { csno = cm.findCourseInfoByCscode(ss.getCscode()); if (csno != null) Toolket.setCellValue(sheet, index, 15, csno.getChiName().trim()); } else Toolket.setCellValue(sheet, index, 15, ""); if (StringUtils.isNotBlank(ss.getTechIdno())) { empl = mm.findEmplByIdno(ss.getTechIdno()); if (empl != null) Toolket.setCellValue(sheet, index, 16, empl.getCname().trim()); else { dempl = mm.findDEmplByIdno(ss.getTechIdno()); if (dempl != null) Toolket.setCellValue(sheet, index, 16, dempl.getCname().trim()); } } else Toolket.setCellValue(sheet, index, 16, ""); Toolket.setCellValue(sheet, index, 17, ss.getSerialNo()); Toolket.setCellValue(sheet, index, 18, Toolket.getCustomNo(ss.getCustomNo())); Toolket.setCellValue(sheet, index, 19, Toolket.getPass(ss.getPass())); Toolket.setCellValue(sheet, index++, 20, Toolket.getApplyType(ss.getApplyType())); } 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, "DeptStdSkillList.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.deptassist.ReportPrintAction.java
/** * 1-11()?/* w w w.j a v a2s.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 printRc111(ActionMapping mapping, DynaActionForm form, HttpServletRequest request, HttpServletResponse response, String sterm) throws Exception { HttpSession session = request.getSession(false); MemberManager mm = (MemberManager) getBean(MEMBER_MANAGER_BEAN_NAME); ServletContext context = request.getSession().getServletContext(); Employee employee = (Employee) getUserCredential(session).getMember(); List<Empl> empls = mm.findTeacherByUnit(employee.getUnit()); String calendarYear = form.getString("calendarYear"); Rcbook rcbook = null; List<Rcbook> rcbooks = null; HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("1-11"); sheet.setColumnWidth(0, 2000); sheet.setColumnWidth(1, 3000); sheet.setColumnWidth(2, 12000); sheet.setColumnWidth(3, 8000); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3)); HSSFFont fontSize12 = workbook.createFont(); fontSize12.setFontHeightInPoints((short) 12); fontSize12.setFontName("Arial Unicode MS"); HSSFFont fontSize10 = workbook.createFont(); fontSize10.setFontHeightInPoints((short) 10); fontSize10.setFontName("Arial Unicode MS"); // Header Toolket.setCellValue(workbook, sheet, 0, 0, "?" + Toolket.getEmpUnit(employee.getUnit()) + "1-11()", fontSize12, HSSFCellStyle.ALIGN_CENTER, false, 35.0F, null); // Column Header Toolket.setCellValue(workbook, sheet, 1, 0, "", fontSize10, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, 1, 1, "??", fontSize10, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, 1, 2, "??", fontSize10, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, 1, 3, "", fontSize10, HSSFCellStyle.ALIGN_CENTER, true, null); int index = 2; for (Empl e : empls) { rcbook = new Rcbook(); rcbook.setIdno(e.getIdno().toUpperCase()); rcbook.setSchoolYear(Short.valueOf(calendarYear)); rcbooks = mm.findRcbooksBy(rcbook); for (Rcbook rc : rcbooks) { Toolket.setCellValue(workbook, sheet, index, 0, rc.getSchoolYear().toString(), fontSize10, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, index, 1, e.getCname().trim(), fontSize10, HSSFCellStyle.ALIGN_CENTER, true, null); Toolket.setCellValue(workbook, sheet, index, 2, rc.getTitle().trim(), fontSize10, HSSFCellStyle.ALIGN_LEFT, true, null); Toolket.setCellValue(workbook, sheet, index++, 3, rc.getPublisher().trim(), fontSize10, HSSFCellStyle.ALIGN_LEFT, true, null); } } 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, "printRc111.xls"); FileOutputStream fos = new FileOutputStream(output); workbook.write(fos); fos.close(); JasperReportUtils.printXlsToFrontEnd(response, output); output.delete(); tempDir.delete(); }