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:controller.LoadImageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from  ww  w  . ja  v a2  s .co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String iid = request.getParameter("param1");
    byte[] sImageBytes;
    try {

        Connection con = JdbcConnection.getConnection();
        String Query = "SELECT image FROM user WHERE email ='" + iid + "';";
        System.out.println("Query is" + Query);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(Query);
        System.out.println("..........1");
        String name = "client_2";
        if (rs.next()) {

            sImageBytes = rs.getBytes("image");

            response.setContentType("image/jpeg");
            response.setContentLength(sImageBytes.length);
            // Give the name of the image in the name variable in the below line   
            response.setHeader("Content-Disposition", "inline; filename=\"" + name + "\"");

            BufferedInputStream input = new BufferedInputStream(new ByteArrayInputStream(sImageBytes));
            BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[8192];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
                System.out.println(".......3");
            }
            output.flush();
        }
    } catch (Exception ex) {
        System.out.println("error :" + ex);
    }
}

From source file:com.commonsware.android.foredown.Downloader.java

@Override
public void onHandleIntent(Intent i) {
    try {/*from w  w w.  j a  v a 2 s.  co m*/
        String filename = i.getData().getLastPathSegment();

        startForeground(FOREGROUND_ID, buildForegroundNotification(filename));

        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        root.mkdirs();

        File output = new File(root, filename);

        if (output.exists()) {
            output.delete();
        }

        URL url = new URL(i.getData().toString());
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        FileOutputStream fos = new FileOutputStream(output.getPath());
        BufferedOutputStream out = new BufferedOutputStream(fos);

        try {
            InputStream in = c.getInputStream();
            byte[] buffer = new byte[8192];
            int len = 0;

            while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
            }

            out.flush();
        } finally {
            fos.getFD().sync();
            out.close();
            c.disconnect();
        }

        stopForeground(true);
        raiseNotification(i, output, null);
    } catch (IOException e2) {
        stopForeground(true);
        raiseNotification(i, null, e2);
    }
}

From source file:android.webkit.cts.CtsTestServer.java

private static FileEntity createFileEntity(String downloadId, int numBytes) throws IOException {
    String storageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equalsIgnoreCase(storageState)) {
        File storageDir = Environment.getExternalStorageDirectory();
        File file = new File(storageDir, downloadId + ".bin");
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
        byte data[] = new byte[1024];
        for (int i = 0; i < data.length; i++) {
            data[i] = 1;/*from ww  w.  j  av a 2  s .  co  m*/
        }
        try {
            for (int i = 0; i < numBytes / data.length; i++) {
                stream.write(data);
            }
            stream.write(data, 0, numBytes % data.length);
            stream.flush();
        } finally {
            stream.close();
        }
        return new FileEntity(file, "application/octet-stream");
    } else {
        throw new IllegalStateException("External storage must be mounted for this test!");
    }
}

From source file:edu.wustl.xipHost.caGrid.RetrieveNBIASecuredTest.java

@Test
public void test() throws Exception {
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    Login login = new GridLogin();
    String userName = "<JIRAusername>";
    String password = "<JIRApassword>";
    DcmFileFilter dcmFilter = new DcmFileFilter();
    login.login(userName, password);//from   w ww .  j  a v  a2 s.  co m
    GlobusCredential globusCred = login.getGlobusCredential();
    boolean isConnectionSecured = login.isConnectionSecured();
    logger.debug("Acquired NBIA GlobusCredential. Connection secured = " + isConnectionSecured);
    if (!isConnectionSecured) {
        fail("Unable to acquire NBIA GlobusCredential. Check username and password.");
        return;
    }
    NCIACoreServiceClient client = new NCIACoreServiceClient(gridServiceUrl, globusCred);
    client.setAnonymousPrefered(false);
    TransferServiceContextReference tscr = client.retrieveDicomDataBySeriesUID("1.3.6.1.4.1.9328.50.1.4718");
    TransferServiceContextClient tclient = new TransferServiceContextClient(tscr.getEndpointReference(),
            globusCred);
    InputStream istream = TransferClientHelper.getData(tclient.getDataTransferDescriptor(), globusCred);
    ZipInputStream zis = new ZipInputStream(istream);
    ZipEntryInputStream zeis = null;
    BufferedInputStream bis = null;
    File importDir = new File("./test-content/NBIA5");
    if (!importDir.exists()) {
        importDir.mkdirs();
    } else {
        File[] files = importDir.listFiles(dcmFilter);
        for (int j = 0; j < files.length; j++) {
            File file = files[j];
            file.delete();
        }
    }
    while (true) {
        try {
            zeis = new ZipEntryInputStream(zis);
        } catch (EOFException e) {
            break;
        } catch (IOException e) {
            logger.error(e, e);
        }
        String unzzipedFile = null;
        try {
            unzzipedFile = importDir.getCanonicalPath();
        } catch (IOException e) {
            logger.error(e, e);
        }
        logger.debug(" filename: " + zeis.getName());
        bis = new BufferedInputStream(zeis);
        byte[] data = new byte[8192];
        int bytesRead = 0;
        String retrievedFilePath = unzzipedFile + File.separator + zeis.getName();
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(retrievedFilePath));
            while ((bytesRead = (bis.read(data, 0, data.length))) != -1) {
                bos.write(data, 0, bytesRead);
            }
            bos.flush();
            bos.close();
        } catch (IOException e) {
            logger.error(e, e);
        }
    }
    try {
        zis.close();
        tclient.destroy();
    } catch (IOException e) {
        logger.error(e, e);
    }
    File[] retrievedFiles = importDir.listFiles(dcmFilter);
    int numbOfRetreivedFiles = retrievedFiles.length;
    assertEquals("Number of retrieved files should be 2 but is. " + numbOfRetreivedFiles, numbOfRetreivedFiles,
            2);
    //Assert file names. They should be equal to items' SeriesInstanceUIDs
    Map<String, File> mapRetrievedFiles = new HashMap<String, File>();
    for (int i = 0; i < numbOfRetreivedFiles; i++) {
        File file = retrievedFiles[i];
        mapRetrievedFiles.put(file.getName(), file);
    }
    boolean retrievedFilesCorrect = false;
    if (mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4716.dcm")
            && mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4720.dcm")) {
        retrievedFilesCorrect = true;
    }
    assertTrue("Retrieved files are not as expected.", retrievedFilesCorrect);
}

From source file:net.sf.nmedit.nomad.core.service.initService.ExplorerLocationMemory.java

public void shutdown() {
    Enumeration<TreeNode> nodes = Nomad.sharedInstance().getExplorer().getRoot().children();

    List<FileContext> locations = new ArrayList<FileContext>();
    TempDir tempDir = TempDir.generalTempDir();
    File userPatches = tempDir.getTempFile("patches");
    String canonicalPatches = null;
    try {/*  ww  w  .j a v  a2  s. c o  m*/
        canonicalPatches = userPatches.getCanonicalPath();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    while (nodes.hasMoreElements()) {
        TreeNode node = nodes.nextElement();
        if (node instanceof FileContext) {
            FileContext fc = (FileContext) node;
            try {
                if (!fc.getFile().getCanonicalPath().equals(canonicalPatches))
                    locations.add(fc);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Properties p = new Properties();
    writeProperties(p, locations);

    File file = getTempFile();

    BufferedOutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file));
        p.store(out, "this file is generated, do not edit it");
    } catch (IOException e) {
        // ignore
    } finally {
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:net.sourceforge.fenixedu.util.sibs.SibsOutgoingPaymentFile.java

public void save(final File destinationFile) {
    BufferedOutputStream outputStream = null;
    try {//  w ww. j  a v  a 2  s.co m
        outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile));
        outputStream.write(render().getBytes());
        outputStream.flush();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.apache.jackrabbit.standalone.cli.fs.ExportFileSystem.java

/**
 * Exports an nt:file to the file system
 * @param node/*ww w.ja v a2  s .  com*/
 *        the <code>Node</code>
 * @param file
 *        the <code>File</code>
 * @throws IOException
 *         if an IOException occurs
 * @throws CommandException
 *         if the <code>File</code> can't be created
 * @throws ValueFormatException
 *         if a <code>Value</code> can't be retrieved
 * @throws PathNotFoundException
 *         if the <code>Node</code> can't be found
 * @throws RepositoryException
 *         if the current working <code>Repository</code> throws an
 *         <code>Exception</code>
 */
private void createFile(Node node, File file)
        throws IOException, CommandException, ValueFormatException, PathNotFoundException, RepositoryException {

    boolean created = file.createNewFile();
    if (!created) {
        throw new CommandException("exception.file.not.created", new String[] { file.getPath() });
    }
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    InputStream in = node.getNode("jcr:content").getProperty("jcr:data").getStream();

    int c;

    while ((c = in.read()) != -1) {
        out.write(c);
    }
    in.close();
    out.flush();
    out.close();
}

From source file:com.gsr.myschool.server.reporting.excel.ExcelController.java

@RequestMapping(method = RequestMethod.GET, value = "/excel/multidossier", produces = "application/vnd.ms-excel")
public void generateMultiDossierExcel(@RequestParam String q, @RequestParam String annee,
        HttpServletResponse response) {//from   w  ww .ja  v a2s  . c  o m
    DossierStatus status = Strings.isNullOrEmpty(q) ? null : DossierStatus.valueOf(q);
    List<DossierMultiple> dossierMultiples = dossierService.findMultipleDossierByStatus(status, annee);

    try {
        response.addHeader("Content-Disposition",
                "attachment; filename=multidossier_" + System.currentTimeMillis() + ".xls");

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        xlsExportService.saveSpreadsheetRecords(DossierMultiple.class, dossierMultiples, outputStream);

        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wavemaker.StudioInstallService.java

public static File unzipFile(File zipfile) {
    int BUFFER = 2048;

    String zipname = zipfile.getName();
    int extindex = zipname.lastIndexOf(".");

    try {//from  w  w w.  jav  a  2s.c  om
        File zipFolder = new File(zipfile.getParentFile(), zipname.substring(0, extindex));
        if (zipFolder.exists())
            org.apache.commons.io.FileUtils.deleteDirectory(zipFolder);
        zipFolder.mkdir();

        File currentDir = zipFolder;
        //File currentDir = zipfile.getParentFile();

        BufferedOutputStream dest = null;
        FileInputStream fis = new FileInputStream(zipfile.toString());
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                File f = new File(currentDir, entry.getName());
                if (f.exists())
                    f.delete(); // relevant if this is the top level folder
                f.mkdir();
            } else {
                int count;
                byte data[] = new byte[BUFFER];
                //needed for non-dir file ace/ace.js created by 7zip
                File destFile = new File(currentDir, entry.getName());
                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(currentDir.toString() + "/" + entry.getName());
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
        zis.close();

        return currentDir;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (File) null;

}

From source file:com.gsr.myschool.server.reporting.bilan.BilanController.java

@RequestMapping(method = RequestMethod.GET, produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)//  ww w  . j ava  2s.c o  m
public void generateBilan(@RequestParam(defaultValue = "") String status, @RequestParam String type,
        @RequestParam(required = false) String annee, @RequestParam(required = false) Boolean historic,
        HttpServletResponse response) {
    ReportDTO dto = null;
    Integer bilanType;
    DossierStatus dossierStatus = null;
    ValueList anneeScolaire;
    try {
        bilanType = Integer.parseInt(type);
        if (!Strings.isNullOrEmpty(status)) {
            dossierStatus = DossierStatus.valueOf(status);
        }
        anneeScolaire = valueListRepos.findByValueAndValueTypeCode(annee, ValueTypeCode.SCHOOL_YEAR);
        if (anneeScolaire == null) {
            anneeScolaire = getCurrentScholarYear();
        }
    } catch (Exception e) {
        return;
    }
    if (historic) {
        if (BilanType.CYCLE.ordinal() == bilanType) {
            dto = getReportCycleHistoric(status, dossierStatus, anneeScolaire);
        } else if (BilanType.NIVEAU_ETUDE.ordinal() == bilanType) {
            dto = getReportNiveauEtudeHistoric(status, dossierStatus, anneeScolaire);
        }
    } else {
        if (BilanType.CYCLE.ordinal() == bilanType) {
            dto = getReportCycle(status, dossierStatus, anneeScolaire);
        } else if (BilanType.NIVEAU_ETUDE.ordinal() == bilanType) {
            dto = getReportNiveauEtude(status, dossierStatus, anneeScolaire);
        }
    }

    try {
        response.addHeader("Content-Disposition", "attachment; filename=" + dto.getFileName());

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte[] result = reportService.generatePdf(dto);

        outputStream.write(result, 0, result.length);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}