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.thoughtworks.go.server.service.SystemService.java

public void streamToFile(InputStream stream, File dest) throws IOException {
    dest.getParentFile().mkdirs();/*from w  ww  . ja  v a2 s . c  om*/
    FileOutputStream out = new FileOutputStream(dest, true);
    try {
        IOUtils.copyLarge(stream, out);
    } finally {
        IOUtils.closeQuietly(out);
    }

}

From source file:com.oprisnik.semdroid.app.parser.manifest.AXMLConverter.java

public static String getManifestString(File apk) {
    String result = null;//from  ww w  . j a v  a 2 s .c o  m
    ZipInputStream zis = null;
    FileInputStream fis = null;
    try {

        fis = new FileInputStream(apk);

        zis = new ZipInputStream(fis);
        for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
            if (entry.getName().equals("AndroidManifest.xml")) {
                result = getManifestString(zis);
                break;
            }
        }
    } catch (FileNotFoundException e) {
        IOUtils.closeQuietly(fis);
    } catch (IOException e) {
    } finally {
        IOUtils.closeQuietly(zis);
    }
    return result;
}

From source file:com.thinkbiganalytics.discovery.util.ParserHelper.java

/**
 * Extracts the given number of rows from the file and returns a new reader for the sample.
 * This method protects memory in the case where a large file can be submitted with no delimiters.
 *///from   w w w .  jav  a2 s.  co  m
public static String extractSampleLines(InputStream is, Charset charset, int rows) throws IOException {

    StringWriter sw = new StringWriter();
    Validate.notNull(is, "empty input stream");
    Validate.notNull(charset, "charset cannot be null");
    Validate.exclusiveBetween(1, MAX_ROWS, rows, "invalid number of sample rows");

    // Sample the file in case there are no newlines
    StringWriter swBlock = new StringWriter();
    IOUtils.copyLarge(new InputStreamReader(is, charset), swBlock, -1, MAX_CHARS);
    try (BufferedReader br = new BufferedReader(new StringReader(swBlock.toString()))) {
        IOUtils.closeQuietly(swBlock);
        String line = br.readLine();
        int linesRead = 0;
        for (int i = 1; i <= rows && line != null; i++) {
            sw.write(line);
            sw.write("\n");
            linesRead++;
            line = br.readLine();
        }
        if (linesRead <= 1 && sw.toString().length() >= MAX_CHARS) {
            throw new IOException("Failed to detect newlines for sample file.");
        }
    }

    return sw.toString();
}

From source file:dotplugin.GraphViz.java

private static File execute(final InputStream input, String format) throws CoreException {
    MultiStatus status = new MultiStatus(Activator.ID, 0, "Errors occurred while running Graphviz", null);
    // we keep the input in memory so we can include it in error messages
    ByteArrayOutputStream dotContents = new ByteArrayOutputStream();
    File dotInput = null, dotOutput = null;
    try {//www.  j a v a  2  s. c o m
        // determine the temp input and output locations
        dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION);
        dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format);
        dotInput.deleteOnExit();
        dotOutput.deleteOnExit();
        FileOutputStream tmpDotInputStream = null;
        try {

            IOUtils.copy(input, dotContents);
            tmpDotInputStream = new FileOutputStream(dotInput);
            IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotInputStream);
        } finally {

            IOUtils.closeQuietly(tmpDotInputStream);
        }

        IStatus result = runDot(format, dotInput, dotOutput);
        status.add(result);
        // status.add(logInput(dotContents));
        if (!result.isOK())
            LogUtils.log(status);
        return dotOutput;
    } catch (SWTException e) {
        status.add(new Status(IStatus.ERROR, Activator.ID, "", e));
    } catch (IOException e) {
        status.add(new Status(IStatus.ERROR, Activator.ID, "", e));
    }
    throw new CoreException(status);
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.createdebate.CorpusPreparator.java

/**
 * Extracts all debates from raw HTML files in inFolder and stores them into outFolder
 * as serialized {@link Debate} objects (see {@link DebateSerializer}.
 *
 * @param inFolder     in folder//from w  ww  .j a v a 2 s .co  m
 * @param outFolder    out folder (must exist)
 * @param debateParser debate parser implementation
 * @throws IOException exception
 */
public static void extractAllDebates(File inFolder, File outFolder, DebateParser debateParser)
        throws IOException {
    File[] files = inFolder.listFiles();
    if (files == null) {
        throw new IOException("No such dir: " + inFolder);
    }

    for (File f : files) {
        InputStream inputStream = new FileInputStream(f);
        try {
            Debate debate = debateParser.parseDebate(inputStream);

            // we ignore empty debates (without arguments)
            if (debate != null && !debate.getArgumentList().isEmpty()) {
                // serialize to xml
                String xml = DebateSerializer.serializeToXML(debate);

                // same name with .xml
                File outputFile = new File(outFolder, f.getName() + ".xml");

                FileUtils.writeStringToFile(outputFile, xml, "utf-8");
                System.out.println("Saved to " + outputFile.getAbsolutePath());

                // ensure we can read it again
                DebateSerializer.deserializeFromXML(FileUtils.readFileToString(outputFile));
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

}

From source file:com.sitewhere.configuration.FileSystemGlobalConfigurationResolver.java

/**
 * Get contents of a file as a byte array.
 * //  w  w  w.j  av  a  2s.  com
 * @param file
 * @return
 * @throws SiteWhereException
 */
public static byte[] getFileQuietly(File file) throws SiteWhereException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        FileInputStream in = new FileInputStream(file);
        IOUtils.copy(in, out);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        return out.toByteArray();
    } catch (FileNotFoundException e) {
        throw new SiteWhereException(e);
    } catch (IOException e) {
        throw new SiteWhereException(e);
    }
}

From source file:ch.ralscha.extdirectspring_itest.ExceptionFormPostControlerTest.java

@After
public void afterTest() {
    IOUtils.closeQuietly(this.client);
}

From source file:com.qwazr.connectors.CassandraConnector.java

@Override
public void close() {
    if (cluster != null) {
        IOUtils.closeQuietly(cluster);
        cluster = null;
    }
}

From source file:gov.nih.nci.caintegrator.application.analysis.SegmentDatasetFileWriterTest.java

private void checkFile(File segFile, List<SegmentData> result) throws IOException {
    assertTrue(segFile.exists());/* w  w w  . j a v  a  2s .  co  m*/
    CSVReader reader = new CSVReader(new FileReader(segFile), '\t');
    checkLine(reader.readNext(), "Track Name", "Chromosome", "Start Position", "End Position", "Segment Value");
    checkLine(reader.readNext(), "Sample 1", "1", "1", "5", "0.1");
    checkLine(reader.readNext(), "Sample 2", "2", "6", "9", "0.2");
    IOUtils.closeQuietly(reader);
}

From source file:com.sap.research.connectivity.gw.GwUtils.java

public static void createClassFileFromTemplate(String packageName, String subFolder, String templateFileName,
        String targetFileName, Map<String, String> replacements, FileManager fileManager,
        Class<?> loadingClass) {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    String targetFile = subFolder + SEPARATOR + targetFileName;
    MutableFile mutableFile = fileManager.exists(targetFile) ? fileManager.updateFile(targetFile)
            : fileManager.createFile(targetFile);
    try {//from  w  ww  .j  a va  2 s  .  c om
        inputStream = FileUtils.getInputStream(loadingClass, templateFileName);
        outputStream = mutableFile.getOutputStream();
        String inputStreamString = IOUtils.toString(inputStream);

        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            inputStreamString = inputStreamString.replace(entry.getKey(), entry.getValue());
        }
        //System.out.println(inputStreamString);
        inputStream = IOUtils.toInputStream(inputStreamString);
        IOUtils.copy(inputStream, outputStream);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}