Homeautomation/src/main/java/de/ph87/homeautomation/channel/ChannelReader.java
Patrick Haßel 0b146b5972 #3 FIX Property- & Device updates
+ Devices in Property::usages
+ code clean
2022-10-26 21:04:18 +02:00

68 lines
2.0 KiB
Java

package de.ph87.homeautomation.channel;
import de.ph87.homeautomation.property.Property;
import de.ph87.homeautomation.shared.Helpers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class ChannelReader {
private final List<IChannelOwner> channelOwners;
private final ChannelRepository channelRepository;
public Optional<IChannelOwner> findByChannel(final Channel channel) {
return channelOwners.stream().filter(owner -> channel.getChannelOwnerClass().isInstance(owner)).findFirst();
}
public IChannelOwner getByChannel(final Channel channel) {
return findByChannel(channel).orElseThrow(RuntimeException::new);
}
public Double read(final Property property) {
final Channel channel = property.getReadChannel();
if (channel == null) {
return null;
}
return getByChannel(channel).read(property.getReadChannel().getId());
}
public ChannelDto toDtoAllowNull(final Channel channel) {
if (channel == null) {
return null;
}
return toDto(channel);
}
public ChannelDto toDto(final Channel channel) {
return getByChannel(channel).toDto(channel.getId());
}
public List<? extends ChannelDto> findAllDto() {
return channelOwners.stream().map(IChannelOwner::findAllDto).reduce(new ArrayList<>(), Helpers::merge);
}
public List<? extends ChannelDto> findAllDtoLike(final String term) {
return channelOwners.stream().map(owner -> owner.findAllDtoLikeIgnoreCase(term)).reduce(new ArrayList<>(), Helpers::merge);
}
public Optional<? extends ChannelDto> findDtoById(final long id) {
return channelRepository.findById(id).map(this::toDto);
}
public Channel getById(final long id) {
return channelRepository.getById(id);
}
}