Example usage for java.io BufferedOutputStream write

List of usage examples for java.io BufferedOutputStream write

Introduction

In this page you can find the example usage for java.io BufferedOutputStream write.

Prototype

@Override
public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte to this buffered output stream.

Usage

From source file:com.vmware.bdd.cli.auth.LoginClientImplTest.java

public LoginTestTemplate(final String expectedUserName, final String expectedPassword, final int responseCode,
        final String sessionId) {

    httpHandler = new HttpHandler() {
        @Override//from   www  .  j a  v  a2  s  .com
        public void handle(HttpExchange httpExchange) throws IOException {
            Headers headers = httpExchange.getRequestHeaders();

            Assert.assertEquals("application/x-www-form-urlencoded; charset=UTF-8",
                    headers.getFirst("Content-Type"));
            Assert.assertEquals("POST", httpExchange.getRequestMethod());

            InputStream reqStream = httpExchange.getRequestBody();

            Reader reader = new InputStreamReader(reqStream);

            StringBuilder sb = new StringBuilder();

            char[] tmp = new char[16];
            int count = reader.read(tmp);
            while (count > 0) {
                sb.append(tmp, 0, count);
                count = reader.read(tmp);
            }

            //            String val = URLDecoder.decode(sb.toString(), "UTF-8");

            List<NameValuePair> namePasswordPairs = URLEncodedUtils.parse(sb.toString(),
                    Charset.forName("UTF-8"));
            Assert.assertEquals(namePasswordPairs.get(0).getValue(), expectedUserName);
            Assert.assertEquals(namePasswordPairs.get(1).getValue(), expectedPassword);

            if (sessionId != null) {
                Headers responseHeaders = httpExchange.getResponseHeaders();
                responseHeaders.set(LoginClientImpl.SET_COOKIE_HEADER,
                        "JSESSIONID=" + sessionId + "; Path=/serengeti; Secure");
            }

            String response = "LoginClientImplTest";
            httpExchange.sendResponseHeaders(responseCode, response.length());

            BufferedOutputStream os = new BufferedOutputStream(httpExchange.getResponseBody());

            os.write(response.getBytes());
            os.close();

        }
    };
}

From source file:org.khmeracademy.btb.auc.pojo.service.impl.UploadImage_serviceimpl.java

@Override
public Image upload(int pro_id, List<MultipartFile> files) {
    Image uploadImage = new Image();
    if (files.isEmpty()) {

    } else {//from w  ww  .  j  av a2 s  .c o m

        //            if(folder=="" || folder==null)
        //                folder = "default";
        String UPLOAD_PATH = "/opt/project/default";
        String THUMBNAIL_PATH = "/opt/project/thumnail/";

        java.io.File path = new java.io.File(UPLOAD_PATH);
        java.io.File thum_path = new java.io.File(THUMBNAIL_PATH);
        if (!path.exists())
            path.mkdirs();
        if (!thum_path.exists()) {
            thum_path.mkdirs();
        }

        List<String> names = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            fileName = UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
            try {
                byte[] bytes = file.getBytes();
                Files.copy(file.getInputStream(), Paths.get(UPLOAD_PATH, fileName)); //copy path name to server
                try {
                    //TODO: USING THUMBNAILS TO RESIZE THE IMAGE

                    Thumbnails.of(UPLOAD_PATH + "/" + fileName).forceSize(640, 640).toFiles(thum_path,
                            Rename.NO_CHANGE);
                } catch (Exception ex) {
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(new File(THUMBNAIL_PATH + fileName)));
                    stream.write(bytes);
                    stream.close();
                }
                names.add(fileName); // add file name
                imRepo.upload(pro_id, fileName); // upload path to database
            } catch (Exception e) {

            }
        }
        uploadImage.setProjectPath("/resources/");
        uploadImage.setServerPath(UPLOAD_PATH);
        uploadImage.setNames(names);
        uploadImage.setMessage("File has been uploaded successfully!!!");
    }
    return uploadImage;
}

From source file:com.castlemock.web.basis.manager.FileManager.java

/**
 * The method uploads a list of MultipartFiles to the server. The output file directory is configurable and can be
 * configured in the main property file under the key "temp.file.directory"
 * @param files The list of files that should be uploaded
 * @return Returns the uploaded files as a list of files. The files have the new server path.
 * @throws IOException Throws an exception if the upload fails.
 *//*w  ww  .ja  v a  2s.co m*/
public List<File> uploadFiles(final List<MultipartFile> files) throws IOException {
    final File fileDirectory = new File(tempFilesFolder);

    if (!fileDirectory.exists()) {
        fileDirectory.mkdirs();
    }

    final List<File> uploadedFiles = new ArrayList<File>();
    LOGGER.debug("Starting uploading files");
    for (MultipartFile file : files) {
        if (file.getOriginalFilename().isEmpty()) {
            continue;
        }

        LOGGER.debug("Uploading file: " + file.getOriginalFilename());
        final File serverFile = new File(
                fileDirectory.getAbsolutePath() + File.separator + file.getOriginalFilename());
        final byte[] bytes = file.getBytes();
        final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        try {
            stream.write(bytes);
            uploadedFiles.add(serverFile);
        } finally {
            stream.close();
        }
    }
    return uploadedFiles;
}

From source file:eu.planets_project.pp.plato.services.characterisation.DROIDIntegration.java

/**
 * Tries to identify the given <param>data</param> and <param>filename</param>.
 * - throws an exception if it is not possible to create a temporary file.
 * /*from  w w  w .j av a2s .co m*/
 * @param filename
 * @param data
 * @return {@link IdentificationFile}
 * @throws Exception
 */
public IdentificationFile identify(String filename, byte[] data) throws Exception {
    String filebody = filename;
    String suffix = "";
    int bodyEnd = filename.lastIndexOf(".");
    if (bodyEnd >= 0) {
        filebody = filename.substring(0, bodyEnd);
        suffix = filename.substring(bodyEnd);
    }
    File tempFile = File.createTempFile(filebody + System.nanoTime(), suffix);
    tempFile.deleteOnExit();
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
    out.write(data);
    out.close();

    return droid.identify(tempFile.getCanonicalPath());
}

From source file:com.zenika.dorm.maven.test.grinder.GrinderGenerateJson.java

/**
 * @param file         to generate checksum
 * @param fileChecksum to put the generated checksum
 *//*  w  w w  .j  ava  2s.c o  m*/
private static void generateChecksum(File file, File fileChecksum, String checksumType) {
    FileOutputStream outputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    FileInputStream inputStream = null;
    BufferedInputStream bufferedInputStream = null;
    try {
        MessageDigest digest = MessageDigest.getInstance(checksumType);

        outputStream = new FileOutputStream(fileChecksum);
        bufferedOutputStream = new BufferedOutputStream(outputStream);

        inputStream = new FileInputStream(file);
        bufferedInputStream = new BufferedInputStream(inputStream);
        byte[] dataBytes = new byte[1024];
        int nread = 0;

        while ((nread = bufferedInputStream.read(dataBytes)) != -1) {
            digest.update(dataBytes, 0, nread);
        }

        byte[] byteDigested = digest.digest();

        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < byteDigested.length; i++) {
            sb.append(Integer.toString((byteDigested[i] & 0xff) + 0x100, 16).substring(1));
        }

        bufferedOutputStream.write(sb.toString().getBytes());
        bufferedOutputStream.flush();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to digest this file: " + file, e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Unable to digest this file: " + file, e);
    } catch (IOException e) {
        throw new RuntimeException("Unable to digest this file: " + file, e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to digest this file: " + file, e);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to digest this file: " + file, e);
            }
        }
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to digest this file: " + file, e);
            }
        }
        if (bufferedOutputStream != null) {
            try {
                bufferedOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to digest this file: " + file, e);
            }
        }
    }
}

From source file:com.peadargrant.filecheck.web.controllers.CheckController.java

@RequestMapping(method = RequestMethod.POST)
public String performCheck(@RequestParam(value = "assignment", required = true) String assignmentCode,
        @RequestParam("file") MultipartFile file, ModelMap model) throws Exception {

    String assignmentsUrl = serverEnvironment.getPropertyAsString("assignmentsUrl");
    model.addAttribute("assignmentsUrl", assignmentsUrl);

    // bail out if the file is empty
    if (file.isEmpty()) {
        model.addAttribute("message", "file.was.empty");
        return "error";
    }/*from www  .j a  v  a 2s  .  co m*/

    // input stream from file 
    byte[] bytes = file.getBytes();
    String name = file.getOriginalFilename();

    // write to temp dir
    String filePath = System.getProperty("java.io.tmpdir") + "/" + name;
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
    stream.write(bytes);
    stream.close();

    // load file
    File inputFile = new File(filePath);

    // get assignment
    Assignment assignment = this.getAssignmentForCode(assignmentCode);
    if (assignment == null) {
        return "assignmentNotFound";
    }
    model.addAttribute(assignment);

    // GUI report table model
    SummaryTableModel summaryTableModel = new SummaryTableModel();
    ReportTableModel reportTableModel = new ReportTableModel(summaryTableModel);

    // checker
    Checker checker = new Checker();
    checker.setReport(reportTableModel);
    checker.runChecks(inputFile, assignment);

    // details for output
    model.addAttribute("fileName", name);
    model.addAttribute("startTime", new java.util.Date());
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    model.addAttribute("remoteIP", ipAddress);

    // final outcome
    model.addAttribute("outcome", summaryTableModel.getFinalOutcome());
    Color finalOutcomeColor = summaryTableModel.getFinalOutcome().getSaturatedColor();
    model.addAttribute("colourr", finalOutcomeColor.getRed());
    model.addAttribute("colourg", finalOutcomeColor.getGreen());
    model.addAttribute("colourb", finalOutcomeColor.getBlue());

    // transformer for parsing tables
    FileCheckWebTableTransformer transformer = new FileCheckWebTableTransformer();

    // summary table headings
    List<String> summaryColumns = transformer.getColumnHeaders(summaryTableModel);
    model.addAttribute("summaryColumns", summaryColumns);

    // summary table
    List summaryContents = transformer.getTableContents(summaryTableModel);
    model.addAttribute("summary", summaryContents);

    // detail table headings
    List<String> detailColumns = transformer.getColumnHeaders(reportTableModel);
    model.addAttribute("detailColumns", detailColumns);

    // detail report table
    List detailContents = transformer.getTableContents(reportTableModel);
    model.addAttribute("detail", detailContents);

    // delete the uploaded file
    inputFile.delete();

    // Return results display
    return "check";
}

From source file:bean.FileUploadBean.java

public String uploadResume() throws IOException, SQLException {

    UploadedFile uploadedPhoto = getResume();
    //System.out.println("Name " + getName());
    //System.out.println("tmp directory" System.getProperty("java.io.tmpdir"));
    //System.out.println("File Name " + uploadedPhoto.getFileName());
    //System.out.println("Size " + uploadedPhoto.getSize());
    this.filePath = "C:/Users/Usuario/Documents/fotos/";

    objOutros.setUrl(this.filePath);
    byte[] bytes = null;

    if (null != uploadedPhoto) {
        bytes = uploadedPhoto.getContents();
        String filename = FilenameUtils.getName(uploadedPhoto.getFileName());
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(this.filePath + filename)));
        stream.write(bytes);
        stream.close();/*from w  w w  . ja v  a  2s .  c  om*/

    }

    return "success";
}

From source file:bean.FileUploadBean.java

public void uploadPhoto(FileUploadEvent e) throws IOException, SQLException {

    UploadedFile uploadedPhoto = e.getFile();

    this.filePath = "C:/Users/Usuario/Documents/fotos/";
    byte[] bytes = null;

    System.out.println("ID do usurio - " + loginBean.getId());

    if (null != uploadedPhoto) {
        bytes = uploadedPhoto.getContents();
        String filename = FilenameUtils.getName(uploadedPhoto.getFileName());
        this.setName(filename);
        this.setUrl(filePath);
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(this.filePath + filename)));
        stream.write(bytes);
        stream.close();//  www. j  a  v  a2  s  . co  m
        documentosBD.inserirDocumentos(getName(), getUrl(), loginBean.getId());
        pdfModify.modificaPDF(this.url, this.getName());

    }

    FacesContext.getCurrentInstance().addMessage("messages",
            new FacesMessage(FacesMessage.SEVERITY_INFO, uploadedPhoto.getFileName(), ""));
}

From source file:com.bristle.javalib.io.FileUtil.java

/**************************************************************************
* Copy the binary contents of the specified InputStream to the specified 
* OutputStream, up to the specified number of bytes, returning the count
* of bytes written.//from ww  w.  ja  v  a 2 s .  com
*@param  streamIn       InputStream to read from
*@param  streamOut      OutputStream to write to
*@param  lngMaxBytes    Max number of bytes to copy, or lngNO_MAX_BYTES 
*                       for unlimited
*@return                Count of bytes written
*@throws TooManyBytesException
*                       When streamIn contains more than intMaxBytes,
*                       resulting in a partially copied binary stream.
*@throws IOException    When an I/O error occurs reading or writing a
*                       stream.
**************************************************************************/
public static long copyBinaryStreamToStream(InputStream streamIn, OutputStream streamOut, long lngMaxBytes)
        throws TooManyBytesException, IOException {
    // Buffer the input and output for efficiency, to avoid lots of 
    // small I/O operations.
    // Note: Don't call the read() and write() methods that could do it 
    //       all in a single byte-array because we don't want to consume 
    //       that caller-specified amount of memory.  Better to do it
    //       one byte at a time, but with buffering for efficiency.
    BufferedInputStream buffIn = new BufferedInputStream(streamIn);
    BufferedOutputStream buffOut = new BufferedOutputStream(streamOut);

    long lngBytesWritten = 0;
    for (int intByte = buffIn.read(); intByte > -1; intByte = buffIn.read()) {
        if (lngMaxBytes != lngNO_MAX_BYTES && lngBytesWritten >= lngMaxBytes) {
            buffOut.flush();
            throw new TooManyBytesException("The input stream contains more than " + lngMaxBytes
                    + " bytes.  Only " + lngBytesWritten + " bytes were written to the " + "output stream",
                    lngBytesWritten);
        }
        buffOut.write(intByte);
        lngBytesWritten++;
    }
    buffOut.flush();
    return lngBytesWritten;
}

From source file:com.athena.chameleon.web.common.controller.FileController.java

@RequestMapping("/download.do")
public void download(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("path") String path) throws Exception {

    Assert.notNull(path, "name must not be null.");

    File file = new File(path);

    Assert.isTrue(file.exists(), path + " does not exist.");

    String name = path.replaceAll("\\\\", "/");
    name = name.substring(name.lastIndexOf("/") + 1, name.length());

    long fileSize = file.length();

    if (fileSize > 0L) {
        response.setHeader("Content-Length", Long.toString(fileSize));
    }//from w  ww  . jav  a 2s  . co m

    String fileExt = name.substring(name.lastIndexOf(".") + 1);

    response.reset();

    if (fileExt.equals("pdf")) {
        response.setContentType("application/pdf");
    } else if (fileExt.equals("zip")) {
        response.setContentType("application/zip");
    } else if (fileExt.equals("ear")) {
        response.setContentType("application/zip");
    } else if (fileExt.equals("war")) {
        response.setContentType("application/zip");
    } else if (fileExt.equals("jar")) {
        response.setContentType("application/zip");
    } else {
        response.setContentType("application/octet-stream");
    }

    if (request.getHeader("User-Agent").toLowerCase().contains("firefox")
            || request.getHeader("User-Agent").toLowerCase().contains("safari")) {
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + new String(name.getBytes("UTF-8"), "ISO-8859-1") + "\"");
        response.setHeader("Content-Transfer-Encoding", "binary");
    } else {
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
    }

    try {
        BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());

        int read = 0;
        while ((read = fin.read()) != -1) {
            outs.write(read);
        }

        IOUtils.closeQuietly(fin);
        IOUtils.closeQuietly(outs);
    } catch (Exception e) {
        e.printStackTrace();
    }
}