001package net.kreatious.pianoleopard.keyboardselect;
002
003import java.util.Optional;
004import java.util.stream.Stream;
005
006import javax.sound.midi.MidiDevice;
007import javax.sound.midi.MidiDevice.Info;
008import javax.sound.midi.MidiSystem;
009import javax.sound.midi.MidiUnavailableException;
010
011/**
012 * Provides the MIDI devices connected to the current system.
013 *
014 * @author Jay-R Studer
015 */
016public class SystemMidiDeviceFactory implements MidiDeviceFactory {
017    @Override
018    public MidiDevice[] getMidiDevices() {
019        return Stream.of(MidiSystem.getMidiDeviceInfo()).map(SystemMidiDeviceFactory::getMidiDevice)
020                .filter(Optional::isPresent).map(Optional::get).toArray(MidiDevice[]::new);
021    }
022
023    private static Optional<MidiDevice> getMidiDevice(Info info) {
024        try {
025            return Optional.of(MidiSystem.getMidiDevice(info));
026        } catch (final MidiUnavailableException e) {
027            return Optional.empty();
028        }
029    }
030}