Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

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

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:org.pegadi.webapp.view.FileView.java

protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // get the file from the map
    File file = (File) map.get("file");

    // check if it exists
    if (file == null || !file.exists() || !file.canRead()) {
        log.warn("Error reading: " + file);
        try {/*from w  w w . j a v  a2 s .  c o m*/
            response.sendError(404);
        } catch (IOException e) {
            log.error("Could not write to response", e);
        }
        return;
    }
    // give some info in the response
    response.setContentType(getServletContext().getMimeType(file.getAbsolutePath()));
    // files does not change so often, allow three days caching
    response.setHeader("Cache-Control", "max-age=259200");
    response.setContentLength((int) file.length());

    // start writing to the response
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
        out = new BufferedOutputStream(response.getOutputStream());
        in = new BufferedInputStream(new FileInputStream(file));
        int c = in.read();
        while (c != -1) {
            out.write(c);
            c = in.read();
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java

private void dumpToFile(URL url) {
    File externalStorage = Environment.getExternalStorageDirectory();
    if (!externalStorage.canWrite())
        return;/*w  w  w  .  ja v  a 2 s . c om*/

    String fn = null;

    String[] f = url.toString().split("/");
    fn = f[f.length - 1].split("\\?")[0];
    Log.w("--------------", fn);

    String base = String.format("%s/dreamDroid/xml", externalStorage);
    File file = new File(String.format("%s/%s", base, fn));
    BufferedOutputStream bos = null;
    try {
        (new File(base)).mkdirs();
        file.createNewFile();
        bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(mBytes);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:it.readbeyond.minstrel.unzipper.Unzipper.java

private String unzip(String inputZip, String destinationDirectory, String mode, JSONObject parameters)
        throws IOException, JSONException {

    // store the zip entries to decompress
    List<String> list = new ArrayList<String>();

    // store the zip entries actually decompressed
    List<String> decompressed = new ArrayList<String>();

    // open input zip file
    File sourceZipFile = new File(inputZip);
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // open destination directory, creating it if needed    
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdirs();/*from   w ww.  ja  v  a2  s. co m*/

    // extract all files
    if (mode.equals(ARGUMENT_MODE_ALL)) {
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            list.add(zipFileEntries.nextElement().getName());
        }
    }

    // extract all files except audio and video
    // (determined by file extension)
    if (mode.equals(ARGUMENT_MODE_ALL_NON_MEDIA)) {
        String[] excludeExtensions = JSONArrayToStringArray(
                parameters.optJSONArray(ARGUMENT_ARGS_EXCLUDE_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            if (!isFile(lower, excludeExtensions)) {
                list.add(name);
            }
        }
    }

    // extract all small files
    // maximum size is passed in args parameter
    // or, if not passed, defaults to const DEFAULT_MAXIMUM_SIZE_FILE
    if (mode.equals(ARGUMENT_MODE_ALL_SMALL)) {
        long maximum_size = parameters.optLong(ARGUMENT_ARGS_MAXIMUM_FILE_SIZE, DEFAULT_MAXIMUM_SIZE_FILE);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            if (ze.getSize() <= maximum_size) {
                list.add(ze.getName());
            }
        }
    }

    // extract only the requested files
    if (mode.equals(ARGUMENT_MODE_SELECTED)) {
        String[] entries = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_ENTRIES));
        for (String entry : entries) {
            ZipEntry ze = zipFile.getEntry(entry);
            if (ze != null) {
                list.add(entry);
            }
        }
    }

    // extract all "structural" files
    if (mode.equals(ARGUMENT_MODE_ALL_STRUCTURE)) {
        String[] extensions = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            boolean extract = isFile(lower, extensions);
            if (extract) {
                list.add(name);
            }
        }
    }

    // NOTE list contains only valid zip entries
    // perform unzip
    for (String currentEntry : list) {
        ZipEntry entry = zipFile.getEntry(currentEntry);
        File destFile = new File(unzipDestinationDirectory, currentEntry);

        File destinationParent = destFile.getParentFile();
        destinationParent.mkdirs();

        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int numberOfBytesRead;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
            while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
                dest.write(data, 0, numberOfBytesRead);
            }
            dest.flush();
            dest.close();
            is.close();
            fos.close();
            decompressed.add(currentEntry);
        }
    }

    zipFile.close();
    return stringify(decompressed);
}

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 .  j  a v a  2s  .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.mirth.connect.connectors.tcp.TcpMessageDispatcher.java

protected void write(Socket socket, String data) throws Exception {
    byte[] buffer = null;
    // When working with binary data the template has to be base64 encoded
    if (connector.isBinary()) {
        buffer = Base64.decodeBase64(data);
    } else {//  w  w  w . j ava  2 s  .c  om
        buffer = data.getBytes(connector.getCharsetEncoding());
    }
    TcpProtocol protocol = connector.getTcpProtocol();
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
    protocol.write(bos, buffer);
    bos.flush();
}

From source file:com.tesshu.subsonic.client.sample4_music_andmovie.StreamDownloadAndPlayApplication.java

@Override
public void start(Stage stage) throws Exception {

    Search2Controller search2 = context.getBean(Search2Controller.class);

    StreamController streamController = context.getBean(StreamController.class);

    SuccessObserver callback = context.getBean(SuccessObserver.class);

    File tmpDirectory = new File(tmpPath);
    tmpDirectory.mkdir();/*from ww w  .  ja  va 2s.c o m*/

    Optional<SearchResult2> result2 = search2.getOf("e", null, null, null, null, 1, null, null);

    result2.ifPresent(result -> {
        Optional<Child> maybeSong = result.getSongs().stream().findFirst();
        maybeSong.ifPresent(song -> {

            streamController.stream(song, maxBitRate, format, null, null, null, null,
                    (subject, inputStream, contentLength) -> {

                        File dir = new File(
                                tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                        dir.mkdirs();

                        File file = new File(tmpPath + "/"
                                + song.getPath().replaceAll("([^.]+?)?$", StringUtils.EMPTY) + format);

                        try {
                            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
                            BufferedInputStream reader = new BufferedInputStream(inputStream);

                            byte buf[] = new byte[256];
                            int len;
                            while ((len = reader.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                            }
                            fos.flush();
                            fos.close();
                            reader.close();
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        String path = Paths.get(file.getPath()).toUri().toString();
                        Group root = new Group();
                        Scene scene = new Scene(root, 640, 480);
                        Media media = new Media(path);
                        MediaPlayer player = new MediaPlayer(media);
                        MediaView view = new MediaView(player);
                        ((Group) scene.getRoot()).getChildren().add(view);
                        stage.setScene(scene);
                        stage.show();

                        player.play();

                    }, callback);

        });

    });
}

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  .jav  a 2  s  .  c om*/
    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);
    }
}

From source file:edu.cloud.iot.reception.ocr.FaceRecognitionActivity.java

public void saveImage(String pPath, String pDir, Bitmap img) {
    try {/*www.  ja v a  2s . c  o  m*/
        FileOutputStream fos = new FileOutputStream(pPath + pDir);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        // Compress Bitmap Image
        image.compress(Bitmap.CompressFormat.JPEG, 50, bos);
        bos.flush();
        bos.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.v("EDebug::FaceRecognitionActivity", ex.getMessage());
    }
}

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

@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
@ResponseBody/*w w  w.  j av a2 s  .  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:org.jboss.ejb3.packagemanager.retriever.impl.HttpPackageRetriever.java

/**
 * @see org.jboss.ejb3.packagemanager.retriever.PackageRetriever#retrievePackage(PackageManagerContext, URL)
 *//*w w w.  j  a va  2s.c om*/
@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

}