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:com.nesscomputing.httpserver.log.file.FileRequestLog.java

@VisibleForTesting
void setWriter(final PrintWriter printWriter) {
    if (!requestLogWriterHolder.compareAndSet(null, printWriter)) {
        Closeables.closeQuietly(printWriter);
    }//from w w  w. java 2  s  . c  o  m
}

From source file:com.sonar.sslr.impl.Lexer.java

public List<Token> lex(URL url) {
    checkNotNull(url, "url cannot be null");

    InputStreamReader reader = null;
    try {/*from   w w w.  j av  a 2  s  .  c o m*/
        this.uri = url.toURI();

        reader = new InputStreamReader(url.openStream(), charset);
        return lex(reader);
    } catch (Exception e) {
        throw new LexerException("Unable to lex url: " + getURI(), e);
    } finally {
        Closeables.closeQuietly(reader);
    }
}

From source file:com.metamx.druid.index.v1.CompressedFloatsSupplierSerializer.java

public void closeAndConsolidate(OutputSupplier<? extends OutputStream> consolidatedOut) throws IOException {
    endBuffer.limit(endBuffer.position());
    endBuffer.rewind();/*from   ww  w .  ja va2  s  . c om*/
    flattener.write(StupidResourceHolder.create(endBuffer));
    endBuffer = null;

    flattener.close();

    OutputStream out = null;
    try {
        out = consolidatedOut.getOutput();

        out.write(CompressedFloatsIndexedSupplier.version);
        out.write(Ints.toByteArray(numInserted));
        out.write(Ints.toByteArray(sizePer));
        ByteStreams.copy(flattener.combineStreams(), out);
    } finally {
        Closeables.closeQuietly(out);
    }
}

From source file:com.metamx.druid.index.v1.MMappedIndexStorageAdapter.java

@Override
public DateTime getMaxTime() {
    final IndexedLongs timestamps = index.getReadOnlyTimestamps();
    final DateTime retVal = new DateTime(timestamps.get(timestamps.size() - 1));
    Closeables.closeQuietly(timestamps);
    return retVal;
}

From source file:org.apache.sqoop.connector.kite.KiteDatasetExecutor.java

/**
 * Closes the writer and releases any system resources.
 *///from w  w  w  .j  av  a2 s. c  o  m
public void closeWriter() {
    if (writer != null) {
        Closeables.closeQuietly(writer);
        writer = null;
    }
}

From source file:org.trancecode.web.html2xml.Html2XmlServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    LOG.trace("{@method} request = {}", request);

    final String requestUri = request.getRequestURI();
    if (!requestUri.matches("^/[^/]+/.+")) {
        response.sendError(500);//from w  w w  . java 2s . c o  m
        return;
    }

    try {
        final StringBuilder pageUrlBuilder = new StringBuilder();
        pageUrlBuilder.append("http:/").append(requestUri);
        if (request.getQueryString() != null) {
            pageUrlBuilder.append("?").append(request.getQueryString());
        }
        final URL pageUrl = new URL(pageUrlBuilder.toString());
        LOG.debug("GET: {}", pageUrl);

        final XMLReader reader = new Parser();
        reader.setProperty(Parser.schemaProperty, new HTMLSchema());
        final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(bytesOut);
            reader.setContentHandler(new XMLWriter(writer));
            final InputSource source = new InputSource();
            source.setByteStream(pageUrl.openStream());
            reader.parse(source);
        } finally {
            Closeables.closeQuietly(writer);
        }

        InputStream bytesIn = null;
        try {
            bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
            ByteStreams.copy(bytesIn, response.getOutputStream());
        } finally {
            Closeables.closeQuietly(bytesIn);
            Closeables.closeQuietly(response.getOutputStream());
        }
    } catch (final Exception e) {
        throw new IllegalStateException(request.getRequestURI(), e);
    }
}

From source file:de.blizzy.documentr.web.branch.BranchController.java

@RequestMapping(value = "/save/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN
        + "}", method = RequestMethod.POST)
@PreAuthorize("hasBranchPermission(#form.projectName, #form.name, EDIT_BRANCH)")
public String saveBranch(@ModelAttribute @Valid BranchForm form, BindingResult bindingResult,
        Authentication authentication) throws IOException, GitAPIException {

    List<String> branches = globalRepositoryManager.listProjectBranches(form.getProjectName());
    boolean firstBranch = branches.isEmpty();
    if (branches.contains(form.getName())) {
        bindingResult.rejectValue("name", "branch.name.exists"); //$NON-NLS-1$ //$NON-NLS-2$
    }/*  www.  j a  v  a2s  . c o  m*/

    if (bindingResult.hasErrors()) {
        return "/project/branch/edit"; //$NON-NLS-1$
    }

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.createProjectBranchRepository(form.getProjectName(), form.getName(),
                form.getStartingBranch());
    } finally {
        Closeables.closeQuietly(repo);
    }

    if (firstBranch) {
        Page page = Page.fromText("Home", StringUtils.EMPTY); //$NON-NLS-1$
        User user = userStore.getUser(authentication.getName());
        pageStore.savePage(form.getProjectName(), form.getName(), DocumentrConstants.HOME_PAGE_NAME, page, null,
                user);
        return "redirect:/page/edit/" + form.getProjectName() + "/" + form.getName() + //$NON-NLS-1$ //$NON-NLS-2$
                "/" + DocumentrConstants.HOME_PAGE_NAME; //$NON-NLS-1$
    }

    return "redirect:/page/" + form.getProjectName() + "/" + form.getName() + //$NON-NLS-1$ //$NON-NLS-2$
            "/" + DocumentrConstants.HOME_PAGE_NAME; //$NON-NLS-1$
}

From source file:org.apache.mahout.cf.taste.example.netflix.TransposeToByUser.java

private static void appendStringsToFile(Iterable<String> strings, File file) throws IOException {
    Writer out = new OutputStreamWriter(new FileOutputStream(file, true), Charsets.UTF_8);
    try {//from   w ww  .  j av a2 s  .  com
        for (String s : strings) {
            out.write(s);
            out.write('\n');
        }
    } finally {
        Closeables.closeQuietly(out);
    }
}

From source file:org.sonar.db.MyBatisConfBuilder.java

public void loadMapper(Class mapperClass) {
    String configFile = configFilePath(mapperClass);
    InputStream input = null;/* www.j  a  v a2  s . c o  m*/
    try {
        input = mapperClass.getResourceAsStream(configFile);
        checkArgument(input != null, format("Can not find mapper XML file %s", configFile));
        new SQXMLMapperBuilder(mapperClass, input, conf, conf.getSqlFragments()).parse();
        loadAndConfigureLogger(mapperClass.getName());
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to load mapper " + mapperClass, e);
    } finally {
        Closeables.closeQuietly(input);
    }
}

From source file:org.apache.mahout.ga.watchmaker.MahoutEvaluator.java

/**
 * Stores a population of candidates in the output file path.
 * //from  w ww.  j a va 2  s  . co m
 * @param fs
 *          FileSystem used to create the output file
 * @param f
 *          output file path
 * @param population
 *          population to store
 */
static void storePopulation(FileSystem fs, Path f, Iterable<?> population) throws IOException {
    FSDataOutputStream out = fs.create(f);
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

    try {
        for (Object candidate : population) {
            writer.write(StringUtils.toString(candidate));
            writer.newLine();
        }
    } finally {
        Closeables.closeQuietly(writer);
    }
}