Skip to content

Commit

Permalink
refactor: 코드리뷰를 반영한다
Browse files Browse the repository at this point in the history
[#21]
  • Loading branch information
be-student committed Jul 19, 2023
1 parent 002690b commit 7fd0167
Show file tree
Hide file tree
Showing 16 changed files with 86 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
import java.util.List;
import java.util.Map;

public record CongestionResponse(Map<String, List<CongestionInfoResponse>> STANDARD,
Map<String, List<CongestionInfoResponse>> QUICK) {
public record CongestionResponse(Map<String, List<CongestionInfoResponse>> standard,
Map<String, List<CongestionInfoResponse>> quick) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
@Entity
@Table(name = "charger")
public class Charger {
private static final BigDecimal OUTPUT_THRESHOLD = BigDecimal.valueOf(50);

@Id
@Column(name = "station_id")
Expand Down Expand Up @@ -62,4 +63,11 @@ public class Charger {
public boolean isAvailable() {
return chargerStatus.isAvailable();
}

public boolean isQuick() {
if (capacity == null) {
return false;
}
return capacity.compareTo(OUTPUT_THRESHOLD) >= 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
import java.util.List;

public interface ChargerRepository extends Repository<Charger, String> {

List<Charger> findAllByStationId(String stationId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,17 @@

public enum ChargerState {

COMMUNICATION_ERROR(1, "1"),
STANDBY(2, "2"),
CHARGING_IN_PROGRESS(3, "3"),
OPERATION_SUSPENDED(4, "4"),
UNDER_INSPECTION(5, "5"),
STATUS_UNKNOWN(9, "9");
COMMUNICATION_ERROR(1),
STANDBY(2),
CHARGING_IN_PROGRESS(3),
OPERATION_SUSPENDED(4),
UNDER_INSPECTION(5),
STATUS_UNKNOWN(9);

private final int value;
private final String valueString;

ChargerState(int value, String valueString) {
ChargerState(int value) {
this.value = value;
this.valueString = valueString;
}

public static ChargerState from(int input) {
Expand All @@ -28,7 +26,7 @@ public static ChargerState from(int input) {

public static ChargerState from(String input) {
return Arrays.stream(ChargerState.values())
.filter(it -> it.valueString.equals(input))
.filter(it -> it.value == input.charAt(0) - '0')
.findAny()
.orElse(STATUS_UNKNOWN);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
@ToString
@Getter
@Builder
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@IdClass(ChargerId.class)
@Entity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ public class PeriodicCongestion {
private double congestion;

@ManyToOne
@JoinColumns({
@JoinColumn(name = "station_id", referencedColumnName = "station_id", insertable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT)),
@JoinColumn(name = "charger_id", referencedColumnName = "charger_id", insertable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
})
@JoinColumns(value = {
@JoinColumn(name = "station_id", referencedColumnName = "station_id", insertable = false, updatable = false),
@JoinColumn(name = "charger_id", referencedColumnName = "charger_id", insertable = false, updatable = false)
}, foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
private Charger charger;

@Column(name = "station_id")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ public enum RequestPeriod {
ZERO(0),
TWELVE(1200);

private static final int UNIT = 100;
private static final List<RequestPeriod> periods = Arrays.stream(values())
.sorted(Comparator.comparingInt(RequestPeriod::getSection))
.toList();
private static final int UNIT = 100;

private final int section;

RequestPeriod(int section) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public ChargeStationRequest requestChargeStationRequest(int pageNo) {
}

@Override
public ChargerStateUpdateRequest requestChargerStatusUpdateRequest(int pageNo) {
public ChargerStateUpdateRequest requestChargerStatusUpdate(int pageNo) {
while (true) {
try {
ChargerStateUpdateRequest result = requestChargeStateUpdateRequestWithRetry(pageNo);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
package com.carffeine.carffeine.infra.repository;

import com.carffeine.carffeine.domain.chargestation.charger.ChargerState;
import com.carffeine.carffeine.domain.chargestation.charger.ChargerStatus;
import com.carffeine.carffeine.service.chargerstation.ChargerStatusCustomRepository;
import com.carffeine.carffeine.service.chargerstation.dto.ChargerStateRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RequiredArgsConstructor
Expand All @@ -22,30 +19,21 @@ public class ChargerStatusCustomRepositoryImpl implements ChargerStatusCustomRep

@Override
@Transactional
public void saveAll(List<ChargerStateRequest> item) {
public void saveAll(List<ChargerStatus> chargerStatuses) {
String sql = "INSERT INTO charger_status (station_id, charger_id, latest_update_time, charger_state) " +
"VALUES (:stationId, :chargerId, :latestUpdateTime, :chargerState) " +
"ON DUPLICATE KEY UPDATE latest_update_time = :latestUpdateTime, charger_state = :chargerState";
SqlParameterSource[] sqlParameterSources = item.stream()
SqlParameterSource[] sqlParameterSources = chargerStatuses.stream()
.map(this::changeToSqlParameterSource)
.toArray(SqlParameterSource[]::new);
namedParameterJdbcTemplate.batchUpdate(sql, sqlParameterSources);
}

private MapSqlParameterSource changeToSqlParameterSource(ChargerStateRequest item) {
private MapSqlParameterSource changeToSqlParameterSource(ChargerStatus item) {
return new MapSqlParameterSource()
.addValue("stationId", item.statId())
.addValue("chargerId", item.chgerId())
.addValue("latestUpdateTime", parseDateTimeFromString(item.statUpdDt()))
.addValue("chargerState", ChargerState.from(item.stat()).name());
}

private LocalDateTime parseDateTimeFromString(String input) {
if (input == null || input.length() != 14) {
return null;
}

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
return LocalDateTime.parse(input, formatter);
.addValue("stationId", item.getStationId())
.addValue("chargerId", item.getChargerId())
.addValue("latestUpdateTime", item.getLatestUpdateTime())
.addValue("chargerState", item.getChargerState().name());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@

public interface ChargerStateRequester {

ChargerStateUpdateRequest requestChargerStatusUpdateRequest(int pageNo);
ChargerStateUpdateRequest requestChargerStatusUpdate(int pageNo);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.carffeine.carffeine.service.chargerstation;

import com.carffeine.carffeine.domain.chargestation.charger.ChargerStatus;
import com.carffeine.carffeine.service.chargerstation.dto.ChargerStateRequest;
import com.carffeine.carffeine.service.chargerstation.dto.ChargerStateUpdateRequest;
import lombok.RequiredArgsConstructor;
Expand All @@ -25,8 +26,11 @@ public void update() {
}

private void updateChargerState(int pageNo) {
ChargerStateUpdateRequest chargerStateUpdateRequest = chargerStateRequester.requestChargerStatusUpdateRequest(pageNo);
ChargerStateUpdateRequest chargerStateUpdateRequest = chargerStateRequester.requestChargerStatusUpdate(pageNo);
List<ChargerStateRequest> chargerStateRequests = chargerStateUpdateRequest.items().item();
chargerStatusCustomRepository.saveAll(chargerStateRequests);
List<ChargerStatus> chargerStatuses = chargerStateRequests.stream()
.map(ChargerStateRequest::toChargerStatus)
.toList();
chargerStatusCustomRepository.saveAll(chargerStatuses);
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.carffeine.carffeine.service.chargerstation;

import com.carffeine.carffeine.service.chargerstation.dto.ChargerStateRequest;
import com.carffeine.carffeine.domain.chargestation.charger.ChargerStatus;

import java.util.List;

public interface ChargerStatusCustomRepository {

void saveAll(List<ChargerStateRequest> item);
void saveAll(List<ChargerStatus> item);
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public StatisticsResponse calculateCongestion(StatisticsRequest statisticsReques

private Map<String, List<CongestionInfoResponse>> calculateQuick(List<PeriodicCongestion> congestions, List<Charger> chargers) {
List<String> quickChargerIds = chargers.stream()
.filter(it -> it.getCapacity().intValue() >= OUTPUT_THRESHOLD)
.filter(Charger::isQuick)
.map(Charger::getChargerId)
.toList();

Expand All @@ -55,7 +55,7 @@ private Map<String, List<CongestionInfoResponse>> calculateQuick(List<PeriodicCo

private Map<String, List<CongestionInfoResponse>> calculateStandard(List<PeriodicCongestion> congestions, List<Charger> chargers) {
List<String> standardChargerIds = chargers.stream()
.filter(it -> it.getCapacity().intValue() < OUTPUT_THRESHOLD)
.filter(it -> !it.isQuick())
.map(Charger::getChargerId)
.toList();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package com.carffeine.carffeine.service.chargerstation.dto;

import com.carffeine.carffeine.domain.chargestation.charger.ChargerState;
import com.carffeine.carffeine.domain.chargestation.charger.ChargerStatus;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public record ChargerStateRequest(
String busiId,
String statId,
Expand All @@ -9,4 +15,23 @@ public record ChargerStateRequest(
String lastTsdt,
String lastTedt,
String nowTsdt) {

private static final int DATETIME_LENGTH = 14;

public ChargerStatus toChargerStatus() {
return ChargerStatus.builder()
.stationId(statId)
.chargerId(chgerId)
.latestUpdateTime(parseDateTimeFromString(statUpdDt))
.chargerState(ChargerState.from(stat))
.build();
}

private LocalDateTime parseDateTimeFromString(String input) {
if (input == null || input.length() != DATETIME_LENGTH) {
return null;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
return LocalDateTime.parse(input, formatter);
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
package com.carffeine.carffeine.infra.repository;

import com.carffeine.carffeine.domain.chargestation.charger.ChargerState;
import com.carffeine.carffeine.domain.chargestation.charger.ChargerStatus;
import com.carffeine.carffeine.domain.chargestation.charger.ChargerStatusRepository;
import com.carffeine.carffeine.service.chargerstation.ChargerStatusCustomRepository;
import com.carffeine.carffeine.service.chargerstation.dto.ChargerStateRequest;
import com.carffeine.carffeine.service.chargerstation.dto.ChargerStateUpdateRequest;
import com.carffeine.carffeine.service.chargerstation.dto.ChargersStateRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.time.LocalDateTime;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -20,8 +19,13 @@
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class ChargerStatusRepositoryImplTest {

private final ChargerStateUpdateRequest request = new ChargerStateUpdateRequest(
3, new ChargersStateRequest(List.of(new ChargerStateRequest("ME", "13", "45", "2", "updateDate", "lastTsdt", "lastTedt", "nowTsdt"))), 1, "3", 5
private static final List<ChargerStatus> chargerStatuses = List.of(
new ChargerStatus(
"stationId",
"chargerId",
LocalDateTime.of(2021, 1, 1, 0, 0, 0),
ChargerState.CHARGING_IN_PROGRESS
)
);

private ChargerStatusCustomRepository chargerStatusCustomRepository;
Expand All @@ -34,8 +38,8 @@ void setUp(NamedParameterJdbcTemplate namedParameterJdbcTemplate, ChargerStatusR
}

@Test
void 저장() {
chargerStatusCustomRepository.saveAll(request.items().item());
void 상태를_저장한다() {
chargerStatusCustomRepository.saveAll(chargerStatuses);

List<ChargerStatus> result = chargerStatusRepository.findAll();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.carffeine.carffeine.domain.chargestation.charger.ChargerRepository;
import com.carffeine.carffeine.domain.chargestation.congestion.PeriodicCongestionRepository;
import com.carffeine.carffeine.service.chargerstation.dto.StatisticsRequest;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator.ReplaceUnderscores;
import org.junit.jupiter.api.Test;
Expand All @@ -17,6 +16,8 @@
import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

@DisplayNameGeneration(ReplaceUnderscores.class)
@SuppressWarnings("NonAsciiCharacters")
@DataJpaTest
Expand All @@ -30,13 +31,13 @@ void setCongestionService(PeriodicCongestionRepository periodicCongestionReposit
}

@Test
void 혼잡도_계산() {
void 상태값이_없는_데이터일_경우_음수가_반환된다() {
StatisticsRequest statisticsRequest = new StatisticsRequest("ME174003");
StatisticsResponse statisticsResponse = congestionService.calculateCongestion(statisticsRequest);

CongestionResponse expected = getExpected();

Assertions.assertThat(expected).usingRecursiveComparison()
assertThat(expected).usingRecursiveComparison()
.isEqualTo(statisticsResponse.congestion());
}

Expand Down

0 comments on commit 7fd0167

Please sign in to comment.