Skip to content

Commit

Permalink
CLOSE #76 Optimize Device loading
Browse files Browse the repository at this point in the history
  • Loading branch information
magx2 committed May 30, 2020
1 parent b6049cf commit d4a037b
Showing 1 changed file with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@
import io.swagger.client.ApiException;
import io.swagger.client.api.IoDevicesApi;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import pl.grzeslowski.jsupla.api.DeviceApi;
import pl.grzeslowski.jsupla.api.channel.Channel;
import pl.grzeslowski.jsupla.api.device.Device;

import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toMap;
import static pl.grzeslowski.jsupla.api.internal.ToStringHelper.niceToString;

@Slf4j
Expand All @@ -30,7 +33,8 @@ final class DeviceApiImpl implements DeviceApi {
@Override
public Device findDevice(int id) {
try {
return mapToDeviceWithChannels(ioDevicesApi.getIoDevice(id, DEFAULT_INCLUDE));
val channels = findChannels();
return mapToDeviceWithChannels(ioDevicesApi.getIoDevice(id, DEFAULT_INCLUDE), channels);
} catch (ApiException e) {
throw new pl.grzeslowski.jsupla.api.ApiException("/findDevice/" + id, e);
}
Expand All @@ -39,20 +43,29 @@ public Device findDevice(int id) {
@Override
public SortedSet<Device> findDevices() {
try {
val channels = findChannels();
return ioDevicesApi.getIoDevices(DEFAULT_INCLUDE)
.stream()
.map(this::mapToDeviceWithChannels)
.map((io.swagger.client.model.Device device) -> mapToDeviceWithChannels(device, channels))
.collect(Collectors.toCollection(TreeSet::new));
} catch (ApiException e) {
throw new pl.grzeslowski.jsupla.api.ApiException("/findDevices", e);
}
}

private Device mapToDeviceWithChannels(final io.swagger.client.model.Device device) {
private SortedSet<Channel> findChannels() {
log.debug("Loading all channels to build device");
return channelApi.findChannels();
}

private Device mapToDeviceWithChannels(final io.swagger.client.model.Device device,
final SortedSet<Channel> cloudChannels) {
log.trace("Got device {}", niceToString(device));
val channelsMap = cloudChannels.stream().collect(toMap(Channel::getId, Function.identity()));
final SortedSet<Channel> channels = device.getChannelsIds()
.stream()
.map(channelApi::findChannel)
.filter(channelsMap::containsKey)
.map(channelsMap::get)
.collect(Collectors.toCollection(TreeSet::new));
return new DeviceImpl(device, channels);
}
Expand Down

0 comments on commit d4a037b

Please sign in to comment.