Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:org.apache.ranger.biz.ServiceDBStore.java

public void getPoliciesInCSV(List<RangerPolicy> policies, HttpServletResponse response) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceDBStore.getPoliciesInCSV()");
    }/*from   ww  w  .  j a  v a 2  s .  com*/
    InputStream in = null;
    ServletOutputStream out = null;
    String CSVFileName = null;
    try {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        CSVFileName = "Ranger_Policies_" + timeStamp + ".csv";
        out = response.getOutputStream();
        StringBuffer sb = writeCSV(policies, CSVFileName, response);
        in = new ByteArrayInputStream(sb.toString().getBytes());
        byte[] outputByte = new byte[sb.length()];
        while (in.read(outputByte, 0, sb.length()) != -1) {
            out.write(outputByte, 0, sb.length());
        }
    } catch (Exception e) {
        LOG.error("Error while generating report file " + CSVFileName, e);
        e.printStackTrace();

    } finally {
        try {
            if (in != null) {
                in.close();
                in = null;
            }
        } catch (Exception ex) {
        }
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (Exception ex) {
        }
    }
}

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();// www. j  a va2 s .c o m
    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:org.etudes.jforum.view.admin.ImportExportAction.java

/**
 * writes the zip file to browser//from ww w .j  a  va2 s .c  o  m
 * 
 * @param file
 *            - zip file to download
 * @throws Exception
 */
private void download(File file) throws Exception {
    FileInputStream fis = null;
    ServletOutputStream out = null;
    try {
        String disposition = "attachment; filename=\"" + file.getName() + "\"";
        fis = new FileInputStream(file);

        response.setContentType("application/zip"); // application/zip
        response.addHeader("Content-Disposition", disposition);

        out = response.getOutputStream();

        int len;
        byte buf[] = new byte[102400];
        while ((len = fis.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        out.flush();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e1) {
        }

        try {
            if (fis != null)
                fis.close();
        } catch (IOException e2) {
        }
    }
}

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 .j  a  va 2 s  .  c om*/

    @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:org.joget.apps.app.controller.ConsoleWebController.java

@RequestMapping("/console/monitor/log/(*:fileName)")
public void consoleMonitorLogs(HttpServletResponse response, @RequestParam("fileName") String fileName)
        throws IOException {
    if (HostManager.isVirtualHostEnabled()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*from   ww  w.  j  av a  2 s.co m*/
    }

    ServletOutputStream stream = response.getOutputStream();

    String decodedFileName = fileName;
    try {
        decodedFileName = URLDecoder.decode(fileName, "UTF8");
    } catch (UnsupportedEncodingException e) {
        // ignore
    }

    File file = LogUtil.getTomcatLogFile(decodedFileName);
    if (file == null || file.isDirectory() || !file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    DataInputStream in = new DataInputStream(new FileInputStream(file));
    byte[] bbuf = new byte[65536];

    try {
        // set attachment filename
        response.setHeader("Content-Disposition",
                "attachment; filename*=UTF-8''" + URLEncoder.encode(decodedFileName, "UTF8"));

        // send output
        int length = 0;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            stream.write(bbuf, 0, length);
        }
    } finally {
        in.close();
        stream.flush();
        stream.close();
    }
}

From source file:org.openmrs.module.tracpatienttransfer.util.FileExporter.java

/**
 * Auto generated method comment/* ww w.j ava 2 s .c om*/
 * 
 * @param request
 * @param response
 * @param res
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToCSVFile(HttpServletRequest request, HttpServletResponse response, List<Integer> res,
        String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;

    try {
        SimpleDateFormat sdf = Context.getDateFormat();
        outputStream = response.getOutputStream();
        ObsService os = Context.getObsService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

        // header
        outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report", null) + ", : " + title);
        outputStream.println();
        if (request.getParameter("reason") != null
                && request.getParameter("reason").trim().compareTo("") != 0) {
            Integer conceptId = Integer.parseInt(request.getParameter("reason"));
            outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report.reasonofexit", null)
                    + ", : " + TransferOutInPatientTag.getConceptNameById("" + conceptId));
            // outputStream.println();
        }

        if (request.getParameter("location") != null
                && request.getParameter("location").trim().compareTo("") != 0) {
            Integer locationId = Integer.parseInt(request.getParameter("location"));
            outputStream.println(MohTracUtil.getMessage("tracpatienttransfer.report.location", null) + ", : "
                    + Context.getLocationService().getLocation(locationId).getName());
            outputStream.println();
        }
        outputStream.println("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdon", null)
                + ", : " + sdf.format(new Date()));// Report date
        outputStream.println("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdby", null)
                + ", : " + Context.getAuthenticatedUser().getPersonName());// Report

        outputStream.println(
                MohTracUtil.getMessage("tracpatienttransfer.report.numberofpatient", null) + ", " + res.size());
        outputStream.println();

        boolean hasRoleToViewPatientsNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

        // column header
        outputStream
                .println(MohTracUtil.getMessage("tracpatienttransfer.general.number", null) + ", "
                        + TransferOutInPatientTag
                                .getIdentifierTypeNameById(
                                        "" + TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
                        + ", "
                        + TransferOutInPatientTag.getIdentifierTypeNameById(""
                                + TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                        + ", "
                        + ((hasRoleToViewPatientsNames)
                                ? MohTracUtil.getMessage("tracpatienttransfer.general.names", null) + ", "
                                : "")
                        + MohTracUtil.getMessage("tracpatienttransfer.general.reasonofexit", null) + ", "
                        + MohTracUtil.getMessage("tracpatienttransfer.general.exitwhen", null)
                        + " ?(dd/MM/yyyy), "
                        // + MohTracUtil.getMessage("Encounter.provider", null)
                        // + ", "
                        + MohTracUtil.getMessage("Encounter.location", null) + "");
        outputStream.println();

        int ids = 0;

        log.info(">>>>>>>>>>>>>> Trying to create a CSV file...");

        for (Integer obsId : res) {
            // log.info(">>>>>>>>>>>>>> Trying to load obs#" + obsId);
            Obs obs = os.getObs(obsId);
            // log.info("----------------------------> It's ok for getObs");
            Integer patientId = obs.getPersonId();
            // log.info("----------------------------> It's ok for patientId");
            ids += 1;

            outputStream.println(ids + ","
                    + TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                            TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
                    + ","
                    + TransferOutInPatientTag
                            .personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                                    TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                    + ","
                    + ((hasRoleToViewPatientsNames) ? TransferOutInPatientTag
                            .getPersonNames(patientId) + "," : "")
                    + TransferOutInPatientTag.conceptValueByObs(obs) + ""
                    + ((obs.getValueCoded().getConceptId()
                            .intValue() == TransferOutInPatientConstant.PATIENT_TRANSFERED_OUT)
                                    ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                            TransferOutInPatientConstant.TRANSFER_OUT_TO_A_LOCATION) + ")"
                                    : (obs.getValueCoded().getConceptId()
                                            .intValue() == TransferOutInPatientConstant.PATIENT_DEAD) ? " ("
                                                    + TransferOutInPatientTag.getObservationValueFromEncounter(
                                                            obs, TransferOutInPatientConstant.CAUSE_OF_DEATH)
                                                    + ")" : "")
                    + "," + new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(obs.getObsDatetime()) // + "," +
                    // TransferOutInPatientTag.getProviderByObs(obs)
                    + "," + obs.getLocation().getName() // + ","
            // + TransferOutInPatientTag.obsVoidedReason(obs)
            );
            log.info("----------------------------> It's ok for outputstream");
        }

        outputStream.flush();
        log.info(">>>>>>>>>>>>>> A CSV file was created successfully.");
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

From source file:ro.cs.ts.web.servlet.ReportServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("doPost START");
    ServletOutputStream sos = response.getOutputStream();
    try {//retrieve the params from the context
        //         ***********************************************************************
        //Servlet's OutputStream
        //get the report type
        String reportType = request.getParameter(IConstant.REPORT_TYPE);
        logger.debug("Report type: " + reportType);

        String uid = (String) request.getParameter(IConstant.REPORT_UID);
        logger.debug("Retrieved UID in  report servlet: " + uid);
        Map<String, ReportParams> reportParamsMap = (Map<String, ReportParams>) TSContext
                .getFromContext(IConstant.REPORT_PARAM_MAP);
        ReportParams reportParams = reportParamsMap.get(uid);

        String format = (String) reportParams.getProperties()
                .get(IConstant.TS_PROJECT_REPORT_SEARCH_CRITERIA_FORMAT);
        // we set the is embeddable attribute
        if (format.toLowerCase().equals("html")
                && ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) == null) {
            logger.debug("The report is HTML embeddable");
            reportParams.setProperty(IConstant.TS_PROJECT_REPORT_IS_EMBEDDABLE, true);
        } else {//from  w w w.ja  va  2 s.  c  o  m
            reportParams.setProperty(IConstant.TS_PROJECT_REPORT_IS_EMBEDDABLE, false);
        }

        logger.debug(ReportsMessageTools.viewReportParams(reportParams));

        DataHandler reportFileReceived = null;
        String reportTitle = null;
        if (reportType.equals(IConstant.REPORT_TYPE_PROJECT)) {
            logger.debug("Retrieving project report:  ");
            reportFileReceived = ReportsWebServiceClient.getInstance().getProjectReport(reportParams);
            reportTitle = (String) reportParams.getProperties()
                    .get(IConstant.TS_PROJECT_REPORT_REPORT_TITLE_PARAM);
        } else if (reportType.equals(IConstant.REPORT_TYPE_TIME_SHEET)) {
            logger.debug("Retrieving time sheet report:  ");
            reportFileReceived = ReportsWebServiceClient.getInstance().getTimeSheetReport(reportParams);
            reportTitle = (String) reportParams.getProperties()
                    .get(IConstant.TS_TIME_SHEET_REPORT_REPORT_TITLE_PARAM);
        } else {
            logger.error("We do not have a report type on the request!!!!");
            throw new BusinessException(ICodeException.REPORT_CREATE, null);
        }

        //set the response content type
        if (format.toLowerCase().equals("html")) {
            response.setContentType("text/html");
            if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"".concat(reportTitle).concat(".html\""));
            } else {
                response.setHeader("Content-Disposition",
                        "inline; filename=\"".concat(reportTitle).concat(".html\""));
            }
        } else if (format.toLowerCase().equals("pdf")) {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition",
                    "inline; filename=\"".concat(reportTitle).concat(".pdf\""));
        } else if (format.toLowerCase().equals("doc")) {
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"".concat(reportTitle).concat(".doc\""));
        } else if (format.toLowerCase().equals("xls")) {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"".concat(reportTitle).concat(".xls\""));
        }

        //write the received report bytes stream to response output stream
        byte buffer[] = new byte[4096];
        BufferedInputStream bis = new BufferedInputStream(reportFileReceived.getInputStream());

        int size = 0;
        int i;
        while ((i = bis.read(buffer, 0, 4096)) != -1) {
            sos.write(buffer, 0, i);
            size += i;
        }

        if (size == 0) {
            response.setContentType("text/plain");
            sos.write("No content !".getBytes());
        }

        bis.close();
        response.setContentLength(size);

        logger.debug("**** report transfer completed !");
    } catch (Exception ex) {
        logger.error("", ex);
        response.setContentType("text/html");
        String exceptionCode = ICodeException.REPORT_CREATE;

        sos.write(("<html xmlns=\"http://www.w3.org/1999/xhtml\">"
                + "<head>   <script type=\"text/javascript\" src=\"js/cs/cs_common.js\"></script>"
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/style.css\"/> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/fonts-min.css\" /> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/container.css\" /> </head> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/button.css\" />"
                + "<body> <div id=\"errorsContainer\" class=\"errorMessagesDiv\"> "
                + "<table class=\"errorMessagesTable\">" + "<tr>" + "<td>" + "</td>" + "<td>"
                + "<div class=\"hd\">" + "<div id=\"closeErrors\" class=\"messagesCloseButon\"></div>"
                + "</div>" + "</td>" + "</tr>" + "<tr>" + "<td>" + "<div class=\"bd\">"
                + "<div style=\"width:470px\"> "
                + messageSource.getMessage(CREATE_ERROR,
                        new Object[] { exceptionCode, ControllerUtils.getInstance().getFormattedCurrentTime() },
                        (Locale) request.getSession()
                                .getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME))
                + "<br/> " + "</div>" + "</div>" + "</td>" + "<td>" + "</td>" + "</tr>" + "</table>"
                + "<div class=\"ft\">&nbsp;</div>" + "</div>" + "<script> "
                + "if(typeof(YAHOO.widget.Module) != \"undefined\") { "
                + "YAHOO.ts.errorsContainer = new YAHOO.widget.Module(\"errorsContainer\", {visible:true} ); "
                + "YAHOO.ts.errorsContainer.render() ;" + "YAHOO.ts.errorsContainer.show();"
                + "YAHOO.util.Event.addListener(\"closeErrors\", \"click\", function () {   "
                + "YAHOO.ts.errorsContainer.hide();" + "YAHOO.ts.errorsContainer.destroy(); "
                + "}, YAHOO.ts.errorsContainer, true);" + "}" + "</script> </body></html>").getBytes());
    } finally {
        if (sos != null) {
            //Flushing and Closing OutputStream
            sos.flush();
            sos.close();
            logger.debug("**** servlet output stream closed.");
        }
    }
    logger.debug("doPost END");
}

From source file:nu.nethome.home.items.web.GraphServlet.java

/**
* This is the main enterence point of the class. This is called when a http request is
* routed to this servlet./*from ww w. j  a va 2s  .c  o m*/
*/
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ServletOutputStream p = res.getOutputStream();
    Date startTime = null;
    Date stopTime = null;

    // Analyse arguments
    String fileName = req.getParameter("file");
    if (fileName != null)
        fileName = getFullFileName(fromURL(fileName));
    String startTimeString = req.getParameter("start");
    String stopTimeString = req.getParameter("stop");
    try {
        if (startTimeString != null) {
            startTime = m_Format.parse(startTimeString);
        }
        if (stopTimeString != null) {
            stopTime = m_Format.parse(stopTimeString);
        }
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    String look = req.getParameter("look");
    if (look == null)
        look = "";

    TimeSeries timeSeries = new TimeSeries("Data", Minute.class);

    // Calculate time window
    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date startOfDay = cal.getTime();
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    Date startOfWeek = cal.getTime();
    cal.set(Calendar.DAY_OF_MONTH, 1);
    Date startOfMonth = cal.getTime();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    Date startOfYear = cal.getTime();

    // if (startTime == null) startTime = startOfWeek;
    if (stopTime == null)
        stopTime = currentTime;
    if (startTime == null)
        startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L);

    try {
        // Open the data file
        File logFile = new File(fileName);
        Scanner fileScanner = new Scanner(logFile);
        Long startTimeMs = startTime.getTime();
        Long month = 1000L * 60L * 60L * 24L * 30L;
        boolean doOptimize = true;
        boolean justOptimized = false;
        try {
            while (fileScanner.hasNext()) {
                try {
                    // Get next log entry
                    String line = fileScanner.nextLine();
                    if (line.length() > 21) {
                        // Adapt the time format
                        String minuteTime = line.substring(0, 16).replace('.', '-');
                        // Parse the time stamp
                        Minute min = Minute.parseMinute(minuteTime);

                        // Ok, this is an ugly optimization. If the current time position in the file
                        // is more than a month (30 days) ahead of the start of the time window, we
                        // quick read two weeks worth of data, assuming that there is 4 samples per hour.
                        // This may lead to scanning past start of window if there are holes in the data
                        // series.
                        if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) {
                            for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) {
                                fileScanner.nextLine();
                            }
                            justOptimized = true;
                            continue;
                        }
                        // Detect if we have scanned past the window start position just after an optimization scan.
                        // If this is the case it may be because of the optimization. In that case we have to switch 
                        // optimization off and start over.
                        if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) {
                            logFile = new File(fileName);
                            fileScanner = new Scanner(logFile);
                            doOptimize = false;
                            continue;
                        }
                        justOptimized = false;
                        // Check if value is within time window
                        if ((min.getFirstMillisecond() > startTimeMs)
                                && (min.getFirstMillisecond() < stopTime.getTime())) {
                            // Parse the value
                            double value = Double.parseDouble((line.substring(20)).replace(',', '.'));
                            // Add the entry
                            timeSeries.add(min, value);
                            doOptimize = false;
                        }
                    }
                } catch (SeriesException se) {
                    // Bad entry, for example due to duplicates at daylight saving time switch
                } catch (NumberFormatException nfe) {
                    // Bad number format in a line, try to continue
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            fileScanner.close();
        }
    } catch (FileNotFoundException f) {
        System.out.println(f.toString());
    }

    // Create a collection for plotting
    TimeSeriesCollection data = new TimeSeriesCollection();
    data.addSeries(timeSeries);

    JFreeChart chart;

    int xSize = 750;
    int ySize = 450;
    // Customize colors and look of the Graph.
    if (look.equals("mobtemp")) {
        // Look for the mobile GUI
        chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false);
        XYPlot plot = chart.getXYPlot();
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        xSize = 175;
        ySize = 180;
    } else {
        // Create a Chart with time range as heading
        SimpleDateFormat localFormat = new SimpleDateFormat();
        String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime);
        chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false);

        Paint background = new Color(0x9D8140);
        chart.setBackgroundPaint(background);
        TextTitle title = chart.getTitle(); // fix title
        Font titleFont = title.getFont();
        titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0);
        title.setFont(titleFont);
        title.setPaint(Color.darkGray);
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(background);
        plot.setDomainGridlinePaint(Color.darkGray);
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        plot.setRangeGridlinePaint(Color.darkGray);
        XYItemRenderer renderer = plot.getRenderer(0);
        renderer.setSeriesPaint(0, Color.darkGray);
        xSize = 750;
        ySize = 450;
    }

    try {
        res.setContentType("image/png");
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "no-cache");
        res.setStatus(HttpServletResponse.SC_OK);
        ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

    p.flush();
    p.close();
    return;
}

From source file:sos.settings.SOSSettingsDialog.java

/**
* Sourcecode bei binren Dokumenten/*from w w w.j a  v a  2s  .  co  m*/
* 
* @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);
    }
}

From source file:com.founder.fix.fixflow.FlowCenter.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from   ww  w. j a  v a 2s.  co  m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID));

    if (StringUtil.isEmpty(userId)) {
        String context = request.getContextPath();
        response.sendRedirect(context + "/");
        return;
    }
    CurrentThread.init();
    ServletOutputStream out = null;
    String action = StringUtil.getString(request.getParameter("action"));
    if (StringUtil.isEmpty(action)) {
        action = StringUtil.getString(request.getAttribute("action"));
    }
    if (StringUtil.isEmpty(action)) {
        action = "getMyTask";
    }
    RequestDispatcher rd = null;
    try {
        Map<String, Object> filter = new HashMap<String, Object>();

        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload Uploader = new ServletFileUpload(new DiskFileItemFactory());
            // Uploader.setSizeMax("); // 
            Uploader.setHeaderEncoding("utf-8");
            List<FileItem> fileItems = Uploader.parseRequest(request);
            for (FileItem item : fileItems) {
                filter.put(item.getFieldName(), item);
                if (item.getFieldName().equals("action"))
                    action = item.getString();
            }
        } else {
            Enumeration enu = request.getParameterNames();
            while (enu.hasMoreElements()) {
                Object tmp = enu.nextElement();
                Object obj = request.getParameter(StringUtil.getString(tmp));

                // if (request.getAttribute("ISGET") != null)
                obj = new String(obj.toString().getBytes("ISO8859-1"), "utf-8");

                filter.put(StringUtil.getString(tmp), obj);
            }
        }

        Enumeration attenums = request.getAttributeNames();
        while (attenums.hasMoreElements()) {
            String paramName = (String) attenums.nextElement();

            Object paramValue = request.getAttribute(paramName);

            // ?map
            filter.put(paramName, paramValue);

        }

        filter.put("userId", userId);
        request.setAttribute("nowAction", action);
        if (action.equals("getMyProcess")) {
            rd = request.getRequestDispatcher("/fixflow/center/startTask.jsp");
            List<Map<String, String>> result = getFlowCenter().queryStartProcess(userId);

            Map<String, List<Map<String, String>>> newResult = new HashMap<String, List<Map<String, String>>>();
            for (Map<String, String> tmp : result) {
                String category = tmp.get("category");
                if (StringUtil.isEmpty(category))
                    category = "";

                List<Map<String, String>> tlist = newResult.get(category);
                if (tlist == null) {
                    tlist = new ArrayList<Map<String, String>>();
                }
                tlist.add(tmp);
                newResult.put(category, tlist);
            }
            request.setAttribute("result", newResult);
            //??sqlserverbug????
            request.setAttribute("userId", userId); // userId add Rex
            try {
                List<Map<String, String>> lastestProcess = getFlowCenter().queryLastestProcess(userId);
                request.setAttribute("lastest", lastestProcess);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (action.equals("getMyTask")) {
            rd = request.getRequestDispatcher("/fixflow/center/todoTask.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().queryMyTaskNotEnd(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getProcessImage")) {
            response.getOutputStream();
        } else if (action.equals("getAllProcess")) {
            rd = request.getRequestDispatcher("/fixflow/center/queryprocess.jsp");
            Map<String, Object> pageResult = getFlowCenter().queryTaskInitiator(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getPlaceOnFile")) {
            rd = request.getRequestDispatcher("/fixflow/center/placeOnFile.jsp");
            Map<String, Object> pageResult = getFlowCenter().queryPlaceOnFile(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getTaskDetailInfo")) {
            rd = request.getRequestDispatcher("/fixflow/center/flowGraphic.jsp");
            Map<String, Object> pageResult = getFlowCenter().getTaskDetailInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getTaskDetailInfoSVG")) {
            rd = request.getRequestDispatcher("/fixflow/center/flowGraphic.jsp");
            Map<String, Object> pageResult = getFlowCenter().getTaskDetailInfoSVG(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getFlowGraph")) {
            InputStream is = getFlowCenter().getFlowGraph(filter);
            out = response.getOutputStream();
            response.setContentType("application/octet-stream;charset=UTF-8");
            byte[] buff = new byte[2048];
            int size = 0;
            while (is != null && (size = is.read(buff)) != -1) {
                out.write(buff, 0, size);
            }
        } else if (action.equals("getUserInfo")) {
            rd = request.getRequestDispatcher("/fixflow/common/userInfo.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().getUserInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getUserIcon")) {
            rd = request.getRequestDispatcher("/fixflow/common/userOperation.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().getUserInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("updateUserIcon")) {
            rd = request.getRequestDispatcher("/FlowCenter?action=getUserInfo");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            getFlowCenter().saveUserIcon(filter);

        } else if (action.equals("selectUserList")) { //
            String isMulti = request.getParameter("isMulti");
            rd = request.getRequestDispatcher("/fixflow/common/selectUserList.jsp?isMulti=" + isMulti);
            Map<String, Object> pageResult = getFlowCenter().getAllUsers(filter);
            filter.putAll(pageResult);

            request.setAttribute("result", filter);
            request.setAttribute("isMulti", isMulti);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("selectNodeList")) { //
            rd = request.getRequestDispatcher("/fixflow/common/selectNodeList.jsp");
            Map<String, Object> pageResult = getFlowCenter().getRollbackNode(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("selectStepList")) { //
            rd = request.getRequestDispatcher("/fixflow/common/selectStepList.jsp");
            Map<String, Object> pageResult = getFlowCenter().getRollbackTask(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("viewDelegation")) { //
            rd = request.getRequestDispatcher("/fixflow/common/setDelegation.jsp");
            Map<String, Object> pageResult = new HashMap<String, Object>();
            pageResult = this.getFlowIdentityService().getUserDelegationInfo(userId);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("saveDelegation")) { //

            String agentInfoJson = StringUtil.getString(request.getParameter("insertAndUpdate"));
            if (StringUtil.isNotEmpty(agentInfoJson)) {
                Map<String, Object> delegationInfo = JSONUtil.parseJSON2Map(agentInfoJson);
                this.getFlowIdentityService().saveUserDelegationInfo(delegationInfo);
            }
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<script>alert('??');window.close();</script>");
        }
    } catch (Exception e) {
        e.printStackTrace();
        request.setAttribute("errorMsg", e.getMessage());
        try {
            CurrentThread.rollBack();
        } catch (SQLException e1) {
            e1.printStackTrace();
            request.setAttribute("errorMsg", e.getMessage());
        }
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        try {
            CurrentThread.clear();
        } catch (SQLException e) {
            request.setAttribute("errorMsg", e.getMessage());
            e.printStackTrace();
        }
    }
    if (rd != null) {
        rd.forward(request, response);
    }
}