Java Code Examples for com.google.common.io.Closeables#closeQuietly()

The following examples show how to use com.google.common.io.Closeables#closeQuietly() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecondaryIndexTable.java    From phoenix-tephra with Apache License 2.0 6 votes vote down vote up
public SecondaryIndexTable(TransactionServiceClient transactionServiceClient, Table table,
                           byte[] secondaryIndex) throws IOException {
  secondaryIndexTableName = TableName.valueOf(table.getName().getNameAsString() + ".idx");
  this.connection = ConnectionFactory.createConnection(table.getConfiguration());
  Table secondaryIndexHTable = null;
  try (Admin hBaseAdmin = this.connection.getAdmin()) {
    if (!hBaseAdmin.tableExists(secondaryIndexTableName)) {
      hBaseAdmin.createTable(TableDescriptorBuilder.newBuilder(secondaryIndexTableName).build());
    }
    secondaryIndexHTable = this.connection.getTable(secondaryIndexTableName);
  } catch (Exception e) {
    Closeables.closeQuietly(connection);
    Throwables.propagate(e);
  }

  this.secondaryIndex = secondaryIndex;
  this.transactionAwareHTable = new TransactionAwareHTable(table);
  this.secondaryIndexTable = new TransactionAwareHTable(secondaryIndexHTable);
  this.transactionContext = new TransactionContext(transactionServiceClient, transactionAwareHTable,
                                                   secondaryIndexTable);
}
 
Example 2
Source File: ScmPomVersionsMergeClientTest.java    From unleash-maven-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@UseDataProvider("merge")
public void testMerge(InputStream local, InputStream remote, InputStream base, InputStream expected)
    throws IOException {
  MergeClient mergeClient = new ScmPomVersionsMergeClient();
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  try {
    mergeClient.merge(local, remote, base, os);
    String resultPOM = os.toString(StandardCharsets.UTF_8.name());
    String expectedPOM = new String(ByteStreams.toByteArray(expected), StandardCharsets.UTF_8);

    // replacement of whitespaces is performed in order to avoid problems with line endings on different systems
    Assert.assertEquals(expectedPOM.replaceAll("\\s+", ""), resultPOM.replaceAll("\\s+", ""));
  } finally {
    Closeables.closeQuietly(local);
    Closeables.closeQuietly(remote);
    Closeables.closeQuietly(base);
    Closeables.close(os, true);
  }
}
 
Example 3
Source File: XmlDataSetProducer.java    From morf with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.alfasoftware.morf.metadata.Schema#getTable(java.lang.String)
 */
@Override
public Table getTable(String name) {
  // Read the meta data for the specified table
  InputStream inputStream = xmlStreamProvider.openInputStreamForTable(name);
  try {
    XMLStreamReader xmlStreamReader = openPullParser(inputStream);
    XmlPullProcessor.readTag(xmlStreamReader, XmlDataSetNode.TABLE_NODE);

    String version = xmlStreamReader.getAttributeValue(XmlDataSetNode.URI, XmlDataSetNode.VERSION_ATTRIBUTE);
    if (StringUtils.isNotEmpty(version)) {
      return new PullProcessorTableMetaData(xmlStreamReader, Integer.parseInt(version));
    } else {
      return new PullProcessorTableMetaData(xmlStreamReader, 1);
    }
  } finally {
    // abandon any remaining content
    Closeables.closeQuietly(inputStream);
  }
}
 
Example 4
Source File: CheckConfigurationTester.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Tests a configuration if there are unresolved properties.
 *
 * @return the list of unresolved properties as ResolvableProperty values.
 * @throws CheckstylePluginException
 *           most likely the configuration file could not be found
 */
public List<ResolvableProperty> getUnresolvedProperties() throws CheckstylePluginException {

  CheckstyleConfigurationFile configFile = mCheckConfiguration.getCheckstyleConfiguration();

  PropertyResolver resolver = configFile.getPropertyResolver();

  // set the project context if the property resolver needs the
  // context
  if (mContextProject != null && resolver instanceof IContextAware) {
    ((IContextAware) resolver).setProjectContext(mContextProject);
  }

  MissingPropertyCollector collector = new MissingPropertyCollector();

  if (resolver instanceof MultiPropertyResolver) {
    ((MultiPropertyResolver) resolver).addPropertyResolver(collector);
  } else {
    MultiPropertyResolver multiResolver = new MultiPropertyResolver();
    multiResolver.addPropertyResolver(resolver);
    multiResolver.addPropertyResolver(collector);
    resolver = multiResolver;
  }

  InputSource in = null;
  try {
    in = configFile.getCheckConfigFileInputSource();
    ConfigurationLoader.loadConfiguration(in, resolver, IgnoredModulesOptions.EXECUTE);
  } catch (CheckstyleException e) {
    CheckstylePluginException.rethrow(e);
  } finally {
    Closeables.closeQuietly(in.getByteStream());
  }

  return collector.getUnresolvedProperties();
}
 
Example 5
Source File: Bug3584224.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Properties test(Properties props, InputStream stream) {
    try {
        if (stream == null) {
            LOGGER.log(Level.WARNING, String.format("File [%s] not found. Using default properties.", PROPERTIES_FILENAME));
        } else {
            props.load(stream);
        }
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, String.format("Error reading [%s]. Using default properties.", PROPERTIES_FILENAME), e);
    } finally {
        Closeables.closeQuietly(stream);
    }
    return props;
}
 
Example 6
Source File: ScmPomVersionsMergeClient.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void merge(InputStream local, InputStream remote, InputStream base, OutputStream result) throws ScmException {
  Optional<Model> localModel = loadModel(local);
  if (!localModel.isPresent()) {
    // TODO implement merge of other files!
    throw new ScmException(ScmOperation.MERGE, "Unable to merge non-POM changes.");
  }

  byte[] remoteData = null;
  try {
    remoteData = ByteStreams.toByteArray(remote);
  } catch (IOException e) {
    throw new ScmException(ScmOperation.MERGE, "Unable to read remote content!", e);
  } finally {
    Closeables.closeQuietly(remote);
  }

  Optional<Model> remoteModel = loadModel(new ByteArrayInputStream(remoteData));
  Optional<Model> baseModel = loadModel(base);

  Model resultModel = loadModel(new ByteArrayInputStream(remoteData)).get();
  mergeVersions(localModel.get(), remoteModel.get(), baseModel.get(), resultModel);
  mergeParentVersions(localModel.get(), remoteModel.get(), baseModel.get(), resultModel);

  try {
    Document document = PomUtil.parsePOM(new ByteArrayInputStream(remoteData));
    PomUtil.setProjectVersion(resultModel, document, resultModel.getVersion());
    if (resultModel.getParent() != null) {
      PomUtil.setParentVersion(resultModel, document, resultModel.getParent().getVersion());
    }
    PomUtil.writePOM(document, result, false);
  } catch (Throwable t) {
    throw new ScmException(ScmOperation.MERGE, "Could not serialize merged POM!", t);
  }
}
 
Example 7
Source File: SecondaryIndexTable.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
  Closeables.closeQuietly(connection);
  try {
    transactionAwareHTable.close();
  } catch (IOException e) {
    try {
      secondaryIndexTable.close();
    } catch (IOException ex) {
      e.addSuppressed(ex);
    }
    throw e;
  }
  secondaryIndexTable.close();
}
 
Example 8
Source File: XmlDataSetProducer.java    From morf with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.alfasoftware.morf.dataset.DataSetProducer#isTableEmpty(java.lang.String)
 */
@Override
public boolean isTableEmpty(String tableName) {
  final InputStream inputStream = xmlStreamProvider.openInputStreamForTable(tableName);

  try {
    final XMLStreamReader pullParser = openPullParser(inputStream);
    PullProcessorRecordIterator pullProcessorRecordIterator = new PullProcessorRecordIterator(pullParser);
    return !pullProcessorRecordIterator.hasNext();
  } finally {
    Closeables.closeQuietly(inputStream);
  }
}
 
Example 9
Source File: CheckSum.java    From exists-maven-plugin with Apache License 2.0 5 votes vote down vote up
public byte[] getChecksumBytes(File file) throws IOException {
  FileInputStream fis = new FileInputStream(file);
  try {
    digest.reset();
    readStream(fis);
    return digest.digest();
  } finally {
    Closeables.closeQuietly(fis);
  }
}
 
Example 10
Source File: PomUtil.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Assumes that the passed input Stream contains content describing a POM and parses the content into a
 * {@link Document} for further manipulation.
 *
 * @param in the stream to be parsed. This stream will be closed after parsing the document.
 * @return the parsed document for further manipulation.
 */
public static final Document parsePOM(InputStream in) {
  try {
    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = documentBuilder.parse(in);
    return document;
  } catch (Exception e) {
    throw new RuntimeException("Could not load the project object model from input stream.", e);
  } finally {
    Closeables.closeQuietly(in);
  }
}
 
Example 11
Source File: CheckerFactory.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a checker for a given configuration file.
 *
 * @param config
 *          the check configuration data
 * @param project
 *          the project to create the checker for
 * @return the checker for the given configuration file
 * @throws CheckstyleException
 *           the configuration file had errors
 * @throws CheckstylePluginException
 *           the configuration could not be read
 */
public static Checker createChecker(ICheckConfiguration config, IProject project)
        throws CheckstyleException, CheckstylePluginException {

  String cacheKey = getCacheKey(config, project);

  CheckstyleConfigurationFile configFileData = config.getCheckstyleConfiguration();
  Checker checker = tryCheckerCache(cacheKey, configFileData.getModificationStamp());

  // clear Checkstyle internal caches upon checker reuse
  if (checker != null) {
    checker.clearCache();
  }

  // no cache hit
  if (checker == null) {
    PropertyResolver resolver = configFileData.getPropertyResolver();

    // set the project context if the property resolver needs the
    // context
    if (resolver instanceof IContextAware) {
      ((IContextAware) resolver).setProjectContext(project);
    }

    InputSource in = null;
    try {
      in = configFileData.getCheckConfigFileInputSource();
      checker = createCheckerInternal(in, resolver, project);
    } finally {
      Closeables.closeQuietly(in.getByteStream());
    }

    // store checker in cache
    Long modified = Long.valueOf(configFileData.getModificationStamp());
    sCheckerMap.put(cacheKey, checker);
    sModifiedMap.put(cacheKey, modified);
  }

  return checker;
}
 
Example 12
Source File: SpringBootWatcher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
protected Thread startOutputProcessor(final KitLogger logger, final InputStream inputStream, final boolean error, final AtomicBoolean outputEnabled) throws IOException {
    Thread printer = new Thread() {
        @Override
        public void run() {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (outputEnabled.get()) {
                        if (error) {
                            logger.error("%s", line);
                        } else {
                            logger.info("%s", line);
                        }
                    }
                }
            } catch (Exception e) {
                if (outputEnabled.get()) {
                    logger.error("Failed to process " + (error ? "stderr" : "stdout") + " from spring-remote process: " + e);
                }
            } finally {
                Closeables.closeQuietly(reader);
            }
        }
    };

    printer.start();
    return printer;
}
 
Example 13
Source File: CheckConfigurationWorkingCopy.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Reads the Checkstyle configuration file and builds the list of configured modules. Elements are
 * of type <code>net.sf.eclipsecs.core.config.Module</code>.
 *
 * @return the list of configured modules in this Checkstyle configuration
 * @throws CheckstylePluginException
 *           error when reading the Checkstyle configuration file
 */
public List<Module> getModules() throws CheckstylePluginException {
  List<Module> result = null;

  InputSource in = null;

  try {
    in = getCheckstyleConfiguration().getCheckConfigFileInputSource();
    result = ConfigurationReader.read(in);
  } finally {
    Closeables.closeQuietly(in.getByteStream());
  }

  return result;
}
 
Example 14
Source File: PmdVersion.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
public static String getVersion() {
  Properties properties = new Properties();

  InputStream input = null;
  try {
    input = PmdVersion.class.getResourceAsStream(PROPERTIES_PATH);
    properties.load(input);
  } catch (IOException e) {
    LoggerFactory.getLogger(PmdVersion.class).warn("Can not load the PMD version from the file " + PROPERTIES_PATH, e);
  } finally {
    Closeables.closeQuietly(input);
  }

  return properties.getProperty("pmd.version", "");
}
 
Example 15
Source File: PmdExecutor.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
public Report execute() {
  TimeProfiler profiler = new TimeProfiler().start("Execute PMD " + PmdVersion.getVersion());

  ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
  URLClassLoader classLoader = createClassloader();
  try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

    return executePmd(classLoader);
  } finally {
    Closeables.closeQuietly(classLoader);
    Thread.currentThread().setContextClassLoader(initialClassLoader);
    profiler.stop();
  }
}
 
Example 16
Source File: JAXBUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static <T> T fromXml(Resource resource, Class<T> clazz) {
   InputStream is = null;
   try{
      is = resource.open();
      return fromXml(is, clazz);
   }catch (Exception e){
      throw new RuntimeException("Error parsing XML document", e);
   }finally{
      Closeables.closeQuietly(is);
   }
}
 
Example 17
Source File: XMLUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static Document parseDocumentDOM(String xmlResource) {
   InputStream is = null;
   try{
      Resource resource = Resources.getResource(xmlResource);
      is = resource.open();
      return parseDocumentDOM(is);
   }
   catch(Exception ioe){
      throw new RuntimeException(ioe);
   }
   finally{
      Closeables.closeQuietly(is);
   }
}
 
Example 18
Source File: XMLUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static <T> T deserializeJAXB(Resource resource, Class<T> clazz) {
   InputStream is = null;
   try{
      is = resource.open();
      return deserializeJAXB(is, clazz);
   }catch (Exception e){
      throw new RuntimeException("Error parsing XML document", e);
   }finally{
      Closeables.closeQuietly(is);
   }
}
 
Example 19
Source File: WalletAppKit.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * If set, the file is expected to contain a checkpoints file calculated with BuildCheckpoints. It makes initial
 * block sync faster for new users - please refer to the documentation on the bitcoinj website
 * (https://bitcoinj.github.io/speeding-up-chain-sync) for further details.
 */
public WalletAppKit setCheckpoints(InputStream checkpoints) {
    if (this.checkpoints != null)
        Closeables.closeQuietly(checkpoints);
    this.checkpoints = checkNotNull(checkpoints);
    return this;
}
 
Example 20
Source File: NewProxyServerTestUtil.java    From browserup-proxy with Apache License 2.0 3 votes vote down vote up
/**
 * Reads and closes the input stream, converting it to a String using the UTF-8 charset. The input stream is guaranteed to be closed, even
 * if the reading/conversion throws an exception.
 *
 * @param in UTF-8-encoded InputStream to read
 * @return String of InputStream's contents
 * @throws IOException if an error occurs reading from the stream
 */
public static String toStringAndClose(InputStream in) throws IOException {
    try {
        return new String(ByteStreams.toByteArray(in), StandardCharsets.UTF_8);
    } finally {
        Closeables.closeQuietly(in);
    }
}