下面列出了com.google.common.io.Closeables#closeQuietly ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
/**
* @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);
}
}
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);
}
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;
}
/**
* 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;
}
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);
}
}
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);
}
}
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);
}
}
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();
}
}
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", "");
}
/**
* 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;
}
/**
* 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();
}
/**
* 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;
}
/**
* 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);
}
}
public byte[] getChecksumBytes(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
try {
digest.reset();
readStream(fis);
return digest.digest();
} finally {
Closeables.closeQuietly(fis);
}
}
/**
* @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);
}
}
@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();
}
@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);
}
}
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;
}
/**
* 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);
}
}