Example usage for com.google.common.io Closeables closeQuietly

List of usage examples for com.google.common.io Closeables closeQuietly

Introduction

In this page you can find the example usage for com.google.common.io Closeables closeQuietly.

Prototype

public static void closeQuietly(@Nullable Reader reader) 

Source Link

Document

Closes the given Reader , logging any IOException that's thrown rather than propagating it.

Usage

From source file:net.sourceforge.vaticanfetcher.util.ConfLoader.java

/**
 * Loads the preferences from the given file, with <tt>containerClass</tt> as the class containing the preferences 
 * enum classes, and returns a list of entries where the value is missing or does not have the proper structure.
 * <p>/*  www.  j av a 2 s  .  c  om*/
 * If <tt>createIfMissing</tt> is true, the given file is created if it doesn't exist. 
 * Otherwise a {@link FileNotFoundException} is thrown.
 */
// TODO doc: containerClass must contain nested enums that implement Loadable or Storable
@MutableCopy
public static List<Loadable> load(File propFile, Class<?> containerClass, boolean createIfMissing)
        throws IOException, FileNotFoundException {
    if (!propFile.exists()) {
        if (createIfMissing)
            propFile.createNewFile();
        else
            throw new FileNotFoundException();
    }
    InputStream in = null;
    try {
        FileInputStream fin = new FileInputStream(propFile);
        FileLock lock = fin.getChannel().lock(0, Long.MAX_VALUE, true);
        try {
            in = new BufferedInputStream(fin);
            return load(in, containerClass);
        } finally {
            lock.release();
        }
    } finally {
        Closeables.closeQuietly(in);
    }
}

From source file:org.sonar.plugins.objectivec.violations.OCLintRuleRepository.java

@Override
public List<Rule> createRules() {
    BufferedReader reader = null;
    try {/*from   w  ww  . j a v  a 2s  . com*/
        reader = new BufferedReader(
                new InputStreamReader(getClass().getResourceAsStream(RULES_FILE), CharEncoding.UTF_8));
        return ocLintRuleParser.parse(reader);
    } catch (final IOException e) {
        throw new SonarException("Fail to load the default OCLint rules.", e);
    } finally {
        Closeables.closeQuietly(reader);
    }
}

From source file:org.sonar.plugins.swift.issues.swiftlint.SwiftLintProfile.java

@Override
public RulesProfile createProfile(ValidationMessages messages) {
    LOGGER.info("Creating SwiftLint Profile");
    Reader config = null;//from   ww  w . ja  v  a  2 s  . c  om

    try {
        config = new InputStreamReader(getClass().getResourceAsStream(PROFILE_PATH));
        final RulesProfile profile = profileImporter.importProfile(config, messages);
        profile.setName(SwiftLintRulesDefinition.REPOSITORY_KEY);
        profile.setLanguage(Swift.KEY);

        return profile;
    } finally {
        Closeables.closeQuietly(config);
    }
}

From source file:org.richfaces.cdk.resource.writer.impl.ThroughputResourceProcessor.java

@Override
public void process(String resourceName, InputStream in, OutputStream out, boolean closeAtFinish)
        throws IOException {
    try {//  w w w  .java 2s.c  o m
        ByteStreams.copy(in, out);
    } finally {
        Closeables.closeQuietly(in);
        if (closeAtFinish) {
            Closeables.closeQuietly(out);
        } else {
            out.flush();
        }
    }
}

From source file:org.sonar.plugins.android.lint.AndroidLintRuleParser.java

public List<Rule> parse(File file) {
    BufferedReader reader = null;
    try {//from   w  ww.  ja  v  a 2 s. c om
        reader = new BufferedReader(new InputStreamReader(FileUtils.openInputStream(file), CharEncoding.UTF_8));
        return parse(reader);

    } catch (IOException e) {
        throw new SonarException("Fail to load the file: " + file, e);

    } finally {
        Closeables.closeQuietly(reader);
    }
}

From source file:org.sonar.javascript.checks.MissingNewlineAtEndOfFileCheck.java

@Override
public void visitFile(AstNode astNode) {
    RandomAccessFile randomAccessFile = null;
    try {/*from  ww w .j ava 2 s .co  m*/
        randomAccessFile = new RandomAccessFile(getContext().getFile(), "r");
        if (!endsWithNewline(randomAccessFile)) {
            getContext().createFileViolation(this, "Add a new line at the end of this file.");
        }
    } catch (IOException e) {
        throw new SonarException(e);
    } finally {
        Closeables.closeQuietly(randomAccessFile);
    }
}

From source file:com.notifier.desktop.tray.impl.SwtTrayManager.java

@Override
public boolean start() throws IOException {
    if (swtManager.getDisplay().getSystemTray() == null) {
        return false;
    }//from   w w  w. j  ava 2  s  .  c  o  m

    InputStream iconStream = getIconStream();
    try {
        trayImage = new Image(swtManager.getDisplay(), iconStream);
    } finally {
        Closeables.closeQuietly(iconStream);
    }

    Tray tray = swtManager.getDisplay().getSystemTray();
    trayItem = new TrayItem(tray, SWT.NONE);
    trayItem.setToolTipText(Application.NAME);
    trayItem.setImage(trayImage);

    final Menu menu = new Menu(swtManager.getShell(), SWT.POP_UP);

    MenuItem preferencesItem = new MenuItem(menu, SWT.PUSH);
    preferencesItem.setText("Preferences...");
    preferencesItem.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event event) {
            if (!swtManager.isShowingPreferencesDialog()) {
                PreferencesDialog preferencesDialog = preferencesDialogProvider.get();
                preferencesDialog.open();
            }
        }
    });

    MenuItem checkUpdatesItem = new MenuItem(menu, SWT.PUSH);
    checkUpdatesItem.setText("Check for Updates");
    checkUpdatesItem.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event event) {
            application.checkForUpdates();
        }
    });

    MenuItem openLogDirItem = new MenuItem(menu, SWT.PUSH);
    openLogDirItem.setText("Show Log");
    openLogDirItem.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event event) {
            Program.launch(OperatingSystems.getWorkDirectory());
        }
    });

    MenuItem aboutItem = new MenuItem(menu, SWT.PUSH);
    aboutItem.setText("About");
    aboutItem.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event event) {
            if (!swtManager.isShowingAboutDialog()) {
                Version version = application.getVersion();
                if (version != null) {
                    AboutDialog aboutDialog = new AboutDialog(version, swtManager);
                    aboutDialog.open();
                }
            }
        }
    });

    MenuItem quitItem = new MenuItem(menu, SWT.PUSH);
    quitItem.setText("Quit");
    quitItem.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event event) {
            application.shutdown();
        }
    });

    trayItem.addListener(SWT.MenuDetect, new Listener() {
        public void handleEvent(Event event) {
            menu.setVisible(true);
        }
    });

    // Double-click event
    if (OperatingSystems.CURRENT_FAMILY != OperatingSystems.Family.MAC) {
        trayItem.addSelectionListener(new SelectionListener() {
            @Override
            public void widgetSelected(SelectionEvent e) {
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent e) {
                if (!swtManager.isShowingPreferencesDialog()
                        && OperatingSystems.CURRENT_FAMILY != OperatingSystems.Family.MAC) {
                    PreferencesDialog preferencesDialog = preferencesDialogProvider.get();
                    preferencesDialog.open();
                }
            }
        });
    }

    return true;
}

From source file:org.apache.mahout.cf.taste.example.grouplens.GroupLensDataModel.java

private static File convertGLFile(File originalFile) throws IOException {
    // Now translate the file; remove commas, then convert "::" delimiter to comma
    File resultFile = new File(new File(System.getProperty("java.io.tmpdir")), "ratings.txt");
    if (resultFile.exists()) {
        resultFile.delete();//  w w  w .  ja  v a  2s .co  m
    }
    Writer writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(resultFile), Charsets.UTF_8);
        for (String line : new FileLineIterable(originalFile, false)) {
            int lastDelimiterStart = line.lastIndexOf(COLON_DELIMTER);
            if (lastDelimiterStart < 0) {
                throw new IOException("Unexpected input format on line: " + line);
            }
            String subLine = line.substring(0, lastDelimiterStart);
            String convertedLine = COLON_DELIMITER_PATTERN.matcher(subLine).replaceAll(",");
            writer.write(convertedLine);
            writer.write('\n');
        }
    } catch (IOException ioe) {
        resultFile.delete();
        throw ioe;
    } finally {
        Closeables.closeQuietly(writer);
    }
    return resultFile;
}

From source file:org.geogit.cli.plumbing.VerifyPatch.java

@Override
public void runInternal(GeogitCLI cli) throws IOException {
    checkParameter(patchFiles.size() < 2, "Only one single patch file accepted");
    checkParameter(!patchFiles.isEmpty(), "No patch file specified");

    ConsoleReader console = cli.getConsole();

    File patchFile = new File(patchFiles.get(0));
    checkParameter(patchFile.exists(), "Patch file cannot be found");
    FileInputStream stream;//from  w  w  w  .ja  va 2 s. c o  m
    try {
        stream = new FileInputStream(patchFile);
    } catch (FileNotFoundException e1) {
        throw new IllegalStateException("Can't open patch file " + patchFile);
    }
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        Closeables.closeQuietly(reader);
        Closeables.closeQuietly(stream);
        throw new IllegalStateException("Error reading patch file " + patchFile, e);
    }
    Patch patch = PatchSerializer.read(reader);
    Closeables.closeQuietly(reader);
    Closeables.closeQuietly(stream);

    VerifyPatchResults verify = cli.getGeogit().command(VerifyPatchOp.class).setPatch(patch).setReverse(reverse)
            .call();
    Patch toReject = verify.getToReject();
    Patch toApply = verify.getToApply();
    if (toReject.isEmpty()) {
        console.println("Patch can be applied.");
    } else {
        console.println("Error: Patch cannot be applied\n");
        console.println("Applicable entries:\n");
        console.println(toApply.toString());
        console.println("\nConflicting entries:\n");
        console.println(toReject.toString());
    }

}

From source file:com.fluxcapacitor.core.server.BaseNettyServer.java

@Override
public void close() {
    Closeables.closeQuietly(nettyServer);
    super.close();
}