Skip to content

Commit

Permalink
Cleanups in FileUtil - direct use methods from NIO
Browse files Browse the repository at this point in the history
- remove unused methods
- direct use methods from NIO
- use try-with-resources
- new FileInputStream -> Files.newInputStream
  • Loading branch information
slawekjaranowski committed Jul 27, 2023
1 parent 85ac3b0 commit 00f8a6d
Show file tree
Hide file tree
Showing 11 changed files with 38 additions and 133 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
import org.codehaus.mojo.license.api.ThirdPartyTool;
import org.codehaus.mojo.license.api.ThirdPartyToolException;
import org.codehaus.mojo.license.model.LicenseMap;
import org.codehaus.mojo.license.utils.FileUtil;
import org.codehaus.mojo.license.utils.MojoHelper;
import org.codehaus.mojo.license.utils.SortedProperties;
import org.codehaus.mojo.license.utils.StringToList;
Expand Down Expand Up @@ -723,7 +722,7 @@ protected void init() throws Exception {

if (generateBundle) {

File bundleFile = FileUtil.getFile(outputDirectory, bundleThirdPartyPath);
File bundleFile = new File(outputDirectory, bundleThirdPartyPath);

LOG.debug("bundle third-party file: {} last modified: {}", bundleFile, bundleFile.lastModified());
doGenerateBundle = force || !bundleFile.exists() || projectFile.lastModified() > bundleFile.lastModified();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -991,12 +991,11 @@ private void initDirectories() throws MojoExecutionException {
FileUtils.cleanDirectory(licensesOutputDirectory);
}
} else {
FileUtil.createDirectoryIfNecessary(licensesOutputDirectory);
Files.createDirectories(licensesOutputDirectory.toPath());
}

FileUtil.createDirectoryIfNecessary(licensesOutputFile.getParentFile());

FileUtil.createDirectoryIfNecessary(licensesErrorsFile.getParentFile());
Files.createDirectories(licensesOutputFile.getParentFile().toPath());
Files.createDirectories(licensesErrorsFile.getParentFile().toPath());
} catch (IOException e) {
throw new MojoExecutionException("Unable to create a directory...", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,7 @@ private void processFile(FileHeaderProcessor processor, File file) throws IOExce
if (doFinalize) {
finalizeFile(file, processFile);
} else {
FileUtil.deleteFile(processFile);
Files.deleteIfExists(processFile.toPath());
}
}
}
Expand Down Expand Up @@ -836,11 +836,8 @@ private void finalizeFile(File file, File processFile) throws IOException {
if (isKeepBackup() && !isDryRun()) {
File backupFile = FileUtil.getBackupFile(file);

if (backupFile.exists()) {

// always delete backup file, before the renaming
FileUtil.deleteFile(backupFile);
}
// always delete backup file, before the renaming
Files.deleteIfExists(backupFile.toPath());

LOG.debug(" - backup original file {}", file);
Files.copy(file.toPath(), backupFile.toPath(), StandardCopyOption.COPY_ATTRIBUTES);
Expand All @@ -849,13 +846,13 @@ private void finalizeFile(File file, File processFile) throws IOException {
if (isDryRun()) {

// dry run, delete temporary file
FileUtil.deleteFile(processFile);
Files.deleteIfExists(processFile.toPath());
} else {
try {
// replace file with the updated one
String updatedContent = FileUtil.readAsString(processFile, getEncoding());
FileUtil.printString(file, updatedContent, getEncoding());
FileUtil.deleteFile(processFile);
Files.deleteIfExists(processFile.toPath());
} catch (IOException e) {
LOG.warn("Error updating {} -> {}", processFile, file, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
Expand All @@ -47,7 +48,6 @@
import org.codehaus.mojo.license.api.ResolvedProjectDependencies;
import org.codehaus.mojo.license.api.ThirdPartyToolException;
import org.codehaus.mojo.license.model.LicenseMap;
import org.codehaus.mojo.license.utils.FileUtil;
import org.codehaus.mojo.license.utils.MojoHelper;
import org.codehaus.mojo.license.utils.SortedProperties;
import org.slf4j.Logger;
Expand Down Expand Up @@ -181,7 +181,7 @@ protected void doAction() throws Exception {

// there is no missing dependencies, but still a missing file, delete it
LOG.info("There is no dependency to put in missing file, delete it at {}", missingFile);
FileUtil.deleteFile(missingFile);
Files.deleteIfExists(missingFile.toPath());
}

if (!unsafe && deployMissingFile && MapUtils.isNotEmpty(unsafeMappings)) {
Expand Down Expand Up @@ -354,7 +354,7 @@ private boolean computeDoGenerateMissingFile(
*/
private void writeMissingFile() throws IOException {

FileUtil.createDirectoryIfNecessary(missingFile.getParentFile());
Files.createDirectories(missingFile.getParentFile().toPath());
LOG.info("Regenerate missing license file {}", missingFile);

FileOutputStream writer = new FileOutputStream(missingFile);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
*/

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
Expand All @@ -41,7 +42,6 @@
import org.codehaus.mojo.license.download.LicenseSummaryReader;
import org.codehaus.mojo.license.download.LicensedArtifact;
import org.codehaus.mojo.license.download.ProjectLicenseInfo;
import org.codehaus.mojo.license.utils.FileUtil;
import org.codehaus.mojo.license.utils.MojoHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -88,7 +88,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
}

try {
FileUtil.createDirectoryIfNecessary(licensesOutputFile.getParentFile());
Files.createDirectories(licensesOutputFile.getParentFile().toPath());

final List<ProjectLicenseInfo> projectLicenseInfos =
LicenseSummaryReader.parseLicenseSummary(licensesInputFile);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
Expand Down Expand Up @@ -490,7 +491,7 @@ private void processFile(FileHeaderTransformer transformer, File file) throws IO
if (doFinalize) {
finalizeFile(file, processFile);
} else {
FileUtil.deleteFile(processFile);
Files.deleteIfExists(processFile.toPath());
}
}
}
Expand All @@ -509,11 +510,8 @@ private void finalizeFile(File file, File processFile) throws IOException {
if (isKeepBackup() && !isDryRun()) {
File backupFile = FileUtil.getBackupFile(file);

if (backupFile.exists()) {

// always delete backup file, before the renaming
FileUtil.deleteFile(backupFile);
}
// always delete backup file, before the renaming
Files.deleteIfExists(backupFile.toPath());

LOG.debug(" - backup original file {}", file);
FileUtil.renameFile(file, backupFile);
Expand All @@ -522,10 +520,9 @@ private void finalizeFile(File file, File processFile) throws IOException {
if (isDryRun()) {

// dry run, delete temporary file
FileUtil.deleteFile(processFile);
Files.deleteIfExists(processFile.toPath());
} else {
try {

// replace file with the updated one
FileUtil.renameFile(processFile, file);
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ protected void doAction() throws Exception {
if (generateBundle) {

// creates the bundled license file
File bundleTarget = FileUtil.getFile(outputDirectory, bundleLicensePath);
File bundleTarget = new File(outputDirectory, bundleLicensePath);
FileUtil.copyFile(licenseFile, bundleTarget);

if (!resourceTarget.getName().equals(bundleTarget.getName())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -599,7 +599,7 @@ public void writeBundleThirdPartyFile(File thirdPartyFile, File outputDirectory,
throws IOException {

// creates the bundled license file
File bundleTarget = FileUtil.getFile(outputDirectory, bundleThirdPartyPath);
File bundleTarget = new File(outputDirectory, bundleThirdPartyPath);
LOG.info("Writing bundled third-party file to {}", bundleTarget);
FileUtil.copyFile(thirdPartyFile, bundleTarget);
}
Expand Down Expand Up @@ -637,7 +637,7 @@ private void loadOneGlobalSet(
LOG.info("Loading global license map from {}: {}", dep.toString(), propFile.getAbsolutePath());
SortedProperties props = new SortedProperties("utf-8");

try (InputStream propStream = new FileInputStream(propFile)) {
try (InputStream propStream = Files.newInputStream(propFile.toPath())) {
props.load(propStream);
} catch (IOException e) {
throw new IOException("Unable to load " + propFile.getAbsolutePath(), e);
Expand Down
94 changes: 5 additions & 89 deletions src/main/java/org/codehaus/mojo/license/utils/FileUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,13 @@
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
Expand All @@ -59,76 +56,6 @@
*/
public class FileUtil {

public static void tryClose(InputStream is) {
if (is == null) {
return;
}
try {
is.close();
} catch (IOException e) {
// do nothing
}
}

public static void tryClose(OutputStream os) {
if (os == null) {
return;
}
try {
os.close();
} catch (IOException e) {
// do nothing
}
}

/**
* Creates the directory (and his parents) if necessary.
*
* @param dir the directory to create if not exisiting
* @return {@code true} if directory was created, {@code false} if was no
* need to create it
* @throws IOException if could not create directory
*/
public static boolean createDirectoryIfNecessary(File dir) throws IOException {
if (!dir.exists()) {
boolean b = dir.mkdirs();
if (!b) {
throw new IOException("Could not create directory " + dir);
}
return true;
}
return false;
}

public static boolean createNewFile(File file) throws IOException {
createDirectoryIfNecessary(file.getParentFile());
if (!file.exists()) {
boolean b = file.createNewFile();
if (!b) {
throw new IOException("Could not create new file " + file);
}
return true;
}
return false;
}

/**
* Delete the given file.
*
* @param file the file to delete
* @throws IOException if could not delete the file
*/
public static void deleteFile(File file) throws IOException {
if (!file.exists()) {
// file does not exist, can not delete it
return;
}
boolean b = file.delete();
if (!b) {
throw new IOException("could not delete file " + file);
}
}

/**
* Rename the given file to a new destination.
*
Expand Down Expand Up @@ -158,18 +85,10 @@ public static void renameFile(File file, File destination) throws IOException {
* @throws IOException if could not copy file.
*/
public static void copyFile(File source, File target) throws IOException {
createDirectoryIfNecessary(target.getParentFile());
Files.createDirectories(target.getParentFile().toPath());
FileUtils.copyFile(source, target);
}

public static File getFile(File base, String... paths) {
StringBuilder buffer = new StringBuilder();
for (String path : paths) {
buffer.append(File.separator).append(path);
}
return new File(base, buffer.substring(1));
}

/**
* @param file the source file
* @return the backup file
Expand Down Expand Up @@ -200,12 +119,9 @@ public static void backupFile(File f) throws IOException {
* @throws IOException if IO pb
*/
public static String readAsString(File file, String encoding) throws IOException {
FileInputStream inf = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(inf, encoding));
try {

try (BufferedReader in = Files.newBufferedReader(file.toPath(), Charset.forName(encoding))) {
return IOUtil.toString(in);
} finally {
in.close();
}
}

Expand All @@ -218,7 +134,7 @@ public static String readAsString(File file, String encoding) throws IOException
* @throws IOException if IO pb
*/
public static void printString(File file, String content, String encoding) throws IOException {
createDirectoryIfNecessary(file.getParentFile());
Files.createDirectories(file.getParentFile().toPath());

BufferedReader in;
PrintWriter out;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
*/

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
Expand Down Expand Up @@ -95,11 +95,8 @@ public Enumeration<Object> keys() {
* @throws java.io.IOException if any io pb
*/
public SortedProperties load(File src) throws IOException {
FileInputStream reader = new FileInputStream(src);
try {
try (InputStream reader = Files.newInputStream(src.toPath())) {
load(reader);
} finally {
reader.close();
}
return this;
}
Expand All @@ -111,11 +108,8 @@ public SortedProperties load(File src) throws IOException {
* @throws java.io.IOException if any io pb
*/
public void store(File dst) throws IOException {
OutputStream writer = new FileOutputStream(dst);
try {
try (OutputStream writer = Files.newOutputStream(dst.toPath())) {
store(writer, null);
} finally {
writer.close();
}
}

Expand Down

0 comments on commit 00f8a6d

Please sign in to comment.