/** * Utility to silently close a {@link Closeable} item (in/out stream, writer, etc.) if not null. * Does not throw IO exception that might arise. It is just logged. * @param closeable stream to close * @return <code>false</code> if close operation had been issued but not completed successfully */ public static boolean closeStream( Closeable closeable ) { return closeStream(closeable, null); }
private Object getClonedInputStream( InputStream is ) throws IOException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[BYTE_BUFFER_SIZE]; int bytesRead = -1; while ( (bytesRead = is.read(buffer)) > -1) { out.write(buffer, 0, bytesRead); } ByteArrayInputStream bis = new ByteArrayInputStream(out.toByteArray()); IoUtils.closeStream(out); return bis; } finally { IoUtils.closeStream(is); } }
/** * Convert the {@link InputStream} to {@link String} and close the passed stream * * @param inputStream the input stream * @return a string representation of the input data * @throws IOException */ public static String streamToString( InputStream inputStream ) throws IOException { try { return new String(loadInputStreamToMemory(inputStream)); } finally { IoUtils.closeStream(inputStream); } }
closeStream(input); closeStream(output);
public static void unlockJavaSecurity() { try { String userTempDir = AtsSystemProperties.SYSTEM_USER_TEMP_DIR; File tempPolicyFile = new File(userTempDir + "/ats_java_security_file.policy"); if (!tempPolicyFile.exists()) { FileWriter fileWriter = null; try { fileWriter = new FileWriter(tempPolicyFile); fileWriter.append("grant{\n" + "\t// Allow everything\n" + "\tpermission java.security.AllPermission;\n" + "};\n"); } finally { IoUtils.closeStream(fileWriter); } } System.setProperty("java.security.policy", tempPolicyFile.getAbsolutePath()); } catch (Exception e) { throw new RuntimeException("Error unlocking java security", e); } } }
/** * Copy file * * @param sourceFileName the source file name * @param destinationFileName the destination file name * @throws IOException on error */ private void copyFile( String sourceFileName, String destinationFileName ) throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { // Create channel on the source srcChannel = new FileInputStream(sourceFileName).getChannel(); // Create channel on the destination dstChannel = new FileOutputStream(destinationFileName).getChannel(); // Copy file contents from source to destination dstChannel.truncate(0); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { // Close the channels IoUtils.closeStream(srcChannel); IoUtils.closeStream(dstChannel); } }
/** * Loads a file and returns it as an InputStream. * <p><em>Note:</em> The returned stream is full in-memory copy {@link ByteArrayInputStream} * so it should be used only for relatively small files. * </p> * * @param filePath * @return * @throws IOException */ public static InputStream readFile( String filePath ) throws IOException { // fix the encoded characters filePath = URLDecoder.decode(filePath, "UTF-8"); File file = new File(filePath); InputStream fis = null; try { fis = new FileInputStream(file); byte[] readBytes = new byte[(int) file.length()]; fis.read(readBytes); return new ByteArrayInputStream(readBytes); } finally { closeStream(fis); } }
private Properties loadPropertiesFile( String agent, String filePath ) { // load the file as a String String fileContent = loadFileContent(agent, filePath); Properties properties = new Properties(); StringReader reader = new StringReader(fileContent); try { properties.load(new StringReader(fileContent)); } catch (IOException ex) { // this will cancel the comparison // the other option is to add a difference to the FileTrace object, instead of throwing an exception here throw new FileSystemOperationException("Error loading '" + filePath + "' properties file."); } finally { IoUtils.closeStream(reader, "Could not close a stream while reading from '" + filePath + "'"); } return properties; }
private String downloadAgentZip( String agentZipUrl, String tempPath ) throws AtsManagerException { File downloadedFile = new File( tempPath + "agent.zip" ); downloadedFile.deleteOnExit(); log.info( "Download ATS agent from " + agentZipUrl + " into " + downloadedFile ); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL( agentZipUrl ); URLConnection conn = url.openConnection(); bis = new BufferedInputStream( conn.getInputStream() ); bos = new BufferedOutputStream( new FileOutputStream( downloadedFile ) ); int inByte; while( ( inByte = bis.read() ) != -1 ) { bos.write( inByte ); } return downloadedFile.getPath(); } catch( Exception e ) { throw new AtsManagerException( "Error downloading agent ZIP file from " + agentZipUrl, e ); } finally { IoUtils.closeStream( bis ); IoUtils.closeStream( bos ); } }
/** * Close HttpClient stream and releases any system resources associated with it */ @PublicAtsApi public void close() { if (this.httpClient != null) { IoUtils.closeStream(this.httpClient, "Failed to close HttpClient"); this.httpClient = null; invalidateInternalClient(); } }
/** * Reads bytes from stream and convert them to hex notation * @param sb buffer to fill with hex data * @param binInputStream input stream * @return the StringBuilder parameter used as a clarification * @throws IOException if exception is caused during reading from the input stream */ protected StringBuilder addBinDataAsHexAndCloseStream( StringBuilder sb, InputStream binInputStream ) throws IOException { if (sb == null) { throw new IllegalArgumentException("Passed null for StringBuilder"); } if (binInputStream == null) { throw new IllegalArgumentException("Passed null for InputStream"); } // read the binary data from the stream and convert it to hex try { byte[] buffer = new byte[BYTE_BUFFER_SIZE]; int bytesRead = binInputStream.read(buffer); while (bytesRead > 0) { sb.append(bytesToHex(buffer, bytesRead)); bytesRead = binInputStream.read(buffer); } } finally { IoUtils.closeStream(binInputStream); } return sb; }
throw new ActionException(e); } finally { IoUtils.closeStream(is);
/** * Unlock file already locked with {@link #lockFile(String) lockFile()} method * * @param fileName file name */ @Override public void unlockFile( String fileName ) { synchronized (lockedFiles) { FileLock fileLock = lockedFiles.get(fileName); if (fileLock != null) { try { fileLock.release(); } catch (Exception e) { throw new FileSystemOperationException("Could not unlock file '" + fileName + "'", e); } finally { IoUtils.closeStream(fileLock.channel()); lockedFiles.remove(fileName); } } else { log.warn("File '" + fileName + "' is not locked, so we will not try to unlock it"); } } }
} finally { IoUtils.closeStream(this.is); this.readFinished = true; this.streamContent.notify();
private void extractGZip( String gzipFilePath, String outputDirPath ) { String outputFileName = new File(gzipFilePath).getName(); outputFileName = outputFileName.substring(0, outputFileName.lastIndexOf(".gz")); String outputFilePath = outputDirPath + File.separator + outputFileName; new File(outputDirPath).mkdirs(); InputStream in = null; try { String filePermissions = getFilePermissions(gzipFilePath); in = new GZIPInputStream(new FileInputStream(gzipFilePath)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFilePath)); IoUtils.copyStream(in, out); if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {//check if the OS is UNIX // set file permissions, after it is created this.setFilePermissions(outputFilePath, filePermissions); } } catch (Exception e) { String errorMsg = "Unable to gunzip " + gzipFilePath + ".Target directory '" + outputDirPath + "' is in inconsistent state."; throw new FileSystemOperationException(errorMsg, e); } finally { IoUtils.closeStream(in, "Could not close stream for file '" + gzipFilePath + "'"); } }
@Override public String[] getLastLinesFromFile( String fileName, int numLinesToRead, Charset chartset ) { LinkedList<String> lastLinesList = new LinkedList<String>(); ReversedLinesFileReader reversedReader = null; try { reversedReader = new ReversedLinesFileReader(new File(fileName), 4096, chartset); while (lastLinesList.size() < numLinesToRead) { String line = reversedReader.readLine(); // check if the file has less lines than the wanted if (line != null) { lastLinesList.addFirst(line); } else { break; } } return lastLinesList.toArray(new String[lastLinesList.size()]); } catch (IOException ioe) { throw new FileSystemOperationException("Error reading file '" + fileName + "'", ioe); } finally { if (reversedReader != null) { IoUtils.closeStream(reversedReader); } } }
throw new FileTransferException(e); } finally { IoUtils.closeStream(fis, "Unable to close the file stream after successful upload!");
value = IoUtils.streamToString(is); } finally { IoUtils.closeStream(is);
+ toFileName + "' on " + toHost + ":" + toPort, ioe); } finally { IoUtils.closeStream(sos); if (socket != null) { try {
/** * Loads an XML file from an InputStream. * <br> * Note: the source stream is closed internally * * @param configurationFileStream the source stream * @return the loaded XML document * @throws IOException * @throws SAXException */ public static Document loadXMLFile( InputStream configurationFileStream ) throws IOException, SAXException { try { DOMParser parser = new DOMParser(); // Required settings from the DomParser parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true); parser.setFeature("http://apache.org/xml/features/allow-java-encodings", true); parser.parse(new InputSource(configurationFileStream)); return parser.getDocument(); } finally { IoUtils.closeStream(configurationFileStream); } }