Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

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

Prototype

public abstract void write(int b) throws IOException;

Source Link

Document

Writes the specified byte to this output stream.

Usage

From source file:org.apache.stratos.logging.view.ui.LogViewerClient.java

public void downloadArchivedLogFiles(String logFile, HttpServletResponse response, String domain,
        String serverKey) throws Exception {
    try {//  w w  w.j a v a  2 s  . c o  m
        logFile = logFile.replace(".gz", "");
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/txt");
        response.setHeader("Content-Disposition", "attachment;filename=" + logFile.replaceAll("\\s", "_"));
        DataHandler data = stub.downloadArchivedLogFiles(logFile, domain, serverKey);
        InputStream fileToDownload = data.getInputStream();
        int c;
        while ((c = fileToDownload.read()) != -1) {
            outputStream.write(c);
        }
        outputStream.flush();
        outputStream.flush();
    } catch (Exception e) {
        String msg = "Error occurred while getting logger data. Backend service may be unavailable";
        log.error(msg, e);
        throw e;
    }
}

From source file:com.ikon.servlet.admin.LanguageServlet.java

/**
 * Show language flag icon//from   w w  w .  ja  v a 2 s.  co  m
 */
private void flag(String userId, HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, IOException {
    log.debug("flag({}, {}, {})", new Object[] { userId, request, response });
    String lgId = WebUtils.getString(request, "lg_id");
    ServletOutputStream out = response.getOutputStream();
    Language language = LanguageDAO.findByPk(lgId);
    byte[] img = SecureStore.b64Decode(new String(language.getImageContent()));

    response.setContentType(language.getImageMime());
    response.setContentLength(img.length);
    out.write(img);
    out.flush();
    log.debug("flag: void");
}

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

/**
 * This method creates and renders a density map for a species.
 * /*  w  ww  .j  ava2  s  .c o m*/
 * @throws Exception
 */
@RequestMapping(value = { "/density/map", "/occurrences/static" }, method = RequestMethod.GET)
public @ResponseBody void speciesDensityMap(SpatialSearchRequestParams requestParams,
        @RequestParam(value = "forceRefresh", required = false, defaultValue = "false") boolean forceRefresh,
        @RequestParam(value = "forcePointsDisplay", required = false, defaultValue = "false") boolean forcePointsDisplay,
        @RequestParam(value = "pointColour", required = false, defaultValue = "0000ff") String pointColour,
        @RequestParam(value = "colourByFq", required = false, defaultValue = "") String colourByFqCSV,
        @RequestParam(value = "colours", required = false, defaultValue = "") String coloursCSV,
        @RequestParam(value = "pointHeatMapThreshold", required = false, defaultValue = "500") Integer pointHeatMapThreshold,
        @RequestParam(value = "opacity", required = false, defaultValue = "1.0") Float opacity,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    response.setContentType("image/png");
    File outputDir = new File(heatmapOutputDir);
    if (!outputDir.exists()) {
        FileUtils.forceMkdir(outputDir);
    }

    //output heatmap path
    String outputHMFile = getOutputFile(request);

    String[] facetValues = null;
    String[] facetColours = null;
    if (StringUtils.trimToNull(colourByFqCSV) != null && StringUtils.trimToNull(coloursCSV) != null) {
        facetValues = colourByFqCSV.split(",");
        facetColours = coloursCSV.split(",");
        if (facetValues.length == 0 || facetValues.length != facetColours.length) {
            throw new IllegalArgumentException(
                    String.format("Mismatch in facet values and colours. Values: %d, Colours: %d",
                            facetValues.length, facetColours.length));
        }
    }

    //Does file exist on disk?
    File f = new File(outputDir + "/" + outputHMFile);

    if (!f.isFile() || !f.exists() || forceRefresh) {
        logger.debug("Regenerating heatmap image");
        //If not, generate
        generateStaticHeatmapImages(requestParams, false, forcePointsDisplay, pointHeatMapThreshold,
                pointColour, facetValues, facetColours, opacity, request);
    } else {
        logger.debug("Heatmap file already exists on disk, sending file back to user");
    }

    try {
        //read file off disk and send back to user
        File file = new File(outputDir + "/" + outputHMFile);
        BufferedImage img = ImageIO.read(file);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(img, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image.", e);
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.projects.workflows.JobControlCompletedHandler.java

/**
 * Invokes this EntryPageHandler object//from   ww  w  .j  a  va2  s.co m
 * <p>
 * @param p_ageDescriptor the description of the page to be produced.
 * @param p_request original request sent from the browser.
 * @param p_response original response object.
 * @param p_context the Servlet context.
 */
public void myInvokePageHandler(WebPageDescriptor p_thePageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);

    if (p_request.getParameter("action") != null
            && "checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobIds = p_request.getParameter("jobIds");
        boolean checkQA = checkQAReport(sessionMgr, jobIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if (p_request.getParameter("action") != null
            && "downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    }

    boolean stateMarch = false;
    if (Job.LOCALIZED.equals((String) sessionMgr.getMyjobsAttribute("lastState")))
        stateMarch = true;
    setJobSearchFilters(sessionMgr, p_request, stateMarch);

    m_exportBean = new NavigationBean(EXPORT_BEAN, p_thePageDescriptor.getPageName());
    HashMap beanMap = invokeJobControlPage(p_thePageDescriptor, p_request, LOCALIZED_BEAN);
    p_request.setAttribute("searchType", p_request.getParameter("searchType"));
    p_request.setAttribute("action", p_request.getParameter("action"));
    performAppropriateOperation(p_request);

    sessionMgr.setMyjobsAttribute("lastState", Job.LOCALIZED);
    JobVoLocalizedSearcher searcher = new JobVoLocalizedSearcher();
    searcher.setJobVos(p_request);

    p_request.setAttribute(EXPORT_URL_PARAM, m_exportBean.getPageURL());
    p_request.setAttribute(JOB_ID, JOB_ID);
    p_request.setAttribute(JOB_LIST_START_PARAM, p_request.getParameter(JOB_LIST_START_PARAM));
    p_request.setAttribute(PAGING_SCRIPTLET,
            getPagingText(p_request, ((NavigationBean) beanMap.get(BASE_BEAN)).getPageURL(), Job.LOCALIZED));
    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);

    sessionMgr.setAttribute("destinationPage", "localized");
    //clear the session for download job from joblist page
    sessionMgr.setAttribute(DownloadFileHandler.DOWNLOAD_JOB_LOCALES, null);
    sessionMgr.setAttribute(DownloadFileHandler.DESKTOP_FOLDER, null);
    setJobProjectsLocales(sessionMgr, session);

    // turn on cache.  do both.  "pragma" for the older browsers.
    p_response.setHeader("Pragma", "yes-cache"); //HTTP 1.0
    p_response.setHeader("Cache-Control", "yes-cache"); //HTTP 1.1
    p_response.addHeader("Cache-Control", "yes-store"); // tell proxy not to cache
    try {
        Company company = ServerProxy.getJobHandler()
                .getCompanyById(CompanyWrapper.getCurrentCompanyIdAsLong());
        p_request.setAttribute("company", company);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // forward to the jsp page.
    RequestDispatcher dispatcher = p_context.getRequestDispatcher(p_thePageDescriptor.getJspURL());
    dispatcher.forward(p_request, p_response);
}

From source file:mx.com.quadrum.contratos.controller.busquedas.DescargarArchivos.java

@ResponseBody
@RequestMapping(value = "descargarArchivos/{idContrato}", method = RequestMethod.GET)
public void descargarArchivos(@PathVariable("idContrato") Integer idContrato, HttpSession session,
        HttpServletRequest request, HttpServletResponse response) {
    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;/* w  ww.ja v a2 s. c  o m*/
    }

    response.setContentType("application/zip");
    Usuario usuario = (Usuario) session.getAttribute(USUARIO);
    Contrato contrato = contratoService.buscarPorId(idContrato);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + contrato.getNombre() + ".zip\"");
    ServletOutputStream sos;
    String pathFiles = USUARIOS + usuario.getMail() + "/" + contrato.getNombre();

    try {
        ZipFile folder = new ZipFile(pathFiles + "/" + contrato.getNombre() + ".zip");

        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        folder.addFolder(pathFiles, parameters);
        sos = response.getOutputStream();
        File zipFile = new File(pathFiles + "/" + contrato.getNombre() + ".zip");
        sos.write(convierteArchivoToArregloBytes(zipFile));
        sos.flush();
        zipFile.delete();
    } catch (IOException ex) {
        Logger.getLogger(DescargarArchivos.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ZipException ex) {
        Logger.getLogger(DescargarArchivos.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:nu.mine.kino.jenkins.plugins.projectmanagement.ProjectSummaryAction.java

private void openFile(StaplerRequest req, StaplerResponse res, String filePath)
        throws FileNotFoundException, IOException {

    System.out.println(filePath);
    System.out.println(req.getContextPath());

    System.out.println(owner.getRootDir());
    File file = new File(owner.getRootDir(), filePath);
    FileInputStream in = null;// w  ww. j a  v a2  s.c  om
    ServletOutputStream out = res.getOutputStream();
    try {
        in = new FileInputStream(file);
        int i;
        while ((i = in.read()) != -1) {
            out.write(i);
        }
    } finally {
        out.close();
        in.close();
    }
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelBean() throws Exception {

    // Setup/*from w w w  .  j a  v a 2s .c o  m*/
    String encoding = "ISO-8859-1"; // Default encoding
    JSOG expected = JSOG.object("bean", JSOG.object().put("foo", "foovalue").put("bar", "barvalue"));
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("bean", new TestBean());

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);

    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelCustomContentType() throws Exception {

    // Setup/*from   w  w  w  .j  a va  2  s  .  c  om*/
    String encoding = "ISO-8859-1"; // Default encoding
    JSOG expected = new JSOG("foobar");
    MediaType contentType = MediaType.TEXT_PLAIN;
    instance.setOutputContentType(contentType);

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expected);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);

    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModel() throws Exception {

    // TODO: Make this test more robust

    // Setup//from   w w  w . ja v  a2s .  c om
    String encoding = "ISO-8859-1"; // Default encoding
    JSOG expected = new JSOG("foobar");
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expected);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);

    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelCustomEncodingString() throws Exception {

    // TODO: Make this test more robust

    // Setup/*from  ww  w.  j a  va  2s  .  c o  m*/
    String encoding = "UTF-8";
    JSOG expected = new JSOG("foobar");
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expected);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);
    instance.setEncoding(encoding);
    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}