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:gov.nih.nci.ncicb.tcga.dcc.dam.usage.UsageLoggerFileImplFastTest.java

public static Map<String, Map<String, String>> parseLog(UsageLoggerFileImpl logger) throws IOException {

    BufferedReader logFile = null;

    try {//from   w  ww  . j a v a2  s  .  c  om
        Map<String, Map<String, String>> log = new HashMap<String, Map<String, String>>();
        //noinspection IOResourceOpenedButNotSafelyClosed
        logFile = new BufferedReader(new FileReader(logger.getFile()));
        String line = logFile.readLine();
        Pattern actionPattern = Pattern.compile("^\\[(.+)\\](.+)=(.*)@(.+)$");
        while (line != null) {
            Matcher m = actionPattern.matcher(line);
            if (m.matches()) {
                String sessionId = m.group(1);
                String actionName = m.group(2);
                String value = m.group(3);
                String date = m.group(4);
                if (value.length() == 0) {
                    value = date;
                }
                Map<String, String> sessionLog = log.get(sessionId);
                if (sessionLog == null) {
                    sessionLog = new HashMap<String, String>();
                    log.put(sessionId, sessionLog);
                }
                sessionLog.put(actionName, value);
            }
            line = logFile.readLine();
        }
        return log;
    } finally {
        IOUtils.closeQuietly(logFile);
    }
}

From source file:au.org.emii.geoserver.extensions.filters.layer.data.io.FilterConfigurationFile.java

private List<Filter> readFilters(File file) throws ParserConfigurationException, SAXException, IOException {
    FileInputStream fileInputStream = null;
    try {/*from   ww  w .ja v a 2 s .c o  m*/
        fileInputStream = new FileInputStream(file);
        return getReader().read(fileInputStream).getFilters();
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:com.comcast.video.dawg.show.video.BufferedImageCerealizer.java

/**
 * {@inheritDoc}/*w w  w. j  a va2  s . c o  m*/
 */
@Override
public BufferedImage deCerealize(String cereal, ObjectCache objectCache) throws CerealException {
    byte[] data = Base64.decodeBase64(cereal);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    try {
        try {
            return ImageIO.read(bais);
        } catch (IOException e) {
            throw new CerealException("Failed to deCerealize BufferedImage", e);
        }
    } finally {
        IOUtils.closeQuietly(bais);
    }
}

From source file:net.dontdrinkandroot.lastfm.api.CheckImplementationStatus.java

public static void main(final String[] args) throws DocumentException, IOException {

    CheckImplementationStatus.xmlReader = new Parser();
    CheckImplementationStatus.saxReader = new SAXReader(CheckImplementationStatus.xmlReader);

    final String packagePrefix = "net.dontdrinkandroot.lastfm.api.model.";

    final Map<String, Map<String, URL>> packages = CheckImplementationStatus.parseOverview();

    final StringBuffer html = new StringBuffer();
    html.append("<html>\n");
    html.append("<head>\n");
    html.append("<title>Implementation Status</title>\n");
    html.append("</head>\n");
    html.append("<body>\n");
    html.append("<h1>Implementation Status</h1>\n");

    final StringBuffer wiki = new StringBuffer();

    int numImplemented = 0;
    int numTested = 0;
    int numMethods = 0;

    final List<String> packageList = new ArrayList<String>(packages.keySet());
    Collections.sort(packageList);

    for (final String pkg : packageList) {

        System.out.println("Parsing " + pkg);
        html.append("<h2>" + pkg + "</h2>\n");
        wiki.append("\n===== " + pkg + " =====\n\n");

        Class<?> modelClass = null;
        final String className = packagePrefix + pkg;
        try {/*from w w  w.  j  a  v a  2  s.  co m*/
            modelClass = Class.forName(className);
            System.out.println("\tClass " + modelClass.getName() + " exists");
        } catch (final ClassNotFoundException e) {
            // e.printStackTrace();
            System.out.println("\t" + className + ": DOES NOT exist");
        }

        Class<?> testClass = null;
        final String testClassName = packagePrefix + pkg + "Test";
        try {
            testClass = Class.forName(testClassName);
            System.out.println("\tTestClass " + testClass.getName() + " exists");
        } catch (final ClassNotFoundException e) {
            // e.printStackTrace();
            System.out.println("\t" + testClassName + ": TestClass for DOES NOT exist");
        }

        final List<String> methods = new ArrayList<String>(packages.get(pkg).keySet());
        Collections.sort(methods);

        final Method[] classMethods = modelClass.getMethods();
        final Method[] testMethods = testClass.getMethods();

        html.append("<table>\n");
        html.append("<tr><th>Method</th><th>Implemented</th><th>Tested</th></tr>\n");
        wiki.append("^ Method  ^ Implemented  ^ Tested  ^\n");

        numMethods += methods.size();

        for (final String method : methods) {

            System.out.println("\t\t parsing " + method);

            html.append("<tr>\n");
            html.append("<td>" + method + "</td>\n");
            wiki.append("| " + method + "  ");

            boolean classMethodFound = false;
            for (final Method classMethod : classMethods) {
                if (classMethod.getName().equals(method)) {
                    classMethodFound = true;
                    break;
                }
            }

            if (classMethodFound) {
                System.out.println("\t\t\tMethod " + method + " found");
                html.append("<td style=\"background-color: green\">true</td>\n");
                wiki.append("| yes  ");
                numImplemented++;
            } else {
                System.out.println("\t\t\t" + method + " NOT found");
                html.append("<td style=\"background-color: red\">false</td>\n");
                wiki.append("| **no**  ");
            }

            boolean testMethodFound = false;
            final String testMethodName = "test" + StringUtils.capitalize(method);
            for (final Method testMethod : testMethods) {
                if (testMethod.getName().equals(testMethodName)) {
                    testMethodFound = true;
                    break;
                }
            }

            if (testMethodFound) {
                System.out.println("\t\t\tTestMethod " + method + " found");
                html.append("<td style=\"background-color: green\">true</td>\n");
                wiki.append("| yes  |\n");
                numTested++;
            } else {
                System.out.println("\t\t\t" + testMethodName + " NOT found");
                html.append("<td style=\"background-color: red\">false</td>\n");
                wiki.append("| **no**  |\n");
            }

            html.append("</tr>\n");

        }

        html.append("</table>\n");

        // for (String methodName : methods) {
        // URL url = pkg.getValue().get(methodName);
        // System.out.println("PARSING: " + pkg.getKey() + "." + methodName + ": " + url);
        // String html = loadIntoString(url);
        // String description = null;
        // Matcher descMatcher = descriptionPattern.matcher(html);
        // if (descMatcher.find()) {
        // description = descMatcher.group(1).trim();
        // }
        // boolean post = false;
        // Matcher postMatcher = postPattern.matcher(html);
        // if (postMatcher.find()) {
        // post = true;
        // }
        // Matcher paramsMatcher = paramsPattern.matcher(html);
        // List<String[]> params = new ArrayList<String[]>();
        // boolean authenticated = false;
        // if (paramsMatcher.find()) {
        // String paramsString = paramsMatcher.group(1);
        // Matcher paramMatcher = paramPattern.matcher(paramsString);
        // while (paramMatcher.find()) {
        // String[] param = new String[3];
        // param[0] = paramMatcher.group(1);
        // param[1] = paramMatcher.group(3);
        // param[2] = paramMatcher.group(5);
        // // System.out.println(paramMatcher.group(1) + "|" + paramMatcher.group(3) + "|" +
        // paramMatcher.group(5));
        // if (param[0].equals("")) {
        // /* DO NOTHING */
        // } else if (param[0].equals("api_key")) {
        // /* DO NOTHING */
        // } else if (param[0].equals("api_sig")) {
        // authenticated = true;
        // } else {
        // params.add(param);
        // }
        // }
        // }
        // }
        // count++;
        //
    }

    html.append("<hr />");
    html.append("<p>" + numImplemented + "/" + numMethods + " implemented (" + numImplemented * 100 / numMethods
            + "%)</p>");
    html.append("<p>" + numTested + "/" + numMethods + " tested (" + numTested * 100 / numMethods + "%)</p>");

    html.append("</body>\n");
    html.append("</html>\n");

    FileOutputStream out = new FileOutputStream(new File(FileUtils.getTempDirectory(), "apistatus.html"));
    IOUtils.write(html, out);
    IOUtils.closeQuietly(out);

    out = new FileOutputStream(new File(FileUtils.getTempDirectory(), "apistatus.wiki.txt"));
    IOUtils.write(wiki, out);
    IOUtils.closeQuietly(out);
}

From source file:com.codebutler.farebot.card.TagReader.java

@NonNull
public C readTag() throws Exception {
    T tech = getTech(mTag);/*from   w  w w .  j a v a  2s  .c o m*/
    try {
        tech.connect();
        return readTag(mTagId, mTag, tech, mCardKeys);
    } finally {
        if (tech.isConnected()) {
            IOUtils.closeQuietly(tech);
        }
    }
}

From source file:com.tc.util.TCPropertyStoreTest.java

private void loadDefaults(String propFile, TCPropertyStore propertyStore) {
    InputStream in = TCPropertiesImpl.class.getResourceAsStream(propFile);
    if (in == null) {
        throw new AssertionError("TC Property file " + propFile + " not Found");
    }/*from  w  w  w .  jav a  2  s .  com*/
    try {
        propertyStore.load(in);
    } catch (IOException e) {
        throw new AssertionError(e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineServiceIntegrationTest.java

public void testImportRules() throws Exception {

    InputStream in = RuleUtil.getResouceAsStream("sae_reporting_rules_sponsor_org_ctep.xml");
    String xml = RuleUtil.getFileContext(in);
    System.out.println(xml);//  w w w. j  a  v a  2 s. c o  m
    File f = File.createTempFile("r_" + System.currentTimeMillis(), "sae.xml");
    System.out.println(f.getAbsolutePath());
    FileWriter fw = new FileWriter(f);
    IOUtils.write(xml, fw);
    IOUtils.closeQuietly(fw);
    assertTrue(f.exists());

    assertTrue(findRuleSets().isEmpty());

    service.importRules(f.getAbsolutePath());
    f.delete();
    List<RuleSet> ruleSets = findRuleSets();
    assertFalse(ruleSets.isEmpty());

    RuleSet rs = ruleSets.get(0);

    assertTrue(rs.isEnabled());

    String xml2 = service.exportRules(rs.getRuleBindURI());

    assertNotNull(xml2);

    f = File.createTempFile("r_" + System.currentTimeMillis(), "sae.xml");
    fw = new FileWriter(f);
    IOUtils.write(xml, fw);
    IOUtils.closeQuietly(fw);
    assertTrue(f.exists());

    List<String> outList = service.importRules(f.getAbsolutePath());
    f.delete();
    assertEquals(rs.getRuleBindURI(), outList.get(0));

    String xml3 = service.exportRules(rs.getRuleBindURI());
    assertNotNull(xml3);

}

From source file:de.fhg.iais.cortex.guice.modules.PropertiesModule.java

public PropertiesModule(String fileName) throws IOException {
    this.properties = new Properties();

    Reader reader = new InputStreamReader(new FileInputStream(fileName), Charsets.UTF_8);
    try {// w  w w .  j  a  va  2s  .  c o m
        this.properties.load(reader);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.ettrema.httpclient.Utils.java

public static HttpResult executeHttpWithResult(HttpClient client, HttpUriRequest m, OutputStream out)
        throws IOException {
    HttpResponse resp = client.execute(m);
    HttpEntity entity = resp.getEntity();
    if (entity != null) {
        InputStream in = null;/*from   w  ww  .  ja va  2 s . c  o  m*/
        try {
            in = entity.getContent();
            if (out != null) {
                IOUtils.copy(in, out);
            }
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
    Map<String, String> mapOfHeaders = new HashMap<String, String>();
    for (Header h : resp.getAllHeaders()) {
        mapOfHeaders.put(h.getName(), h.getValue()); // TODO: should concatenate multi-valued headers
    }
    HttpResult result = new HttpResult(resp.getStatusLine().getStatusCode(), mapOfHeaders);
    return result;
}

From source file:net.orpiske.ssps.common.archive.CompressedArchiveUtils.java

/**
 * Decompress a file//  w ww.  jav  a 2  s. co  m
 * @param source the source file to be uncompressed
 * @param destination the destination directory
 * @return the number of bytes read
 * @throws IOException for lower level I/O errors
 */
public static long gzDecompress(File source, File destination) throws IOException {
    FileOutputStream out;

    prepareDestination(destination);
    out = new FileOutputStream(destination);

    FileInputStream fin = null;
    BufferedInputStream bin = null;
    GzipCompressorInputStream gzIn = null;

    try {
        fin = new FileInputStream(source);
        bin = new BufferedInputStream(fin);
        gzIn = new GzipCompressorInputStream(bin);

        IOUtils.copy(gzIn, out);

        gzIn.close();

        fin.close();
        bin.close();
        out.close();
    } catch (IOException e) {
        IOUtils.closeQuietly(out);

        IOUtils.closeQuietly(fin);
        IOUtils.closeQuietly(bin);
        IOUtils.closeQuietly(gzIn);

        throw e;
    }

    return gzIn.getBytesRead();
}