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:fr.olympicinsa.riocognized.ImageController.java

@RequestMapping("/download/{imageId}")
public String download(@PathVariable("imageId") Long imageId, HttpServletResponse response) {

    Image doc = imageRepository.findOne(imageId);
    try {//from w w w.  j av a 2s.co  m
        ByteArrayInputStream bis = new ByteArrayInputStream(doc.getContent());
        response.setHeader("Content-Disposition", "inline;filename=\"" + doc.getFilename() + "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType(doc.getContentType());
        IOUtils.copy(bis, out);
        out.flush();
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.cpjit.swagger4j.support.internal.DefaultApiViewWriter.java

@Deprecated
@Override//w  w w  . j a v  a  2  s  .c o m
public void writeApis(HttpServletRequest request, HttpServletResponse response, Properties props)
        throws Exception {
    APIParseable restParser = APIParser.newInstance(props);
    response.setContentType("application/json;charset=utf-8");
    String devMode = props.getProperty("devMode");
    if (Boolean.valueOf(devMode)) {
        Object apis = restParser.parseAndNotStore();
        JSONWriter writer = new JSONWriter(response.getWriter());
        writer.writeObject(apis);
        writer.flush();
        writer.close();
    } else {
        if (!scanfed) {
            restParser.parse();
            scanfed = true;
        }
        byte[] bs = Files.readAllBytes(Paths.get(props.getProperty("apiFile")));
        OutputStream out = response.getOutputStream();
        out.write(bs);
        out.flush();
        out.close();
    }
}

From source file:fr.olympicinsa.riocognized.AdvertController.java

@RequestMapping("")
public String getAdvert(HttpServletResponse response) {

    ImagePub ad = imageService.findOneRandom();
    try {/*w  w w  .  ja  v a  2 s  .  com*/
        ByteArrayInputStream bis = new ByteArrayInputStream(ad.getContent());
        response.setHeader("Content-Disposition", "inline;filename=\"" + ad.getFilename() + "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType(ad.getContentType());
        IOUtils.copy(bis, out);
        out.flush();
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:fr.olympicinsa.riocognized.AdvertController.java

@RequestMapping("/download/{imageId}")
public String download(@PathVariable("imageId") Long imageId, HttpServletResponse response) {

    ImagePub doc = imagePubRepository.findOne(imageId);
    try {//from w  w  w.j a v a  2  s .  c  o  m
        ByteArrayInputStream bis = new ByteArrayInputStream(doc.getContent());
        response.setHeader("Content-Disposition", "inline;filename=\"" + doc.getFilename() + "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType(doc.getContentType());
        IOUtils.copy(bis, out);
        out.flush();
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractServiceProviderLogoController.java

private void logoResponse(String imagePath, String defaultImagePath, HttpServletResponse response) {
    FileInputStream fileinputstream = null;
    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        try {/*from   w  w  w .  j  ava  2 s . com*/
            if (imagePath != null && !imagePath.trim().equals("")) {
                String absoluteImagePath = FilenameUtils.concat(rootImageDir, imagePath);
                fileinputstream = new FileInputStream(absoluteImagePath);
                if (fileinputstream != null) {
                    int numberBytes = fileinputstream.available();
                    byte bytearray[] = new byte[numberBytes];
                    fileinputstream.read(bytearray);
                    response.setContentType("image/" + FilenameUtils.getExtension(imagePath));
                    // TODO:Set Cache headers for browser to force browser to cache to reduce load
                    OutputStream outputStream = response.getOutputStream();
                    response.setContentLength(numberBytes);
                    outputStream.write(bytearray);
                    outputStream.flush();
                    outputStream.close();
                    fileinputstream.close();
                    return;
                }
            }
        } catch (FileNotFoundException e) {
            logger.debug("###File not found in retrieving logo");
        } catch (IOException e) {
            logger.debug("###IO Error in retrieving logo");
        }
    }
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", defaultImagePath);
}

From source file:com.github.cambierr.jcollector.sender.OpenTsdbHttp.java

@Override
public void send(ConcurrentLinkedQueue<Metric> _metrics) throws IOException {

    JSONArray entries = toJson(_metrics);

    if (entries.length() == 0) {
        return;//  w w w .  ja  v  a2s. co  m
    }

    HttpURLConnection conn = (HttpURLConnection) host.openConnection();
    if (auth != null) {
        conn.setRequestProperty("Authorization", auth.getAuth());
    }

    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

    OutputStream body = conn.getOutputStream();
    body.write(entries.toString().getBytes());
    body.flush();

    if (conn.getResponseCode() >= 400) {
        BufferedReader responseBody = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        String output;
        StringBuilder sb = new StringBuilder("Could not push data to OpenTSDB through ")
                .append(getClass().getSimpleName()).append("\n");
        while ((output = responseBody.readLine()) != null) {
            sb.append(output).append("\n");
        }
        Worker.logger.log(Level.WARNING, sb.toString());
        throw new IOException(conn.getResponseMessage() + " (" + conn.getResponseCode() + ")");
    }
}

From source file:com.mindquarry.jcr.xml.source.JCRSourceQueryTest.java

public void testQueryForBinary() throws InvalidNodeTypeDefException, ParseException, Exception {

    JCRNodeSource source = (JCRNodeSource) resolveSource(BASE_URL + "images/photo.png");

    assertNotNull(source);//from  w w  w.  jav a  2  s . c om
    assertEquals(false, source.exists());

    OutputStream os = source.getOutputStream();
    assertNotNull(os);

    String content = "foo is a bar";
    os.write(content.getBytes());
    os.flush();
    os.close();

    QueryResultSource qResult = (QueryResultSource) resolveSource(
            BASE_URL + "images?/*[contains(local-name(), 'photo.png')]");
    assertNotNull(qResult);

    Collection results = qResult.getChildren();
    assertEquals(1, results.size());

    Iterator it = results.iterator();
    JCRNodeSource rSrc = (JCRNodeSource) it.next();
    InputStream rSrcIn = rSrc.getInputStream();

    ByteArrayOutputStream actualOut = new ByteArrayOutputStream();
    IOUtils.copy(rSrcIn, actualOut);
    rSrcIn.close();

    assertEquals(content, actualOut.toString());
    actualOut.close();

    rSrc.delete();
}

From source file:me.ineson.demo.app.rest.SolarBodyEndpoint.java

@GET
@Path("{solarBodyId}/image")
public Response findImageById(@PathParam("solarBodyId") Long solarBodyId) {
    log.debug("Find solar body image by id {}", solarBodyId);

    SolarBodyImageRestClient client = new SolarBodyImageRestClient();
    SolarBodyImage image = client.findById(config.getStringManadtory(Config.SERVICE_REST_URL), solarBodyId);

    if (image == null) {
        return Response.status(Status.NOT_FOUND).build();
    }//www  . ja  v a  2  s. com

    return Response.ok().entity(new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            output.write(image.getImage());
            output.flush();
        }
    }).type(image.getContentType()).header("content-attachment", "filename=" + image.getFilename())
            .header("Content-Length", image.getImage().length).build();

    //return 
    //Response.ok(image, MediaType.APPLICATION_OCTET_STREAM).header("content-attachment; filename=image_from_server.png") .build();
}

From source file:ca.nrc.cadc.web.ServerToServerFTPTransfer.java

public void send(final OutputStreamWrapper outputStreamWrapper, final String filename) throws IOException {
    final FTPClient ftpClient = connect();
    ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
    ftpClient.enterLocalPassiveMode();// w ww. ja  v  a 2  s  .  c  om

    try {
        final OutputStream outputStream = ftpClient.storeFileStream(filename);

        outputStreamWrapper.write(outputStream);

        outputStream.flush();
        outputStream.close();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }
}

From source file:com.cloudbees.jenkins.support.SupportPlugin.java

public static void writeBundle(OutputStream outputStream, final List<Component> components) throws IOException {
    StringBuilder manifest = new StringBuilder();
    StringWriter errors = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(errors);
    appendManifestHeader(manifest);/*  w w  w . ja  v a 2  s  .c o m*/
    List<Content> contents = appendManifestContents(manifest, errorWriter, components);
    contents.add(new StringContent("manifest.md", manifest.toString()));
    try {
        try (BulkChange change = new BulkChange(ContentMappings.get());
                ZipArchiveOutputStream binaryOut = new ZipArchiveOutputStream(
                        new BufferedOutputStream(outputStream, 16384))) {
            Optional<ContentFilter> maybeFilter = getContentFilter();
            Optional<FilteredOutputStream> maybeFilteredOut = maybeFilter
                    .map(filter -> new FilteredOutputStream(binaryOut, filter));
            OutputStream textOut = maybeFilteredOut.map(OutputStream.class::cast).orElse(binaryOut);
            OutputStreamSelector selector = new OutputStreamSelector(() -> binaryOut, () -> textOut);
            IgnoreCloseOutputStream unfilteredOut = new IgnoreCloseOutputStream(binaryOut);
            IgnoreCloseOutputStream filteredOut = new IgnoreCloseOutputStream(selector);
            for (Content content : contents) {
                if (content == null) {
                    continue;
                }
                final String name = maybeFilter.map(filter -> filter.filter(content.getName()))
                        .orElseGet(content::getName);
                final ZipArchiveEntry entry = new ZipArchiveEntry(name);
                entry.setTime(content.getTime());
                try {
                    binaryOut.putArchiveEntry(entry);
                    binaryOut.flush();
                    OutputStream out = content.shouldBeFiltered() ? filteredOut : unfilteredOut;
                    if (content instanceof PrefilteredContent && maybeFilter.isPresent()) {
                        ((PrefilteredContent) content).writeTo(out, maybeFilter.get());
                    } else {
                        content.writeTo(out);
                    }
                    out.flush();
                } catch (Throwable e) {
                    String msg = "Could not attach ''" + name + "'' to support bundle";
                    logger.log(Level.WARNING, msg, e);
                    errorWriter.println(msg);
                    errorWriter
                            .println("-----------------------------------------------------------------------");
                    errorWriter.println();
                    SupportLogFormatter.printStackTrace(e, errorWriter);
                    errorWriter.println();
                } finally {
                    maybeFilteredOut.ifPresent(FilteredOutputStream::reset);
                    selector.reset();
                    binaryOut.closeArchiveEntry();
                }
            }
            errorWriter.close();
            String errorContent = errors.toString();
            if (StringUtils.isNotBlank(errorContent)) {
                try {
                    binaryOut.putArchiveEntry(new ZipArchiveEntry("manifest/errors.txt"));
                    textOut.write(errorContent.getBytes(StandardCharsets.UTF_8));
                    textOut.flush();
                    binaryOut.closeArchiveEntry();
                } catch (IOException e) {
                    logger.log(Level.WARNING, "Could not write manifest/errors.txt to zip archive", e);
                }
            }
            binaryOut.flush();
            change.commit();
        }
    } finally {
        outputStream.flush();
    }
}