Example usage for java.io OutputStream flush

List of usage examples for java.io OutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.arcanix.php.phar.PharEntry.java

public PharEntry(final File file, final String localPath, final PharCompression pharCompression)
        throws IOException {
    this.file = file;
    this.localPath = localPath;
    this.pharCompression = pharCompression;

    byte[] uncompressedBytes = Files.readAllBytes(this.file.toPath());
    this.checksum = new CRC32();
    this.checksum.update(uncompressedBytes);

    ByteArrayOutputStream compressed = new ByteArrayOutputStream();

    OutputStream compressor = null;
    try {//from   ww  w . jav  a  2s.c  om
        compressor = getCompressorOutputStream(compressed);
        Files.copy(this.file.toPath(), compressor);
        compressor.flush();
    } finally {
        compressor.close();
    }

    this.compressedBytes = compressed.toByteArray();
}

From source file:com.brienwheeler.lib.io.ReconnectingSocket.java

private void tryToWrite(byte data[]) {
    Socket writeSocket = socket.get();
    if (writeSocket == null)
        return;//from   w  w  w.jav a  2  s  .  c  o  m

    try {
        OutputStream outputStream = writeSocket.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
    } catch (IOException e) {
        if (socket.compareAndSet(writeSocket, null)) {
            log.error("error writing to " + hostname, e);
            onDisconnected();
            startConnectThread(reconnectPeriodicity);
            try {
                writeSocket.close();
            } catch (IOException e1) {
                // silent
            }
        }
    }
}

From source file:com.thoughtworks.studios.shine.cruise.stage.details.StageStorage.java

public void save(Graph graph) {
    StageIdentifier identifier = extractStageIdentifier(graph);

    if (isStageStored(identifier)) {
        return;/*w ww  . j  a va  2 s. com*/
    }

    synchronized (stageKey(identifier)) {
        if (isStageStored(identifier)) {
            return;
        }

        File file = new File(tmpStagePath(identifier));

        file.getParentFile().mkdirs();
        try {
            OutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file)));
            graph.persistToTurtle(os);
            os.flush();
            os.close();
            file.renameTo(new File(stagePath(identifier)));
        } catch (IOException e) {
            throw new ShineRuntimeException(e);
        } finally {
            file.delete();
        }
    }
}

From source file:de.knowwe.revisions.manager.action.DownloadRevisionZip.java

@Override
public void execute(UserActionContext context) throws IOException {
    if (context.getParameters().containsKey("date")) {
        String dateParam = context.getParameter("date");
        Date date;//w w w.j a  v  a2 s .c  om
        try {
            date = new Date(Long.parseLong(dateParam));

            String filename = "revision-" + DATE_FORMAT.format(date) + ".zip";
            context.setContentType("application/force-download");
            context.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
            OutputStream outs = context.getOutputStream();
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(outs));
            zipRev(date, zos, context);
            outs.flush();
            outs.close();
        } catch (Exception e) {
            context.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.valueOf(e));
            e.printStackTrace();
        }

    }
}

From source file:it.flosslab.mvc.presentation.action.anagrafica.AnagraficaAction.java

private ActionForward performSearch(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String tipo) {
    SoggettoDelegate soggettoDelegate = SoggettoDelegate.getInstance();
    List<SoggettoVO> soggetti = new ArrayList<SoggettoVO>();
    if ("F".equals(tipo)) {
        String prefixSurname = request.getParameter("q").toLowerCase();
        soggetti = soggettoDelegate.getListaPersonaFisica(1, prefixSurname, "", "");
    }//from w ww.ja  va 2 s.c o  m
    if ("G".equals(tipo)) {
        String denominazione = request.getParameter("q").toLowerCase();
        soggetti = soggettoDelegate.getListaPersonaGiuridica(1, denominazione, "");
    }
    try {
        OutputStream out = response.getOutputStream();
        response.setContentType("text/plain");
        IOUtils.write(this.createRenderedList(soggetti, tipo), out);
        out.flush();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:com.orange.clara.cloud.servicedbdumper.filer.compression.GzipCompressing.java

@Async
public Future<Boolean> gziptIt(InputStream inputStream, OutputStream outputStream) throws IOException {
    logger.debug("Start compressing...");
    GZIPOutputStream gout = new GZIPOutputStream(outputStream);
    ByteStreams.copy(inputStream, gout);
    gout.flush();//ww  w  .java  2  s. com
    gout.close();
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    logger.debug("Finish compressing");
    return new AsyncResult<Boolean>(true);
}

From source file:com.baidu.jprotobuf.rpc.client.ProxyFactoryBeanTestBase.java

protected HttpServer createServer() throws Exception {

    servlet.init();/* ww w  .ja  va  2  s  .c  o  m*/

    HttpServerProvider provider = HttpServerProvider.provider();
    HttpServer httpserver = provider.createHttpServer(new InetSocketAddress(8080), 10);

    httpserver.createContext(getPathInfo(), new HttpHandler() {

        @Override
        public void handle(HttpExchange httpExchange) throws IOException {

            MockHttpServletRequest request = new MockHttpServletRequest();
            request.setPathInfo(getPathInfo());

            String queryString = httpExchange.getRequestURI().getRawQuery();

            if (queryString != null) {
                if (queryString.indexOf(ServiceExporter.INPUT_IDL_PARAMETER) != -1) {
                    request.addParameter(ServiceExporter.INPUT_IDL_PARAMETER, "");
                }
                if (queryString.indexOf(ServiceExporter.OUTPUT_IDL_PARAMETER) != -1) {
                    request.addParameter(ServiceExporter.OUTPUT_IDL_PARAMETER, "");
                }
            }

            request.setQueryString(queryString);
            InputStream requestBody = httpExchange.getRequestBody();
            request.setContent(IOUtils.toByteArray(requestBody));

            MockHttpServletResponse response = new MockHttpServletResponse();
            response.setOutputStreamAccessAllowed(true);

            try {
                servlet.service(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            }
            httpExchange.sendResponseHeaders(200, response.getContentLength());
            OutputStream out = httpExchange.getResponseBody(); // ?
            out.write(response.getContentAsByteArray());
            out.flush();
            httpExchange.close();
        }
    });
    httpserver.setExecutor(null);
    httpserver.start();

    return httpserver;
}

From source file:com.zlfun.framework.misc.UploadUtils.java

public static boolean download(HttpServletRequest request, HttpServletResponse response, String uuid) {

    InputStream bis;// w  ww.  j a  v  a  2s. c  o m
    boolean ret = false;
    try {

        byte[] voiceData = FsUtils.readFromDisk(uuid);
        if (voiceData != null) {
            long p = 0L;
            long toLength = 0L;
            long contentLength = 0L;
            int rangeSwitch = 0; // 0,1,?bytes=27000-2,???bytes=27000-39000
            long fileLength;
            String rangBytes = "";
            fileLength = voiceData.length;

            // get file content
            bis = new ByteArrayInputStream(voiceData);

            // tell the client to allow accept-ranges
            response.reset();
            response.setHeader("Accept-Ranges", "bytes");

            // client requests a file block download start byte
            String range = request.getHeader("Range");
            if (range != null && range.trim().length() > 0 && !"null".equals(range)) {
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
                rangBytes = range.replaceAll("bytes=", "");
                if (rangBytes.endsWith("-")) { // bytes=270000-
                    rangeSwitch = 1;
                    p = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                    contentLength = fileLength - p; // 270000?bytes270000
                } else { // bytes=270000-320000
                    rangeSwitch = 2;
                    String temp1 = rangBytes.substring(0, rangBytes.indexOf("-"));
                    String temp2 = rangBytes.substring(rangBytes.indexOf("-") + 1, rangBytes.length());
                    p = Long.parseLong(temp1);
                    toLength = Long.parseLong(temp2);
                    contentLength = toLength - p + 1; // 
                    // 270000-320000
                    // 
                }
            } else {
                contentLength = fileLength;
            }

            // Content-Length?????
            // Content-Length: [?] - [?]
            response.setHeader("Content-Length", new Long(contentLength).toString());

            // 
            // ??:
            // Content-Range: bytes [?]-[? - 1]/[?]
            if (rangeSwitch == 1) {
                String contentRange = new StringBuffer("bytes ").append(new Long(p).toString()).append("-")
                        .append(new Long(fileLength - 1).toString()).append("/")
                        .append(new Long(fileLength).toString()).toString();
                response.setHeader("Content-Range", contentRange);
                bis.skip(p);
            } else if (rangeSwitch == 2) {
                String contentRange = range.replace("=", " ") + "/" + new Long(fileLength).toString();
                response.setHeader("Content-Range", contentRange);
                bis.skip(p);
            } else {
                String contentRange = new StringBuffer("bytes ").append("0-").append(fileLength - 1).append("/")
                        .append(fileLength).toString();
                response.setHeader("Content-Range", contentRange);
            }

            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", getContentDisposition(request, uuid));

            OutputStream out = response.getOutputStream();

            int n = 0;
            long readLength = 0;
            int bsize = 1024;
            byte[] bytes = new byte[bsize];
            if (rangeSwitch == 2) {
                //  bytes=27000-39000 27000?
                while (readLength <= contentLength - bsize) {
                    n = bis.read(bytes);
                    readLength += n;
                    out.write(bytes, 0, n);
                }
                if (readLength <= contentLength) {
                    n = bis.read(bytes, 0, (int) (contentLength - readLength));
                    out.write(bytes, 0, n);
                }
            } else {
                while ((n = bis.read(bytes)) != -1) {
                    out.write(bytes, 0, n);
                }
            }
            out.flush();
            out.close();
            bis.close();
            return true;
        } else {
            return false;
        }
    } catch (IOException ex) {
        //  ClientAbortException 
        Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }

}

From source file:com.yohanliyanage.jenkins.plugins.sparkdeploy.deployer.DeploymentManager.java

@SuppressWarnings("unchecked")
private Map<String, Object> invokeUrl(String method, URL url, String payload) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setRequestProperty("Accept", "application/json");

    if (payload != null) {
        if (verbose) {
            logger.println("[Spark-Deployer] VERBOSE : Invoking URL: " + method + " " + url.toString()
                    + " with payload : \n" + payload);
        }//  ww w  . ja  v  a2  s .  c  o m
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStream os = connection.getOutputStream();
        os.write(payload.getBytes());
        os.flush();
    } else {
        if (verbose) {
            logger.println("[Spark-Deployer] VERBOSE : Invoking URL " + method + " " + url.toString());
        }
    }

    InputStream responseStream;

    if (isSuccessResponseCode(connection.getResponseCode())) {
        // 2xx - Success
        responseStream = connection.getInputStream();
    } else {
        responseStream = connection.getErrorStream();
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));

    StringBuilder response = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        response.append(line).append(System.lineSeparator());
    }

    if (verbose) {
        logger.println("[Spark-Deployer] VERBOSE : Response from Spark : \n" + response);
    }

    if (!isSuccessResponseCode(connection.getResponseCode())) {
        throw new RuntimeException("Operation Failed. Response is " + connection.getResponseCode() + " : "
                + connection.getResponseMessage());
    }

    return (Map) mapper.readValue(response.toString(), HashMap.class);
}