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:mx.com.quadrum.contratos.controller.busquedas.MuestraPdf.java

@RequestMapping(value = "muestraPdf/{idContrato}/{idEmpleado}", method = RequestMethod.GET)
public void muestraPdf(@PathVariable("idContrato") Integer idContrato,
        @PathVariable("idEmpleado") Integer idEmpleado, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {//from   www  .j a  v a  2 s . c  o  m

    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;
    }
    Contrato contrato = contratoService.buscarPorId(idContrato);
    response.setContentType("application/pdf");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    Usuario usuario = usuarioService.buscarPorId(idEmpleado);
    File pdf = new File(
            USUARIOS + usuario.getMail() + "\\" + contrato.getNombre() + "\\" + contrato.getNombre() + ".pdf");
    try {
        InputStream in = new FileInputStream(pdf);
        byte[] data = new byte[in.available()];
        in.read(data);
        javax.servlet.ServletOutputStream servletoutputstream = response.getOutputStream();

        servletoutputstream.write(data);
        servletoutputstream.flush();
        servletoutputstream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:be.fedict.eid.pkira.blm.model.reporting.ReportConfigurationHandler.java

public void generateReport() {
    if (StringUtils.isBlank(startMonth) || StringUtils.isBlank(endMonth)) {
        return;/*from w w w.j a va2s. c o  m*/
    }

    if (startMonth.compareTo(endMonth) > 0) {
        facesMessages.addFromResourceBundle(Severity.ERROR, "reports.startAfterEnd");
        return;
    }

    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    response.setContentType("test/xml");
    String fileName = (StringUtils.equals(startMonth, endMonth) ? startMonth : startMonth + " - " + endMonth)
            + ".xml\"";
    response.addHeader("Content-disposition", "attachment; filename=\"" + fileName);

    String report = reportManager.generateReport(startMonth, endMonth, includeCertificateAuthorityReport,
            includeCertificateDomainReport);

    try {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(report.getBytes());
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    facesContext.responseComplete();
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {//w ww .ja  v  a 2 s . c  o m
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:de.berlios.jedi.presentation.admin.GetJispObjectAction.java

/**
 * Handle server requests./*  ww w  . j  a  v a  2 s .c o  m*/
 * 
 * @param mapping
 *            The ActionMapping used to select this instance.
 * @param form
 *            The optional ActionForm bean for this request (if any).
 * @param request
 *            The HTTP request we are processing.
 * @param response
 *            The HTTP response we are creating.
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    JispIdManager jispIdManager = (JispIdManager) request.getSession()
            .getAttribute(AdminKeys.JISP_ID_MANAGER_KEY);

    String jispObjectId = request.getParameter("jispObjectId");

    if (jispObjectId == null) {
        return errorForward(mapping, request, new ActionMessage("missedId", "jispObjectId"), "adminMissedId");
    }

    JispObject jispObject = jispIdManager.getJispObject(jispObjectId);

    if (jispObject == null) {
        return errorForward(mapping, request, new ActionMessage("invalidId", "jispObjectId"), "adminInvalidId");
    }

    response.setContentType(jispObject.getMimeType());

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        out.write(jispObject.getData());
    } catch (IOException e) {
        LogFactory.getLog(GetJispObjectAction.class)
                .error("IOException when writing the JispObject to the" + " ServlerOutputStream", e);

        return errorForward(mapping, request, new ActionMessage("failedJispObjectWriteToOutputStream"),
                "adminFailedJispObjectWriteToOutputStream");
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}

From source file:com.seer.datacruncher.spring.SchemasUpdateController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String json = request.getReader().readLine();
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    SchemaEntity schemaEntity = mapper.readValue(json, SchemaEntity.class);

    if (schemaEntity.getIdDatabase() > 0) {
        schemaEntity.setPublishToDb(true);
    }/*  ww w.  j  a  va  2  s .  c o m*/
    if (schemaEntity.getIdValidationDatabase() > 0) {
        schemaEntity.setInputToDb(true);
    }

    SchemaTriggerStatusEntity newSchemaTriggerStatusEntity = schemaEntity.getSchemaEvents();
    Create createTrigger = new Create();
    createTrigger.setSuccess(true);
    createTrigger.setMessage("");
    Update update;

    ReadList readTriggersList = schemaTriggerStatusDao.findByIdSchema(schemaEntity.getIdSchema());
    if (CollectionUtils.isNotEmpty(readTriggersList.getResults())) {
        if (schemaEntity.getIsEventTrigger()) {
            SchemaTriggerStatusEntity schemaTriggerStatusEntity = (SchemaTriggerStatusEntity) readTriggersList
                    .getResults().get(0);
            if (schemaTriggerStatusEntity.getIdEventTrigger() != newSchemaTriggerStatusEntity
                    .getIdEventTrigger()
                    || schemaTriggerStatusEntity.getIdStatus() != newSchemaTriggerStatusEntity.getIdStatus()) {
                schemaTriggerStatusEntity.setIdEventTrigger(newSchemaTriggerStatusEntity.getIdEventTrigger());
                schemaTriggerStatusEntity.setIdStatus(newSchemaTriggerStatusEntity.getIdStatus());
                update = schemaTriggerStatusDao.update(schemaTriggerStatusEntity);
                if (update.isSuccess()) {
                    schemaEntity.setSchemaEvents(schemaTriggerStatusEntity);
                } else {
                    createTrigger.setSuccess(false);
                    createTrigger.setMessage("Event update error:" + update.getMessage());
                }
            }

        } else {
            Destroy destroy = schemaTriggerStatusDao.destroyEventsBySchema(schemaEntity.getIdSchema());
            if (!destroy.isSuccess()) {
                createTrigger.setSuccess(false);
                createTrigger.setMessage("Event delete error:" + destroy.getMessage());
            }
        }
    } else {
        if (schemaEntity.getIsEventTrigger()) {
            newSchemaTriggerStatusEntity.setIdSchema(schemaEntity.getIdSchema());
            createTrigger = schemaTriggerStatusDao.create(newSchemaTriggerStatusEntity);
            if (createTrigger.getSuccess())
                schemaEntity.setSchemaEvents(newSchemaTriggerStatusEntity);
        }
    }

    if (createTrigger.getSuccess()) {
        update = schemasDao.update(schemaEntity);
    } else {
        update = new Update();
        update.setSuccess(createTrigger.getSuccess());
        update.setMessage("Event " + createTrigger.getMessage());
    }

    response.setContentType("application/json");
    ServletOutputStream out = response.getOutputStream();
    out.write(mapper.writeValueAsBytes(update));
    out.flush();
    out.close();
    return null;
}

From source file:de.berlios.jedi.presentation.editor.GetJispObjectAction.java

/**
 * Handle server requests./*from  w  ww .j  ava  2 s  .c om*/
 * 
 * @param mapping
 *            The ActionMapping used to select this instance.
 * @param form
 *            The optional ActionForm bean for this request (if any).
 * @param request
 *            The HTTP request we are processing.
 * @param response
 *            The HTTP response we are creating.
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    JispIdManager jispIdManager = (JispIdManager) request.getSession()
            .getAttribute(EditorKeys.JISP_ID_MANAGER_KEY);

    String jispObjectId = request.getParameter("jispObjectId");

    if (jispObjectId == null) {
        return errorForward(mapping, request, new ActionMessage("missedId", "jispObjectId"), "missedId",
                Keys.ADD_STATUS_FORWARD_NAME);
    }

    JispObject jispObject = jispIdManager.getJispObject(jispObjectId);

    if (jispObject == null) {
        return errorForward(mapping, request, new ActionMessage("invalidId", "jispObjectId"), "invalidId",
                Keys.ADD_STATUS_FORWARD_NAME);
    }

    response.setContentType(jispObject.getMimeType());

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        out.write(jispObject.getData());
    } catch (IOException e) {
        LogFactory.getLog(GetJispObjectAction.class)
                .error("IOException when writing the JispObject to the" + " ServlerOutputStream", e);

        return errorForward(mapping, request, new ActionMessage("failedJispObjectWriteToOutputStream"),
                "failedJispObjectWriteToOutputStream", Keys.ADD_STATUS_FORWARD_NAME);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}

From source file:com.baidu.stqa.signet.web.common.exception.ExceptionResolver.java

@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
    Object errors = null;/*from  w  w  w .j  a v a  2s .  c o  m*/

    if (ex instanceof MethodArgumentNotValidException) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        errors = getDecorateErrors(ex);
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        errors = ex.getMessage();
        LOGGER.error(ex);
    }

    ObjectMapper mapper = new ObjectMapper();
    String errorJson = "Error occur when covert object to json!";
    try {
        errorJson = mapper.writeValueAsString(errors);
    } catch (Exception e) {
        e.printStackTrace();
    }

    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        outputStream.write(errorJson.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:org.primeframework.mvc.action.result.JSONResult.java

public void execute(JSON json) throws IOException, ServletException {
    ActionInvocation current = actionInvocationStore.getCurrent();
    Object action = current.action;
    if (action == null) {
        throw new PrimeException(
                "There is no action class and somehow we got into the JSONResult code. Bad mojo!");
    }//from  ww w.  j av  a 2s. c  o  m

    ActionConfiguration configuration = current.configuration;
    if (configuration == null) {
        throw new PrimeException(
                "The action [" + action.getClass() + "] has no configuration. This should be impossible!");
    }

    // If there are error messages, put them in a well known container and render that instead of looking for the
    // @JSONResponse annotation
    Object jacksonObject;
    List<Message> messages = messageStore.get(MessageScope.REQUEST);
    if (messages.size() > 0) {
        jacksonObject = convertErrors(messages);
    } else {
        JacksonActionConfiguration jacksonActionConfiguration = (JacksonActionConfiguration) configuration.additionalConfiguration
                .get(JacksonActionConfiguration.class);
        if (jacksonActionConfiguration == null || jacksonActionConfiguration.responseMember == null) {
            throw new PrimeException("The action [" + action.getClass()
                    + "] is missing a field annotated with @JSONResponse. This is used to figure out what to send back in the response.");
        }

        jacksonObject = expressionEvaluator.getValue(jacksonActionConfiguration.responseMember, action);
        if (jacksonObject == null) {
            throw new PrimeException("The @JSONResponse field [" + jacksonActionConfiguration.responseMember
                    + "] in the action [" + action.getClass() + "] is null. It cannot be null!");
        }
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    objectMapper.writeValue(baos, jacksonObject);

    byte[] result = baos.toByteArray();
    response.setStatus(json.status());
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.setContentLength(result.length);

    if (!isCurrentActionHeadRequest(current)) {
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(result);
        outputStream.flush();
    }
}

From source file:com.nkapps.billing.controllers.OverpaymentController.java

@RequestMapping(value = "/return-text-file", method = RequestMethod.POST)
public void returnTextFile(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String fileName;/*from  ww  w.  jav a 2  s .c  o  m*/
    String fileContent;
    Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue();
    String issuerIp = authService.getClientIp(request);

    if ("single".equals(request.getParameter("type"))) {
        fileName = "Vozvrat - "
                + new SimpleDateFormat("dd.MM.yyyy HH-mm-ss").format(Calendar.getInstance().getTime());

        String bankStatementId = request.getParameter("bankStatementId");
        fileContent = overpaymentService.singleReturnBankStatementText(bankStatementId, issuerSerialNumber,
                issuerIp);
    } else {
        fileName = "Vozvrati_v_den - " + request.getParameter("paymentDate");

        Date paymentDate = new SimpleDateFormat("dd.MM.yyyy").parse(request.getParameter("paymentDate"));
        fileContent = overpaymentService.allReturnBankStatementText(paymentDate, issuerSerialNumber, issuerIp);
    }

    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".txt\"");
    response.addHeader("Cache-Control", "max-age=1, must-revalidate");
    response.addHeader("Pragma", "no-cache");

    ServletOutputStream stream = response.getOutputStream();
    stream.write(fileContent.getBytes());
    stream.close();
}

From source file:cn.newgxu.lab.core.config.MappingJacksonJsonpView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (request.getMethod().toUpperCase().equals("GET")) {
        if (request.getParameterMap().containsKey("callback")) {
            ServletOutputStream ostream = response.getOutputStream();
            //            try
            ostream.write(new String("try{" + request.getParameter("callback") + "(").getBytes());
            super.render(model, request, response);
            ostream.write(new String(");}catch(e){}").getBytes());
            //            ????closeflushspring?
            //            ?
            ostream.flush();//www  .j ava2 s.  c  o  m
            ostream.close();
        } else {
            super.render(model, request, response);
        }
    } else {
        super.render(model, request, response);
    }
}