Skip to content

Commit

Permalink
Inspection fixes, recommended changes for upgraded Java versions
Browse files Browse the repository at this point in the history
  • Loading branch information
retrodaredevil committed Mar 29, 2023
1 parent 735fdcd commit d3f48f4
Show file tree
Hide file tree
Showing 43 changed files with 107 additions and 153 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

Stores solar data in a database to view on Android, Grafana, or PVOutput

<p align="center">
<p style="text-align: center;">
<a href="#supported-products">Supported Products</a> &bull;
<a href="https://solarthing.readthedocs.io/">Documentation</a> &bull;
<a href="#features">Features</a> &bull;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public void setDeclaredAction(String name, ActionEnvironment actionEnvironment,
declaredActionMap.put(name, new DeclaredAction(actionEnvironment, actionNode));
}
public LockSet getLockSet(String name) {
// TODO lockSetMap is never updated, so a call to this method is guaranteed to result in a NoSuchElementException
if (!lockSetMap.containsKey(name)) {
if (outerVariableEnvironment == null) {
throw new NoSuchElementException("LockSet with name='" + name + "' not declared!");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ private void receivePacketWithIntegrity(String sender, TargetPacketGroup packetG
}


// TODO put thought into how to better design the alter manager program and SolarThing database replication
/**
* @deprecated This method *probably* works perfectly fine, but it is untested against malicious data and the fact that we have to use this method itself shows
* how we are using this as a bandaid for the real problem: We need to be sure that the solarthing_open database is secure
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import me.retrodaredevil.action.node.environment.InjectEnvironment;
import me.retrodaredevil.solarthing.reason.ExecutionReason;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
Expand All @@ -13,7 +12,7 @@ public class EnvironmentUpdaterMultiplexer implements EnvironmentUpdater {
private final List<EnvironmentUpdater> environmentUpdaterList;

public EnvironmentUpdaterMultiplexer(Collection<? extends EnvironmentUpdater> environmentUpdaters) {
this.environmentUpdaterList = Collections.unmodifiableList(new ArrayList<>(environmentUpdaters));
this.environmentUpdaterList = List.copyOf(environmentUpdaters);
}
public EnvironmentUpdaterMultiplexer(EnvironmentUpdater... environmentUpdaters) {
this.environmentUpdaterList = Collections.unmodifiableList(Arrays.asList(environmentUpdaters));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public final class MultiRoverModbusEnvironment {
private final Map<Integer, RoverModbusEnvironment> map;

public MultiRoverModbusEnvironment(Map<Integer, RoverModbusEnvironment> map) {
this.map = Collections.unmodifiableMap(new HashMap<>(map));
this.map = Map.copyOf(map);
}
public MultiRoverModbusEnvironment() {
this.map = Collections.emptyMap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public final class MultiTracerModbusEnvironment {
private final Map<Integer, TracerModbusEnvironment> map;

public MultiTracerModbusEnvironment(Map<Integer, TracerModbusEnvironment> map) {
this.map = Collections.unmodifiableMap(new HashMap<>(map));
this.map = Map.copyOf(map);
}
public MultiTracerModbusEnvironment() {
this.map = Collections.emptyMap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@
import me.retrodaredevil.solarthing.annotations.NotNull;
import me.retrodaredevil.solarthing.message.MessageSender;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ChatBotHandlerMultiplexer implements ChatBotHandler {
private final List<ChatBotHandler> chatBotHandlerList;

public ChatBotHandlerMultiplexer(List<? extends ChatBotHandler> chatBotHandlerList) {
this.chatBotHandlerList = Collections.unmodifiableList(new ArrayList<>(chatBotHandlerList));
this.chatBotHandlerList = List.copyOf(chatBotHandlerList);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ public boolean handleMessage(Message message, MessageSender messageSender) {
String durationString = aliasSplit[1];
defaultDuration = TimeUtil.lenientParseDurationOrNull(durationString);
if (defaultDuration == null) {
messageSender.sendMessage("Invalid duration: " + defaultDuration);
messageSender.sendMessage("Invalid duration: " + durationString);
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public InfluxDbDatabaseSettings(InfluxProperties influxProperties, OkHttpPropert
this.okHttpProperties = requireNonNull(okHttpProperties);
this.databaseName = databaseName;
this.measurementName = measurementName;
this.frequentStatusRetentionPolicyList = Collections.unmodifiableList(new ArrayList<>(frequentRetentionPolicies));
this.frequentStatusRetentionPolicyList = List.copyOf(frequentRetentionPolicies);
this.eventRetentionPolicySetting = eventRetentionPolicySetting;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import static java.util.Objects.requireNonNull;

@SuppressWarnings("CanBeFinal")
@JsonTypeName("automation")
@JsonExplicit
public class AutomationProgramOptions extends DatabaseTimeZoneOptionBase implements ActionsOption {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import java.nio.file.Path;

@SuppressWarnings("CanBeFinal")
@JsonExplicit
public abstract class DatabaseTimeZoneOptionBase extends TimeZoneOptionBase implements DatabaseOption, TimeZoneOption {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import static java.util.Objects.requireNonNull;

@SuppressWarnings({"FieldMayBeFinal", "CanBeFinal"})
@JsonTypeName("mate")
@JsonIgnoreProperties("allow_commands")
public class MateProgramOptions extends PacketHandlingOptionBase implements IOBundleOption, ProgramOptions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import java.util.List;
import java.util.Map;

@SuppressWarnings("FieldMayBeFinal")
@SuppressWarnings({"FieldMayBeFinal", "CanBeFinal"})
@JsonTypeName("pvoutput-upload")
@JsonExplicit
public class PVOutputUploadProgramOptions extends DatabaseTimeZoneOptionBase implements AnalyticsOption, DatabaseOption, ProgramOptions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import static java.util.Objects.requireNonNull;

@SuppressWarnings("FieldCanBeLocal")
@SuppressWarnings({"FieldCanBeLocal", "CanBeFinal"})
abstract class PacketHandlingOptionBase extends TimeZoneOptionBase implements PacketHandlingOption, ActionsOption, CommandOption, AnalyticsOption {
// private static final Logger LOGGER = LoggerFactory.getLogger(PacketHandlingOptionBase.class);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import static java.util.Objects.requireNonNull;

@SuppressWarnings({"FieldMayBeFinal", "CanBeFinal"})
public abstract class RequestProgramOptionsBase extends PacketHandlingOptionBase implements CommandOption, ActionsOption {

// When defined as a Duration, Jackson will parse numbers as second values for the duration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import static java.util.Objects.requireNonNull;

@SuppressWarnings({"FieldMayBeFinal", "CanBeFinal"})
@JsonTypeName("rover-setup")
@JsonExplicit
public class RoverSetupProgramOptions implements ProgramOptions, RoverOption {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public boolean isIgnoreUnsuccessfulCreate() {
return ignoreUnsuccessfulCreate;
}

@SuppressWarnings({"FieldMayBeFinal", "CanBeFinal"})
@JsonPOJOBuilder
static class Builder {
@JsonProperty("name")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
package me.retrodaredevil.solarthing.message;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class MessageSenderMultiplexer implements MessageSender {
private final List<MessageSender> messageSenderList;

public MessageSenderMultiplexer(Collection<? extends MessageSender> messageSenders) {
this.messageSenderList = Collections.unmodifiableList(new ArrayList<>(messageSenders));
this.messageSenderList = List.copyOf(messageSenders);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,7 @@ public TemperatureEvent(
throw new IllegalArgumentException("Either celsius or fahrenheit must be defined!");
}
this.timeout = Duration.parse(timeoutDurationString);
if (temperatureType == null) {
this.temperatureType = TemperatureType.BATTERY;
} else {
this.temperatureType = temperatureType;
}
this.temperatureType = temperatureType == null ? TemperatureType.BATTERY : temperatureType;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ private void receivePacketGroup(StoredPacketGroup storedPacketGroup, TargetPacke
}
LargeIntegrityPacket largeIntegrityPacket = (LargeIntegrityPacket) packet;
String sender = largeIntegrityPacket.getSender();
final String invalidSenderReason = sender == null ? "sender is null!" : SenderUtil.getInvalidSenderNameReason(sender);
final String invalidSenderReason = SenderUtil.getInvalidSenderNameReason(sender);
if(invalidSenderReason != null){
LOGGER.warn(SolarThingConstants.SUMMARY_MARKER, invalidSenderReason);
reject(storedPacketGroup, SecurityRejectPacket.Reason.INVALID_DATA, invalidSenderReason);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@

import java.io.IOException;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.Arrays;
Expand All @@ -63,7 +65,6 @@ public class PVOutputUploadMain {

@SuppressWarnings({"SameReturnValue", "deprecation"})
public static int startPVOutputUpload(PVOutputUploadProgramOptions options, CommandOptions commandOptions, Path dataDirectory, boolean isValidate){
final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); // Not thread safe, otherwise this would be a static field

LOGGER.info(SolarThingConstants.SUMMARY_MARKER, "Starting PV Output upload program");
ZoneId zoneId = options.getZoneId();
Expand Down Expand Up @@ -91,13 +92,13 @@ public static int startPVOutputUpload(PVOutputUploadProgramOptions options, Comm
String toDateString = commandOptions.getPVOutputToDate();
if(fromDateString != null && toDateString != null) {
System.out.println("Starting range upload");
final SimpleDate fromDate;
final SimpleDate toDate;
final LocalDate fromDate;
final LocalDate toDate;
try {
// TODO Don't use SimpleDateFormat anymore and remove supress warnings for deprecation
fromDate = SimpleDate.fromDate(DATE_FORMAT.parse(fromDateString));
toDate = SimpleDate.fromDate(DATE_FORMAT.parse(toDateString));
} catch (ParseException e) {
fromDate = LocalDate.parse(fromDateString, DateTimeFormatter.ISO_LOCAL_DATE);
toDate = LocalDate.parse(toDateString, DateTimeFormatter.ISO_LOCAL_DATE);
} catch (DateTimeParseException e) {
e.printStackTrace();
System.err.println("Unable to parser either from date or to date. Use the yyyy-MM-dd format");
return SolarThingConstants.EXIT_CODE_INVALID_OPTIONS;
Expand All @@ -123,61 +124,57 @@ public static int startPVOutputUpload(PVOutputUploadProgramOptions options, Comm
}
@SuppressWarnings("CatchAndPrintStackTrace")
private static int startRangeUpload(
SimpleDate fromDate, SimpleDate toDate,
LocalDate fromDate, LocalDate toDate,
PVOutputUploadProgramOptions options, SolarThingDatabase database,
PVOutputHandler handler, PVOutputService service, ZoneId zoneId
) {
List<AddOutputParameters> addOutputParameters = new ArrayList<>();
SimpleDate date = fromDate;
while(date.compareTo(toDate) <= 0) {
for(LocalDate date = fromDate; !date.isAfter(toDate); date = date.plusDays(1)) { // toDate is inclusive
System.out.println("Doing " + date);
SimpleDate tomorrow = date.tomorrow();
long dayStart = date.getDayStartDateMillis(zoneId);
long dayEnd = tomorrow.getDayStartDateMillis(zoneId);
Instant dayStart = date.atStartOfDay(zoneId).toInstant();
Instant dayEnd = date.plusDays(1).atStartOfDay(zoneId).toInstant();

List<? extends PacketGroup> rawPacketGroups = null;
try {
rawPacketGroups = database.getStatusDatabase().query(new MillisQueryBuilder()
.startKey(dayStart)
.endKey(dayEnd)
.startKey(dayStart.toEpochMilli())
.endKey(dayEnd.toEpochMilli())
.inclusiveEnd(false)
.build()
);
System.out.println("Got " + rawPacketGroups.size() + " packets for date: " + date.toPVOutputString());
System.out.println("Got " + rawPacketGroups.size() + " packets for date: " + date);
} catch (SolarThingDatabaseException e) {
e.printStackTrace();
System.err.println("Couldn't query packets. Skipping " + date.toPVOutputString());
System.err.println("Couldn't query packets. Skipping " + date);
}
if (rawPacketGroups != null) {
List<FragmentedPacketGroup> packetGroups = PacketUtil.getPacketGroups(options.getSourceId(), options.getDefaultInstanceOptions(), rawPacketGroups);

if (packetGroups != null) {
if (!handler.checkPackets(dayStart, packetGroups)) {
System.err.println("Unsuccessfully checked packets for " + date.toPVOutputString());
if (!handler.checkPackets(dayStart.toEpochMilli(), packetGroups)) {
System.err.println("Unsuccessfully checked packets for " + date);
try {
System.out.println(MAPPER.writeValueAsString(packetGroups.get(packetGroups.size() - 1)));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
} else {
AddStatusParameters statusParameters = handler.getStatus(dayStart, packetGroups);
AddStatusParameters statusParameters = handler.getStatus(dayStart.toEpochMilli(), packetGroups);
AddOutputParametersBuilder outputParametersBuilder = new AddOutputParametersBuilder(statusParameters.getDate())
.setGenerated(statusParameters.getEnergyGeneration())
.setConsumption(statusParameters.getEnergyConsumption());
PVOutputHandler.setImportedExported(outputParametersBuilder, packetGroups, AccumulationConfig.createDefault(dayStart), options.isIncludeImport(), options.isIncludeExport());
PVOutputHandler.setImportedExported(outputParametersBuilder, packetGroups, AccumulationConfig.createDefault(dayStart.toEpochMilli()), options.isIncludeImport(), options.isIncludeExport());
AddOutputParameters outputParameters = outputParametersBuilder.build();
addOutputParameters.add(outputParameters);
System.out.println("Added parameters for " + date.toPVOutputString() + " to queue.");
System.out.println("Added parameters for " + date + " to queue.");
System.out.println("Generated: " + statusParameters.getEnergyGeneration());
System.out.println(Arrays.toString(outputParameters.toCsvArray()));
System.out.println(CsvUtil.toCsvString(outputParameters.toCsvArray()));
}
} else {
System.err.println("Didn't find any packets with source: " + options.getSourceId() + " for date: " + date.toPVOutputString());
System.err.println("Didn't find any packets with source: " + options.getSourceId() + " for date: " + date);
}
}

date = tomorrow;
}
System.out.println("Going to upload in batches of 30...");
for (int i = 0; i < addOutputParameters.size(); i += 30) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import java.time.Duration;

public class JacksonTestUtil {
public class JacksonUtilTest {
@Test
void testDefaultMapper() throws JsonProcessingException {
ObjectMapper mapper = JacksonUtil.defaultMapper();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import me.retrodaredevil.solarthing.config.databases.IndividualSettings;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@JsonExplicit
Expand All @@ -34,7 +33,7 @@ private DatabaseConfig(){

public DatabaseConfig(DatabaseSettings settings, Map<String, IndividualSettings> frequencySettingsMap) {
this.settings = settings;
this.individualSettingsMap = Collections.unmodifiableMap(new HashMap<>(frequencySettingsMap));
this.individualSettingsMap = Map.copyOf(frequencySettingsMap);
type = settings.getDatabaseType().getName();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public CouchDbAlterDatabase(CouchDbDatabase database, ObjectMapper mapper) {
ObjectNode objectNode = (ObjectNode) jsonNode;
final StoredAlterPacket storedAlterPacket;
try {
storedAlterPacket = mapper.treeToValue(objectNode, StoredAlterPacket.class);;
storedAlterPacket = mapper.treeToValue(objectNode, StoredAlterPacket.class);
} catch (JsonProcessingException e) {
throw new SolarThingDatabaseException("Could not parse. JsonData: " + jsonData.getJson(), e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public float getCpuTemperatureFahrenheit() {
}

@Override
public List<Core> getCores() {
public @NotNull List<Core> getCores() {
return cores;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

import java.security.PublicKey;

import static java.util.Objects.requireNonNull;

public final class ImmutableAuthNewSenderPacket implements AuthNewSenderPacket {

private final String sender;
Expand All @@ -19,8 +21,8 @@ public ImmutableAuthNewSenderPacket(
@JsonProperty(value = "sender", required = true) String sender,
@JsonProperty(value = "publicKey", required = true) String publicKey
) throws InvalidKeyException {
this.sender = sender;
this.publicKey = publicKey;
this.sender = requireNonNull(sender);
this.publicKey = requireNonNull(publicKey);
publicKeyObject = KeyUtil.decodePublicKey(publicKey);
}

Expand Down
Loading

0 comments on commit d3f48f4

Please sign in to comment.