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:it.openprj.jValidator.spring.ExtraCheckCustomCodeValidator.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String code = request.getParameter("value");
    String name = request.getParameter("name");
    String addReq = request.getParameter("addReq");

    //TODO: take the result message from "locale"
    String result = null;//from  www  . j  a  v a 2s  .c  o  m
    ObjectMapper mapper = new ObjectMapper();
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();
    if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) {
        result = I18n.getMessage("error.extracheck.invaliddata");
    } else {
        name = name.trim();
        if (addReq.equalsIgnoreCase("true")) {
            ReadList list = checksTypeDao.findCustomCodeByName(name);
            if (list != null && CollectionUtils.isNotEmpty(list.getResults())) {
                result = I18n.getMessage("error.extracheck.name.alreadyexist");
                out.write(mapper.writeValueAsBytes(result));
                out.flush();
                out.close();
                return null;
            }
        }
        try {
            File sourceDir = new File(System.getProperty("java.io.tmpdir"), "jValidator/src");
            sourceDir.mkdirs();
            String classNamePack = name.replace('.', File.separatorChar);
            String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java";
            File sourceFile = new File(srcFilePath);
            if (sourceFile.exists()) {
                sourceFile.delete();
            }
            FileUtils.writeStringToFile(new File(srcFilePath), code);
            DynamicClassLoader dynacode = DynamicClassLoader.getInstance();
            dynacode.addSourceDir(sourceDir);
            CustomCodeValidator customCodeValidator = (CustomCodeValidator) dynacode
                    .newProxyInstance(CustomCodeValidator.class, name);
            boolean isValid = false;
            if (customCodeValidator != null) {
                Class clazz = dynacode.getLoadedClass(name);
                if (clazz != null) {
                    Class[] interfaces = clazz.getInterfaces();
                    if (ArrayUtils.isNotEmpty(interfaces)) {
                        for (Class clz : interfaces) {
                            if ((clz.getName().equalsIgnoreCase(
                                    "it.openprj.jValidator.utils.validation.SingleValidation"))) {
                                isValid = true;
                            }
                        }
                    }
                }
            }
            if (isValid) {
                result = "Success";
            } else {
                result = I18n.getMessage("error.extracheck.wrongimpl");
            }
        } catch (Exception e) {
            result = "Failed. Reason:" + e.getMessage();
        }
    }
    out.write(mapper.writeValueAsBytes(result));
    out.flush();
    out.close();
    return null;
}

From source file:org.wso2.carbon.logging.view.ui.LogViewerClient.java

public void downloadArchivedLogFiles(String logFile, HttpServletResponse response, String tenantDomain,
        String serverKey) throws RemoteException, LogViewerException {
    String msg = "Error occurred while getting logger data. Backend service may be " + "unavailable";

    InputStream fileToDownload = null;
    try {//  w  w w  .j a  v a2s  .  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, tenantDomain, serverKey);
        fileToDownload = data.getInputStream();
        int c;
        while ((c = fileToDownload.read()) != -1) {
            outputStream.write(c);
        }
        outputStream.flush();
        outputStream.flush();
    } catch (RemoteException e) {
        log.error(msg, e);
        throw e;
    } catch (LogViewerException e) {
        log.error(msg, e);
        throw e;
    } catch (IOException e) {
        String errorWhileDownloadingMsg = "Error while downloading file.";
        log.error(errorWhileDownloadingMsg, e);
        throw new LogViewerException(errorWhileDownloadingMsg, e);
    } finally {
        try {
            if (fileToDownload != null) {
                fileToDownload.close();
            }
        } catch (IOException e) {
            log.error("Couldn't close the InputStream " + e.getMessage(), e);
        }
    }
}

From source file:au.org.ala.layers.web.UserDataService.java

private void setImageBlank(HttpServletResponse response) {
    if (blankImageBytes == null && blankImageObject != null) {
        synchronized (blankImageObject) {
            if (blankImageBytes == null) {
                try {
                    RandomAccessFile raf = new RandomAccessFile(
                            UserDataService.class.getResource("/blank.png").getFile(), "r");
                    blankImageBytes = new byte[(int) raf.length()];
                    raf.read(blankImageBytes);
                    raf.close();/*  www.j  a v a  2  s .  c  o m*/
                } catch (IOException e) {
                    logger.error("error reading default blank tile", e);
                }
            }
        }
    }
    if (blankImageObject != null) {
        response.setContentType("image/png");
        try {
            ServletOutputStream outStream = response.getOutputStream();
            outStream.write(blankImageBytes);
            outStream.flush();
            outStream.close();
        } catch (IOException e) {
            logger.error("error outputting blank tile", e);
        }
    }
}

From source file:it.eng.spagobi.mapcatalogue.service.DetailMapModule.java

/**
 * sends an error message to the client/*from  w ww  . j  ava2  s .c  om*/
 * @param out The servlet output stream
 */
private void sendError(ServletOutputStream out) {
    try {
        out.write("<html>".getBytes());
        out.write("<body>".getBytes());
        out.write("<br/><br/><center><h2><span style=\"color:red;\">Unable to produce map</span></h2></center>"
                .getBytes());
        out.write("</body>".getBytes());
        out.write("</html>".getBytes());
    } catch (Exception e) {
        TracerSingleton.log(SpagoBIConstants.NAME_MODULE, TracerSingleton.MAJOR,
                "GeoAction :: sendError : " + "Unable to write into output stream ", e);
    }
}

From source file:com.jd.survey.web.survey.PrivateSurveyController.java

/**
 * Returns the survey logo image binary  
 * @param departmentId/*ww w  .java2s .c  o  m*/
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN", "ROLE_SURVEY_PARTICIPANT" })
@RequestMapping(value = "/logo/{id}", produces = "text/html")
public void getSurveyLogo(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {
        uiModel.asMap().clear();
        User user = userService.user_findByLogin(principal.getName());
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToCreateSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            throw (new RuntimeException("Unauthorized access to logo"));
        } else {
            SurveyDefinition surveyDefinition = surveySettingsService
                    .surveyDefinition_findById(surveyDefinitionId);
            //response.setContentType("image/png");
            ServletOutputStream servletOutputStream = response.getOutputStream();
            servletOutputStream.write(surveyDefinition.getLogo());
            servletOutputStream.flush();
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.sample.JavaHTTPResource.java

public void execute(HttpHost host, HttpUriRequest req, HttpServletResponse resultResponse)
        throws IOException, IllegalStateException, SAXException {
    HttpResponse RSSResponse = client.execute(host, req);
    ServletOutputStream os = resultResponse.getOutputStream();
    if (RSSResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        resultResponse.addHeader("Content-Type", "application/json");
        //String json = IOUtils.toString(RSSResponse.getEntity().getContent());
        InputStream in = RSSResponse.getEntity().getContent();
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String read;//from   www .  j ava 2  s.c om

        while ((read = br.readLine()) != null) {
            //System.out.println(read);
            sb.append(read);
        }

        br.close();
        os.write(sb.toString().getBytes(Charset.forName("UTF-8")));

    } else {
        resultResponse.setStatus(RSSResponse.getStatusLine().getStatusCode());
        RSSResponse.getEntity().getContent().close();
        os.write(RSSResponse.getStatusLine().getReasonPhrase().getBytes());
    }
    os.flush();
    os.close();
}

From source file:ai.h2o.servicebuilder.MakePythonWarServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long startTime = System.currentTimeMillis();
    File tmpDir = null;//from   w ww  . j  a  v a  2 s  .c om
    try {
        //create temp directory
        tmpDir = createTempDirectory("makeWar");
        logger.debug("tmpDir " + tmpDir);

        //  create output directories
        File webInfDir = new File(tmpDir.getPath(), "WEB-INF");
        if (!webInfDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF)");
        File outDir = new File(webInfDir.getPath(), "classes");
        if (!outDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/classes)");
        File libDir = new File(webInfDir.getPath(), "lib");
        if (!libDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/lib)");

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String pojofile = null;
        String jarfile = null;
        String mojofile = null;
        String pythonfile = null;
        String predictorClassName = null;
        String pythonenvfile = null;
        ArrayList<String> pojos = new ArrayList<String>();
        ArrayList<String> rawfiles = new ArrayList<String>();
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) {
                if (field.equals("pojo")) { // pojo file name, use this or a mojo file
                    pojofile = filename;
                    pojos.add(pojofile);
                    predictorClassName = filename.replace(".java", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added pojo model {}", filename);
                }
                if (field.equals("jar")) {
                    jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("python")) {
                    pythonfile = "WEB-INF" + File.separator + "python.py";
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(webInfDir, "python.py"));
                }
                if (field.equals("pythonextra")) { // optional extra files for python
                    pythonfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("mojo")) { // a raw model zip file, a mojo file (optional)
                    mojofile = filename;
                    rawfiles.add(mojofile);
                    predictorClassName = filename.replace(".zip", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added mojo model {}", filename);
                }
                if (field.equals("envfile")) { // optional conda environment file
                    pythonenvfile = filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.debug("using conda environment file {}", pythonenvfile);
                }
            }
        }
        logger.debug("jar {}  pojo {}  mojo {}  python {}  envfile {}", jarfile, pojofile, mojofile, pythonfile,
                pythonenvfile);
        if ((pojofile == null || jarfile == null) && (mojofile == null || jarfile == null))
            throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar ");

        if (pojofile != null) {
            // Compile the pojo
            runCmd(tmpDir,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile, "-d", outDir.getPath(),
                            pojofile),
                    "Compilation of pojo failed");
            logger.info("compiled pojo {}", pojofile);
        }

        if (servletPath == null)
            throw new Exception("servletPath is null");

        FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir);
        String extraPath = "extra" + File.separator;
        String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator;
        String srcPath = extraPath + "src" + File.separator;
        copyExtraFile(servletPath, extraPath, tmpDir, "pyindex.html", "index.html");
        copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css");
        copyExtraFile(servletPath, webInfPath, webInfDir, "web-pythonpredict.xml", "web.xml");
        FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir);

        // change the class name in the predictor template file to the predictor we have
        String modelCode = null;
        if (!pojos.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos);
            modelCode = "null";
        } else if (!rawfiles.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles);
            modelCode = "MojoModel.load(fileName)";
        }
        InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, "null",
                pythonenvfile == null ? "" : pythonenvfile, srcPath + "ServletUtil-TEMPLATE.java",
                "ServletUtil.java");

        copyExtraFile(servletPath, srcPath, tmpDir, "PredictPythonServlet.java", "PredictPythonServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java");

        // compile extra
        runCmd(tmpDir,
                Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                        "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp",
                        "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(),
                        "InfoServlet.java", "StatsServlet.java", "PredictPythonServlet.java",
                        "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java"),
                "Compilation of servlet failed");

        // create the war jar file
        Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.add(new File(tmpDir, "index.html"));
        filesc.add(new File(tmpDir, "jquery.js"));
        filesc.add(new File(tmpDir, "predict.js"));
        filesc.add(new File(tmpDir, "custom.css"));
        filesc.add(new File(tmpDir, "modelnames.txt"));
        for (String m : pojos) {
            filesc.add(new File(tmpDir, m));
        }
        for (String m : rawfiles) {
            filesc.add(new File(tmpDir, m));
        }
        Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);
        dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);

        File[] files = filesc.toArray(new File[] {});
        if (files.length == 0)
            throw new Exception("Can't list compiler output files (out)");

        byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator);
        if (resjar == null)
            throw new Exception("Can't create war of compiler output");
        logger.info("war created from {} files, size {}", files.length, resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor";
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);

        Long elapsedMs = System.currentTimeMillis() - startTime;
        logger.info("Done python war creation in {}", elapsedMs);
    } catch (Exception e) {
        logger.error("doPost failed", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                logger.error("Can't delete tmp directory");
            }
        }
    }

}

From source file:org.wso2.carbon.identity.provider.openid.handlers.OpenIDHandler.java

/**
 * Send a direct response to the RP./* w ww  . j  a va2s.  c  o m*/
 *
 * @param httpResp HttpServletResponse
 * @param response Response message
 * @return
 * @throws IOException
 */
private void directResponse(HttpServletResponse httpResp, String response) throws IOException {
    ServletOutputStream stream = null;
    try {
        stream = httpResp.getOutputStream();
        stream.write(response.getBytes());
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:ispyb.client.common.shipping.UploadShipmentAction.java

/**
 * DownloadFile/*from www  .  j a  va  2  s.co m*/
 * 
 * @param mapping
 * @param actForm
 * @param request
 * @param response
 * @return
 */
public ActionForward DownloadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request,
        HttpServletResponse response) {

    ActionMessages errors = new ActionMessages();
    String fileType = request.getParameter(Constants.TEMPLATE_FILE_TYPE);

    if (fileType == null)
        fileType = this.mFileType;
    try {
        String targetUpload = new String("");
        String attachmentFilename = new String("");
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_TEMPLATE)) {
            targetUpload = Constants.TEMPLATE_RELATIVE_PATH;
            targetUpload = request.getRealPath(targetUpload);
            attachmentFilename = Constants.TEMPLATE_XLS_FILENAME;
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE)) {
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE_ADVANCED)) {
            targetUpload = PopulateTemplate(request, true, false, true, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, true, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_EXPORT_SHIPPING)) {
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE_FROM_SHIPMENT)) {
            Integer _shippingId = Integer.decode(request.getParameter(Constants.SHIPPING_ID));
            int shippingId = (_shippingId != null) ? _shippingId.intValue() : 0;
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, true,
                    shippingId);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, true,
                    shippingId);
        }

        try {

            byte[] imageBytes = FileUtil.readBytes(targetUpload);
            response.setContentLength(imageBytes.length);
            ServletOutputStream out = response.getOutputStream();
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=0");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);

            out.write(imageBytes);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString()));
        LOG.error(e.toString());
        saveErrors(request, errors);
        return mapping.findForward("error");
    }

    return null;
}

From source file:org.wso2.carbon.humantask.ui.clients.HumanTaskPackageManagementServiceClient.java

/**
 * Download package archive.//from   w  w w .j a  va  2s  . c  o m
 *
 * @param humanTaskPackageName : The package name.
 * @param response             :
 * @throws PackageManagementException :
 * @throws java.io.IOException        :
 */
public void downloadHumanTaskPackage(String humanTaskPackageName, HttpServletResponse response)
        throws PackageManagementException, IOException {
    try {
        ServletOutputStream out = response.getOutputStream();

        HumanTaskPackageDownloadData downloadData = stub.downloadHumanTaskPackage(humanTaskPackageName);
        if (downloadData != null) {
            DataHandler handler = downloadData.getPackageFileData();
            response.setHeader("Content-Disposition", "fileName=" + downloadData.getPackageName());
            response.setContentType(handler.getContentType());
            InputStream in = handler.getDataSource().getInputStream();
            int nextChar;
            while ((nextChar = in.read()) != -1) {
                out.write((char) nextChar);
            }
            out.flush();
            in.close();
        } else {
            out.write("The requested package archive was not found on the server".getBytes());
        }
    } catch (RemoteException e) {
        log.error(e);
        throw e;
    } catch (IOException e) {
        log.error(e);
        throw e;
    }
}