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

Fix a few Sonarcloud issues in AuditManager #7729

Merged
merged 2 commits into from
Nov 27, 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
31 changes: 9 additions & 22 deletions java/code/src/com/redhat/rhn/common/util/FileUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static void writeStringToFile(String contents, String path) {
try {
File file = new File(path);
if (file.exists()) {
file.delete();
Files.delete(file.toPath());
}
file.createNewFile();
try (FileOutputStream fos = new FileOutputStream(file);
Expand All @@ -82,7 +82,7 @@ public static void writeStringToFile(String contents, String path) {
}
catch (Exception e) {
log.error("Error trying to write file to disk: [{}]", path, e);
throw new RuntimeException(e);
throw new RhnRuntimeException(e);
}
}

Expand Down Expand Up @@ -171,9 +171,7 @@ public static byte[] readByteArrayFromFile(File fileToRead, long start, long end
log.debug("size of array: {}", size);
// Create the byte array to hold the data
byte[] bytes = new byte[size];
InputStream is = null;
try {
is = new FileInputStream(fileToRead);
try (InputStream is = new FileInputStream(fileToRead)) {
// Read in the bytes
int offset = 0;
int numRead = 0;
Expand All @@ -189,17 +187,7 @@ public static byte[] readByteArrayFromFile(File fileToRead, long start, long end
}
catch (IOException fnf) {
log.error("Could not read from: {}", fileToRead.getAbsolutePath());
throw new RuntimeException(fnf);
}
finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
throw new RhnRuntimeException(fnf);
}
return bytes;
}
Expand All @@ -211,10 +199,8 @@ public static byte[] readByteArrayFromFile(File fileToRead, long start, long end
* @return tail of file as string
*/
public static String getTailOfFile(String pathToFile, Integer lines) {
InputStream fileStream = null;
CircularFifoBuffer buffer = new CircularFifoBuffer(lines);
try {
fileStream = new FileInputStream(pathToFile);
try (InputStream fileStream = new FileInputStream(pathToFile)) {
LineIterator it = org.apache.commons.io.IOUtils.lineIterator(fileStream,
(String) null);
while (it.hasNext()) {
Expand All @@ -223,10 +209,11 @@ public static String getTailOfFile(String pathToFile, Integer lines) {
}
catch (FileNotFoundException e) {
log.error("File not found: {}", pathToFile);
throw new RuntimeException(e);
throw new RhnRuntimeException(e);
}
finally {
org.apache.commons.io.IOUtils.closeQuietly(fileStream);
catch (IOException e) {
log.error(String.format("Failed to close file %s", pathToFile));
throw new RhnRuntimeException(e);
}
// Construct a string from the buffered lines
StringBuilder sb = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import com.redhat.rhn.common.util.DatePicker;
import com.redhat.rhn.frontend.action.common.DateRangePicker;
import com.redhat.rhn.frontend.dto.AuditDto;
import com.redhat.rhn.frontend.dto.AuditReviewDto;
import com.redhat.rhn.frontend.struts.RequestContext;
import com.redhat.rhn.frontend.struts.RhnAction;
Expand Down Expand Up @@ -98,7 +99,7 @@ private Long processEndMilli(DynaActionForm dform,
private DateRangePicker.DatePickerResults processTimeArgs(
DynaActionForm dform,
HttpServletRequest request,
Boolean processDates) {
boolean processDates) {
Date start, end;
DateRangePicker drp = new DateRangePicker(dform, request,
new Date(processStartMilli(dform, request)),
Expand All @@ -108,7 +109,7 @@ private DateRangePicker.DatePickerResults processTimeArgs(
DateRangePicker.DatePickerResults dpresults =
drp.processDatePickers(processDates, false);

if (processDates) { // we need to redo {start,end}{Disp,Milli}
if (processDates) {
start = dpresults.getStart().getDate();
end = dpresults.getEnd().getDate();
request.setAttribute("startDisp", start.toString());
Expand Down Expand Up @@ -162,13 +163,13 @@ public ActionForward execute(ActionMapping mapping,
HttpServletResponse response) {
ActionMessages amsgs;
AuditReviewDto aureview;
Boolean parseDates, submitted, unrev;
boolean parseDates, submitted, unrev;
DateRangePicker.DatePickerResults dpresults;
DynaActionForm dform = (DynaActionForm)form;
HttpSession session = request.getSession(true);
JSONWriter jsonwr = new JSONWriter();
List<String> result = null;
Long start, end, seqno, cacheSeqno;
List<AuditDto> result = null;
long start, end;
Map<String, String[]> typemap;
RequestContext requestContext = new RequestContext(request);
String machine;
Expand All @@ -182,13 +183,13 @@ public ActionForward execute(ActionMapping mapping,
// what machine are we looking at?
machine = dform.getString("machine");
// should we look at the DatePickers?
parseDates = (Boolean)dform.get("parseDates") != null;
parseDates = dform.get("parseDates") != null;
// did we receive a form with some checkboxes checked?
submitted = (autypes != null && autypes.length > 0);
// can we mark this section reviewed?
unrev = (Boolean)dform.get("unreviewable") != null;
unrev = dform.get("unreviewable") != null;
// get the "page creation time" to determine cache usage
seqno = (Long)dform.get("seqno");
Long seqno = (Long)dform.get("seqno");

if (seqno == null) {
log.debug("(re-)initializing cache");
Expand Down Expand Up @@ -223,7 +224,7 @@ else if (!submitted && request.getAttribute("machine") != null) {
start = dpresults.getStart().getDate().getTime();
end = dpresults.getEnd().getDate().getTime();

cacheSeqno = (Long)session.getAttribute("auditCacheSeqno");
Long cacheSeqno = (Long)session.getAttribute("auditCacheSeqno");

// if the cached seqno is greater or equal to the seqno the browser
// sent, we've seen it before; do a new search
Expand All @@ -237,7 +238,7 @@ else if (!submitted && request.getAttribute("machine") != null) {
else {
log.debug("using cached result");
// may be null (indicates the cached result was null)
result = (List)session.getAttribute("auditResultCache");
result = (List<AuditDto>)session.getAttribute("auditResultCache");
}

if (result == null) {
Expand Down
3 changes: 2 additions & 1 deletion java/code/src/com/redhat/rhn/frontend/dto/AuditDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@
*/
package com.redhat.rhn.frontend.dto;

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

/**
* AuditDto
*/
public class AuditDto extends BaseDto {
public class AuditDto extends BaseDto implements Serializable {
private Long id;
private int serial;
private Date time;
Expand Down
83 changes: 34 additions & 49 deletions java/code/src/com/redhat/rhn/manager/audit/AuditManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/
package com.redhat.rhn.manager.audit;

import com.redhat.rhn.common.RhnRuntimeException;
import com.redhat.rhn.common.conf.Config;
import com.redhat.rhn.common.db.datasource.DataResult;
import com.redhat.rhn.frontend.dto.AuditDto;
Expand All @@ -29,6 +30,7 @@
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
Expand Down Expand Up @@ -79,56 +81,35 @@ public static void markReviewed(String machine, Long start, Long end, String use
* @param end The end time; can be null
* @return The set of matching audit logs
*/
public static DataResult getAuditLogs(String[] types, String machine,
Long start, Long end) {
DataResult dr = null;
List l;
Long fileStart, fileEnd;
public static DataResult<AuditDto> getAuditLogs(String[] types, String machine, long start, long end) {
DataResult<AuditDto> dr = new DataResult<>(new ArrayList<>());

if (types == null) {
types = new String[0];
}

if (start == null) {
start = 0L;
}

if (end == null) {
end = Long.MAX_VALUE;
}

try {
DataResult<AuditReviewDto> aureviewsections = getMachineReviewSections(machine);
if (aureviewsections != null) {
for (AuditReviewDto aureview : getMachineReviewSections(machine)) {
fileStart = aureview.getStart().getTime();
fileEnd = aureview.getEnd().getTime();

if (fileEnd < start || fileStart > end) {
continue;
}
for (AuditReviewDto aureview : getMachineReviewSections(machine)) {
long fileStart = aureview.getStart().getTime();
long fileEnd = aureview.getEnd().getTime();

File auditLog = new File(
logDirStr + "/" + aureview.getName() + "/audit/audit-" +
(fileStart / 1000) + "-" +
(fileEnd / 1000) + ".parsed");
if (fileEnd < start || fileStart > end) {
continue;
}

l = readAuditFile(auditLog, types, start, end);
File auditLog = new File(
logDirStr + File.separator + aureview.getName() + "/audit/audit-" +
(fileStart / 1000) + "-" +
(fileEnd / 1000) + ".parsed");

if (dr == null) {
dr = new DataResult(l);
}
else {
dr.addAll(l);
}
}
dr.addAll(readAuditFile(auditLog, types, start, end));
}
}
catch (IOException ioex) {
log.warn("AAAAHHHH IOException", ioex);
}

if (dr == null || dr.isEmpty()) {
if (dr.isEmpty()) {
return null;
}

Expand Down Expand Up @@ -220,12 +201,9 @@ public static AuditReviewDto getFirstUnreviewed(String machineName) {
DataResult<AuditReviewDto> dr = getMachineReviewSections(machineName);

for (AuditReviewDto aurev : dr) {
if (aurev.getReviewedBy() == null) { // an unreviewed log!
if (firstUnreviewed == null ||
aurev.getStart().getTime() <
firstUnreviewed.getStart().getTime()) {
firstUnreviewed = aurev;
}
if (aurev.getReviewedBy() == null && // an unreviewed log!
(firstUnreviewed == null || aurev.getStart().getTime() < firstUnreviewed.getStart().getTime())) {
firstUnreviewed = aurev;
}
}

Expand All @@ -242,12 +220,9 @@ public static AuditReviewDto getLastReview(String machineName) {
DataResult<AuditReviewDto> dr = getMachineReviewSections(machineName);

for (AuditReviewDto aurev : dr) {
if (aurev.getReviewedOn() != null) {
if (lastReviewed == null ||
aurev.getReviewedOn().getTime() >
lastReviewed.getReviewedOn().getTime()) {
lastReviewed = aurev;
}
if (aurev.getReviewedOn() != null && (lastReviewed == null ||
aurev.getReviewedOn().getTime() > lastReviewed.getReviewedOn().getTime())) {
lastReviewed = aurev;
}
}

Expand Down Expand Up @@ -304,15 +279,25 @@ public static DataResult<AuditMachineDto> getMachines() {
* @param machineName The machine to get review sections for; can be null
* @return The set of review sections
*/
@SuppressWarnings("javasecurity:S2083") // host.list() is validated right after it is declared
public static DataResult<AuditReviewDto> getMachineReviewSections(String machineName) {
// if machineName is null, get all review sections by recursion
if (machineName == null || machineName.isEmpty()) {
return getRecursiveReviewSections();
}

// otherwise, just look up this one machine
File hostDir = Path.of(logDirStr, machineName.replace(File.separator, ""), "audit").toFile();
File hostDir = Path.of(logDirStr, machineName, "audit").toFile();

try {
String hostPath = hostDir.getCanonicalPath();
if (!hostPath.startsWith(logDirStr)) {
throw new RhnRuntimeException("Invalid machine name");
}
}
catch (IOException e) {
log.warn("Failed getting canonical path of {}", hostDir.getAbsolutePath(), e);
return new DataResult<>(new LinkedList<>());
}

if (!hostDir.exists()) {
return new DataResult<>(new LinkedList<>());
Expand Down