Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:au.org.ala.biocache.web.WMSController.java

private void writeBytes(HttpServletResponse response, byte[] bytes) throws IOException {
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    ServletOutputStream outStream = response.getOutputStream();
    outStream.write(bytes);//w  w w  . j  a v  a 2 s.  c  o  m
    outStream.flush();
    outStream.close();
}

From source file:au.org.ala.biocache.web.WMSController.java

void displayBlankImage(HttpServletResponse response) {
    try {//  w ww.  j  a v  a 2  s .co  m
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(blankImageBytes);
        outStream.flush();
        outStream.close();
    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:ec.gob.ceaaces.controller.MallasController.java

public void presentarReporteXls() {
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();//from   w  ww .  j  a v  a  2  s . c  o m
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition",
                "attachment; filename=mallas_" + simpleDateFormat.format(new Date()) + ".xls");
        response.setContentLength(reporteBytes.length);
        ServletOutputStream out = response.getOutputStream();
        out.write(reporteBytes, 0, reporteBytes.length);
        out.flush();
        FacesContext.getCurrentInstance().responseComplete();
    } catch (Exception e) {
        e.printStackTrace();
        JsfUtil.msgError("Error al generar el reporte, comunquese con el administrador del sistema");
    }
}

From source file:de.sub.goobi.forms.ProzessverwaltungForm.java

/**
 * Create excel.//w w w. j  a v  a 2s.c  om
 */
public void CreateExcel() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {

        /*
         * Vorbereiten der Header-Informationen
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        try {
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType("export.xls");
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"export.xls\"");
            ServletOutputStream out = response.getOutputStream();
            HSSFWorkbook wb = (HSSFWorkbook) this.myCurrentTable.getExcelRenderer().getRendering();
            wb.write(out);
            out.flush();
            facesContext.responseComplete();

        } catch (IOException e) {

        }
    }
}

From source file:de.sub.goobi.forms.ProzessverwaltungForm.java

/**
 * transforms xml logfile with given xslt and provides download.
 *///w  w w .  java2  s  .  c om
public void TransformXml() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {
        String OutputFileName = "export.xml";
        /*
         * Vorbereiten der Header-Informationen
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String contentType = servletContext.getMimeType(OutputFileName);
        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "attachment;filename=\"" + OutputFileName + "\"");

        response.setContentType("text/xml");

        try {
            ServletOutputStream out = response.getOutputStream();
            ExportXmlLog export = new ExportXmlLog();
            export.startTransformation(out, this.myProzess, this.selectedXslt);
            out.flush();
        } catch (ConfigurationException e) {
            Helper.setFehlerMeldung("could not create logfile: ", e);
        } catch (XSLTransformException e) {
            Helper.setFehlerMeldung("could not create transformation: ", e);
        } catch (IOException e) {
            Helper.setFehlerMeldung("could not create transformation: ", e);
        }
        facesContext.responseComplete();
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.BolonhaManager.ManageCompetenceCourseInformationVersions.java

public ActionForward exportCompetenceCourseExecutionToExcel(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws FenixServiceException {
    final List<CompetenceCourse> competenceCourses = getDepartmentCompetenceCourses();

    try {//from  www.j  av a2 s. c  om
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=list.xls");

        final ServletOutputStream outputStream = response.getOutputStream();

        final Spreadsheet spreadsheet = new Spreadsheet("list");
        spreadsheet.setHeader(BundleUtil.getString(Bundle.BOLONHA, "competenceCourse"));
        spreadsheet.setHeader(BundleUtil.getString(Bundle.BOLONHA, "curricularPlan"));
        spreadsheet.setHeader(BundleUtil.getString(Bundle.BOLONHA, "curricularYear"));
        spreadsheet.setHeader(BundleUtil.getString(Bundle.BOLONHA, "label.semester"));

        for (final CompetenceCourse competenceCourse : competenceCourses) {
            if (competenceCourse.getCurricularStage() == CurricularStage.APPROVED) {
                for (final CurricularCourse curricularCourse : competenceCourse
                        .getAssociatedCurricularCoursesSet()) {
                    for (final ExecutionCourse executionCourse : curricularCourse
                            .getAssociatedExecutionCoursesSet()) {
                        final ExecutionSemester executionSemester = executionCourse.getExecutionPeriod();
                        for (final DegreeModuleScope degreeModuleScope : curricularCourse
                                .getDegreeModuleScopes()) {
                            if (degreeModuleScope.isActiveForExecutionPeriod(executionSemester)) {
                                final DegreeCurricularPlan degreeCurricularPlan = curricularCourse
                                        .getDegreeCurricularPlan();
                                final Row row = spreadsheet.addRow();

                                row.setCell(competenceCourse.getName(executionSemester));
                                row.setCell(degreeCurricularPlan.getName());
                                row.setCell(degreeModuleScope.getCurricularYear());
                                row.setCell(degreeModuleScope.getCurricularSemester());
                            }
                        }
                    }
                }
            }
        }

        spreadsheet.exportToXLSSheet(outputStream);
        outputStream.flush();
        response.flushBuffer();
    } catch (final IOException e) {
        throw new FenixServiceException(e);
    }
    return null;
}

From source file:au.org.ala.biocache.web.WMSController.java

/**
 * WMS service for webportal.//from w  w w .j  a v a 2  s . c  o m
 *
 * @param cql_filter q value.
 * @param env        ';' delimited field:value pairs.  See Env
 * @param bboxString
 * @param width
 * @param height
 * @param cache      'on' = use cache, 'off' = do not use cache this
 *                   also removes any related cache data.
 * @param response
 * @throws Exception
 */
@RequestMapping(value = { "/webportal/wms/reflect", "/ogc/wms/reflect",
        "/mapping/wms/reflect" }, method = RequestMethod.GET)
public void generateWmsTile(SpatialSearchRequestParams requestParams,
        @RequestParam(value = "CQL_FILTER", required = false, defaultValue = "") String cql_filter,
        @RequestParam(value = "ENV", required = false, defaultValue = "") String env,
        @RequestParam(value = "SRS", required = false, defaultValue = "EPSG:900913") String srs, //default to google mercator
        @RequestParam(value = "STYLES", required = false, defaultValue = "") String styles,
        @RequestParam(value = "BBOX", required = true, defaultValue = "") String bboxString,
        @RequestParam(value = "WIDTH", required = true, defaultValue = "256") Integer width,
        @RequestParam(value = "HEIGHT", required = true, defaultValue = "256") Integer height,
        @RequestParam(value = "CACHE", required = true, defaultValue = "off") String cache,
        @RequestParam(value = "REQUEST", required = true, defaultValue = "") String requestString,
        @RequestParam(value = "OUTLINE", required = true, defaultValue = "false") boolean outlinePoints,
        @RequestParam(value = "OUTLINECOLOUR", required = true, defaultValue = "0x000000") String outlineColour,
        @RequestParam(value = "LAYERS", required = false, defaultValue = "") String layers,
        @RequestParam(value = "HQ", required = false) String[] hqs, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    //Some WMS clients are ignoring sections of the GetCapabilities....
    if ("GetLegendGraphic".equalsIgnoreCase(requestString)) {
        getLegendGraphic(env, styles, 30, 20, request, response);
        return;
    }

    Set<Integer> hq = new HashSet<Integer>();
    if (hqs != null && hqs.length > 0) {
        for (String h : hqs) {
            hq.add(Integer.parseInt(h));
        }
    }

    logger.debug("WMS tile: " + request.getQueryString());

    response.setHeader("Cache-Control", "max-age=86400"); //age == 1 day
    response.setContentType("image/png"); //only png images generated

    boolean is4326 = false;
    WmsEnv vars = new WmsEnv(env, styles);
    double[] mbbox = new double[4];
    double[] bbox = new double[4];
    double[] pbbox = new double[4];
    double[] tilebbox = new double[4];
    int size = vars.size + (vars.highlight != null ? HIGHLIGHT_RADIUS * 2 + (int) (vars.size * 0.2) : 0) + 5; //bounding box buffer

    double resolution;
    if ("EPSG:4326".equals(srs)) {
        is4326 = true;
        //bboxString = convertBBox4326To900913(bboxString);    // to work around a UDIG bug

        resolution = getBBoxes4326(bboxString, width, height, size, vars.uncertainty, mbbox, bbox, pbbox,
                tilebbox);
    } else {
        resolution = getBBoxes(bboxString, width, height, size, vars.uncertainty, mbbox, bbox, pbbox, tilebbox);
    }

    PointType pointType = getPointTypeForDegreesPerPixel(resolution);
    logger.debug("Rendering: " + pointType.name());

    String q = "";

    //CQL Filter takes precedence of the layer
    if (StringUtils.trimToNull(cql_filter) != null) {
        q = getQ(cql_filter);
    } else if (StringUtils.trimToNull(layers) != null && !"ALA:Occurrences".equalsIgnoreCase(layers)) {
        q = convertLayersParamToQ(layers);
    }

    String[] boundingBoxFqs = new String[2];
    boundingBoxFqs[0] = String.format("longitude:[%f TO %f]", bbox[0], bbox[2]);
    boundingBoxFqs[1] = String.format("latitude:[%f TO %f]", bbox[1], bbox[3]);

    int pointWidth = vars.size * 2;
    double width_mult = (width / (pbbox[2] - pbbox[0]));
    double height_mult = (height / (pbbox[1] - pbbox[3]));

    //build request
    if (q.length() > 0) {
        requestParams.setQ(q);
    } else {
        q = requestParams.getQ();
    }

    //bounding box test (q must be 'qid:' + number)
    if (q.startsWith("qid:")) {
        double[] queryBBox = ParamsCache.get(Long.parseLong(q.substring(4))).getBbox();
        if (queryBBox != null && (queryBBox[0] > bbox[2] || queryBBox[2] < bbox[0] || queryBBox[1] > bbox[3]
                || queryBBox[3] < bbox[1])) {
            displayBlankImage(response);
            return;
        }
    }

    String[] originalFqs = getFq(requestParams);

    //get from cache
    WMSTile wco = null;
    if (WMSCache.isEnabled() && cache.equalsIgnoreCase("on")) {
        wco = getWMSCacheObject(vars, pointType, requestParams, bbox);
    } else if (!cache.equalsIgnoreCase("on")) {
        WMSCache.remove(requestParams.getUrlParams(), vars.colourMode, pointType);
    }

    ImgObj imgObj = null;
    if (wco == null) {
        imgObj = wmsUncached(requestParams, vars, pointType, pbbox, mbbox, width, height, width_mult,
                height_mult, pointWidth, originalFqs, hq, boundingBoxFqs, outlinePoints, outlineColour,
                response, is4326, tilebbox);
    } else {
        imgObj = wmsCached(wco, requestParams, vars, pointType, pbbox, bbox, mbbox, width, height, width_mult,
                height_mult, pointWidth, originalFqs, hq, boundingBoxFqs, outlinePoints, outlineColour,
                response, is4326, tilebbox);
    }

    if (imgObj != null && imgObj.g != null) {
        imgObj.g.dispose();
        try {
            ServletOutputStream outStream = response.getOutputStream();
            ImageIO.write(imgObj.img, "png", outStream);
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            logger.error("Unable to write image", e);
        }
    } else {
        displayBlankImage(response);
    }
}

From source file:es.juntadeandalucia.panelGestion.presentacion.controlador.impl.GeosearchController.java

/**
 * This method /*from  w  w w.  j  ava  2s .  co m*/
 * TODO
 *
 * Para realizar la configuracin se obtienen los archivos de configuracin
 * se realizan las modificaciones necesarias y se le facilita al usuario
 * dichos archivos para que finalice l el procedimiento de configuracin.
 * Las ltimas versiones de Solr admiten modificaciones del Schema a travs
 * de un API REST pero consideramos lioso realizar por un lado la configuracin
 * del schema mediante API y transparente al usuario y por otro lado darle los
 * archivos al usuario para que los sustituya en Geosearch.
 * 
 * @see https://wiki.apache.org/solr/SchemaRESTAPI
 */
public void downloadConfig() {
    String errorMessage = null;

    ServletOutputStream os = null;

    try {
        // checks
        // checks if specified a table
        if (tables.isEmpty()) {
            throw new Exception("No se ha especificado ninguna tabla");
        }
        // checks if specified a field
        boolean specifiedField = false;
        tables_loop: for (GeosearchTableVO table : tables) {
            List<GeosearchFieldVO> fields = table.getFields();
            for (GeosearchFieldVO field : fields) {
                if (field.isDefined()) {
                    specifiedField = true;
                    break tables_loop;
                }
            }
        }
        if (!specifiedField) {
            throw new Exception("No se ha configurado ningn campo de las tablas seleccionadas");
        }
        // checks duplicated fields each table
        for (GeosearchTableVO table : tables) {
            if (tableHasDuplicatedFields(table)) {
                throw new Exception("Existen campos duplicados en la tabla '".concat(table.getTable().getName())
                        .concat("'. Revise su configuracin."));
            }
        }

        // ovverides the duplicated field values
        overrideDuplicatedFields();

        checkFieldErrors();

        // gets the zip file with configuration
        byte[] configurationData = generateConfigurationZipData();

        // configures the response
        HttpServletResponse response = (HttpServletResponse) externalCtx.getResponse();
        response.setContentType(CONTENT_TYPE);
        response.addHeader("Content-disposition", "attachment; filename=\"".concat(FILE_NAME).concat("\""));

        os = response.getOutputStream();
        os.write(configurationData);
        os.flush();
        os.close();
        facesContext.responseComplete();
    } catch (GeosearchException e) {
        errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (ParserConfigurationException e) {
        errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (XPathExpressionException e) {
        errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (TransformerException e) {
        errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (IOException e) {
        errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (Exception e) {
        errorMessage = "Error en la descarga de la configuracin: " + e.getLocalizedMessage();
    } finally {
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
        }
    }

    if (errorMessage != null) {
        StatusMessages.instance().add(Severity.ERROR, errorMessage);
        log.error(errorMessage);
    } else {
        // saves the new service for each table
        try {
            ServiceType geosearchType = serviceService.getServiceType("geobusquedas");
            for (GeosearchTableVO geosearchTable : tables) {
                Table table = geosearchTable.getTable();
                Service geosearchService = new Service();
                geosearchService.setName(table.getName());
                geosearchService.setServiceUrl(PanelSettings.geosearchMaster.getUrl().concat("/").concat(core));
                geosearchService.setType(geosearchType);
                serviceService.create(geosearchService, table);
            }
        } catch (Exception e) {
            errorMessage = "";
            StatusMessages.instance().add(Severity.ERROR, errorMessage);
            log.error(errorMessage);
        }
    }
}

From source file:de.sub.goobi.forms.ProzessverwaltungForm.java

/**
 * Generate result set.//from  w w w.  j  a v a2 s  .c o  m
 */
public void generateResult() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {

        /*
         * Vorbereiten der Header-Informationen
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        try {
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType("search.xls");
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"search.xls\"");
            ServletOutputStream out = response.getOutputStream();
            SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses,
                    this.showArchivedProjects);
            HSSFWorkbook wb = sr.getResult();
            wb.write(out);
            out.flush();
            facesContext.responseComplete();

        } catch (IOException e) {

        }
    }
}

From source file:org.kitodo.services.data.ProcessService.java

private void writeToOutputStream(FacesContext facesContext, File file, String fileName) throws IOException {
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
    String contentType = servletContext.getMimeType(fileName);
    response.setContentType(contentType);
    response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

    ServletOutputStream outputStream = response.getOutputStream();
    FileInputStream fileInputStream = new FileInputStream(file);
    byte[] bytes = IOUtils.toByteArray(fileInputStream);
    fileInputStream.close();//from  ww w. ja  va  2 s.c  o m
    outputStream.write(bytes);
    outputStream.flush();
    facesContext.responseComplete();
}