Example usage for org.apache.commons.io IOUtils closeQuietly

List of usage examples for org.apache.commons.io IOUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils closeQuietly.

Prototype

public static void closeQuietly(OutputStream output) 

Source Link

Document

Unconditionally close an OutputStream.

Usage

From source file:com.alibaba.simpleimage.JPEGQualityTest.java

public void testQualityConsistent() throws Exception {
    for (File imgFile : quaDir.listFiles()) {
        if (imgFile.getName().indexOf("jpg") < 0) {
            continue;
        }/*  w  w  w.  j a v  a 2 s  .c  om*/

        InputStream in = new FileInputStream(imgFile);
        OutputStream out = new FileOutputStream(new File(resultDir, "QUALITY_" + imgFile.getName()));
        WriteRender wr = null;
        try {
            ReadRender rr = new ReadRender(in, true);
            wr = new WriteRender(rr, out);

            wr.render();
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

    ImageWrapper wi = null;

    wi = readImage(resultDir, "QUALITY_quality_80.jpg");
    assertTrue(wi.getQuality() == 80);

    wi = readImage(resultDir, "QUALITY_quality_90.jpg");
    assertTrue(wi.getQuality() == 90);

    wi = readImage(resultDir, "QUALITY_quality_95.jpg");
    assertTrue(wi.getQuality() == 95);

    wi = readImage(resultDir, "QUALITY_seq_1x1_1x1_1x1.jpg");
    for (int i = 0; i < 3; i++) {
        assertTrue(wi.getHorizontalSamplingFactor(0) == 1);
        assertTrue(wi.getVerticalSamplingFactor(0) == 1);
    }

    wi = readImage(resultDir, "QUALITY_seq_1x2_1x1_1x1.jpg");
    assertTrue(wi.getHorizontalSamplingFactor(0) == 1);
    assertTrue(wi.getVerticalSamplingFactor(0) == 2);
    assertTrue(wi.getHorizontalSamplingFactor(1) == 1);
    assertTrue(wi.getVerticalSamplingFactor(1) == 1);
    assertTrue(wi.getHorizontalSamplingFactor(2) == 1);
    assertTrue(wi.getVerticalSamplingFactor(2) == 1);

    wi = readImage(resultDir, "QUALITY_seq_2x1_1x1_1x1.jpg");
    assertTrue(wi.getHorizontalSamplingFactor(0) == 2);
    assertTrue(wi.getVerticalSamplingFactor(0) == 1);
    assertTrue(wi.getHorizontalSamplingFactor(1) == 1);
    assertTrue(wi.getVerticalSamplingFactor(1) == 1);
    assertTrue(wi.getHorizontalSamplingFactor(2) == 1);
    assertTrue(wi.getVerticalSamplingFactor(2) == 1);

    wi = readImage(resultDir, "QUALITY_seq_2x2_1x1_1x1.jpg");
    assertTrue(wi.getHorizontalSamplingFactor(0) == 2);
    assertTrue(wi.getVerticalSamplingFactor(0) == 2);
    assertTrue(wi.getHorizontalSamplingFactor(1) == 1);
    assertTrue(wi.getVerticalSamplingFactor(1) == 1);
    assertTrue(wi.getHorizontalSamplingFactor(2) == 1);
    assertTrue(wi.getVerticalSamplingFactor(2) == 1);
}

From source file:com.hyperaware.conference.android.eventmobi.fetcher.fetcher.StreamingFetcher.java

@Override
public T fetch() throws FetchException {
    InputStream is = null;/*from  w  w  w .  j  a v  a  2 s  .c o  m*/
    try {
        is = new BufferedInputStream(streamer.stream());
        return parser.parse(is);
    } catch (final Exception e) {
        throw new FetchException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:net.hamnaberg.rest.URIListHandler.java

public List<URI> handle(Payload payload) {
    List<URI> uris = new ArrayList<URI>();
    InputStream stream = payload.getInputStream();
    try {// ww w  .j a  v  a  2 s.  c  o m
        String value = IOUtils.toString(stream);
        String[] list = value.split("\r\n");
        for (String uri : list) {
            if (uri.charAt(0) == '#') {
                continue;
            }
            uris.add(URI.create(uri));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return uris;
}

From source file:com.alibaba.simpleimage.render.ScaleRenderTest.java

public void write(ImageRender sr) throws Exception {
    OutputStream output = null;/* w  ww . j  a  v a  2s. c o m*/
    ImageRender wr = null;
    try {
        output = new FileOutputStream(
                new File("./src/test/resources/conf.test/simpleimage/result/snow-result.jpg"));
        wr = new WriteRender(sr, output, ImageFormat.JPEG);
        wr.render();
    } finally {
        if (wr != null) {
            wr.dispose();
        }
        IOUtils.closeQuietly(output);
    }
}

From source file:com.junoyoon.BullsUtil.java

public static void copyResource(String toDir, String fileName) throws IOException {
    File file = new File(toDir);
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();//from w ww  . j  ava  2  s. c o  m
    }
    try {
        InputStream is = BullsUtil.class.getClassLoader().getResourceAsStream(fileName);
        FileOutputStream fs = new FileOutputStream(toDir);
        IOUtils.copy(is, fs);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(fs);
    } catch (Exception e) {
        BullsHtml.printErrorAndExit(e);
    }
}

From source file:gate.corpora.twitter.Population.java

/**
 * //  w w w.  j a v a  2  s . com
 * @param corpus
 * @param inputUrl
 * @param encoding
 * @param contentKeys
 * @param featureKeys
 * @param tweetsPerDoc 0 = put them all in one document; otherwise the number per document
 * @throws ResourceInstantiationException
 */
public static void populateCorpus(final Corpus corpus, URL inputUrl, String encoding, List<String> contentKeys,
        List<String> featureKeys, int tweetsPerDoc) throws ResourceInstantiationException {
    try {
        InputStream input = inputUrl.openStream();
        List<String> lines = IOUtils.readLines(input, encoding);
        IOUtils.closeQuietly(input);

        // TODO: sort this out so it processes one at a time instead of reading the
        // whole hog into memory

        // For now, we assume the streaming API format (concatenated maps, not in a list)
        List<Tweet> tweets = TweetUtils.readTweetStrings(lines, contentKeys, featureKeys);

        int digits = (int) Math.ceil(Math.log10(tweets.size()));
        int tweetCounter = 0;
        Document document = newDocument(inputUrl, tweetCounter, digits);
        StringBuilder content = new StringBuilder();
        Map<PreAnnotation, Integer> annotandaOffsets = new HashMap<PreAnnotation, Integer>();

        for (Tweet tweet : tweets) {
            if ((tweetsPerDoc > 0) && (tweetCounter > 0) && ((tweetCounter % tweetsPerDoc) == 0)) {
                closeDocument(document, content, annotandaOffsets, corpus);
                document = newDocument(inputUrl, tweetCounter, digits);
                content = new StringBuilder();
                annotandaOffsets = new HashMap<PreAnnotation, Integer>();
            }

            int startOffset = content.length();
            content.append(tweet.getString());
            for (PreAnnotation preAnn : tweet.getAnnotations()) {
                annotandaOffsets.put(preAnn, startOffset);
            }

            content.append('\n');
            tweetCounter++;
        } // end of Tweet loop

        if (content.length() > 0) {
            closeDocument(document, content, annotandaOffsets, corpus);
        } else {
            Factory.deleteResource(document);
        }

        if (corpus.getDataStore() != null) {
            corpus.getDataStore().sync(corpus);
        }

    } catch (Exception e) {
        throw new ResourceInstantiationException(e);
    }
}

From source file:com.deploymentio.cfnstacker.template.JsonFormatter.java

/**
 * Write formatted version of the given JSON string to the given file.
 *///from w  ww. ja va  2s.c o m
public void writeFormattedJSONString(JsonNode node, File file)
        throws IOException, JsonGenerationException, JsonMappingException {

    FileWriter writer = new FileWriter(file);
    mapper.writeValue(writer, node);

    IOUtils.closeQuietly(writer);
    logger.debug("Wrote formatted JSON: File=" + file.getAbsolutePath());
}

From source file:com.norconex.commons.lang.io.CachedOutputStreamTest.java

@Test
public void testContentMatchMemCache() throws IOException {
    String content = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    CachedStreamFactory factory = new CachedStreamFactory(200, 100);
    CachedOutputStream cache = factory.newOuputStream();
    InputStream is = null;/*from   w  ww. j a v  a  2  s  . co m*/

    try {
        cache.write(content.getBytes());
        is = cache.getInputStream();
        Assert.assertEquals(content, readCacheToString(is));
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(cache);
    }
}

From source file:com.alibaba.simpleimage.BaseTest.java

public ImageWrapper read(File file) throws Exception {
    ImageRender rr = null;/*www . ja  v a2s.co  m*/
    InputStream in = null;
    try {
        in = new FileInputStream(file);
        rr = new ReadRender(in);

        return rr.render();
    } finally {
        IOUtils.closeQuietly(in);
        if (rr != null) {
            rr.dispose();
        }
    }
}

From source file:com.sap.prd.mobile.ios.mios.Forker.java

static int forkProcess(final PrintStream out, final File executionDirectory, final String... args)
        throws IOException {

    if (out == null)
        throw new IllegalArgumentException("Print stream for log handling was not provided.");

    if (args == null || args.length == 0)
        throw new IllegalArgumentException("No arguments has been provided.");

    for (final String arg : args)
        if (arg == null || arg.isEmpty())
            throw new IllegalArgumentException(
                    "Invalid argument '" + arg + "' provided with arguments '" + Arrays.asList(args) + "'.");

    final ProcessBuilder builder = new ProcessBuilder(args);

    if (executionDirectory != null)
        builder.directory(executionDirectory);

    builder.redirectErrorStream(true);//  www.  jav  a 2 s.  c o  m

    InputStream is = null;

    //
    // TODO: check if there is any support for forking processes in
    // maven/plexus
    //

    try {

        final Process process = builder.start();

        is = process.getInputStream();

        handleLog(is, out);

        return process.waitFor();

    } catch (InterruptedException e) {
        throw new RuntimeException(e.getClass().getName()
                + " caught during while waiting for a forked process. This exception is not expected to be caught at that time.",
                e);
    } finally {
        //
        // Exception raised during close operation below are not reported.
        // That is actually bad.
        // We do not have any logging facility here and we cannot throw the
        // exception since this would swallow any
        // other exception raised in the try block.
        // May be we should revisit that ...
        //
        IOUtils.closeQuietly(is);
    }
}