List of usage examples for javax.servlet ServletOutputStream close
public void close() throws IOException
From source file:it.openprj.jValidator.spring.SchemaFieldsPopupUpdateController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idSchema = request.getParameter("idSchema"); String idSchemaField = request.getParameter("idSchemaField"); String idFieldType = request.getParameter("idFieldType"); String name = request.getParameter("name"); String description = request.getParameter("description"); String minLenght = request.getParameter("minLenght"); String maxLenght = request.getParameter("maxLenght"); String nillableAlphanumeric = request.getParameter("nillableAlphanumeric"); String idCheckType = request.getParameter("extraCheck"); String minInclusive = request.getParameter("minInclusive"); String maxInclusive = request.getParameter("maxInclusive"); String fractionDigits = request.getParameter("fractionDigits"); String nillableNumeric = request.getParameter("nillableNumeric"); String numericType = request.getParameter("numericType"); String idDateTimeType = request.getParameter("idDateTimeType"); String idDateType = request.getParameter("idDateType"); String idTimeType = request.getParameter("idTimeType"); String isForecastable = request.getParameter("isForecastable"); String forecastAccuracy = request.getParameter("forecastAccuracy"); String forecastSpeed = request.getParameter("forecastSpeed"); String nillableDate = request.getParameter("nillableDate"); String size = request.getParameter("size"); String idCustomError = request.getParameter("idCustomError"); String maxOccurs = request.getParameter("maxOccurs"); String linkToDb = request.getParameter("linkToDb"); String isAttribute = request.getParameter("isAttribute"); String errorType = request.getParameter("errorType"); String selectedExtraCheckVals = request.getParameter("selectedExtraCheck"); int errorToleranceValue = Integer.parseInt(request.getParameter("errorToleranceValue") == null ? "-1" : request.getParameter("errorToleranceValue")); SchemaEntity schemaEntity = schemasDao.find(Long.parseLong(idSchema)); SchemaFieldEntity schemaFieldEntity = schemaFieldsDao.find(Long.parseLong(idSchemaField)); schemasXSDDao.destroy(schemaFieldEntity.getIdSchema()); String oldLinkToDb = schemaFieldEntity.getLinkToDb(); schemaFieldEntity.setIdFieldType(Integer.parseInt(idFieldType)); schemaFieldEntity.setName(name);/* ww w . j a v a 2 s .co m*/ schemaFieldEntity.setDescription(description.replace('\u200b', ' ')); schemaFieldEntity.setErrorToleranceValue(errorToleranceValue); if (errorType != null) schemaFieldEntity.setErrorType(Integer.parseInt(request.getParameter("errorType"))); if ("1".equals(isAttribute) || "true".equals(isAttribute)) { schemaFieldEntity.setIs_Attribute(true); } else { schemaFieldEntity.setIs_Attribute(false); } if (maxOccurs != null && !maxOccurs.equals("")) { schemaFieldEntity.setMaxOccurs(Integer.parseInt(maxOccurs)); } else { schemaFieldEntity.setMaxOccurs(1); } boolean isLinkedToDbChanged = false; if (linkToDb != null && !linkToDb.isEmpty()) { schemaFieldEntity.setLinkToDb(linkToDb); isLinkedToDbChanged = true; } if (idCustomError != null && !idCustomError.isEmpty() && Long.parseLong(idCustomError) != -7) { schemaFieldEntity.setIdCustomError(Long.parseLong(idCustomError)); } if (schemaFieldEntity.getIdFieldType() == FieldType.alphanumeric) { if (minLenght != null && !minLenght.equals("")) { schemaFieldEntity.setMinLength(Integer.parseInt(minLenght)); } else { schemaFieldEntity.setMinLength(null); } if (maxLenght != null && !maxLenght.equals("")) { schemaFieldEntity.setMaxLength(Integer.parseInt(maxLenght)); } else { schemaFieldEntity.setMaxLength(null); } if (idCheckType != null && !idCheckType.equals("")) { schemaFieldEntity.setIdCheckType(Integer.parseInt(idCheckType)); } else { schemaFieldEntity.setIdCheckType(0); } if (StringUtils.isNotEmpty(selectedExtraCheckVals)) { // Delete existing entries from database schemaFieldsDao.destroySchemFieldCheckTypes(Long.parseLong(idSchemaField)); String[] extraCheckIds = selectedExtraCheckVals.split(","); Set<SchemaFieldCheckTypesEntity> schemaFieldCheckTypeSet = new HashSet<SchemaFieldCheckTypesEntity>( extraCheckIds.length); SchemaFieldCheckTypesEntity schemaFieldCheckTypesEntity; for (String extraCheck : extraCheckIds) { schemaFieldCheckTypesEntity = new SchemaFieldCheckTypesEntity(); schemaFieldCheckTypesEntity.setIdCheckType(Long.parseLong(extraCheck)); schemaFieldCheckTypesEntity.setSchemaFieldEntity(schemaFieldEntity); schemaFieldCheckTypeSet.add(schemaFieldCheckTypesEntity); schemaFieldCheckTypesEntity = null; } schemaFieldEntity.setSchemaFieldCheckTypeSet(schemaFieldCheckTypeSet); } else { List<String> list = schemaFieldsDao.findSchemaFieldCheckTypes(Long.parseLong(idSchemaField)); if (list.size() > 0) { // Delete existing entries from database schemaFieldsDao.destroySchemFieldCheckTypes(Long.parseLong(idSchemaField)); Set<SchemaFieldCheckTypesEntity> schemaFieldCheckTypeSet = new HashSet<SchemaFieldCheckTypesEntity>(); schemaFieldEntity.setSchemaFieldCheckTypeSet(schemaFieldCheckTypeSet); } } if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) { String idAlignAlphanumeric = request.getParameter("idAlignAlphanumeric"); String fillCharAlphanumeric = request.getParameter("fillCharAlphanumeric"); schemaFieldEntity.setNillable(false); schemaFieldEntity.setSize(size); if (idAlignAlphanumeric != null && !idAlignAlphanumeric.equals("")) { schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignAlphanumeric)); } else { schemaFieldEntity.setIdAlign(null); } if (fillCharAlphanumeric != null && !fillCharAlphanumeric.equals("")) { schemaFieldEntity.setFillChar(fillCharAlphanumeric); } else { schemaFieldEntity.setFillChar(null); } } else { if (nillableAlphanumeric != null && (nillableAlphanumeric.equals("1") || nillableAlphanumeric.equals("true"))) { schemaFieldEntity.setNillable(true); } else { schemaFieldEntity.setNillable(false); } } } if (schemaFieldEntity.getIdFieldType() == FieldType.numeric) { if (!minInclusive.equals("")) { schemaFieldEntity.setMinInclusive(Double.parseDouble(minInclusive)); } else { schemaFieldEntity.setMinInclusive(null); } if (!maxInclusive.equals("")) { schemaFieldEntity.setMaxInclusive(Double.parseDouble(maxInclusive)); } else { schemaFieldEntity.setMaxInclusive(null); } if (!fractionDigits.equals("")) { schemaFieldEntity.setFractionDigits(Integer.parseInt(fractionDigits)); } else { schemaFieldEntity.setFractionDigits(null); } if (numericType.equals("1")) { schemaFieldEntity.setIdNumericType(1); } else { schemaFieldEntity.setIdNumericType(2); } schemaFieldEntity.setIsForecastable(Boolean.parseBoolean(isForecastable)); schemaFieldEntity.setForecastSpeed(Integer.parseInt(forecastSpeed)); schemaFieldEntity.setForecastAccuracy(Integer.parseInt(forecastAccuracy)); if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) { String idAlignNumeric = request.getParameter("idAlignNumeric"); String fillCharNumeric = request.getParameter("fillCharNumeric"); schemaFieldEntity.setNillable(false); schemaFieldEntity.setSize(size); if (!idAlignNumeric.equals("")) { schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignNumeric)); } else { schemaFieldEntity.setIdAlign(null); } if (!fillCharNumeric.equals("")) { schemaFieldEntity.setFillChar(fillCharNumeric); } else { schemaFieldEntity.setFillChar(null); } } else { if (nillableNumeric.equals("1") || nillableNumeric.equals("true")) { schemaFieldEntity.setNillable(true); } else { schemaFieldEntity.setNillable(false); } } } if (schemaFieldEntity.getIdFieldType() == FieldType.date) { int maxLength = 0; schemaFieldEntity.setIdDateFmtType(Integer.parseInt(idDateTimeType)); if (!idDateType.equals("")) { schemaFieldEntity.setIdDateType(Integer.parseInt(idDateType)); switch (Integer.parseInt(idDateType)) { case DateTimeType.DDMMYY: maxLength = 6; break; case DateTimeType.slashDDMMYY: case DateTimeType.signDDMMYY: case DateTimeType.dotDDMMYY: case DateTimeType.DDMMYYYY: case DateTimeType.YYYYMMDD: maxLength = 8; break; case DateTimeType.slashDDMMYYYY: case DateTimeType.signDDMMYYYY: case DateTimeType.dotDDMMYYYY: case DateTimeType.slashYYYYMMDD: case DateTimeType.signYYYYMMDD: case DateTimeType.dotYYYYMMDD: maxLength = 10; break; } } else { schemaFieldEntity.setIdDateType(null); } if (!idTimeType.equals("")) { schemaFieldEntity.setIdTimeType(Integer.parseInt(idTimeType)); if (maxLength > 0) { maxLength = maxLength + 1; } switch (Integer.parseInt(idTimeType)) { case DateTimeType.dblpnthhmm: case DateTimeType.dothhmm: maxLength = maxLength + 5; break; case DateTimeType.dblpnthhmmss: case DateTimeType.dothhmmss: maxLength = maxLength + 8; break; case DateTimeType.dblpntZhhmmss: case DateTimeType.dotZhhmmss: maxLength = maxLength + 11; break; case DateTimeType.dblpnthmmss: case DateTimeType.dothmmss: maxLength = maxLength + 7; break; } } else { schemaFieldEntity.setIdTimeType(null); } schemaFieldEntity.setMaxLength(maxLength); if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) { schemaFieldEntity.setNillable(false); schemaFieldEntity.setSize(maxLength + ""); } else { if (nillableDate.equals("1") || nillableDate.equals("true")) { schemaFieldEntity.setNillable(true); } else { schemaFieldEntity.setNillable(false); } } int dateTimeType = schemaFieldEntity.getIdDateTimeType(); if ((dateTimeType == DateTimeType.xsdDateTime || dateTimeType == DateTimeType.xsdDate || dateTimeType == DateTimeType.xsdTime || dateTimeType == DateTimeType.unixTimestamp) && schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) { String idAlignDateTime = request.getParameter("idAlignDateTime"); String fillCharDateTime = request.getParameter("fillCharDateTime"); schemaFieldEntity.setSize(size); if (!idAlignDateTime.equals("")) { schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignDateTime)); } else { schemaFieldEntity.setIdAlign(null); } if (!fillCharDateTime.equals("")) { schemaFieldEntity.setFillChar(fillCharDateTime); } else { schemaFieldEntity.setFillChar(null); } } else { schemaFieldEntity.setIdAlign(null); schemaFieldEntity.setFillChar(null); } } Update update = schemaFieldsDao.update(schemaFieldEntity); if (update.isSuccess()) { schemaEntity.setIsActive(0); schemasDao.update(schemaEntity); } if (linkToDb != null && linkToDb.trim().length() > 0 && linkToDb.indexOf(".") == -1) { if (oldLinkToDb == null || oldLinkToDb.trim().length() == 0) { addLinkedTableFields(schemaFieldEntity, linkToDb); } else if (!linkToDb.equals(oldLinkToDb)) { deleteLinkedTableFields(schemaFieldEntity, oldLinkToDb); addLinkedTableFields(schemaFieldEntity, linkToDb); } } if (isLinkedToDbChanged) { update.setExtraMessage("isLinkedToDbChanged"); } ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json"); ServletOutputStream out = response.getOutputStream(); out.write(mapper.writeValueAsBytes(update)); out.flush(); out.close(); return null; }
From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.statistics.StatisticsAction.java
private ActionForward streamCSV(final HttpServletResponse response, final String fileName, final String csvContent) throws IOException { response.setContentType("application/csv"); response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".csv"); ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(csvContent.getBytes()); outputStream.flush();/*from w w w . j av a 2 s. co m*/ outputStream.close(); return null; }
From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.statistics.StatisticsAction.java
private ActionForward streamSpreadsheet(final HttpServletResponse response, final String fileName, final Spreadsheet resultSheet, final Integer year) throws IOException { response.setContentType("application/xls "); response.setHeader("Content-disposition", "attachment; filename=" + fileName + year + ".xls"); ServletOutputStream outputStream = response.getOutputStream(); resultSheet.exportToXLSSheet(outputStream); outputStream.flush();//from w ww.ja v a 2s . c o m outputStream.close(); return null; }
From source file:com.seer.datacruncher.spring.EventTriggerValidator.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("code"); String name = request.getParameter("name"); String addReq = request.getParameter("addReq"); String result = null;// www .j av a 2 s . c om ObjectMapper mapper = new ObjectMapper(); ServletOutputStream out = null; response.setContentType("application/json"); out = response.getOutputStream(); if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) { result = I18n.getMessage("error.trigger.invaliddata");//"Failed. Reason:Invalid Data"; } else { name = name.trim(); if (addReq.equalsIgnoreCase("true")) { ReadList list = eventTriggerDao.findTriggersByName(name); if (list != null && CollectionUtils.isNotEmpty(list.getResults())) { result = I18n.getMessage("error.trigger.name.alreadyexist");//"Failed. Reason:Name alredy exist"; out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; } } try { File sourceDir = new File(System.getProperty("java.io.tmpdir"), "DataCruncher/src"); sourceDir.mkdirs(); String classNamePack = name.replace('.', File.separatorChar); String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java"; File sourceFile = new File(srcFilePath); if (sourceFile.exists()) { sourceFile.delete(); } FileUtils.writeStringToFile(new File(srcFilePath), code); DynamicClassLoader dynacode = DynamicClassLoader.getInstance(); dynacode.addSourceDir(sourceDir); EventTrigger eventTrigger = (EventTrigger) dynacode.newProxyInstance(EventTrigger.class, name); boolean isValid = false; if (eventTrigger != null) { Class clazz = dynacode.getLoadedClass(name); if (clazz != null) { Class[] interfaces = clazz.getInterfaces(); if (ArrayUtils.isNotEmpty(interfaces)) { for (Class clz : interfaces) { if (clz.getName() .equalsIgnoreCase("com.seer.datacruncher.eventtrigger.EventTrigger")) { isValid = true; } } } else if (clazz.getSuperclass() != null && clazz.getSuperclass().getName() .equalsIgnoreCase("com.seer.datacruncher.eventtrigger.EventTriggerImpl")) { isValid = true; } } } if (isValid) { result = "Success"; } else { result = I18n.getMessage("error.trigger.wrongimpl");//"Failed. Reason: Custom code should implement com.seer.datacruncher.eventtrigger.EventTrigger Interface"; } } catch (Exception e) { result = "Failed. Reason:" + e.getMessage(); } } out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; }
From source file:org.codelabor.system.file.web.struts.action.FileUploadAction.java
public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(getServlet().getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String fileId = (String) paramMap.get("fileId"); StringBuilder sb = new StringBuilder(); FileDTO fileDTO;/*from w ww.j a v a2 s .c o m*/ fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.setLength(0); sb.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } response.setContentType(fileDTO.getContentType()); // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); return null; }
From source file:de.berlios.jedi.presentation.editor.DownloadPackageAction.java
/** * Handle server requests./*from www .j av a 2 s.c o m*/ * * @param mapping * The ActionMapping used to select this instance. * @param form * The optional ActionForm bean for this request (if any). * @param request * The HTTP request we are processing. * @param response * The HTTP response we are creating. */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { JispPackagesList jispPackagesList = (JispPackagesList) request.getSession() .getAttribute(EditorKeys.JISP_PACKAGES_LIST_KEY); JispPackage jispPackage = (JispPackage) request.getSession().getAttribute(EditorKeys.JISP_PACKAGE); setJispMetadata(jispPackage, jispPackagesList); JispFile jispFile = null; try { jispFile = new EditorLogicService().getJispFileFromJispPackage(jispPackage); } catch (UnsupportedOperationException e) { LogFactory.getLog(DownloadPackageAction.class).fatal("UTF-8 encoding not supported!!!", e); return errorForward(mapping, request, new ActionMessage("utf8NotSupported"), "utf8NotSupported", Keys.ADD_STATUS_FORWARD_NAME); } catch (JispIncompletePackageException e) { LogFactory.getLog(DownloadPackageAction.class).error("Incomplete JispPackage", e); return errorForward(mapping, request, new ActionMessage("incompleteJispPackage", e.getMessage()), "incompleteJispPackage", Keys.ADD_STATUS_FORWARD_NAME); } response.setContentType("application/vnd.jisp"); // Filename should be equal to the name of the root directory of the // jisp file response.setHeader("Content-disposition", "attachment; filename=\"" + JispUtil.getDefaultRootDirectoryName(jispPackage) + ".jisp\""); ServletOutputStream out = null; try { out = response.getOutputStream(); out.write(jispFile.getData()); } catch (IOException e) { LogFactory.getLog(DownloadPackageAction.class) .error("IOException when writing the JispFile to the " + "ServlerOutputStream", e); return errorForward(mapping, request, new ActionMessage("failedJispFileWriteToOutputStream"), "failedJispFileWriteToOutputStream", Keys.ADD_STATUS_FORWARD_NAME); } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } } return null; }
From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java
protected void doWrite(HttpServletResponse response, byte[] content) throws IOException { ServletOutputStream o = response.getOutputStream(); o.write(content);/* w w w . j a va 2 s.c o m*/ o.flush(); o.close(); }
From source file:it.openprj.jValidator.spring.EventTriggerValidator.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("code"); String name = request.getParameter("name"); String addReq = request.getParameter("addReq"); String result = null;/*from w w w . jav a2 s .c o m*/ ObjectMapper mapper = new ObjectMapper(); ServletOutputStream out = null; response.setContentType("application/json"); out = response.getOutputStream(); if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) { result = I18n.getMessage("error.trigger.invaliddata");//"Failed. Reason:Invalid Data"; } else { name = name.trim(); if (addReq.equalsIgnoreCase("true")) { ReadList list = eventTriggerDao.findTriggersByName(name); if (list != null && CollectionUtils.isNotEmpty(list.getResults())) { result = I18n.getMessage("error.trigger.name.alreadyexist");//"Failed. Reason:Name alredy exist"; out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; } } try { File sourceDir = new File(System.getProperty("java.io.tmpdir"), "jValidator/src"); sourceDir.mkdirs(); String classNamePack = name.replace('.', File.separatorChar); String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java"; File sourceFile = new File(srcFilePath); if (sourceFile.exists()) { sourceFile.delete(); } FileUtils.writeStringToFile(new File(srcFilePath), code); DynamicClassLoader dynacode = DynamicClassLoader.getInstance(); dynacode.addSourceDir(sourceDir); EventTrigger eventTrigger = (EventTrigger) dynacode.newProxyInstance(EventTrigger.class, name); boolean isValid = false; if (eventTrigger != null) { Class clazz = dynacode.getLoadedClass(name); if (clazz != null) { Class[] interfaces = clazz.getInterfaces(); if (ArrayUtils.isNotEmpty(interfaces)) { for (Class clz : interfaces) { if (clz.getName() .equalsIgnoreCase("it.openprj.jValidator.eventtrigger.EventTrigger")) { isValid = true; } } } else if (clazz.getSuperclass() != null && clazz.getSuperclass().getName() .equalsIgnoreCase("it.openprj.jValidator.eventtrigger.EventTriggerImpl")) { isValid = true; } } } if (isValid) { result = "Success"; } else { result = I18n.getMessage("error.trigger.wrongimpl");//"Failed. Reason: Custom code should implement it.openprj.jValidator.eventtrigger.EventTrigger Interface"; } } catch (Exception e) { result = "Failed. Reason:" + e.getMessage(); } } out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; }
From source file:pivotal.au.se.gemfirexdweb.controller.QueryController.java
@RequestMapping(value = "/query", method = RequestMethod.POST) public String worksheetAction(@ModelAttribute("queryAttribute") QueryWindow queryAttribute, Model model, HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception { if (session.getAttribute("user_key") == null) { logger.debug("user_key is null new Login required"); response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } else {//from w w w . java 2 s .c om Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key")); if (conn == null) { response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } else { if (conn.isClosed()) { response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login"); return null; } } } logger.debug("Received request to action SQL from query worksheet"); logger.info(queryAttribute); UserPref userPrefs = (UserPref) session.getAttribute("prefs"); ConnectionManager cm = ConnectionManager.getInstance(); if (queryAttribute.getQuery() != null) { if (queryAttribute.getSaveWorksheet().equals("Y")) { response.setContentType(SAVE_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME); ServletOutputStream out = response.getOutputStream(); out.println(queryAttribute.getQuery()); out.close(); return null; } // retrieve connection Connection conn = cm.getConnection(session.getId()); String query = queryAttribute.getQuery().trim(); logger.debug("Query = " + query); String[] splitQueryStr = spiltQuery(query); CommandResult result = new CommandResult(); if (query.length() > 0) { if (splitQueryStr.length == 1) { String s = checkForComments(query); s = s.trim(); if (determineQueryType(s).equals("SELECT")) { try { final String explain = queryAttribute.getExplainPlan(); if (!explain.equals("N")) { logger.debug("Need to run explain plan."); String explainString = ""; if (explain.equals("Y")) { explainString = "explain as xml %s"; } else if (explain.equals("T")) { explainString = "explain %s"; } String xPlan = QueryUtil.runExplainPlan(conn, String.format(explainString, query)); logger.debug("received xPath : " + xPlan); if (explain.equals("Y")) { model.addAttribute("explainresult", xPlan); } else if (explain.equals("T")) { model.addAttribute("explaintxtresult", xPlan); } } else { if (queryAttribute.getShowMember().equals("Y")) { String replace = "select dsid() as \"Member\","; s = query.toLowerCase().replaceFirst("select", replace); } long start = System.currentTimeMillis(); Result res = QueryUtil.runQuery(conn, s, userPrefs.getMaxRecordsinSQLQueryWindow()); long end = System.currentTimeMillis(); double timeTaken = new Double(end - start).doubleValue(); DecimalFormat df = new DecimalFormat("#.##"); model.addAttribute("queryResults", res); model.addAttribute("query", s); model.addAttribute("querysql", s); if (queryAttribute.getQueryCount().equals("Y")) { model.addAttribute("queryResultCount", res.getRowCount()); } if (queryAttribute.getElapsedTime().equals("Y")) { model.addAttribute("elapsedTime", df.format(timeTaken / 1000)); } addCommandToHistory(session, userPrefs, s); } } catch (Exception ex) { result.setCommand(s); result.setMessage(ex.getMessage() == null ? "Unable to run query" : ex.getMessage()); result.setRows(-1); model.addAttribute("result", result); model.addAttribute("query", s); } } else { if (s.length() > 0) { if (determineQueryType(s).equals("COMMIT")) { result = QueryUtil.runCommitOrRollback(conn, true, queryAttribute.getElapsedTime()); model.addAttribute("result", result); if (result.getMessage().startsWith("SUCCESS")) { addCommandToHistory(session, userPrefs, s); } } else if (determineQueryType(s).equals("ROLLBACK")) { result = QueryUtil.runCommitOrRollback(conn, false, queryAttribute.getElapsedTime()); model.addAttribute("result", result); if (result.getMessage().startsWith("SUCCESS")) { addCommandToHistory(session, userPrefs, s); } } else if (determineQueryType(s).equals("CALL")) { String procName = getProcName(s); if (procName != null) { String schema = null; int x = procName.indexOf("."); if (x != -1) { String newProcName = procName.substring((procName.indexOf(".") + 1)); schema = procName.substring(0, (procName.indexOf("."))); procName = newProcName; } else { schema = (String) session.getAttribute("schema"); } logger.debug("schema for stored procedure = " + schema); logger.debug("call statement called for proc with name " + procName); // need to get schema name to check proc details int numberOfDynamicResultSets = QueryUtil.checkForDynamicResultSetProc(conn, schema, procName); if (numberOfDynamicResultSets > 0) { logger.debug("call statement with " + numberOfDynamicResultSets + " dynamic resultset(s)"); try { List<Result> procResults = QueryUtil.runStoredprocWithResultSet(conn, s, userPrefs.getMaxRecordsinSQLQueryWindow(), numberOfDynamicResultSets); model.addAttribute("procresults", procResults); model.addAttribute("callstatement", procName); model.addAttribute("dynamicresults", numberOfDynamicResultSets); addCommandToHistory(session, userPrefs, s); } catch (Exception ex) { result.setCommand(s); result.setMessage(ex.getMessage() == null ? "Unable to run query" : ex.getMessage()); result.setRows(-1); model.addAttribute("result", result); model.addAttribute("query", s); } } else { result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime()); model.addAttribute("result", result); if (result.getMessage().startsWith("SUCCESS")) { addCommandToHistory(session, userPrefs, s); } } } else { result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime()); model.addAttribute("result", result); if (result.getMessage().startsWith("SUCCESS")) { addCommandToHistory(session, userPrefs, s); } } } else { result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime()); model.addAttribute("result", result); if (result.getMessage().startsWith("SUCCESS")) { addCommandToHistory(session, userPrefs, s); } } } } } else { logger.debug("multiple SQL statements need to be executed"); SortedMap<String, Object> queryResults = handleMultipleStatements(splitQueryStr, conn, userPrefs, queryAttribute, session); logger.debug("keys : " + queryResults.keySet()); model.addAttribute("sqlResultMap", queryResults); model.addAttribute("statementsExecuted", queryResults.size()); } } } else { if (ServletFileUpload.isMultipartContent(request)) { logger.debug("is multipartcontent request"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> fileItemsList = upload.parseRequest(request); logger.debug("fileItemList size = " + fileItemsList.size()); Iterator<?> it = fileItemsList.iterator(); while (it.hasNext()) { FileItem fileItemTemp = (FileItem) it.next(); if (fileItemTemp.getFieldName().equals("sqlfilename")) { QueryWindow qw = new QueryWindow(); qw.setQuery(fileItemTemp.getString()); model.addAttribute("queryAttribute", qw); model.addAttribute("sqlfile", fileItemTemp.getName()); } } } } return "query"; }
From source file:org.fenixedu.parking.ui.Action.ParkingManagerDispatchAction.java
public ActionForward exportToPDFParkingCard(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { String parkingPartyID = request.getParameter("parkingPartyID"); final ParkingParty parkingParty = FenixFramework.getDomainObject(parkingPartyID); String parkingGroupID = request.getParameter("groupID"); if (parkingGroupID != null) { String parkingRequestID = request.getParameter("code"); if (request.getParameter("groupID") == null) { saveErrorMessage(request, "group", "error.invalidGroup"); request.setAttribute("externalId", parkingRequestID); return showRequest(mapping, actionForm, request, response); }//w w w.j a v a 2s .c o m if (!isValidGroup(parkingGroupID)) { saveErrorMessage(request, "group", "error.invalidGroup"); request.setAttribute("externalId", parkingRequestID); return showRequest(mapping, actionForm, request, response); } } ParkingGroup parkingGroup = null; if (parkingGroupID != null) { parkingGroup = FenixFramework.getDomainObject(parkingGroupID); } else { parkingGroup = parkingParty.getParkingGroup(); } Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("imageUrl", "images/Logo_IST_color.tiff"); Person person = (Person) parkingParty.getParty(); parameters.put("number", getMostSignificantNumberString(person, parkingGroup)); List<Person> persons = new ArrayList<Person>(); persons.add(person); ReportResult report = ReportsUtils.generateReport("parkingManager.parkingCard", parameters, persons); byte[] data = report.getData(); response.setContentType(report.getContentType()); response.addHeader("Content-Disposition", "attachment; filename=cartao." + report.getFileExtension()); response.setContentLength(data.length); ServletOutputStream writer = response.getOutputStream(); writer.write(data); writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); }