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:ch.ralscha.extdirectspring.controller.RouterController.java

@SuppressWarnings("resource")
public void writeJsonResponse(HttpServletResponse response, Object responseObject, Class<?> jsonView,
        boolean streamResponse, boolean isMultipart) throws IOException {

    ObjectMapper objectMapper = this.configurationService.getJsonHandler().getMapper();

    if (isMultipart) {
        response.setContentType(RouterController.TEXT_HTML.toString());
        response.setCharacterEncoding(RouterController.TEXT_HTML.getCharset().name());

        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        bos.write("<html><body><textarea>".getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        String responseJson;//from ww w  . j av a 2 s  . c o m
        if (jsonView == null) {
            responseJson = objectMapper.writeValueAsString(responseObject);
        } else {
            responseJson = objectMapper.writerWithView(jsonView).writeValueAsString(responseObject);
        }

        responseJson = responseJson.replace("&quot;", "\\&quot;");
        bos.write(responseJson.getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        String frameDomain = this.configurationService.getConfiguration().getFrameDomain();
        String frameDomainScript = "";
        if (frameDomain != null) {
            frameDomainScript = String
                    .format(this.configurationService.getConfiguration().getFrameDomainScript(), frameDomain);
        }
        bos.write(("</textarea>" + frameDomainScript + "</body></html>")
                .getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        response.setContentLength(bos.size());
        FileCopyUtils.copy(bos.toByteArray(), response.getOutputStream());
    } else {

        response.setContentType(APPLICATION_JSON.toString());
        response.setCharacterEncoding(APPLICATION_JSON.getCharset().name());

        ServletOutputStream outputStream = response.getOutputStream();

        if (!streamResponse) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(bos, JsonEncoding.UTF8);

            if (jsonView == null) {
                objectMapper.writeValue(jsonGenerator, responseObject);
            } else {
                objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
            }

            response.setContentLength(bos.size());
            outputStream.write(bos.toByteArray());
            jsonGenerator.close();
        } else {
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(outputStream,
                    JsonEncoding.UTF8);
            if (jsonView == null) {
                objectMapper.writeValue(jsonGenerator, responseObject);
            } else {
                objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
            }
            jsonGenerator.close();
        }

        outputStream.flush();
    }
}

From source file:org.tap4j.plugin.TapResult.java

public void doDownloadAttachment(StaplerRequest request, StaplerResponse response) {
    String f = request.getParameter("f");
    String key = request.getParameter("key");
    try {// ww w  .jav  a  2 s .c  o m
        FilePath tapDir = new FilePath(new FilePath(new File(build.getRootDir(), Constants.TAP_DIR_NAME)), f);
        ServletOutputStream sos = response.getOutputStream();
        if (tapDir.exists()) {
            String tapStream = tapDir.readToString();
            TapConsumer consumer = TapConsumerFactory.makeTap13YamlConsumer();
            TestSet ts = consumer.load(tapStream);

            TapAttachment attachment = getAttachment(ts, key);
            if (attachment != null) {
                response.setContentType("application/force-download");
                //response.setContentLength((int)tapDir.length());
                response.setContentLength(attachment.getSize());
                response.setHeader("Content-Transfer-Encoding", "binary");
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + attachment.getFileName() + "\"");//fileName);

                sos.write(attachment.getContent());
                sos.print('\n');
            } else {
                sos.println("Couldn't locate attachment in YAMLish: " + f);
            }
        } else {
            sos.println("Couldn't read FilePath.");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
    }
}

From source file:com.jd.survey.web.settings.SurveyDefinitionController.java

/**
 * Exports the survey definition as a JSON file
 * @param surveyDefinitionId/*from w  w  w . ja va 2s.  com*/
 * @param response
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "export", produces = "text/html")
public void exportToJson(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../../accessDenied");

        }

        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        //set the exported survey definition status to Inactive
        surveyDefinition.setStatus(SurveyDefinitionStatus.I);

        String json = jsonHelperService.serializeSurveyDefinition(surveyDefinition);
        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=surveyDef" + surveyDefinitionId + ".jsn");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(json.getBytes("UTF-8"));
        servletOutputStream.flush();
        //Returning the original survey's status to Published.
        surveyDefinition.setStatus(SurveyDefinitionStatus.P);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.kuali.kra.coi.disclosure.CoiDisclosureAction.java

/**
 * //  ww  w .java2 s.  co  m
 * This method is for use with a JSON/AJAX call and should not be used as a post method
 * 
 */
public ActionForward getDisclosureEventTypeInfo(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String eventType = request.getParameter("eventType");
    Map<String, Object> fieldValues = new HashMap<String, Object>();
    fieldValues.put("eventTypeCode", eventType);

    List<CoiDisclosureEventType> disclosureEventTypes = (List<CoiDisclosureEventType>) getBusinessObjectService()
            .findMatching(CoiDisclosureEventType.class, fieldValues);
    StringWriter writer = new StringWriter();
    if (!CollectionUtils.isEmpty(disclosureEventTypes)) {
        CoiDisclosureEventType disclosureEventType = disclosureEventTypes.get(0);
        CoiDisclosureEventTypeAjaxBean disclosureEventTypeAjaxBean = new CoiDisclosureEventTypeAjaxBean();
        disclosureEventTypeAjaxBean.setDisclosureEventType(disclosureEventType);

        //Special code to handle select box
        if (disclosureEventType.isUseSelectBox1()) {
            try {
                String valuesFinder = disclosureEventType.getSelectBox1ValuesFinder();
                if (StringUtils.isNotBlank(valuesFinder)) {
                    Class valuesFinderClass = Class.forName(valuesFinder);
                    KeyValuesFinder keyValuesFinder = (KeyValuesFinder) valuesFinderClass.newInstance();
                    List<KeyValue> keyValues = keyValuesFinder.getKeyValues();
                    if (!CollectionUtils.isEmpty(keyValues)) {
                        disclosureEventTypeAjaxBean.setKeyValues(keyValues);
                    }
                }
            } catch (Exception e) {
                //Failed to load select box 
            }
        }

        // disclosure ID and label are always required, so put in a default
        if (StringUtils.isEmpty(disclosureEventType.getProjectIdLabel())) {
            disclosureEventType.setProjectIdLabel(CoreApiServiceLocator.getKualiConfigurationService()
                    .getPropertyValueAsString(DEFAULT_EVENT_ID_STRING));
        }
        if (StringUtils.isEmpty(disclosureEventType.getProjectTitleLabel())) {
            disclosureEventType.setProjectTitleLabel(CoreApiServiceLocator.getKualiConfigurationService()
                    .getPropertyValueAsString(DEFAULT_EVENT_TITLE_STRING));
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, disclosureEventTypeAjaxBean);

        response.setContentType("application/json");
        ServletOutputStream out = response.getOutputStream();

        try {
            out.write(writer.getBuffer().toString().getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace(new PrintWriter(out));
        }

    }
    return null;
}

From source file:com.globalsight.everest.webapp.pagehandler.tasks.UpdateLeverageHandler.java

@ActionHandler(action = "checkHaveNonReadyWFSelected", formClass = "")
public void checkHaveNonReadyWFSelected(HttpServletRequest p_request, HttpServletResponse p_response,
        Object form) throws Exception {
    HttpSession session = p_request.getSession(false);
    Locale uiLocale = (Locale) session.getAttribute(WebAppConstants.UILOCALE);

    String selectedWfs = (String) p_request.getParameter("selectedWorkFlows");
    List<Long> wfIds = UpdateLeverageHelper.getWfIds(selectedWfs);
    StringBuffer readyWfIds = new StringBuffer();
    StringBuffer nonReadyWfs = new StringBuffer();
    int count = 0;
    for (Iterator<Long> it = wfIds.iterator(); it.hasNext();) {
        Long wfId = it.next();//from   w ww  . j a  v a2 s  . c  o  m
        Workflow wf = workflowManager.getWorkflowById(wfId);
        if (Workflow.READY_TO_BE_DISPATCHED.equals(wf.getState())) {
            readyWfIds.append(" ").append(wfId);
        } else {
            count++;
            String wfDisplayName = wf.getTargetLocale().getDisplayName(uiLocale);
            if (nonReadyWfs.length() == 0) {
                nonReadyWfs.append(count).append(". ").append(wfDisplayName);
            } else {
                nonReadyWfs.append("_returnPH_").append(count).append(". ").append(wfDisplayName);
            }
        }
    }

    // Write back
    String strReadyWfIds = (readyWfIds.toString().trim().length() > 0 ? readyWfIds.toString().trim() : "");
    String strNonReadyWfs = (nonReadyWfs.length() > 0 ? nonReadyWfs.toString() : "");
    ServletOutputStream out = p_response.getOutputStream();
    try {
        p_response.setContentType("text/plain");
        out = p_response.getOutputStream();
        StringBuffer sb = new StringBuffer();
        sb.append("{\"readyWfIds\":\"");
        sb.append(strReadyWfIds).append("\", \"nonReadyWfs\":\"").append(strNonReadyWfs).append("\"}");
        out.write(sb.toString().getBytes("UTF-8"));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        out.close();
        pageReturn();
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.erasmus.ErasmusIndividualCandidacyProcessPublicDA.java

public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    MobilityIndividualApplicationProcess process = (MobilityIndividualApplicationProcess) getProcess(request);

    final LearningAgreementDocument document = new LearningAgreementDocument(process);
    byte[] data = ReportsUtils.exportMultipleToPdfAsByteArray(document);

    response.setContentLength(data.length);
    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf");

    final ServletOutputStream writer = response.getOutputStream();
    writer.write(data);
    writer.flush();//from w ww.  ja v  a 2 s . c om
    writer.close();

    response.flushBuffer();
    return mapping.findForward("");
}

From source file:org.kuali.ole.web.DocumentServlet.java

/**
 * Method sends the response generated for the given request
 *
 * @param res//  w  ww .  j  av a  2  s.co m
 * @param file
 * @throws IOException
 */
private void sendResponseAsFile(HttpServletResponse res, File file) throws IOException {
    ServletOutputStream stream = res.getOutputStream();
    FileInputStream fos = new FileInputStream(file.getAbsolutePath());
    BufferedInputStream buf = new BufferedInputStream(fos);
    int readBytes = 0;
    while ((readBytes = buf.read()) != -1) {
        stream.write(readBytes);
    }
    if (stream != null) {
        stream.close();
    }
    if (buf != null) {
        buf.close();
    }
    res.flushBuffer();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.erasmus.ErasmusIndividualCandidacyProcessPublicDA.java

public ActionForward retrieveApprovedLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    final ApprovedLearningAgreementDocumentFile file = getDomainObject(request, "agreementId");
    final String hash = request.getParameter("hash");

    final MobilityIndividualApplicationProcess process = file.getProcess();
    final DegreeOfficePublicCandidacyHashCode candidacyHashCode = process.getCandidacyHashCode();
    if (candidacyHashCode.getValue().equals(hash)) {
        final byte[] content = file.getContent();
        response.setContentLength(content.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());

        final ServletOutputStream writer = response.getOutputStream();
        writer.write(content);
        writer.flush();/*from ww  w. ja  v  a 2s. co m*/
        writer.close();

        response.flushBuffer();
    }

    return null;
}

From source file:be.fedict.eid.idp.sp.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();

    byte[] photoData = (byte[]) session.getAttribute(PHOTO_SESSION_ATTRIBUTE);

    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*//from  w  w w . ja  va  2  s. c  om
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:com.gae.ImageUpServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    //ReturnValue value = new ReturnValue();
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    resp.setContentType("image/jpeg");
    ServletOutputStream out = resp.getOutputStream();
    try {//from w  w  w . j  a  v a2 s .  co m
        List<FileItem> list = upload.parseRequest(req);
        //FileItem list = upload.parseRequest(req);
        for (FileItem item : list) {
            if (!(item.isFormField())) {
                filename = item.getName();
                if (filename != null && !"".equals(filename)) {
                    int size = (int) item.getSize();
                    byte[] data = new byte[size];
                    InputStream in = item.getInputStream();
                    in.read(data);
                    ImagesService imagesService = ImagesServiceFactory.getImagesService();
                    Image newImage = ImagesServiceFactory.makeImage(data);
                    byte[] newImageData = newImage.getImageData();

                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   
                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   

                    out.write(newImageData);
                    out.flush();

                    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    Key key = KeyFactory.createKey(kind, skey);
                    Blob blobImage = new Blob(newImageData);
                    DirectBeans_textjson dbeans = new DirectBeans_textjson();
                    /*  ?Date?     */
                    //Entity entity = dbeans.setentity("add", kind, true, key, id, val);

                    //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val);
                    //Entity entity = value.entity;
                    //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue();
                    DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val);
                    Entity entity = eval.entity;

                    /*  ?Date                         */
                    //for(int i=0; i<id.length; i++ ){
                    //   if(id[i].equals("image")){
                    //      //filetitle = val[i];
                    //      //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]);   
                    //   }
                    //}                

                    entity.setProperty("image", blobImage);
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss");
                    sdf.setTimeZone(TimeZone.getTimeZone("JST"));
                    entity.setProperty("moddate", sdf.format(date));
                    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    ds.put(entity);
                    out.println("? KEY:" + key);
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}