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(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this buffered output stream.

Usage

From source file:jmassivesort.algs.chunks.OneOffChunkReader_LF_ASCII_Test.java

private void readChunksWriteToOutput(int numChunks, File src, BufferedOutputStream outWr) throws IOException {
    for (int j = 1; j <= numChunks; j++) {
        OneOffChunkReader reader = new OneOffChunkReader(j, numChunks, src);

        Chunk chunk = reader.readChunk();
        int lastMarker = chunk.allMarkers().size() - 1;

        if (j > 1 && (lastMarker > 0 || (lastMarker == 0 && chunk.allMarkers().get(0).len > 0)))
            outWr.write(lns, 0, lns.length);

        int k;// ww  w .ja  v  a  2  s  .  c o  m
        for (k = 0; k <= lastMarker; k++) {
            Chunk.ChunkMarker marker = chunk.allMarkers().get(k);

            outWr.write(chunk.rawData(), marker.off, marker.len);
            if (k < lastMarker || (lastMarker == 0 && marker.len == 0))
                outWr.write(lns, 0, lns.length);
        }
    }
}

From source file:eu.scape_project.arc2warc.PayloadContent.java

private void copyAndCheck(OutputStream outputStream) throws IOException {
    MessageDigest md;/*from w  ww .java 2 s  . c  o m*/
    try {
        md = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException("SHA-1 not known");
    }
    BufferedInputStream buffis = new BufferedInputStream(inputStream);
    BufferedOutputStream buffos = new BufferedOutputStream(outputStream);
    try {
        byte[] tempBuffer = new byte[BUFFER_SIZE];
        int bytesRead;
        boolean firstByteArray = true;
        while ((bytesRead = buffis.read(tempBuffer)) != -1) {
            md.update(tempBuffer, 0, bytesRead);
            buffos.write(tempBuffer, 0, bytesRead);
            if (doPayloadIdentification && firstByteArray && bytesRead > 0) {
                identified = identifyPayloadType(tempBuffer);
            }
            firstByteArray = false;
        }
        digestStr = "sha1:" + calcDigest(md);
        consumed = true;
    } finally {
        IOUtils.closeQuietly(buffis);
        IOUtils.closeQuietly(buffos);
    }
}

From source file:jhttpp2.Jhttpp2HTTPSession.java

/** converts an String into a Byte-Array to write it with the OutputStream */
public void write(BufferedOutputStream o, String p) throws IOException {
    o.write(p.getBytes(), 0, p.length());
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * @param req servlet request//www .j  a  v  a2 s. co  m
 * @param resp servlet response
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    URL url = getURL(req, req.getParameter("uri"));
    HttpURLConnection con = (HttpURLConnection) (url.openConnection());
    con.setDoOutput(true);
    con.setAllowUserInteraction(false);
    con.setUseCaches(false);

    // TODO: figure out why this is necessary for HTTPS URLs
    if (con instanceof HttpsURLConnection) {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                    return true;
                } else {
                    log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return false;
                }
            }
        };
        ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
    }
    // pass along all appropriate HTTP headers
    Enumeration headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hname = (String) headerNames.nextElement();
        if (!unproxiedHeaders.contains(hname.toLowerCase())) {
            con.addRequestProperty(hname, req.getHeader(hname));
        }
    }
    con.connect();

    // read POST data from incoming request, write to outgoing request
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream());
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    // read result headers of POST, write to response
    Map<String, List<String>> headers = con.getHeaderFields();
    for (String key : headers.keySet()) {
        if (key != null) { // TODO: why is this check necessary!
            List<String> header = headers.get(key);
            if (header.size() > 0)
                resp.setHeader(key, header.get(0));
        }
    }

    // read result data of POST, write out to response
    in = new BufferedInputStream(con.getInputStream());
    out = new BufferedOutputStream(resp.getOutputStream());
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    con.disconnect();
}

From source file:julie.com.mikaelson.file.controller.FileInfoController.java

@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
@ResponseBody//from ww  w .  j a  v a2s .  c  o  m
public Map<String, Object> handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String fileName = request.getParameter("image_file");
    fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
    String overFlg = request.getParameter("over"); // 0:go on;1:over
    System.out.println("get: " + fileName);
    byte[] buf = new byte[1024];

    File file = new File("./" + /*
                                * "[" +
                                * UUID.randomUUID().toString() +
                                * "]" +
                                */fileName);
    InputStream is = null;
    BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file, true));
    try {

        is = request.getInputStream();

        while (true) {

            int bytesIn = is.read(buf, 0, 1024);
            System.out.println(bytesIn);
            if (bytesIn == -1) {
                break;
            } else {
                fileOut.write(buf, 0, bytesIn);
            }
        }

        fileOut.flush();
        fileOut.close();
        System.out.println(file.getAbsolutePath());
    } catch (IOException e) {
        System.out.println("error  info");
    }
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("over", overFlg);
    map.put("data", fileName);
    return map;
}

From source file:com.gsr.myschool.server.reporting.convocation.ConvocationServiceImpl.java

@Override
public File generateConvocation(Dossier dossier) {
    DossierSession dossierSession = dossierSessionRepos.findByDossierId(dossier.getId());
    List<InfoParent> parents = infoParentRepos.findByDossierId(dossier.getId());

    NiveauEtude niveauEtude = dossier.getNiveauEtude();
    SessionExamen session = dossierSession.getSessionExamen();
    if (niveauEtude == null || session == null)
        return null;

    List<SessionNiveauEtude> matieres = sessionExamenNERepos
            .findBySessionExamenIdAndNiveauEtudeId(session.getId(), niveauEtude.getId());

    SimpleDateFormat dateFormat = new SimpleDateFormat(GlobalParameters.DATE_FORMAT);
    ReportDTO dto;//from   w  w w. ja  va  2 s  .c  o m

    Map<String, Object> myMap = new HashMap<String, Object>();

    myMap.put("date", dateFormat.format(new Date()));

    if (session.getDateSession() != null) {
        myMap.put("dateTest", dateFormat.format(session.getDateSession()));
    } else {
        myMap.put("dateTest", "8:00");
    }

    myMap.put("heureAccueilDebut", session.getWelcomKids());
    myMap.put("heureAccueilFin", "8:00");

    myMap.put("heureDebut", session.getDebutTest());
    myMap.put("heureRecuperation", session.getGatherKids());

    myMap.put("niveauEtude", niveauEtude.getNom());
    myMap.put("section", niveauEtude.getFiliere().getNom());

    myMap.put("adresse", session.getAdresse());
    myMap.put("phone", session.getTelephone());

    for (InfoParent parent : parents) {
        if (!Strings.isNullOrEmpty(parent.getNom())) {
            myMap.put("nomParent", parent.getNom());
        }
    }
    myMap.put("prenomEnfant", dossier.getCandidat().getFirstname());

    if (niveauEtude.getAnnee() <= 5) {
        dto = new ReportDTO(reportMSGS);
    } else if (niveauEtude.getAnnee() >= 6 && niveauEtude.getAnnee() <= 10) {
        dto = new ReportDTO(reportCP);

        List<Map> myList = new ArrayList<Map>();
        for (SessionNiveauEtude matiere : matieres) {
            myList.add(matiere.getReportsAttributes());
        }
        myMap.put("matieres", myList);
    } else if (niveauEtude.getAnnee() >= 11 && niveauEtude.getAnnee() <= 17) {
        dto = new ReportDTO(reportSeconde);

        List<Map> myList = new ArrayList<Map>();
        for (SessionNiveauEtude matiere : matieres) {
            myList.add(matiere.getReportsAttributes());
        }
        myMap.put("matieres", myList);
    } else {
        dto = new ReportDTO(convocationPrepa);

        List<Map> myList = new ArrayList<Map>();
        for (SessionNiveauEtude matiere : matieres) {
            myList.add(matiere.getReportsAttributes());
        }
        myMap.put("matieres", myList);
        myMap.put("prenomEnfant",
                dossier.getCandidat().getFirstname() + " " + dossier.getCandidat().getLastname());
        if (dossier.getCandidat().getBacSerie() != null) {
            myMap.put("typeBac", dossier.getCandidat().getBacSerie().getValue());
        }
        myMap.put("anneeScolaire", DateUtils.currentYear() + "-" + (DateUtils.currentYear() + 1));
        myMap.put("session", session.getNom());
    }

    dto.setReportParameters(myMap);

    try {
        File convocation = new File("convocation_" + dossier.getGeneratedNumDossier() + ".pdf");
        FileOutputStream fs = new FileOutputStream(convocation);
        BufferedOutputStream outputStream = new BufferedOutputStream(fs);
        byte[] result = reportService.generatePdf(dto);

        outputStream.write(result, 0, result.length);
        outputStream.flush();
        outputStream.close();

        return convocation;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.greenline.guahao.biz.manager.storage.impl.DefaultStorageManagerImpl.java

/**
 * ?/*from   w w w  .  j  a v a2s  .c om*/
 * 
 * @param in
 * @param path
 * @return
 */
public StoreResult create(InputStream inputStream, String path) {
    StoreResult ret = new StoreResult();
    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    try {
        in = new BufferedInputStream(inputStream);
        out = new BufferedOutputStream(new FileOutputStream(rootDirectory + path));
        ret.setPath(path);
        int len = 0;
        byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];
        while (-1 != (len = in.read(bytes))) {
            out.write(bytes, 0, len);
        }
    } catch (Exception e) {
        logger.error(".", e);
        ret.setResult(ResultEnum.ERROR);
        ret.setMessage(e.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return ret;
}

From source file:org.jboss.ejb3.packagemanager.retriever.impl.HttpPackageRetriever.java

/**
 * @see org.jboss.ejb3.packagemanager.retriever.PackageRetriever#retrievePackage(PackageManagerContext, URL)
 *///from  w ww  . j a  v  a 2  s  .  co m
@Override
public File retrievePackage(PackageManagerContext pkgMgrCtx, URL packagePath) throws PackageRetrievalException {
    if (!packagePath.getProtocol().equals("http")) {
        throw new PackageRetrievalException("Cannot handle " + packagePath);
    }
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(packagePath.toExternalForm());
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);
    } catch (Exception e) {
        throw new PackageRetrievalException("Exception while retrieving package " + packagePath, e);
    }
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new PackageRetrievalException("Http retrieval wasn't successful, returned status code  "
                + httpResponse.getStatusLine().getStatusCode());
    }
    HttpEntity httpEntity = httpResponse.getEntity();

    try {
        // TODO: should this tmp be deleted on exit?
        File tmpPkgFile = File.createTempFile("tmp", ".jar",
                pkgMgrCtx.getPackageManagerEnvironment().getPackageManagerTmpDir());
        FileOutputStream fos = new FileOutputStream(tmpPkgFile);
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bos = new BufferedOutputStream(fos);
            InputStream is = httpEntity.getContent();
            bis = new BufferedInputStream(is);
            byte[] content = new byte[4096];
            int length;
            while ((length = bis.read(content)) != -1) {
                bos.write(content, 0, length);
            }
            bos.flush();
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (bis != null) {
                bis.close();
            }
        }
        return tmpPkgFile;

    } catch (IOException ioe) {
        throw new PackageRetrievalException("Could not process the retrieved package", ioe);
    }
    // TODO: I need to read the HttpClient 4.x javadocs to figure out the API for closing the
    // Http connection

}

From source file:jmassivesort.algs.chunks.SequentialChunkReader_LF_ASCII_Test.java

private void readAllChunksAndWriteToOutput(int chSz, File src, BufferedOutputStream outWr) throws IOException {
    SequentialChunkReader reader = new SequentialChunkReader(chSz, src);
    Chunk ch;/*from   ww w . j a  va 2  s  . c om*/
    int chCount = 0;
    while ((ch = reader.nextChunk()) != null) {
        chCount++;
        int lastMarker = ch.allMarkers().size() - 1;

        if (chCount > 1 && (lastMarker > 0 || (lastMarker == 0 && ch.allMarkers().get(0).len > 0)))
            outWr.write(lns, 0, lns.length);

        int k;
        for (k = 0; k <= lastMarker; k++) {
            Chunk.ChunkMarker marker = ch.allMarkers().get(k);

            outWr.write(ch.rawData(), marker.off, marker.len);
            if (k < lastMarker || (lastMarker == 0 && marker.len == 0))
                outWr.write(lns, 0, lns.length);
        }
    }
}

From source file:cn.isif.util_plus.http.ResponseStream.java

public void readFile(String savePath) throws IOException {
    if (_directResult != null)
        return;/*from   w w w  .ja  v a  2s. c  o  m*/
    if (baseStream == null)
        return;
    BufferedOutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(savePath));
        BufferedInputStream ins = new BufferedInputStream(baseStream);
        byte[] buffer = new byte[4096];
        int len = 0;
        while ((len = ins.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(baseStream);
    }
}