public static String readFromResource(String resource) throws IOException { InputStream in = null; try { in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); if (in == null) { in = Utils.class.getResourceAsStream(resource); } if (in == null) { return null; } String text = Utils.read(in); return text; } finally { Closeables.closeQuietly(in); } }
protected Class<?> findClassInJarFile(String qualifiedClassName) throws ClassNotFoundException { URI classUri = URIUtil.buildUri(StandardLocation.CLASS_OUTPUT, qualifiedClassName); String internalClassName = classUri.getPath().substring(1); JarFile jarFile = null; try { for (int i = 0; i < jarFiles.size(); i++) { jarFile = jarFiles.get(i); JarEntry jarEntry = jarFile.getJarEntry(internalClassName); if (jarEntry != null) { InputStream inputStream = jarFile.getInputStream(jarEntry); try { byte[] byteCode = new byte[(int) jarEntry.getSize()]; ByteStreams.read(inputStream, byteCode, 0, byteCode.length); return defineClass(qualifiedClassName, byteCode, 0, byteCode.length); } finally { Closeables.closeQuietly(inputStream); } } } } catch (IOException e) { throw new IllegalStateException(String.format("Failed to lookup class %s in jar file %s", qualifiedClassName, jarFile), e); } return null; }
private void closeSource(final StreamSource source) { if( source != null ) { try { // one of these should be non-null Closeables.close(source.getReader(), true); Closeables.close(source.getInputStream(), true); } catch( Throwable th ) { // Ignore } } }
public Combiner(ManifestResolver resolver, Writer output) throws IOException, XmlPullParserException { this.output = output; this.resolver = resolver; Reader reader = null; try { reader = resolver.getStream(); parser = new MXParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); parser.setInput(reader); parseXml(); } finally { Closeables.close(reader, true); // Quietly } }
private ObjectNode createItemFromFile(String jsonFile, String token, String stagingUuid, int responseCode, boolean returnError) throws Exception { final StringWriter sw = new StringWriter(); final InputStream input = ItemApiEditTest.class.getResourceAsStream(jsonFile); try { CharStreams.copy(new InputStreamReader(input), sw); } finally { Closeables.close(input, true); } String newItemJson = sw.toString(); return createItemFromString(newItemJson, token, stagingUuid, responseCode, returnError); }
private static String getStringValue(@NonNull IAbstractFile file, @NonNull String xPath) throws StreamException, XPathExpressionException { XPath xpath = AndroidXPathFactory.newXPath(); InputStream is = null; try { is = file.getContents(); return xpath.evaluate(xPath, new InputSource(is)); } finally { try { Closeables.close(is, true /* swallowIOException */); } catch (IOException e) { // cannot happen } } }
public static boolean createNewStore(String storeType, File storeFile, char[] storePassword, DN dn) { if (storeType == null) { storeType = "jks"; } try { KeyStore ks = KeyStore.getInstance(storeType); ks.load(null, null); Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn)); ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()}); FileOutputStream fos = new FileOutputStream(storeFile); boolean threw = true; try { ks.store(fos, storePassword); threw = false; } finally { Closeables.close(fos, threw); } } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) { return false; } return true; }
public static boolean addNewKey(KeyStore ks, File storeFile, char[] storePassword, DN dn) { try { Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn)); ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()}); FileOutputStream fos = new FileOutputStream(storeFile); boolean threw = true; try { ks.store(fos, storePassword); threw = false; } finally { Closeables.close(fos, threw); } } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) { return false; } return 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 static Map<Long, String> getMovies(String base) { Map<Long, String> movies = new HashMap<>(); try { File file = new File(base + "hot_movies.csv"); FileLineIterator iterator = new FileLineIterator(file, false); String line = iterator.next(); while (!line.isEmpty()) { String[] m = line.split(","); movies.put(Long.parseLong(m[0]), m[2]); line = iterator.next(); } Closeables.close(iterator, true); } catch (Exception ex) { } return movies; }
@Override public OutputStream write(String entry) throws IOException { saveInputFile(); File file = changedEntries.get(entry); if (file == null) { file = new File(changedFiles, entry); createParentDirs(file); changedEntries.put(entry, file); } OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); Closeables.close(outputStreams.put(entry, out), true); if (removedEntries.remove(entry)) { deleteIfExists(new File(removedFiles, entry).toPath()); } return out; }
@Override public void saveTo(File target) throws IOException { for (OutputStream out : outputStreams.values()) { Closeables.close(out, false); } outputStreams.clear(); try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)))) { if (zipFile != null) { for (ZipEntry entry : Collections.list(zipFile.entries())) { if (!changedEntries.containsKey(entry.getName()) && !removedEntries.contains(entry.getName())) { out.putNextEntry(entry); Utils.copy(zipFile.getInputStream(entry), out); } } } for (Map.Entry<String, File> e : changedEntries.entrySet()) { out.putNextEntry(new ZipEntry(e.getKey())); Utils.copy(new BufferedInputStream(new FileInputStream(e.getValue())), out); } } }
private void dumpBindingsToFile( BindingType bindingType, Map<KbaChangeSetQualifier, KbaChangeSet> kbaChangeSet, IPath outputLocation, String description) throws FileNotFoundException, IOException { String output = getBindingsPrintout(bindingType, kbaChangeSet, description); File file = outputLocation.toFile(); PrintStream stream = null; try { stream = new PrintStream(new FileOutputStream(file)); stream.print(output); } finally { Closeables.closeQuietly(stream); } }
@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 result = os.toString(); Assert.assertEquals(new String(ByteStreams.toByteArray(expected)), result); } finally { Closeables.closeQuietly(local); Closeables.closeQuietly(remote); Closeables.closeQuietly(base); Closeables.close(os, true); } }
/** * Loads the keys from the specified translation file into a set. * @param file translation file. * @return a Set object which holds the loaded keys. */ private Set<String> getTranslationKeys(File file) { Set<String> keys = new HashSet<String>(); InputStream inStream = null; try { inStream = new FileInputStream(file); final Properties translations = new Properties(); translations.load(inStream); keys = translations.stringPropertyNames(); } catch (final IOException ex) { logIoException(ex, file); } finally { Closeables.closeQuietly(inStream); } return keys; }
@Override protected void processFiltered(File file, FileText fileText) { final UniqueProperties properties = new UniqueProperties(); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); properties.load(fileInputStream); } catch (IOException ex) { log(0, MSG_IO_EXCEPTION_KEY, file.getPath(), ex.getLocalizedMessage()); } finally { Closeables.closeQuietly(fileInputStream); } for (Entry<String> duplication : properties .getDuplicatedKeys().entrySet()) { final String keyName = duplication.getElement(); final int lineNumber = getLineNumber(fileText, keyName); // Number of occurrences is number of duplications + 1 log(lineNumber, MSG_KEY, keyName, duplication.getCount() + 1); } }
/** * Load the header from a file. * @throws CheckstyleException if the file cannot be loaded */ private void loadHeaderFile() throws CheckstyleException { checkHeaderNotInitialized(); Reader headerReader = null; try { headerReader = new InputStreamReader(new BufferedInputStream( headerFile.toURL().openStream()), charset); loadHeader(headerReader); } catch (final IOException ex) { throw new CheckstyleException( "unable to load header file " + headerFile, ex); } finally { Closeables.closeQuietly(headerReader); } }
/** * Set the header to check against. Individual lines in the header * must be separated by '\n' characters. * @param header header content to check against. * @throws IllegalArgumentException if the header cannot be interpreted */ public void setHeader(String header) { if (!CommonUtils.isBlank(header)) { checkHeaderNotInitialized(); final String headerExpandedNewLines = ESCAPED_LINE_FEED_PATTERN .matcher(header).replaceAll("\n"); final Reader headerReader = new StringReader(headerExpandedNewLines); try { loadHeader(headerReader); } catch (final IOException ex) { throw new IllegalArgumentException("unable to load header", ex); } finally { Closeables.closeQuietly(headerReader); } } }
/** * Reads the file provided and parses it with package names loader. * @param packageFile file from package * @param namesLoader package names loader * @throws SAXException if an error while parsing occurs * @throws CheckstyleException if unable to open file */ private static void processFile(URL packageFile, PackageNamesLoader namesLoader) throws SAXException, CheckstyleException { InputStream stream = null; try { stream = new BufferedInputStream(packageFile.openStream()); final InputSource source = new InputSource(stream); namesLoader.parseInputSource(source); } catch (IOException ex) { throw new CheckstyleException("unable to open " + packageFile, ex); } finally { Closeables.closeQuietly(stream); } }
/** * Load cached values from file. * @throws IOException when there is a problems with file read */ public void load() throws IOException { // get the current config so if the file isn't found // the first time the hash will be added to output file configHash = getHashCodeBasedOnObjectContent(config); if (new File(fileName).exists()) { FileInputStream inStream = null; try { inStream = new FileInputStream(fileName); details.load(inStream); final String cachedConfigHash = details.getProperty(CONFIG_HASH_KEY); if (!configHash.equals(cachedConfigHash)) { // Detected configuration change - clear cache reset(); } } finally { Closeables.closeQuietly(inStream); } } else { // put the hash in the file if the file is going to be created reset(); } }
/** * Pitest requires all closes of streams and readers to be verified. Using PowerMock * is almost only possibility to check it without rewriting production code. * * @throws Exception when code tested throws some exception */ @Test public void testCloseRandomAccessFile() throws Exception { mockStatic(Closeables.class); doNothing().when(Closeables.class); Closeables.close(any(RandomAccessFile.class), anyBoolean()); final DefaultConfiguration checkConfig = createModuleConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify( createChecker(checkConfig), getPath("InputNewlineAtEndOfFileLf.java"), expected); verifyStatic(times(1)); Closeables.close(any(RandomAccessFile.class), anyBoolean()); }
/** * Test of setHeader method, of class RegexpHeaderCheck. */ @Test public void testSetHeaderSimple() { //check if reader finally closed mockStatic(Closeables.class); doNothing().when(Closeables.class); Closeables.closeQuietly(any(Reader.class)); final RegexpHeaderCheck instance = new RegexpHeaderCheck(); // check valid header passes final String header = "abc.*"; instance.setHeader(header); verifyStatic(times(2)); Closeables.closeQuietly(any(Reader.class)); }
/** * Write {@link Serializable} to disk. * * @throws IOException if serialization fails. */ public static void saveToDisk(File file, Serializable serializable) throws IOException { ensureExists(file.getParentFile()); FileOutputStream fos = null; try { fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); try { oos.writeObject(serializable); } finally { Closeables.close(oos, false); } } finally { Closeables.close(fos, false); } }
/** * Pitest requires all closes of streams and readers to be verified. Using PowerMock * is almost only possibility to check it without rewriting production code. * * @throws Exception when code tested throws some exception */ @Test public void testResourcesAreClosed() throws Exception { mockStatic(Closeables.class); doNothing().when(Closeables.class); Closeables.closeQuietly(any(InputStream.class)); final DefaultConfiguration checkConfig = createModuleConfig(TranslationCheck.class); checkConfig.addAttribute("requiredTranslations", "es"); final File[] propertyFiles = { new File(getPath("messages_home.properties")), new File(getPath("messages_home_es_US.properties")), }; final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify( createChecker(checkConfig), propertyFiles, getPath(""), expected); verifyStatic(times(2)); Closeables.closeQuietly(any(FileInputStream.class)); }
@Test public final void testSetPropertiesFile() throws IOException { //check if input stream finally closed mockStatic(Closeables.class); doNothing().when(Closeables.class); Closeables.closeQuietly(any(InputStream.class)); TestRootModuleChecker.reset(); final CheckstyleAntTask antTask = getCheckstyleAntTask(CUSTOM_ROOT_CONFIG_FILE); antTask.setFile(new File(getPath(VIOLATED_INPUT))); antTask.setProperties(new File(getPath( "InputCheckstyleAntTaskCheckstyleAntTest.properties"))); antTask.execute(); assertEquals("Property is not set", "ignore", TestRootModuleChecker.getProperty()); verifyStatic(times(1)); Closeables.closeQuietly(any(InputStream.class)); }
@Test public void testExistingTargetFilePlainOutputProperties() throws Exception { mockStatic(Closeables.class); doNothing().when(Closeables.class); Closeables.closeQuietly(any(InputStream.class)); //exit.expectSystemExitWithStatus(0); exit.checkAssertionAfterwards(new Assertion() { @Override public void checkAssertion() { assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL + auditFinishMessage.getMessage() + EOL, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); } }); Main.main("-c", getPath("InputMainConfig-classname-prop.xml"), "-p", getPath("InputMainMycheckstyle.properties"), getPath("InputMain.java")); verifyStatic(times(1)); Closeables.closeQuietly(any(InputStream.class)); }
@Test public void testCloseAndFlushOutputStreamAfterCreatingHashCode() throws IOException { mockStatic(Closeables.class); doNothing().when(Closeables.class); Closeables.close(any(ObjectOutputStream.class), Matchers.eq(false)); mockStatic(Flushables.class); doNothing().when(Flushables.class); Flushables.flush(any(ObjectOutputStream.class), Matchers.eq(false)); final Configuration config = new DefaultConfiguration("myName"); final PropertyCacheFile cache = new PropertyCacheFile(config, "fileDoesNotExist.txt"); cache.load(); verifyStatic(times(1)); Closeables.close(any(ObjectOutputStream.class), Matchers.eq(false)); verifyStatic(times(1)); Flushables.flush(any(ObjectOutputStream.class), Matchers.eq(false)); }
@Test public void testPopulateDetails() throws IOException { mockStatic(Closeables.class); doNothing().when(Closeables.class); Closeables.closeQuietly(any(FileInputStream.class)); final Configuration config = new DefaultConfiguration("myName"); final PropertyCacheFile cache = new PropertyCacheFile(config, getPath("InputPropertyCacheFile")); cache.load(); final String hash = cache.get(PropertyCacheFile.CONFIG_HASH_KEY); assertNotNull("Config hash key should not be null", hash); assertNull("Should return null if key is not in cache", cache.get("key")); cache.load(); assertEquals("Invalid config hash key", hash, cache.get(PropertyCacheFile.CONFIG_HASH_KEY)); assertEquals("Invalid cache value", "value", cache.get("key")); assertNotNull("Config hash key should not be null", cache.get(PropertyCacheFile.CONFIG_HASH_KEY)); verifyStatic(times(2)); Closeables.closeQuietly(any(FileInputStream.class)); }
@Test public void testFlushAndCloseCacheFileOutputStream() throws IOException { mockStatic(Closeables.class); doNothing().when(Closeables.class); Closeables.close(any(FileOutputStream.class), Matchers.eq(false)); mockStatic(Flushables.class); doNothing().when(Flushables.class); Flushables.flush(any(FileOutputStream.class), Matchers.eq(false)); final Configuration config = new DefaultConfiguration("myName"); final PropertyCacheFile cache = new PropertyCacheFile(config, temporaryFolder.newFile().getPath()); cache.put("CheckedFileName.java", System.currentTimeMillis()); cache.persist(); verifyStatic(times(1)); Closeables.close(any(FileOutputStream.class), Matchers.eq(false)); verifyStatic(times(1)); Flushables.flush(any(FileOutputStream.class), Matchers.eq(false)); }
@Override protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration emoConfiguration) throws Exception { _outputOnly = namespace.getBoolean("output_only"); DdlConfiguration ddlConfiguration = parseDdlConfiguration(toFile(namespace.getString("config-ddl"))); CuratorFramework curator = null; if (!_outputOnly) { curator = emoConfiguration.getZooKeeperConfiguration().newCurator(); curator.start(); } try { createKeyspacesIfNecessary(emoConfiguration, ddlConfiguration, curator, bootstrap.getMetricRegistry()); } finally { Closeables.close(curator, true); } }
public String toCqlScript() { try { final InputStream cqlStream = CreateKeyspacesCommand.class.getResourceAsStream(_templateResourceName); if (cqlStream == null) { throw new IllegalStateException("couldn't find " + _templateResourceName + " in classpath"); } String cql; try { cql = CharStreams.toString(new InputStreamReader(cqlStream, "UTF-8")); } finally { Closeables.close(cqlStream, true); } // replace bindings for (Map.Entry<String, String> binding : _bindings.entrySet()) { cql = cql.replace("${" + binding.getKey() + "}", binding.getValue()); } return cql; } catch (IOException e) { throw new RuntimeException(e); } }
/** * Read the next row from the split, storing the coordinate in "key" and the content in "value". If there are no * more rows then false is returned and "key" and "value" are not modified. * @return true if a row was read, false if there were no more rows */ public boolean setNextKeyValue(Text key, Row value) throws IOException { if (!_rows.hasNext()) { Closeables.close(this, true); return false; } try { Map<String, Object> content = _rows.next(); key.set(Coordinate.fromJson(content).toString()); value.set(content); _rowsRead += 1; } catch (Exception e) { for (Throwable cause : Throwables.getCausalChain(e)) { Throwables.propagateIfInstanceOf(cause, IOException.class); } throw new IOException("Failed to read next row", e); } return true; }
/** * In order to fail fast create the initial iterator on instantiation. This way exceptions such as * TableNotStashedException will be thrown immediately and not deferred until the first iteration. */ public StashRowIterable() { _initialIterator = createStashRowIterator(); // Force the first record to be evaluated by calling hasNext() try { _initialIterator.hasNext(); _openIterators.add(_initialIterator); } catch (Exception e) { try { Closeables.close(_initialIterator, true); } catch (IOException e2) { // Already caught and logged } throw Throwables.propagate(e); } }
StashSplitIterator(AmazonS3 s3, String bucket, String key) { InputStream rawIn = new RestartingS3InputStream(s3, bucket, key); try { // File is gzipped // Note: // Because the content may be concatenated gzip files we cannot use the default GZIPInputStream. // GzipCompressorInputStream supports concatenated gzip files. GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(rawIn, true); _in = new BufferedReader(new InputStreamReader(gzipIn, Charsets.UTF_8)); // Create a line reader _reader = new LineReader(_in); } catch (Exception e) { try { Closeables.close(rawIn, true); } catch (IOException ignore) { // Won't happen, already caught and logged } throw Throwables.propagate(e); } }
private StreamSupplier streamSupplier(final BlobRequest request, final BlobResponse response) { return new StreamSupplier() { @Override public void writeTo(OutputStream out) throws IOException { InputStream in = response.getInputStream(); if (in == null) { // The original stream has already been consumed. Re-open a new stream from the server. in = get(request).getInputStream(); } try { ByteStreams.copy(in, out); } finally { Closeables.close(in, true); } } }; }
@SuppressWarnings("Duplicates") private void initializeClient() { final URL url = Resources.getResource("server.properties"); final ByteSource byteSource = Resources.asByteSource(url); final Properties properties = new Properties(); InputStream inputStream = null; try { inputStream = byteSource.openBufferedStream(); properties.load(inputStream); final String serverUrl = properties.getProperty("secure.url"); final String user = properties.getProperty("default.user"); final String password = properties.getProperty("default.password"); bpmClient = BpmClientFactory.createClient(serverUrl, user, password); } catch (IOException e) { e.printStackTrace(); } finally { Closeables.closeQuietly(inputStream); } }
public void testNormal() {// 12.526秒 Jedis jedis = new Jedis("120.25.241.144", 6379); jedis.auth("b840fc02d52404542994"); long start = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { jedis.set("n" + i, "n" + i); System.out.println(i); } long end = System.currentTimeMillis(); System.out.println("共花费:" + (end - start) / 1000.0 + "秒"); jedis.disconnect(); try { Closeables.close(jedis, true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void testTrans() {// 0.304秒 Jedis jedis = new Jedis("120.25.241.144", 6379); jedis.auth("b840fc02d52404542994"); long start = System.currentTimeMillis(); Transaction tx = jedis.multi(); for (int i = 0; i < 1000; i++) { tx.set("n" + i, "n" + i); System.out.println(i); } tx.exec(); long end = System.currentTimeMillis(); System.out.println("共花费:" + (end - start) / 1000.0 + "秒"); jedis.disconnect(); try { Closeables.close(jedis, true); } catch (IOException e) { e.printStackTrace(); } }
public void testPipelined() {// 0.076秒 Jedis jedis = new Jedis("120.25.241.144", 6379); jedis.auth("b840fc02d52404542994"); long start = System.currentTimeMillis(); Pipeline pipeline = jedis.pipelined(); for (int i = 0; i < 1000; i++) { pipeline.set("n" + i, "n" + i); System.out.println(i); } pipeline.syncAndReturnAll(); long end = System.currentTimeMillis(); System.out.println("共花费:" + (end - start) / 1000.0 + "秒"); jedis.disconnect(); try { Closeables.close(jedis, true); } catch (IOException e) { e.printStackTrace(); } }