List of usage examples for javax.servlet ServletOutputStream write
public abstract void write(int b) throws IOException;
From source file:edu.harvard.iq.dataverse.DatasetPage.java
public void downloadRsyncScript() { String bibFormatDowload = new BibtexCitation(workingVersion).toString(); FacesContext ctx = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse(); response.setContentType("application/download"); String contentDispositionString; contentDispositionString = "attachment;filename=" + rsyncScriptFilename; response.setHeader("Content-Disposition", contentDispositionString); try {//from w ww. j av a 2 s . c o m ServletOutputStream out = response.getOutputStream(); out.write(getRsyncScript().getBytes()); out.flush(); ctx.responseComplete(); } catch (IOException e) { String error = "Problem getting bytes from rsync script: " + e; logger.warning(error); return; } // If the script has been successfully downloaded, lock the dataset: String lockInfoMessage = "script downloaded"; DatasetLock lock = datasetService.addDatasetLock(dataset.getId(), DatasetLock.Reason.DcmUpload, session.getUser() != null ? ((AuthenticatedUser) session.getUser()).getId() : null, lockInfoMessage); if (lock != null) { dataset.addLock(lock); } else { logger.log(Level.WARNING, "Failed to lock the dataset (dataset id={0})", dataset.getId()); } }
From source file:org.cloudifysource.rest.controllers.ServiceController.java
/** * Exception handler for all of known internal server exceptions. * * @param response/*from w ww . ja v a2s .co m*/ * The response object to edit, if not committed yet. * @param e * The exception that occurred, from which data is read for logging and for the response error message. * @throws IOException * Reporting failure to edit the response object */ @ExceptionHandler(RestErrorException.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public void handleServerErrors(final HttpServletResponse response, final RestErrorException e) throws IOException { if (response.isCommitted()) { logger.log(Level.WARNING, "Caught exception, but response already commited. Not sending error message based on exception", e); } else { final Map<String, Object> errorDescriptionMap = e.getErrorDescription(); final String errorMap = new ObjectMapper().writeValueAsString(errorDescriptionMap); logger.log(Level.INFO, "caught exception. Sending response message " + errorDescriptionMap.get("error"), e); final byte[] messageBytes = errorMap.getBytes(); final ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(messageBytes); } }
From source file:org.cloudifysource.rest.controllers.ServiceController.java
/** * Exception handler for all of the internal server's exceptions. * * @param response//from w ww .ja v a 2 s. co m * The response object to edit, if not committed yet. * @param e * The exception that occurred, from which data is read for logging and for the response error message. * @throws IOException * Reporting failure to edit the response object */ @ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public void resolveDocumentNotFoundException(final HttpServletResponse response, final Exception e) throws IOException { if (response.isCommitted()) { logger.log(Level.WARNING, "Caught exception, but response already commited. Not sending error message based on exception", e); } else { String message; if (e instanceof AccessDeniedException || e instanceof BadCredentialsException) { message = "{\"status\":\"error\", \"error\":\"" + CloudifyErrorMessages.NO_PERMISSION_ACCESS_DENIED.getName() + "\"}"; logger.log(Level.INFO, e.getMessage(), e); } else { // Some sort of unhandled application exception. logger.log(Level.WARNING, "An unexpected error was thrown: " + e.getMessage(), e); final Map<String, Object> restErrorMap = RestUtils.verboseErrorStatus( CloudifyErrorMessages.GENERAL_SERVER_ERROR.getName(), ExceptionUtils.getStackTrace(e), e.getMessage()); message = new ObjectMapper().writeValueAsString(restErrorMap); } final ServletOutputStream outputStream = response.getOutputStream(); final byte[] messageBytes = message.getBytes(); outputStream.write(messageBytes); } }
From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java
@Override public void newCheckDetails(HttpServletResponse theResponse, HttpServletRequest theRequest) throws BankingException { Session printBeanSession = itsSessionFactory.openSession(); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) printBeanSession .getSessionFactory();/* w w w . ja va 2s . c o m*/ ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); Map<String, Object> params = new HashMap<String, Object>(); Connection connection = null; try { itsLogger.info("Testing:--->" + theRequest.getParameter("moTransactionID")); params.put("traxID", Integer.parseInt(theRequest.getParameter("moTransactionID"))); ServletOutputStream out = theResponse.getOutputStream(); String fileName = theRequest.getParameter("fileName"); theResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName); theResponse.setContentType("application/pdf"); connection = connectionProvider.getConnection(); String path_JRXML = theRequest.getSession().getServletContext() .getRealPath("/resources/jasper_reports/newcheck.jrxml"); JasperReport report = JasperCompileManager.compileReport(path_JRXML); JasperPrint print = JasperFillManager.fillReport(report, params, connection); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JasperExportManager.exportReportToPdfStream(print, baos); out.write(baos.toByteArray()); out.flush(); out.close(); } catch (Exception e) { itsLogger.error(e.getMessage(), e); BankingException aBankingException = new BankingException(e.getMessage(), e); } finally { try { if (connectionProvider != null) { connectionProvider.closeConnection(connection); connectionProvider = null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } printBeanSession.flush(); printBeanSession.close(); } }
From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java
@Override public void creditCheckDetails(HttpServletResponse theResponse, HttpServletRequest theRequest) throws BankingException { Session printBeanSession = itsSessionFactory.openSession(); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) printBeanSession .getSessionFactory();/*from w w w . ja v a2 s . c o m*/ ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); Map<String, Object> params = new HashMap<String, Object>(); Connection connection = null; Rxaddress address = null; try { itsLogger.info("Testing:--->" + theRequest.getParameter("moTransactionID")); ServletOutputStream out = theResponse.getOutputStream(); String fileName = theRequest.getParameter("fileName"); theResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName); theResponse.setContentType("application/pdf"); connection = connectionProvider.getConnection(); String path_JRXML = theRequest.getSession().getServletContext() .getRealPath("/resources/jasper_reports/CreditPayment.jrxml"); JasperReport report = JasperCompileManager.compileReport(path_JRXML); JasperPrint print = JasperFillManager.fillReport(report, params, connection); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JasperExportManager.exportReportToPdfStream(print, baos); out.write(baos.toByteArray()); out.flush(); out.close(); } catch (Exception e) { itsLogger.error(e.getMessage(), e); BankingException aBankingException = new BankingException(e.getMessage(), e); // throw aBankingException; } finally { try { if (connectionProvider != null) { connectionProvider.closeConnection(connection); connectionProvider = null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } printBeanSession.flush(); printBeanSession.close(); } }
From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java
@Override public void printCheckDetails(HttpServletResponse theResponse, HttpServletRequest theRequest) throws BankingException { Session printBeanSession = itsSessionFactory.openSession(); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) printBeanSession .getSessionFactory();/*from w w w . j av a 2 s. c om*/ ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); Map<String, Object> params = new HashMap<String, Object>(); //Rxaddress address = null; Connection connection = null; InputStream imageStream = null; try { Integer addressID = rxAddressID[0]; //address = (Rxaddress)printBeanSession.get(Rxaddress.class,addressID); params.put("Name", ""); params.put("Address2", ""); params.put("Address3", ""); itsLogger.info(billId.length); String count = billId.length + ""; params.put("BillCount", count); params.put("CheckDate", checkDate); TsUserSetting objtsusersettings = (TsUserSetting) printBeanSession.get(TsUserSetting.class, 1); Blob blob = objtsusersettings.getCompanyLogo(); imageStream = blob.getBinaryStream(); //params.put("companyLogo", imageStream); itsLogger.info("Check Date: " + checkDate); ServletOutputStream out = theResponse.getOutputStream(); String fileName = theRequest.getParameter("fileName"); theResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName); theResponse.setContentType("application/pdf"); connection = connectionProvider.getConnection(); String path_JRXML = theRequest.getSession().getServletContext() .getRealPath("/resources/jasper_reports/PrintChecksfinal.jrxml"); //String path_JRXML = theRequest.getSession().getServletContext().getRealPath("/resources/jasper_reports/CheckMICR.jrxml"); JasperReport report = JasperCompileManager.compileReport(path_JRXML); JasperPrint print = JasperFillManager.fillReport(report, params, connection); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JasperExportManager.exportReportToPdfStream(print, baos); out.write(baos.toByteArray()); out.flush(); out.close(); } catch (Exception e) { itsLogger.error(e.getMessage(), e); BankingException aBankingException = new BankingException(e.getMessage(), e); } finally { try { if (imageStream != null) { imageStream.close(); } if (connectionProvider != null) { connectionProvider.closeConnection(connection); connectionProvider = null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } printBeanSession.flush(); printBeanSession.close(); } }
From source file:com.seer.datacruncher.profiler.spring.ProfilerInfoUpdateController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream out = null; response.setContentType("application/json"); out = response.getOutputStream();/*from w w w . java2 s . c o m*/ @SuppressWarnings("unchecked") Hashtable<String, String> dbParams = (Hashtable<String, String>) request.getSession(true) .getAttribute("dbConnectionData"); if (dbParams != null) { request.setAttribute("serverName", CommonUtil.notNullValue(dbParams.get("Database_DSN"))); } String selectedValue = CommonUtil.notNullValue(request.getParameter("selectedValue")); request.setAttribute("selectedValue", selectedValue); String tableName = CommonUtil.notNullValue(request.getParameter("parent")); request.setAttribute("parentValue", tableName); ObjectMapper mapper = new ObjectMapper(); Vector vector = RdbmsConnection.getTable(); int i = vector.indexOf(tableName); Vector avector[] = (Vector[]) null; avector = TableMetaInfo.populateTable(5, i, i + 1, avector); QueryDialog querydialog = new QueryDialog(1, tableName, avector); try { querydialog.executeAction(""); } catch (Exception e) { e.printStackTrace(); } String strColumnName = ""; List<String> listPrimaryKeys = new ArrayList<String>(); Map<String, Integer> mapColumnNames = new HashMap<String, Integer>(); try { RdbmsConnection.openConn(); DatabaseMetaData dbmd = RdbmsConnection.getMetaData(); ResultSet resultset = dbmd.getPrimaryKeys(null, null, tableName); while (resultset.next()) { listPrimaryKeys.add(resultset.getString("COLUMN_NAME")); } resultset = dbmd.getColumns(null, null, tableName, null); while (resultset.next()) { strColumnName = resultset.getString(4); mapColumnNames.put(strColumnName, resultset.getInt(5)); } RdbmsConnection.closeConn(); } catch (Exception ex) { ex.printStackTrace(); } Map<String, Integer> mapPrimaryKeys = new HashMap<String, Integer>(); if (strColumnName.trim().length() > 0) { try { JSONArray array = new JSONArray(request.getParameter("data")); for (int count = 0; count < array.length(); count++) { JSONObject jsonObject = new JSONObject(array.get(count).toString()); StringBuilder queryString = new StringBuilder(); Iterator<String> keyIterator = jsonObject.keys(); while (keyIterator.hasNext()) { String strKey = keyIterator.next(); if (listPrimaryKeys.contains(strKey)) { mapPrimaryKeys.put(strKey, ((int) Double.parseDouble(jsonObject.get(strKey).toString()))); continue; } if (jsonObject.get(strKey) != null) { if (mapColumnNames.get(strKey) == 4 || mapColumnNames.get(strKey) == 5 || mapColumnNames.get(strKey) == -6) { queryString.append( strKey + "=" + Integer.parseInt(jsonObject.get(strKey).toString()) + ","); } else if (mapColumnNames.get(strKey) == 2 || mapColumnNames.get(strKey) == 3 || mapColumnNames.get(strKey) == 7 || mapColumnNames.get(strKey) == 6 || mapColumnNames.get(strKey) == -5) { queryString.append(strKey + "=" + jsonObject.get(strKey) + ","); } else if (mapColumnNames.get(strKey) == 91 || mapColumnNames.get(strKey) == 92 || mapColumnNames.get(strKey) == 93) { queryString.append(strKey + "=" + jsonObject.get(strKey) + ","); } else if (mapColumnNames.get(strKey) == -7 || mapColumnNames.get(strKey) == 16 || mapColumnNames.get(strKey) == -3 || mapColumnNames.get(strKey) == -4) { queryString.append(strKey + "=" + jsonObject.get(strKey) + ","); } else if (mapColumnNames.get(strKey) == -1 || mapColumnNames.get(strKey) == 1 || mapColumnNames.get(strKey) == 12) { queryString.append(strKey + "=\"" + jsonObject.get(strKey) + "\","); } } } StringBuilder whereClause = new StringBuilder(" where "); for (String primaryKey : listPrimaryKeys) { whereClause.append(primaryKey + "=" + mapPrimaryKeys.get(primaryKey).intValue()); whereClause.append(" and "); } String strWhereClause = whereClause.toString(); strWhereClause = strWhereClause.substring(0, strWhereClause.lastIndexOf("and")); queryString = new StringBuilder("UPDATE " + tableName + " SET ") .append(queryString.toString().substring(0, queryString.toString().length() - 1)); queryString.append(strWhereClause); RdbmsConnection.openConn(); RdbmsConnection.executeUpdate(queryString.toString()); RdbmsConnection.closeConn(); } } catch (Exception ex) { ex.printStackTrace(); } } Update update = new Update(); update.setSuccess(true); GridUtil gridUtil = new GridUtil(); gridUtil.generateGridData(querydialog.getTableGridDTO(), false, null); update.setResults(gridUtil.getData()); out.write(mapper.writeValueAsBytes(update)); out.flush(); out.close(); return null; }
From source file:net.sf.appstatus.web.pages.BatchPage.java
@Override public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, IOException { setup(resp, "text/html"); ServletOutputStream os = resp.getOutputStream(); Map<String, String> valuesMap = new HashMap<String, String>(); StrBuilder sbRunningBatchesBatchesTable = new StrBuilder(); StrBuilder sbFinishedBatchesBatchesTable = new StrBuilder(); StrBuilder sbErrorsBatchesBatchesTable = new StrBuilder(); StrBuilder sbConfBatchesBatchesTable = new StrBuilder(); IBatchManager manager = webHandler.getAppStatus().getBatchManager(); List<IBatch> runningBatches = manager.getRunningBatches(); if (HtmlUtils.generateBeginTable(sbRunningBatchesBatchesTable, runningBatches.size())) { HtmlUtils.generateHeaders(sbRunningBatchesBatchesTable, "", "Id", "Group", "Name", "Start", "Progress", // "End (est.)", "Status", "Task", "Last Msg", "Items", "Rejected", "Last Update"); for (IBatch batch : runningBatches) { HtmlUtils.generateRow(sbRunningBatchesBatchesTable, getIcon(batch), generateId(resp, batch.getUuid()), // batch.getGroup(), batch.getName(), batch.getStartDate(), getProgressBar(batch), // batch.getEndDate(), batch.getStatus(), batch.getCurrentTask(), // batch.getLastMessage(), batch.getItemCount(), HtmlUtils.countAndDetail(batch.getRejectedItemsId()), // batch.getLastUpdate(), // batch.getStatus() != IBatch.STATUS_ZOMBIE ? "" // : "<form action='?p=batch' method='post'><input type='submit' name='" + CLEAR_ITEM // + "' value='Delete' class='btn btn-small' /><input type=hidden name='" // + ITEM_UUID + "' value='" + batch.getUuid() + "'/></form>"); }// www.j a va 2 s. c om HtmlUtils.generateEndTable(sbRunningBatchesBatchesTable, runningBatches.size()); } // Batch Schedule List<IBatchConfiguration> batchConfigurations = new ArrayList<IBatchConfiguration>(); IBatchScheduleManager scheduleManager = webHandler.getAppStatus().getBatchScheduleManager(); if (scheduleManager != null) { batchConfigurations.addAll(scheduleManager.getBatchConfigurations()); } if (HtmlUtils.generateBeginTable(sbConfBatchesBatchesTable, batchConfigurations.size())) { HtmlUtils.generateHeaders(sbConfBatchesBatchesTable, "", "Group", "Name", "Last run", "Next", "Exec. expr"); for (IBatchConfiguration batch : batchConfigurations) { addExecutionInformations(batch, manager.getBatches(batch.getGroup(), batch.getName())); HtmlUtils.generateRow(sbConfBatchesBatchesTable, Resources.STATUS_JOB, batch.getGroup(), batch.getName(), batch.getLastExecution(), batch.getNextExecution(), batch.getSchedule()); } HtmlUtils.generateEndTable(sbConfBatchesBatchesTable, runningBatches.size()); } List<IBatch> finishedBatches = manager.getFinishedBatches(); if (HtmlUtils.generateBeginTable(sbFinishedBatchesBatchesTable, finishedBatches.size())) { HtmlUtils.generateHeaders(sbFinishedBatchesBatchesTable, "", "Id", "Group", "Name", "Start", "Progress", // "End", "Status", "Task", "Last Msg", "Items", "Rejected", "Last Update", ""); for (IBatch batch : finishedBatches) { HtmlUtils.generateRow(sbFinishedBatchesBatchesTable, getIcon(batch), generateId(resp, batch.getUuid()), // batch.getGroup(), batch.getName(), batch.getStartDate(), getProgressBar(batch), // batch.getEndDate(), batch.getStatus(), batch.getCurrentTask(), batch.getLastMessage(), // batch.getItemCount(), HtmlUtils.countAndDetail(batch.getRejectedItemsId()), // batch.getLastUpdate(), // "<form action='?p=batch' method='post'><input type='submit' name='" // + CLEAR_ITEM + "' value='Delete' class='btn btn-small' /><input type=hidden name='" // + ITEM_UUID + "' value='" + batch.getUuid() + "'/></form>"); } HtmlUtils.generateEndTable(sbFinishedBatchesBatchesTable, finishedBatches.size()); } List<IBatch> errorBatches = manager.getErrorBatches(); if (HtmlUtils.generateBeginTable(sbErrorsBatchesBatchesTable, errorBatches.size())) { HtmlUtils.generateHeaders(sbErrorsBatchesBatchesTable, "", "Id", "Group", "Name", "Start", "Progress", // "End", "Status", "Task", "Last Msg", "Items", "Rejected", "Last Update", ""); for (IBatch batch : errorBatches) { HtmlUtils.generateRow(sbErrorsBatchesBatchesTable, getIcon(batch), generateId(resp, batch.getUuid()), // batch.getGroup(), batch.getName(), batch.getStartDate(), getProgressBar(batch), // batch.getEndDate(), batch.getStatus(), batch.getCurrentTask(), batch.getLastMessage(), // batch.getItemCount(), HtmlUtils.countAndDetail(batch.getRejectedItemsId()), // batch.getLastUpdate(), // "<form action='?p=batch' method='post'><input type='submit' name='" // + CLEAR_ITEM + "' value='Delete' class='btn btn-small'/><input type=hidden name='" // + ITEM_UUID + "' value='" + batch.getUuid() + "'/></form>"); } HtmlUtils.generateEndTable(sbErrorsBatchesBatchesTable, errorBatches.size()); } valuesMap.put("confBatchesBatchesTable", sbConfBatchesBatchesTable.toString()); valuesMap.put("runningBatchesBatchesTable", sbRunningBatchesBatchesTable.toString()); valuesMap.put("finishedBatchesBatchesTable", sbFinishedBatchesBatchesTable.toString()); valuesMap.put("errorsBatchesBatchesTable", sbErrorsBatchesBatchesTable.toString()); valuesMap.put("clearActions", generateClearActions()); String content = HtmlUtils.applyLayout(valuesMap, PAGECONTENTLAYOUT); valuesMap.clear(); valuesMap.put("content", content); os.write(getPage(webHandler, valuesMap).getBytes(ENCODING)); }
From source file:sos.settings.SOSSettingsDialog.java
/** * Sourcecode bei binren Dokumenten//from w w w .ja v a 2 s . com * * @return boolean Fehlerzustand * @access public * @author Robert Ehrlich <re@sos-berlin.com> * @version 1.0-2004/03/17 */ private void downloadSource(String application, String section, String entry) throws Exception { this.debug(3, "download_source : application = " + application + " section = " + section + " entry = " + entry); if (application == null || application.length() == 0) { this.setError("application for download is empty", SOSClassUtil.getMethodName()); return; } if (section == null || section.length() == 0) { this.setError("section for download is empty", SOSClassUtil.getMethodName()); return; } if (entry == null || entry.length() == 0) { this.setError("entry for download is empty", SOSClassUtil.getMethodName()); return; } byte[] data; try { String sql = "select \"LONG_VALUE\" from " + this.settings.source + " where \"" + this.settings.entryApplication + "\" = " + this.dbQuoted(application) + " and \"" + this.settings.entrySection + "\" = " + this.dbQuoted(section) + " and \"" + this.settings.entryName + "\" = " + this.dbQuoted(entry); data = this.connection.getBlob(sql); if (data == null || data.length == 0) { this.setError("no data found for application <b>" + application + "</b> section <br>" + section + "</b> entry <b>" + entry + "</b>", SOSClassUtil.getMethodName()); return; } } catch (Exception e) { this.setError(e.getMessage(), SOSClassUtil.getMethodName()); return; } String r_file_name = this.getRequestValue("file_name"); String file_name = (r_file_name != null && r_file_name.length() > 0) ? r_file_name : this.settings.defaultDocumentFileName; String header_ext = "application/octet-stream"; // da beim Download getOutputStream benutz wird(damit schreibt man binre Sachen) // kommt es ohne aufzurumen zu einer Exception (nur in Tomcate LOGs), // weil out bereits aktiv ist(es kann entweder OutputStream oder Writer geben) // muss auch in der jsp Datei gesetzt werden this.out.clear(); // keine Header mehr !!! this.response.setContentType(header_ext); this.response.setIntHeader("Content-length", data.length); this.response.setHeader("Content-Disposition", "attachment; filename=" + file_name); //this.response.flushBuffer(); //this.response.getWriter().write(new String(data)); //this.response.getWriter().close(); this.isSourceDownloaded = false; try { javax.servlet.ServletOutputStream os = response.getOutputStream(); os.write(data); os.flush(); os.close(); this.isSourceDownloaded = true; System.out.println("--------------- Downloaded -----------------"); } catch (Exception e) { System.out.println("EXCEPTION : " + e); } }