Formatting cleanup

This commit is contained in:
Ziver Koc 2021-03-23 21:54:29 +01:00
parent c7e286f51e
commit 5a1be3c2e4
50 changed files with 283 additions and 282 deletions

View file

@ -65,11 +65,11 @@ public class EventControllerManager extends HalAbstractControllerManager<HalEven
*/
@Override
public void register(Event event) {
if(event.getDeviceConfig() == null) {
if (event.getDeviceConfig() == null) {
logger.warning("Event config is null: " + event);
return;
}
if(!availableEvents.contains(event.getDeviceConfig().getClass())) {
if (!availableEvents.contains(event.getDeviceConfig().getClass())) {
logger.warning("Event data plugin not available: " + event.getDeviceConfig().getClass());
return;
}
@ -78,7 +78,7 @@ public class EventControllerManager extends HalAbstractControllerManager<HalEven
Class<? extends HalEventController> c = event.getController();
HalEventController controller = getControllerInstance(c);
if(controller != null)
if (controller != null)
controller.register(event.getDeviceConfig());
registeredEvents.add(event);
detectedEvents.remove(HalDeviceUtil.findDevice(event.getDeviceConfig(), detectedEvents)); // Remove if this device was detected
@ -91,7 +91,7 @@ public class EventControllerManager extends HalAbstractControllerManager<HalEven
*/
@Override
public void deregister(Event event){
if(event.getDeviceConfig() == null) {
if (event.getDeviceConfig() == null) {
logger.warning("Event config is null: "+ event);
return;
}
@ -171,7 +171,7 @@ public class EventControllerManager extends HalAbstractControllerManager<HalEven
logger.info("Received report from unregistered event" +
"(" + eventConfig.getClass().getSimpleName() + "): " + eventConfig);
event = HalDeviceUtil.findDevice(eventConfig, detectedEvents);
if(event == null) {
if (event == null) {
event = new Event();
detectedEvents.add(event);
}
@ -179,7 +179,7 @@ public class EventControllerManager extends HalAbstractControllerManager<HalEven
}
event.setDeviceData(eventData);
// call listeners
for(HalDeviceReportListener<HalEventConfig,HalEventData> listener : event.getReportListeners())
for (HalDeviceReportListener<HalEventConfig,HalEventData> listener : event.getReportListeners())
listener.reportReceived(event.getDeviceConfig(), eventData);
}catch (SQLException e){
@ -189,7 +189,7 @@ public class EventControllerManager extends HalAbstractControllerManager<HalEven
public void send(Event event){
HalEventController controller = getControllerInstance(event.getController());
if(controller != null) {
if (controller != null) {
controller.send(event.getDeviceConfig(), event.getDeviceData());
reportReceived(event.getDeviceConfig(), event.getDeviceData()); // save action to db
}
@ -207,9 +207,9 @@ public class EventControllerManager extends HalAbstractControllerManager<HalEven
@Override
public void preConfigurationAction(Configurator configurator, Object obj) {
if(obj instanceof HalEventConfig) {
if (obj instanceof HalEventConfig) {
Event event = HalDeviceUtil.findDevice((HalEventConfig) obj, registeredEvents);
if(event != null){
if (event != null){
deregister(event);
limboEvents.add(event);
}
@ -220,7 +220,7 @@ public class EventControllerManager extends HalAbstractControllerManager<HalEven
public void postConfigurationAction(Configurator configurator, Object obj) {
if (obj instanceof HalEventConfig) {
Event event = HalDeviceUtil.findDevice((HalEventConfig) obj, limboEvents);
if(event != null){
if (event != null){
register(event);
limboEvents.remove(event);
}

View file

@ -74,7 +74,7 @@ public class HalContext {
File dbFile = FileUtil.find(DB_FILE);
db = new DBConnection(DBConnection.DBMS.SQLite, DB_FILE);
if(dbFile == null){
if (dbFile == null){
logger.info("No database file found, creating new DB...");
} else {
dbConf = db.exec("SELECT * FROM conf", new PropertiesSQLResult());
@ -92,9 +92,9 @@ public class HalContext {
-1);
logger.info("DB version: "+ dbVersion);
if(defaultDBVersion > dbVersion ) {
if (defaultDBVersion > dbVersion ) {
logger.info("Starting DB upgrade from v" + dbVersion + " to v" + defaultDBVersion + "...");
if(dbFile != null){
if (dbFile != null){
File backupDB = FileUtil.getNextFile(dbFile);
logger.fine("Backing up DB to: "+ backupDB);
FileUtil.copy(dbFile, backupDB);
@ -115,8 +115,8 @@ public class HalContext {
new SQLResultHandler<Object>() {
@Override
public Object handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
while(result.next()){
if(result.getBoolean("force_upgrade")){
while (result.next()){
if (result.getBoolean("force_upgrade")){
logger.fine("Forced upgrade enabled");
handler.setForcedDBUpgrade(true); //set to true if any of the intermediate db version requires it.
}
@ -139,19 +139,19 @@ public class HalContext {
boolean clearExternalAggrData = false;
boolean clearInternalAggrData = false;
while(result.next()){
if(result.getBoolean("clear_external_aggr_data"))
while (result.next()){
if (result.getBoolean("clear_external_aggr_data"))
clearExternalAggrData = true;
if(result.getBoolean("clear_internal_aggr_data"))
if (result.getBoolean("clear_internal_aggr_data"))
clearInternalAggrData = true;
}
if(clearExternalAggrData){
if (clearExternalAggrData){
logger.fine("Clearing external aggregate data");
db.exec("DELETE FROM sensor_data_aggr WHERE sensor_id = "
+ "(SELECT sensor.id FROM user, sensor WHERE user.external == 1 AND sensor.user_id = user.id)");
}
if(clearInternalAggrData){
if (clearInternalAggrData){
logger.fine("Clearing local aggregate data");
db.exec("DELETE FROM sensor_data_aggr WHERE sensor_id IN "
+ "(SELECT sensor.id FROM user, sensor WHERE user.external == 0 AND sensor.user_id = user.id)");

View file

@ -67,11 +67,11 @@ public class SensorControllerManager extends HalAbstractControllerManager<HalAbs
*/
@Override
public void register(Sensor sensor) {
if(sensor.getDeviceConfig() == null) {
if (sensor.getDeviceConfig() == null) {
logger.warning("Sensor config is null: " + sensor);
return;
}
if(!availableSensors.contains(sensor.getDeviceConfig().getClass())) {
if (!availableSensors.contains(sensor.getDeviceConfig().getClass())) {
logger.warning("Sensor data plugin not available: " + sensor.getDeviceConfig().getClass());
return;
}
@ -80,7 +80,7 @@ public class SensorControllerManager extends HalAbstractControllerManager<HalAbs
Class<? extends HalAbstractController> c = sensor.getController();
HalAbstractController controller = getControllerInstance(c);
if(controller != null)
if (controller != null)
controller.register(sensor.getDeviceConfig());
registeredSensors.add(sensor);
detectedSensors.remove(
@ -94,7 +94,7 @@ public class SensorControllerManager extends HalAbstractControllerManager<HalAbs
*/
@Override
public void deregister(Sensor sensor){
if(sensor.getDeviceConfig() == null) {
if (sensor.getDeviceConfig() == null) {
logger.warning("Sensor config is null: "+ sensor);
return;
}
@ -175,7 +175,7 @@ public class SensorControllerManager extends HalAbstractControllerManager<HalAbs
logger.finest("Received report from unregistered sensor" +
"(" + sensorConfig.getClass().getSimpleName() + "): " + sensorConfig);
sensor = HalDeviceUtil.findDevice(sensorConfig, detectedSensors);
if(sensor == null) {
if (sensor == null) {
sensor = new Sensor();
detectedSensors.add(sensor);
}
@ -183,7 +183,7 @@ public class SensorControllerManager extends HalAbstractControllerManager<HalAbs
}
sensor.setDeviceData(sensorData);
// call listeners
for(HalDeviceReportListener<HalSensorConfig,HalSensorData> listener : sensor.getReportListeners())
for (HalDeviceReportListener<HalSensorConfig,HalSensorData> listener : sensor.getReportListeners())
listener.reportReceived(sensorConfig, sensorData);
} catch (SQLException e){

View file

@ -51,7 +51,7 @@ public class SensorDataAggregatorDaemon implements HalDaemon {
public void run(){
try {
List<Sensor> sensorList = Sensor.getLocalSensors(HalContext.getDB());
for(Sensor sensor : sensorList){
for (Sensor sensor : sensorList){
logger.fine("Aggregating sensor_id: " + sensor.getId());
aggregateSensor(sensor);
}
@ -62,7 +62,7 @@ public class SensorDataAggregatorDaemon implements HalDaemon {
}
public void aggregateSensor(Sensor sensor) {
if(sensor.getDeviceConfig() == null){
if (sensor.getDeviceConfig() == null){
logger.fine("The sensor config is not available - ignoring it");
return;
}
@ -128,7 +128,7 @@ public class SensorDataAggregatorDaemon implements HalDaemon {
}
// Is there any new data to evaluate?
if(dbMaxRawTimestamp < dbMaxAggrEndTimestamp || dbMaxRawTimestamp < periodOldestStartTimestamp){
if (dbMaxRawTimestamp < dbMaxAggrEndTimestamp || dbMaxRawTimestamp < periodOldestStartTimestamp){
logger.fine("No new data to evaluate - aggregation is up to date");
return;
}
@ -215,8 +215,8 @@ public class SensorDataAggregatorDaemon implements HalDaemon {
"INSERT INTO sensor_data_aggr" +
"(sensor_id, sequence_id, timestamp_start, timestamp_end, data, confidence) " +
"VALUES(?, ?, ?, ?, ?, ?)");
while(result.next()){
if(sensorId != result.getInt("sensor_id")){
while (result.next()){
if (sensorId != result.getInt("sensor_id")){
throw new IllegalArgumentException("found entry for aggregation for the wrong sensorId " +
"(expecting: "+sensorId+", but was: "+result.getInt("sensor_id")+")");
}
@ -224,10 +224,10 @@ public class SensorDataAggregatorDaemon implements HalDaemon {
long timestamp = result.getLong("timestamp");
UTCTimePeriod dataPeriod = new UTCTimePeriod(timestamp, this.aggrPeriodLength);
if(currentPeriod == null)
if (currentPeriod == null)
currentPeriod = dataPeriod;
if(!dataPeriod.equals(currentPeriod)){
if (!dataPeriod.equals(currentPeriod)){
saveData(preparedInsertStmt, confidenceSum, sum, samples, currentPeriod, ++highestSequenceId);
// Reset variables
@ -242,7 +242,7 @@ public class SensorDataAggregatorDaemon implements HalDaemon {
}
//check if the last period is complete and also should be aggregated
if(currentPeriod != null &&
if (currentPeriod != null &&
currentPeriod.getEndTimestamp() <= new UTCTimePeriod(aggregationStartTime, aggrPeriodLength).getPreviosPeriod().getEndTimestamp()){
saveData(preparedInsertStmt, confidenceSum, sum, samples, currentPeriod, ++highestSequenceId);
}

View file

@ -30,7 +30,7 @@ public class SensorDataCleanupDaemon implements HalDaemon {
public void run(){
try {
List<Sensor> sensorList = Sensor.getSensors(HalContext.getDB());
for(Sensor sensor : sensorList){
for (Sensor sensor : sensorList){
logger.fine("Deleting old aggregated data for sensor id: " + sensor.getId());
cleanupSensor(sensor);
}
@ -97,8 +97,8 @@ public class SensorDataCleanupDaemon implements HalDaemon {
try{
HalContext.getDB().getConnection().setAutoCommit(false);
PreparedStatement preparedDeleteStmt = HalContext.getDB().getPreparedStatement("DELETE FROM sensor_data_aggr WHERE sensor_id == ? AND sequence_id == ?");
while(result.next()){
if(sensorId != result.getInt("sensor_id")){
while (result.next()){
if (sensorId != result.getInt("sensor_id")){
throw new IllegalArgumentException("Found entry for aggregation for the wrong sensorId (expecting: "+sensorId+", but was: "+result.getInt("sensor_id")+")");
}
logger.finer("Deleting sensor(id: "+ sensorId +") aggregate entry timestamp: "+ result.getLong("timestamp_start") +" - "+ result.getLong("timestamp_end") + " (" + UTCTimeUtility.timeInMsToString(1+result.getLong("timestamp_end")-result.getLong("timestamp_start")) + ")");

View file

@ -83,7 +83,7 @@ public abstract class HalAbstractDevice<V extends HalAbstractDevice, C extends H
* DeviceData will be reset if the input is set as null.
*/
public void setDeviceConfig(C data) {
if(data != null) {
if (data != null) {
type = data.getClass().getName();
deviceConfig = data;
deviceData = getLatestDeviceData(HalContext.getDB());

View file

@ -30,7 +30,7 @@ public class EventConfigWebPage extends HalWebPage {
super.getRootNav().createSubNav("Settings").createSubNav(this.getId(), "Event Settings").setWeight(200);
eventConfigurations = new ArrayList<>();
for(Class c : EventControllerManager.getInstance().getAvailableDeviceConfigs())
for (Class c : EventControllerManager.getInstance().getAvailableDeviceConfigs())
eventConfigurations.add(new ClassConfigurationData(c));
}
@ -45,7 +45,7 @@ public class EventConfigWebPage extends HalWebPage {
User localUser = User.getLocalUser(db);
// Save new input
if(request.containsKey("action")){
if (request.containsKey("action")) {
int id = (ObjectUtil.isEmpty(request.get("id")) ? -1 : Integer.parseInt(request.get("id")));
Event event;

View file

@ -27,7 +27,7 @@ public class EventOverviewWebPage extends HalWebPage {
private static final String DETAIL_TEMPLATE = HalContext.RESOURCE_WEB_ROOT + "/event_detail.tmpl";
public EventOverviewWebPage(){
public EventOverviewWebPage() {
super("event_overview");
super.getRootNav().createSubNav("Events").createSubNav(this.getId(), "Overview");
}

View file

@ -24,10 +24,10 @@ public class HalAlertManager implements HttpPage {
private UserMessageManager messageManager = new UserMessageManager();
private HalAlertManager(){}
private HalAlertManager() {}
public String getUrl(){
public String getUrl() {
return "/" + PAGE_NAME;
}
@ -74,10 +74,10 @@ public class HalAlertManager implements HttpPage {
public static void initialize(){
public static void initialize() {
instance = new HalAlertManager();
}
public static HalAlertManager getInstance(){
public static HalAlertManager getInstance() {
return instance;
}
}

View file

@ -15,7 +15,7 @@ public class PluginConfigWebPage extends HalWebPage {
private static final String TEMPLATE = HalContext.RESOURCE_WEB_ROOT + "/plugin_config.tmpl";
public PluginConfigWebPage(){
public PluginConfigWebPage() {
super("plugins");
super.getRootNav().createSubNav("Settings").createSubNav(this.getId(), "Plugins").setWeight(500);
}

View file

@ -12,7 +12,7 @@ public class PropertyConfigWebPage extends HalWebPage {
private static final String TEMPLATE = HalContext.RESOURCE_WEB_ROOT + "/property_config.tmpl";
public PropertyConfigWebPage(){
public PropertyConfigWebPage() {
super("properties");
super.getRootNav().createSubNav("Settings").createSubNav(this.getId(), "Properties");
}

View file

@ -31,7 +31,7 @@ public class SensorConfigWebPage extends HalWebPage {
super.getRootNav().createSubNav("Settings").createSubNav(this.getId(), "Sensor Settings").setWeight(100);
sensorConfigurations = new ArrayList<>();
for(Class c : SensorControllerManager.getInstance().getAvailableDeviceConfigs())
for (Class c : SensorControllerManager.getInstance().getAvailableDeviceConfigs())
sensorConfigurations.add(new ClassConfigurationData(c));
}
@ -46,7 +46,7 @@ public class SensorConfigWebPage extends HalWebPage {
User localUser = User.getLocalUser(db);
// Save new input
if(request.containsKey("action")){
if (request.containsKey("action")) {
int id = (ObjectUtil.isEmpty(request.get("id")) ? -1 : Integer.parseInt(request.get("id")));
Sensor sensor;
User user;
@ -70,7 +70,7 @@ public class SensorConfigWebPage extends HalWebPage {
case "modify_local_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null){
if (sensor != null) {
logger.info("Modifying sensor: " + sensor.getName());
sensor.setName(request.get("name"));
sensor.setType(request.get("type"));
@ -89,7 +89,7 @@ public class SensorConfigWebPage extends HalWebPage {
case "remove_local_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null) {
if (sensor != null) {
logger.warning("Removing sensor: " + sensor.getName());
SensorControllerManager.getInstance().deregister(sensor);
sensor.delete(db);
@ -122,7 +122,7 @@ public class SensorConfigWebPage extends HalWebPage {
case "modify_external_user":
user = User.getUser(db, id);
if(user != null){
if (user != null) {
logger.info("Modifying external user: " + user.getHostname());
user.setHostname(request.get("hostname"));
user.setPort(Integer.parseInt(request.get("port")));
@ -154,7 +154,7 @@ public class SensorConfigWebPage extends HalWebPage {
// External Sensors
case "modify_external_sensor":
sensor = Sensor.getSensor(db, id);
if(sensor != null){
if (sensor != null) {
logger.warning("Modifying external sensor: " + sensor.getName());
sensor.setSynced(Boolean.parseBoolean(request.get("sync")));
sensor.save(db);

View file

@ -23,7 +23,7 @@ public class SensorOverviewWebPage extends HalWebPage {
private static final String DETAIL_TEMPLATE = HalContext.RESOURCE_WEB_ROOT + "/sensor_detail.tmpl";
public SensorOverviewWebPage(){
public SensorOverviewWebPage() {
super("sensor_overview");
super.getRootNav().createSubNav("Sensors").createSubNav(this.getId(), "Overview");
}

View file

@ -33,10 +33,10 @@ public class TriggerWebPage extends HalWebPage {
super.getRootNav().createSubNav("Events").createSubNav(this.getId(), "Triggers");
triggerConfigurators = new ArrayList<>();
for(Class c : TriggerManager.getInstance().getAvailableTriggers())
for (Class c : TriggerManager.getInstance().getAvailableTriggers())
triggerConfigurators.add(new ClassConfigurationData(c));
actionConfigurators = new ArrayList<>();
for(Class c : TriggerManager.getInstance().getAvailableActions())
for (Class c : TriggerManager.getInstance().getAvailableActions())
actionConfigurators.add(new ClassConfigurationData(c));
}
@ -78,7 +78,7 @@ public class TriggerWebPage extends HalWebPage {
// Triggers
case "create_trigger":
if (flow == null){
if (flow == null) {
logger.warning("Invalid flow id: " + request.get("flow-id"));
HalAlertManager.getInstance().addAlert(new UserMessage(
MessageLevel.ERROR, "Invalid flow id: " + request.get("flow-id"), MessageTTL.ONE_VIEW));
@ -107,7 +107,7 @@ public class TriggerWebPage extends HalWebPage {
// Triggers
case "create_action":
if (flow == null){
if (flow == null) {
HalAlertManager.getInstance().addAlert(new UserMessage(
MessageLevel.ERROR, "Invalid flow id", MessageTTL.ONE_VIEW));
break;

View file

@ -101,7 +101,7 @@ public class TriggerFlow extends DBBean {
public boolean evaluate(){
if (triggerList.isEmpty() || !enabled)
return false;
for(Trigger trigger : triggerList){
for (Trigger trigger : triggerList){
if (!trigger.evaluate())
return false;
}
@ -114,7 +114,7 @@ public class TriggerFlow extends DBBean {
public void execute(){
if (!enabled)
return;
for(Action action : actionList){
for (Action action : actionList){
action.execute();
}
}
@ -123,7 +123,7 @@ public class TriggerFlow extends DBBean {
* Resets all trigger evaluations
*/
public void reset() {
for(Trigger trigger : triggerList){
for (Trigger trigger : triggerList){
trigger.reset();
}
}

View file

@ -48,7 +48,7 @@ public class User extends DBBean{
@Override
public void delete(DBConnection db) throws SQLException {
List<Sensor> sensorList = Sensor.getSensors(db, this);
for(Sensor sensor : sensorList){
for (Sensor sensor : sensorList){
sensor.delete(db);
}
super.delete(db);

View file

@ -44,7 +44,7 @@ public class AggregateDataListSqlResult implements SQLResultHandler<ArrayList<Ag
+ " ORDER BY timestamp_start ASC");
stmt.setLong(1, sensor.getId());
stmt.setLong(2, sensor.getUser().getId());
switch(aggrPeriodLength){
switch(aggrPeriodLength) {
case SECOND: stmt.setLong(3, UTCTimeUtility.SECOND_IN_MS-1); break;
case MINUTE: stmt.setLong(3, UTCTimeUtility.MINUTE_IN_MS-1); break;
case FIVE_MINUTES: stmt.setLong(3, UTCTimeUtility.FIVE_MINUTES_IN_MS-1); break;
@ -61,7 +61,7 @@ public class AggregateDataListSqlResult implements SQLResultHandler<ArrayList<Ag
private Sensor sensor;
private AggregateDataListSqlResult(Sensor sensor){
private AggregateDataListSqlResult(Sensor sensor) {
this.sensor = sensor;
}
@ -71,7 +71,7 @@ public class AggregateDataListSqlResult implements SQLResultHandler<ArrayList<Ag
public ArrayList<AggregateData> handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
ArrayList<AggregateData> list = new ArrayList<>();
long previousTimestampEnd = -1;
while (result.next()){
while (result.next()) {
int id = result.getInt("id");
long timestampStart = result.getLong("timestamp_start");
@ -84,7 +84,7 @@ public class AggregateDataListSqlResult implements SQLResultHandler<ArrayList<Ag
float estimatedData = data/confidence; //estimate the "real" value of the data by looking at the confidence value
// Add null data point to list if one or more periods of data is missing before this
if (previousTimestampEnd != -1 && sensor.getDeviceConfig() != null){
if (previousTimestampEnd != -1 && sensor.getDeviceConfig() != null) {
boolean shortInterval = timestampEnd-timestampStart < sensor.getDeviceConfig().getDataInterval();
long distance = timestampStart - (previousTimestampEnd + 1);
if (// Only add nulls if the report interval is smaller than the aggregated interval

View file

@ -13,7 +13,7 @@ public class DeviceDataSqlResult implements SQLResultHandler<HalDeviceData> {
private Class<? extends HalDeviceData> clazz;
public DeviceDataSqlResult(Class<? extends HalDeviceData> clazz){
public DeviceDataSqlResult(Class<? extends HalDeviceData> clazz) {
this.clazz = clazz;
}
@ -27,9 +27,9 @@ public class DeviceDataSqlResult implements SQLResultHandler<HalDeviceData> {
dataObj.setTimestamp(result.getLong("timestamp"));
return dataObj;
}
} catch (SQLException e){
} catch (SQLException e) {
throw e;
} catch (Exception e){
} catch (Exception e) {
throw new SQLException(e);
}
return null;

View file

@ -13,11 +13,11 @@ public class HistoryDataListSqlResult implements SQLResultHandler<List<HistoryDa
public long timestamp;
public float data;
}
@Override
public List<HistoryData> handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
ArrayList<HistoryData> list = new ArrayList<HistoryData>();
while(result.next()){
while (result.next()) {
HistoryData data = new HistoryData();
data.timestamp = result.getLong("timestamp");
data.data = result.getFloat("data");

View file

@ -7,36 +7,37 @@ public class UTCTimePeriod{
private final long end;
private final AggregationPeriodLength periodLength;
public UTCTimePeriod(long timestamp, AggregationPeriodLength periodLength){
public UTCTimePeriod(long timestamp, AggregationPeriodLength periodLength) {
start = UTCTimeUtility.getTimestampPeriodStart(periodLength, timestamp);
end = UTCTimeUtility.getTimestampPeriodEnd(periodLength, timestamp);
this.periodLength = periodLength;
}
public long getStartTimestamp(){
public long getStartTimestamp() {
return start;
}
public long getEndTimestamp(){
public long getEndTimestamp() {
return end;
}
public UTCTimePeriod getNextPeriod(){
public UTCTimePeriod getNextPeriod() {
return new UTCTimePeriod(end+1, periodLength);
}
public UTCTimePeriod getPreviosPeriod(){
public UTCTimePeriod getPreviosPeriod() {
return new UTCTimePeriod(start-1, periodLength);
}
public boolean containsTimestamp(long timestamp){
public boolean containsTimestamp(long timestamp) {
return start <= timestamp && timestamp <= end;
}
public boolean equals(Object other){
if(other == null)
public boolean equals(Object other) {
if (other == null)
return false;
if(other instanceof UTCTimePeriod){
if (other instanceof UTCTimePeriod) {
UTCTimePeriod o = (UTCTimePeriod)other;
return start == o.start
&& end == o.end
@ -45,7 +46,7 @@ public class UTCTimePeriod{
return false;
}
public String toString(){
public String toString() {
return start + "=>" + end + " (" + UTCTimeUtility.getDateString(start) + "=>" + UTCTimeUtility.getDateString(end) + ")";
}

View file

@ -24,7 +24,7 @@ public class UTCTimeUtility {
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(timestamp);
cal.setFirstDayOfWeek(Calendar.MONDAY);
switch(aggrPeriodLength){
switch(aggrPeriodLength) {
case YEAR:
cal.set(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
@ -82,7 +82,7 @@ public class UTCTimeUtility {
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(timestamp);
cal.setFirstDayOfWeek(Calendar.MONDAY);
switch(aggrPeriodLength){
switch(aggrPeriodLength) {
case YEAR:
cal.set(Calendar.DAY_OF_YEAR, cal.getActualMaximum(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 23);
@ -137,7 +137,7 @@ public class UTCTimeUtility {
}
public static int getMillisecondInSecondFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -145,7 +145,7 @@ public class UTCTimeUtility {
}
public static int getSecondOfMinuteFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -153,7 +153,7 @@ public class UTCTimeUtility {
}
public static int getMinuteOfHourFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -161,7 +161,7 @@ public class UTCTimeUtility {
}
public static int getHourOfDayFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -169,7 +169,7 @@ public class UTCTimeUtility {
}
public static int getDayOfWeekFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -177,7 +177,7 @@ public class UTCTimeUtility {
}
public static int getDayOfMonthFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -185,7 +185,7 @@ public class UTCTimeUtility {
}
public static int getDayOfYearFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -193,7 +193,7 @@ public class UTCTimeUtility {
}
public static int getWeekOfYearFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -201,7 +201,7 @@ public class UTCTimeUtility {
}
public static int getMonthOfYearFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -209,7 +209,7 @@ public class UTCTimeUtility {
}
public static int getYearFromTimestamp(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);
cal.setTimeInMillis(ms);
@ -217,15 +217,15 @@ public class UTCTimeUtility {
}
public static String timeInMsToString(long ms) throws NumberFormatException{
if(ms < 0)
if (ms < 0)
throw new NumberFormatException("argument must be positive");
String retval = "";
int weeks = (int) (ms / WEEK_IN_MS);
if(weeks > 0){
if (weeks > 0) {
retval += weeks + "w+";
}
int days = ((int) (ms / DAY_IN_MS)) % 7;
if(days > 0){
if (days > 0) {
retval += days + "d+";
}
int hours = (int) ((ms % DAY_IN_MS) / HOUR_IN_MS);
@ -239,7 +239,7 @@ public class UTCTimeUtility {
return retval;
}
public static String getDateString(long timestamp){
public static String getDateString(long timestamp) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
format.setTimeZone(TIMEZONE);
Calendar cal = Calendar.getInstance(TIMEZONE, LOCALE);

View file

@ -16,8 +16,8 @@ import static org.junit.Assert.assertTrue;
@RunWith(Parameterized.class)
public class TimePeriodTest {
private final long currentTime_UTC;
/**
* Constructor
* @param timestamp
@ -25,7 +25,7 @@ public class TimePeriodTest {
public TimePeriodTest(long timestamp){
this.currentTime_UTC = timestamp;
}
@Parameters
public static Collection<Object[]> data(){
return Arrays.asList(new Object[][] {
@ -46,59 +46,59 @@ public class TimePeriodTest {
{System.currentTimeMillis()+(7*UTCTimeUtility.MINUTE_IN_MS)}, //current time + 7m
});
}
@Test
public void testYearTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.YEAR);
}
@Test
public void testMonthTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.MONTH);
}
@Test
public void testWeekTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.WEEK);
}
@Test
public void testDayTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.DAY);
}
@Test
public void testHourTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.HOUR);
}
@Test
public void test15MiuteTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.FIFTEEN_MINUTES);
}
@Test
public void test5MiuteTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.FIVE_MINUTES);
}
@Test
public void testMiuteTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.MINUTE);
}
@Test
public void testSecondTimePeriod(){
testSeriesOfPeriods(AggregationPeriodLength.SECOND);
}
private void testSeriesOfPeriods(AggregationPeriodLength periodLength){
UTCTimePeriod tp = new UTCTimePeriod(currentTime_UTC, periodLength);
//test next 50 periods
UTCTimePeriod prevTp = tp;
UTCTimePeriod nextTp = null;
for(int i = 0; i < 50; ++i){
for (int i = 0; i < 50; ++i){
nextTp = prevTp.getNextPeriod();
assertTrue("previos period end must be older than the next period end", prevTp.getEndTimestamp() < nextTp.getStartTimestamp());
assertTrue("previous period +1ms must be equal to next period start", prevTp.getEndTimestamp()+1 == nextTp.getStartTimestamp());
@ -106,10 +106,10 @@ public class TimePeriodTest {
testPeriod(nextTp, periodLength);
prevTp = nextTp;
}
//test previous 50 periods
nextTp = tp;
for(int i = 0; i < 50; ++i){
for (int i = 0; i < 50; ++i){
prevTp = nextTp.getPreviosPeriod();
assertTrue("previos period end must be older than the next period end", prevTp.getEndTimestamp() < nextTp.getStartTimestamp());
assertTrue("previous period +1ms must be equal to next period start", prevTp.getEndTimestamp()+1 == nextTp.getStartTimestamp());
@ -118,11 +118,11 @@ public class TimePeriodTest {
nextTp = prevTp;
}
}
private void testPeriod(UTCTimePeriod period, AggregationPeriodLength periodLength){
private void testPeriod(UTCTimePeriod period, AggregationPeriodLength periodLength){
//verify that the period start and end is in the same period
assertEquals("start and/or end timestamp is not in the same period", period.getStartTimestamp(), UTCTimeUtility.getTimestampPeriodStart(periodLength, period.getEndTimestamp()));
assertEquals("start and/or end timestamp is not in the same period", period.getEndTimestamp(), UTCTimeUtility.getTimestampPeriodEnd(periodLength, period.getStartTimestamp()));
}
}