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

[improve] optimize DateUtil and add test case #1974

Merged
merged 7 commits into from
May 13, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.apache.hertzbeat.alert.dto;

import java.util.Optional;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
Expand Down Expand Up @@ -54,10 +55,18 @@ public void refreshAlertTime() {
if (StringUtils.isNotBlank(alertDateTime)) {
Long timeStamp = null;
if (StringUtils.isNotBlank(dateTimeFormat)) {
timeStamp = DateUtil.getTimeStampFromFormat(alertDateTime, dateTimeFormat);
Optional<Long> tsf = DateUtil.getTimeStampFromFormat(alertDateTime, dateTimeFormat);
boolean present = tsf.isPresent();
if (present) {
timeStamp = tsf.get();
}
}
if (timeStamp == null) {
timeStamp = DateUtil.getTimeStampFromSomeFormats(alertDateTime);
Optional<Long> tsf = DateUtil.getTimeStampFromSomeFormats(alertDateTime);
boolean present = tsf.isPresent();
if (present) {
timeStamp = tsf.get();
}
}
if (timeStamp != null) {
setAlertTime(timeStamp);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,9 @@ public Integer getAlertDuration() {

@Override
public long getAlertTime() {
return DateUtil.getTimeStampFromFormat(getFirstOccurTime(), "yyyy-MM-dd HH:mm:ss");

return DateUtil.getTimeStampFromFormat(getFirstOccurTime(), "yyyy-MM-dd HH:mm:ss")
.orElse(0L);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@
* Alarm template keyword matching replacement engine tool
*/
@Slf4j
public class AlertTemplateUtil {
public final class AlertTemplateUtil {

private AlertTemplateUtil() {
}

/**
* Match the variable ${key}
Expand Down
48 changes: 33 additions & 15 deletions alerter/src/main/java/org/apache/hertzbeat/alert/util/DateUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,49 +17,67 @@

package org.apache.hertzbeat.alert.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;

/**
* date time common util
*/
@Slf4j
public class DateUtil {
public final class DateUtil {

private DateUtil() {
}

private static final String[] DATE_FORMATS = {
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"yyyy-MM-dd HH:mm:ss"
};

/**
* convert date to timestamp
* @param date date
* @return timestamp
*/
public static Long getTimeStampFromSomeFormats(String date) {
SimpleDateFormat sdf;
public static Optional<Long> getTimeStampFromSomeFormats(String date) {
for (String dateFormat : DATE_FORMATS) {
try {
sdf = new SimpleDateFormat(dateFormat);
return sdf.parse(date).getTime();
} catch (ParseException e) {
log.error(e.getMessage());
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.appendPattern(dateFormat)
// enable string conversion in strict mode.
.parseStrict()
.toFormatter();
LocalDateTime time = LocalDateTime.parse(date, dateTimeFormatter);
return Optional.of(time.toInstant(ZoneOffset.UTC).toEpochMilli());
} catch (Exception e) {
log.warn("Error parsing date '{}' with format '{}': {}",
date, dateFormat, e.getMessage());
}
}
return null;

log.error("Error parsing date '{}', no corresponding date format", date);
return Optional.empty();
}

/**
* convert format data to timestamp
*/
public static Long getTimeStampFromFormat(String date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
public static Optional<Long> getTimeStampFromFormat(String date, String format) {
try {
return sdf.parse(date).getTime();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
return Optional.of(dateTime.toInstant(java.time.ZoneOffset.UTC).toEpochMilli());
} catch (Exception e) {
log.error(e.getMessage());
log.error("Error parsing date '{}' with format '{}': {}",
date, format, e.getMessage());
}
return null;

return Optional.empty();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.hertzbeat.alert.util;

import org.junit.jupiter.api.Test;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;

/**
* Test case for {@link DateUtil}
*/
class DateUtilTest {

@Test
void getTimeStampFromSomeFormats() {
String date = "2024-05-13";
Optional<Long> actualTimestamp = DateUtil.getTimeStampFromSomeFormats(date);
assertFalse(actualTimestamp.isPresent());

date = "2024-05-13T12:34:56.789Z";
actualTimestamp = DateUtil.getTimeStampFromSomeFormats(date);
assertTrue(actualTimestamp.isPresent());
assertEquals(1715603696789L, actualTimestamp.get());

date = "2023-02-22T07:27:15.404000000Z";
actualTimestamp = DateUtil.getTimeStampFromSomeFormats(date);
assertTrue(actualTimestamp.isPresent());
assertEquals(1677050835404L, actualTimestamp.get());
}

@Test
void getTimeStampFromFormat() {
String date = "2024-05-13 10:30:00";
String format = "yyyy-MM-dd HH:mm:ss";
Optional<Long> actualTimestamp = DateUtil.getTimeStampFromFormat(date, format);
assertTrue(actualTimestamp.isPresent());
assertEquals(1715596200000L, actualTimestamp.get());

date = "2024-05-13";
format = "yyyy-MM-dd HH:mm:ss.SSS";
actualTimestamp = DateUtil.getTimeStampFromFormat(date, format);
assertFalse(actualTimestamp.isPresent());
}
}
Loading