Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use try-with-resources to properly close streams #7274

Merged
merged 3 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions java/code/src/com/redhat/rhn/frontend/dto/AuditDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* AuditDto
Expand All @@ -27,7 +28,7 @@ public class AuditDto extends BaseDto {
private int milli;
private String node;

private LinkedHashMap<String, String> kvmap;
private Map<String, String> kvmap;

private String type;

Expand All @@ -39,8 +40,7 @@ public class AuditDto extends BaseDto {
* @param nodeIn Audit generating node
* @param kvmapIn HashMap of audit data
*/
public AuditDto(int serialIn, Date timeIn, int milliIn, String nodeIn,
LinkedHashMap<String, String> kvmapIn) {
public AuditDto(int serialIn, Date timeIn, int milliIn, String nodeIn, Map<String, String> kvmapIn) {
this.id = (long) serialIn;
this.serial = serialIn;
this.time = timeIn;
Expand Down Expand Up @@ -91,7 +91,7 @@ public String getNode() {
/**
* @return Returns the key-value audit data.
*/
public LinkedHashMap<String, String> getKvmap() {
public Map<String, String> getKvmap() {
return kvmap;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -595,11 +595,12 @@ public byte[] getPackage(User loggedInUser, Integer pid) throws IOException {
}

byte[] toReturn = new byte[(int) file.length()];
BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
if (br.read(toReturn) != file.length()) {
throw new PackageDownloadException("api.package.download.ioerror");
try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(file))) {
if (br.read(toReturn) != file.length()) {
throw new PackageDownloadException("api.package.download.ioerror");
}
return toReturn;
}
return toReturn;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5672,8 +5672,7 @@ public Map transitionDataForSystem(String clientCert) throws FileNotFoundExcepti
break;
}

try {
BufferedReader br = new BufferedReader(new FileReader(file));
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
String[] header = null;
Integer systemIdPos = null, uuidPos = null;
Expand Down Expand Up @@ -5719,7 +5718,6 @@ public Map transitionDataForSystem(String clientCert) throws FileNotFoundExcepti
}
}
}
br.close();
}
catch (IOException e) {
log.warn("Cannot read {}", file.getName());
Expand Down
124 changes: 55 additions & 69 deletions java/code/src/com/redhat/rhn/manager/audit/AuditManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
Expand Down Expand Up @@ -62,13 +63,11 @@ private AuditManager() {
* @param username User marking the review
* @throws IOException Thrown when the audit review log isn't writeable
*/
public static void markReviewed(String machine, Long start, Long end,
String username) throws IOException {
FileWriter fwr = new FileWriter(reviewFile, true); // append!

fwr.write(machine + "," + (start / 1000) + "," + (end / 1000) + "," +
username + "," + (new Date().getTime() / 1000) + "\n");
fwr.close();
public static void markReviewed(String machine, Long start, Long end, String username) throws IOException {
try (FileWriter fwr = new FileWriter(reviewFile, true)) { // append!
fwr.write(machine + "," + (start / 1000) + "," + (end / 1000) + "," +
username + "," + (new Date().getTime() / 1000) + "\n");
}
}

/**
Expand Down Expand Up @@ -371,87 +370,74 @@ public static DataResult<AuditReviewDto> getMachineReviewSections(
* @throws IOException Throws when the audit review file is unreadable
* @return An AuditReviewDto, possibly with review info set
*/
public static AuditReviewDto getReviewInfo(String machine, long start,
long end) throws IOException {
BufferedReader brdr;
public static AuditReviewDto getReviewInfo(String machine, long start, long end) throws IOException {
Date reviewedOn = null;
String str, part1, reviewedBy = null;
String[] revInfo;

part1 = machine + "," + (start / 1000) + "," + (end / 1000) + ",";

brdr = new BufferedReader(new FileReader(reviewFile));
try (BufferedReader brdr = new BufferedReader(new FileReader(reviewFile))) {

while ((str = brdr.readLine()) != null) {
if (str.startsWith(part1)) {
revInfo = str.split(",");
reviewedBy = revInfo[3];
reviewedOn = new Date(Long.parseLong(revInfo[4]) * 1000);
break;
while ((str = brdr.readLine()) != null) {
if (str.startsWith(part1)) {
revInfo = str.split(",");
reviewedBy = revInfo[3];
reviewedOn = new Date(Long.parseLong(revInfo[4]) * 1000);
break;
}
}

return new AuditReviewDto(machine, new Date(start), new Date(end), reviewedBy, reviewedOn);
}
}

brdr.close();
private static List<AuditDto> readAuditFile(File aufile, String[] types, Long start, Long end) throws IOException {
List<AuditDto> events = new LinkedList<>();

return new AuditReviewDto(machine, new Date(start), new Date(end),
reviewedBy, reviewedOn);
}
try (BufferedReader reader = new BufferedReader(new FileReader(aufile))) {
Map<String, String> hmap = new LinkedHashMap<>();

private static List readAuditFile(File aufile, String[] types, Long start,
Long end) throws IOException {
int milli = 0, serial = -1;
BufferedReader brdr;
LinkedHashMap<String, String> hmap;
LinkedList<AuditDto> events;
Long time = -1L;
String node = null, str, strtime = null;

brdr = new BufferedReader(new FileReader(aufile));
events = new LinkedList<>();
hmap = new LinkedHashMap<>();

for (str = brdr.readLine(); str != null; str = brdr.readLine()) {
if (str.equals("")) {
strtime = hmap.remove("seconds");

try {
serial = Integer.parseInt(hmap.remove("serial"));
}
catch (NumberFormatException nfex) {
serial = -1;
}
for (String str = reader.readLine(); str != null; str = reader.readLine()) {
if (str.equals("")) {
int serial = getSerial(hmap);
long time = getTime(hmap);

if (time >= start && time <= end && Arrays.asList(types).contains(hmap.get("type"))) {
events.add(new AuditDto(serial, new Date(time), 0, null, hmap));
}

try {
time = Long.parseLong(strtime) * 1000;
hmap.clear();
}
catch (NumberFormatException nfex) {
time = 0L;
else if (str.indexOf('=') >= 0) {
hmap.put(
str.substring(0, str.indexOf('=')).trim(),
str.substring(str.indexOf('=') + 1).trim());
}

if (time >= start && time <= end) {
for (String type : types) {
if (type.equals(hmap.get("type"))) {
events.add(new AuditDto(
serial, new Date(time), milli, node, hmap));
break;
}
}
else {
log.debug("unknown string: {}", str);
}

hmap.clear();
}
else if (str.indexOf('=') >= 0) {
hmap.put(
str.substring(0, str.indexOf('=')).trim(),
str.substring(str.indexOf('=') + 1).trim());
}
else {
log.debug("unknown string: {}", str);
}

return events;
}
}

brdr.close();
private static Long getTime(Map<String, String> hmap) {
try {
return Long.parseLong(hmap.remove("seconds")) * 1000;
}
catch (NumberFormatException ex) {
return 0L;
}
}

return events;
private static int getSerial(Map<String, String> hmap) {
try {
return Integer.parseInt(hmap.remove("serial"));
}
catch (NumberFormatException nfex) {
return -1;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* Class responsible for executing one-time upgrade logic
Expand Down Expand Up @@ -316,10 +317,12 @@ private void regenerateConfigChannelFiles() {

// list of directories with given prefix and natural number suffix in the salt root
private Set<Path> listDirsWithPrefix(String prefix) throws IOException {
return Files.list(saltRootPath)
try (Stream<Path> pathStream = Files.list(saltRootPath)) {
return pathStream
.filter(path -> path.getFileName().toString().matches("^" + prefix + "\\d*$") &&
path.toFile().isDirectory())
path.toFile().isDirectory())
.collect(Collectors.toSet());
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -476,11 +476,8 @@ private void generateSolv(Channel channel) {
private void generateBadRepo(Channel channel, String prefix) {
log.warn("No repo will be generated for channel {}", channel.getLabel());
deleteRepomdFiles(channel.getLabel(), false);
try {
FileWriter norepo = new FileWriter(prefix + NOREPO_FILE);
norepo.write("No repo will be generated for channel " +
channel.getLabel() + ".\n");
norepo.close();
try (FileWriter norepo = new FileWriter(prefix + NOREPO_FILE)) {
norepo.write("No repo will be generated for channel " + channel.getLabel() + ".\n");
}
catch (IOException e) {
log.warn("Cannot create " + NOREPO_FILE + " file.");
Expand Down Expand Up @@ -549,29 +546,36 @@ private RepomdIndexData loadRepoMetadataFile(Channel channel, String checksumAlg
return null;
}

DigestInputStream digestStream;
try {
digestStream = new DigestInputStream(stream, MessageDigest
.getInstance(checksumAlgo));
try (DigestInputStream digestStream = new DigestInputStream(stream, MessageDigest.getInstance(checksumAlgo))) {

if (!computeDigest(digestStream)) {
return null;
}

Date timeStamp = new Date(metadataFile.lastModified());

return new RepomdIndexData(
StringUtil.getHexString(digestStream.getMessageDigest().digest()),
null,
timeStamp
);
}
catch (NoSuchAlgorithmException nsae) {
catch (IOException | NoSuchAlgorithmException nsae) {
throw new RepomdRuntimeException(nsae);
}
byte[] bytes = new byte[10];
}

private static boolean computeDigest(DigestInputStream digestStream) {
try {
byte[] bytes = new byte[10];
while (digestStream.read(bytes) != -1) {
// no-op
// no-op, just fully consume the stream so that the digest is computed
}
}
catch (IOException e) {
return null;
return false;
}

Date timeStamp = new Date(metadataFile.lastModified());

return new RepomdIndexData(StringUtil.getHexString(digestStream
.getMessageDigest().digest()), null, timeStamp);
return true;
}

/**
Expand Down
6 changes: 3 additions & 3 deletions java/code/src/com/suse/manager/reactor/PGEventStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,9 @@ public PGEventStream() throws SaltException {
connection = (PGConnection) dataSource.getConnection();
connection.addNotificationListener(this);

Statement stmt = connection.createStatement();
stmt.execute("LISTEN suseSaltEvent");
stmt.close();
try (Statement stmt = connection.createStatement()) {
stmt.execute("LISTEN suseSaltEvent");
}

startConnectionWatchdog();

Expand Down
22 changes: 12 additions & 10 deletions java/code/src/com/suse/manager/webui/utils/MinionActionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -181,17 +181,19 @@ public void cleanupScriptActions() throws IOException {
Path scriptsDir = saltUtils.getScriptsDir();
if (Files.isDirectory(scriptsDir)) {
Pattern p = Pattern.compile("script_(\\d*).sh");
Files.list(scriptsDir).forEach(file -> {
Matcher m = p.matcher(file.getFileName().toString());
if (m.find()) {
long actionId = Long.parseLong(m.group(1));
Action action = ActionFactory.lookupById(actionId);
if (action == null || action.allServersFinished()) {
LOG.info("Deleting script file: {}", file);
FileUtils.deleteFile(file);
try (Stream<Path> pathStream = Files.list(scriptsDir)) {
pathStream.forEach(file -> {
Matcher m = p.matcher(file.getFileName().toString());
if (m.find()) {
long actionId = Long.parseLong(m.group(1));
Action action = ActionFactory.lookupById(actionId);
if (action == null || action.allServersFinished()) {
LOG.info("Deleting script file: {}", file);
FileUtils.deleteFile(file);
}
}
}
});
});
}
}
}

Expand Down
Loading