file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
MPDConnectionMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDConnectionMonitor.java
package org.bff.javampd.monitor; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.List; import org.bff.javampd.server.ConnectionChangeEvent; import org.bff.javampd.server.ConnectionChangeListener; import org.bff.javampd.server.Server; @Singleton public class MPDConnectionMonitor implements ConnectionMonitor { private final List<ConnectionChangeListener> connectionListeners; private Server server; private boolean connected = true; MPDConnectionMonitor() { this.connectionListeners = new ArrayList<>(); } /** * Adds a {@link org.bff.javampd.server.ConnectionChangeListener} to this object to receive {@link * org.bff.javampd.server.ConnectionChangeEvent}s. * * @param ccl the ConnectionChangeListener to add */ @Override public synchronized void addConnectionChangeListener(ConnectionChangeListener ccl) { connectionListeners.add(ccl); } /** * Removes a {@link ConnectionChangeListener} from this object. * * @param ccl the ConnectionChangeListener to remove */ @Override public synchronized void removeConnectionChangeListener(ConnectionChangeListener ccl) { connectionListeners.remove(ccl); } /** * Sends the appropriate {@link org.bff.javampd.server.ConnectionChangeEvent} to all registered * {@link ConnectionChangeListener}s. * * @param isConnected the connection status */ protected synchronized void fireConnectionChangeEvent(boolean isConnected) { var cce = new ConnectionChangeEvent(this, isConnected); for (ConnectionChangeListener ccl : connectionListeners) { ccl.connectionChangeEventReceived(cce); } } @Override public void checkStatus() { boolean conn = this.server.isConnected(); if (connected != conn) { connected = conn; fireConnectionChangeEvent(conn); } } @Override public void setServer(Server server) { this.server = server; } @Override public boolean isConnected() { return this.connected; } }
2,014
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDOutputMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDOutputMonitor.java
package org.bff.javampd.monitor; import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.*; import org.bff.javampd.admin.Admin; import org.bff.javampd.output.MPDOutput; import org.bff.javampd.output.OutputChangeEvent; import org.bff.javampd.output.OutputChangeListener; @Singleton public class MPDOutputMonitor implements OutputMonitor { private final Map<Integer, MPDOutput> outputMap; private final List<OutputChangeListener> outputListeners; private final Admin admin; @Inject MPDOutputMonitor(Admin admin) { this.admin = admin; this.outputMap = new HashMap<>(); this.outputListeners = new ArrayList<>(); } @Override public void checkStatus() { List<MPDOutput> outputs = new ArrayList<>(admin.getOutputs()); if (outputs.size() > outputMap.size()) { fireOutputChangeEvent( new OutputChangeEvent(this, OutputChangeEvent.OUTPUT_EVENT.OUTPUT_ADDED)); loadOutputs(outputs); } else if (outputs.size() < outputMap.size()) { fireOutputChangeEvent( new OutputChangeEvent(this, OutputChangeEvent.OUTPUT_EVENT.OUTPUT_DELETED)); loadOutputs(outputs); } else { compareOutputs(outputs); } } private void compareOutputs(List<MPDOutput> outputs) { for (MPDOutput output : outputs) { var mpdOutput = outputMap.get(output.getId()); if (mpdOutput.isEnabled() != output.isEnabled()) { fireOutputChangeEvent( new OutputChangeEvent(output, OutputChangeEvent.OUTPUT_EVENT.OUTPUT_CHANGED)); loadOutputs(outputs); return; } } } @Override public synchronized void addOutputChangeListener(OutputChangeListener vcl) { outputListeners.add(vcl); } @Override public synchronized void removeOutputChangeListener(OutputChangeListener vcl) { outputListeners.remove(vcl); } /** * Sends the appropriate {@link OutputChangeEvent} to all registered {@link * org.bff.javampd.output.OutputChangeListener}s. * * @param event the event id to send */ protected synchronized void fireOutputChangeEvent(OutputChangeEvent event) { for (OutputChangeListener ocl : outputListeners) { ocl.outputChanged(event); } } private void loadOutputs(Collection<MPDOutput> outputs) { outputMap.clear(); for (MPDOutput output : outputs) { outputMap.put(output.getId(), output); } } }
2,410
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TrackMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/TrackMonitor.java
package org.bff.javampd.monitor; import org.bff.javampd.player.TrackPositionChangeListener; public interface TrackMonitor extends StatusMonitor { void addTrackPositionChangeListener(TrackPositionChangeListener tpcl); void removeTrackPositionChangeListener(TrackPositionChangeListener tpcl); void resetElapsedTime(); }
329
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
StandAloneMonitorThread.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/StandAloneMonitorThread.java
package org.bff.javampd.monitor; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import lombok.Getter; import lombok.Setter; import org.bff.javampd.MPDException; import org.bff.javampd.server.ServerStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StandAloneMonitorThread implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(StandAloneMonitorThread.class); private final List<ThreadedMonitor> monitors; private final ServerStatus serverStatus; private final ConnectionMonitor connectionMonitor; private final int delay; private final int exceptionDelay; @Setter private boolean stopped; @Getter private boolean done; @Getter private boolean initialized; /** * Creates the monitor thread with the given delay seconds. * * @param serverStatus server status * @param connectionMonitor connection monitor * @param delay the number of seconds between each poll * @param exceptionDelay the number of seconds to wait should an error occur */ public StandAloneMonitorThread( ServerStatus serverStatus, ConnectionMonitor connectionMonitor, int delay, int exceptionDelay) { this.serverStatus = serverStatus; this.connectionMonitor = connectionMonitor; this.delay = delay; this.exceptionDelay = exceptionDelay; this.monitors = new ArrayList<>(); } /** * Adds the {@link ThreadedMonitor}s only if it doesnt already exist in the monitor list * * @param monitors the {@link ThreadedMonitor}s to add */ public void addMonitor(ThreadedMonitor... monitors) { for (ThreadedMonitor monitor : monitors) { if (!this.monitors.contains(monitor)) { this.monitors.add(monitor); } } } /** * Removes the {@link ThreadedMonitor} from the list of monitors * * @param monitor the {@link ThreadedMonitor} to remove */ public synchronized void removeMonitor(ThreadedMonitor monitor) { this.monitors.remove(monitor); } @Override public void run() { this.stopped = false; this.done = false; this.initialized = false; loadInitialStatus(); while (!this.stopped) { monitor(); } resetMonitors(); this.done = true; } private void monitor() { List<String> response; try { synchronized (this) { response = new ArrayList<>(serverStatus.getStatus()); processResponse(response); monitors.forEach(ThreadedMonitor::checkStatus); } TimeUnit.SECONDS.sleep(delay); } catch (InterruptedException ie) { LOGGER.error("StandAloneMonitor interrupted", ie); setStopped(true); Thread.currentThread().interrupt(); } catch (MPDException mpdException) { LOGGER.error("Error while checking statuses", mpdException); var retry = true; while (retry) { retry = retry(); } } } private boolean retry() { try { TimeUnit.SECONDS.sleep(this.exceptionDelay); } catch (InterruptedException ex) { LOGGER.error("StandAloneMonitor interrupted", ex); setStopped(true); Thread.currentThread().interrupt(); return false; } try { connectionMonitor.checkStatus(); return !connectionMonitor.isConnected(); } catch (MPDException e) { throw new MPDException("Error checking connection status.", e); } } private void resetMonitors() { this.monitors.forEach(ThreadedMonitor::reset); } private void processResponse(List<String> response) { response.forEach(this::processResponseStatus); } private void processResponseStatus(String line) { for (ThreadedMonitor monitor : monitors) { monitor.processResponseLine(line); } } private void loadInitialStatus() { try { // initial load so no events fired List<String> response = new ArrayList<>(serverStatus.getStatus()); processResponse(response); this.initialized = true; } catch (MPDException ex) { throw new MPDException("Problem with initialization", ex); } } }
4,115
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDVolumeMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDVolumeMonitor.java
package org.bff.javampd.monitor; import com.google.inject.Singleton; import org.bff.javampd.player.VolumeChangeDelegate; import org.bff.javampd.player.VolumeChangeListener; import org.bff.javampd.server.Status; @Singleton public class MPDVolumeMonitor implements VolumeMonitor { private int newVolume; private int oldVolume; private final VolumeChangeDelegate volumeChangeDelegate; MPDVolumeMonitor() { this.volumeChangeDelegate = new VolumeChangeDelegate(); } @Override public void processResponseStatus(String line) { if (Status.lookup(line) == Status.VOLUME) { newVolume = Integer.parseInt(line.substring(Status.VOLUME.getStatusPrefix().length()).trim()); } } @Override public void reset() { newVolume = 0; oldVolume = 0; } @Override public void checkStatus() { if (oldVolume != newVolume) { fireVolumeChangeEvent(newVolume); oldVolume = newVolume; } } @Override public synchronized void addVolumeChangeListener(VolumeChangeListener vcl) { volumeChangeDelegate.addVolumeChangeListener(vcl); } @Override public synchronized void removeVolumeChangeListener(VolumeChangeListener vcl) { volumeChangeDelegate.removeVolumeChangedListener(vcl); } /** * Sends the appropriate {@link org.bff.javampd.player.VolumeChangeEvent} to all registered {@link * VolumeChangeListener}. * * @param volume the new volume */ protected synchronized void fireVolumeChangeEvent(int volume) { volumeChangeDelegate.fireVolumeChangeEvent(this, volume); } }
1,560
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ThreadedMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/ThreadedMonitor.java
package org.bff.javampd.monitor; /** Threaded version of a {@link Monitor} */ public class ThreadedMonitor { private final Monitor monitor; private final int delay; private int count; /** * Threaded version of {@link Monitor} * * @param monitor the {@link Monitor} * @param delay The number of seconds to delay before performing the check status. If your {@link * #checkStatus} is expensive this should be a larger number. */ ThreadedMonitor(Monitor monitor, int delay) { this.monitor = monitor; this.delay = delay; } public void checkStatus() { if (count++ == delay) { count = 0; monitor.checkStatus(); } } public void processResponseLine(String line) { if (monitor instanceof StatusMonitor statusMonitor) { statusMonitor.processResponseStatus(line); } } public void reset() { if (monitor instanceof StatusMonitor statusMonitor) { statusMonitor.reset(); } } }
968
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
OutputMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/OutputMonitor.java
package org.bff.javampd.monitor; import org.bff.javampd.output.OutputChangeListener; public interface OutputMonitor extends Monitor { /** * Adds a {@link org.bff.javampd.output.OutputChangeListener} to this object to receive {@link * org.bff.javampd.output.OutputChangeEvent}s. * * @param vcl the OutputChangeListener to add */ void addOutputChangeListener(OutputChangeListener vcl); /** * Removes a {@link org.bff.javampd.output.OutputChangeListener} from this object. * * @param vcl the OutputChangeListener to remove */ void removeOutputChangeListener(OutputChangeListener vcl); }
623
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDGenreDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/genre/MPDGenreDatabase.java
package org.bff.javampd.genre; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.bff.javampd.database.TagLister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MPDGenreDatabase represents a genre database to a {@link org.bff.javampd.server.MPD}. To obtain * an instance of the class you must use the {@link * org.bff.javampd.database.MusicDatabase#getGenreDatabase()} method from the {@link * org.bff.javampd.server.MPD} connection class. * * @author Bill */ public class MPDGenreDatabase implements GenreDatabase { private static final Logger LOGGER = LoggerFactory.getLogger(MPDGenreDatabase.class); private final TagLister tagLister; @Inject public MPDGenreDatabase(TagLister tagLister) { this.tagLister = tagLister; } @Override public Collection<MPDGenre> listAllGenres() { return tagLister.list(TagLister.ListType.GENRE).stream() .map(s -> new MPDGenre(s.substring(s.split(":")[0].length() + 1).trim())) .toList(); } @Override public MPDGenre listGenreByName(String name) { List<String> list = new ArrayList<>(); list.add(TagLister.ListType.GENRE.getType()); list.add(name); MPDGenre genre = null; List<MPDGenre> genres = new ArrayList<>(); tagLister .list(TagLister.ListType.GENRE, list) .forEach(response -> genres.add(new MPDGenre(response.split(":")[1].trim()))); if (genres.size() > 1) { LOGGER.warn("Multiple genres returned for name {}", name); } if (!genres.isEmpty()) { genre = genres.getFirst(); } return genre; } }
1,658
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDGenre.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/genre/MPDGenre.java
package org.bff.javampd.genre; /** * MPDGenre represents a genre * * @author Bill */ public record MPDGenre(String name) {}
129
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
GenreDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/genre/GenreDatabase.java
package org.bff.javampd.genre; import java.util.Collection; /** * Database for genre related items * * @author bill */ public interface GenreDatabase { /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.genre.MPDGenre}s of all genres * in the database. * * @return a {@link java.util.Collection} of {@link org.bff.javampd.genre.MPDGenre}s containing * the genre names */ Collection<MPDGenre> listAllGenres(); /** * Returns a {@link org.bff.javampd.genre.MPDGenre} with the passed name. * * @param name the name of the genre * @return a {@link org.bff.javampd.genre.MPDGenre} */ MPDGenre listGenreByName(String name); }
692
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AlbumDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/album/AlbumDatabase.java
package org.bff.javampd.album; import java.util.Collection; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.genre.MPDGenre; /** * Database for artist related items * * @author bill */ public interface AlbumDatabase { /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s of all albums * by a particular genre. * * @param genre the genre to find albums * @return a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s of all albums */ Collection<MPDAlbum> listAlbumsByGenre(MPDGenre genre); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s of all albums * for a particular year. * * @param year the year to find albums * @return a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s of all years */ Collection<MPDAlbum> listAlbumsByYear(String year); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s of all albums * by a particular artist. * * @param artist the artist to find albums * @return a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s by the {@link * MPDArtist} */ Collection<MPDAlbum> listAlbumsByArtist(MPDArtist artist); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s of all albums * by an album artist. An album artist denotes the artist for a musical release, as distinct from * artists for the tracks that constitute a release * * @param albumArtist the album artist to find albums * @return a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s by the {@link * MPDArtist} */ Collection<MPDAlbum> listAlbumsByAlbumArtist(MPDArtist albumArtist); /** * Returns a list of album names. To hydrate the {@link org.bff.javampd.album.MPDAlbum} call * #findAlbum(String). This method will return an empty string album name if one exists in your * collection. * * @return a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s of all albums */ Collection<String> listAllAlbumNames(); /** * Returns a list of all {@link org.bff.javampd.album.MPDAlbum}s. This could be very slow for * large collections. * * @return a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s of all albums */ Collection<MPDAlbum> listAllAlbums(); /** * Returns a list of {@link MPDAlbum}s for the album name. * * @param albumName the album's name * @return a {@link java.util.Collection} of {@link org.bff.javampd.album.MPDAlbum}s */ Collection<MPDAlbum> findAlbum(String albumName); }
2,735
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAlbumConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/album/MPDAlbumConverter.java
package org.bff.javampd.album; import java.util.*; import lombok.extern.slf4j.Slf4j; /** * Converts a response from the server to an {@link MPDAlbum} * * @author bill */ @Slf4j public class MPDAlbumConverter implements AlbumConverter { private static final String DELIMITING_PREFIX = AlbumProcessor.getDelimitingPrefix(); @Override public Collection<MPDAlbum> convertResponseToAlbum(List<String> list) { var hashMap = new LinkedHashMap<String, MPDAlbum>(); Iterator<String> iterator = list.iterator(); var artists = new ArrayList<String>(); var genres = new ArrayList<String>(); var dates = new ArrayList<String>(); String albumArtist = null; var album = ""; String line; while (iterator.hasNext()) { line = iterator.next(); var albumProcessor = AlbumProcessor.lookup(line); if (albumProcessor != null) { var tag = albumProcessor.getProcessor().processTag(line); switch (albumProcessor.getProcessor().getType()) { case ALBUM: album = tag; break; case ALBUM_ARTIST: albumArtist = tag; break; case ARTIST: artists.add(tag); break; case GENRE: genres.add(tag); break; case DATE: dates.add(tag); break; default: log.warn("Unprocessed album type {} found.", tag); break; } } else { log.warn("Processor not found - {}", line); } if (line.startsWith(DELIMITING_PREFIX)) { var a = hashMap.get(album); if (a == null) { hashMap.put( album, MPDAlbum.builder(album) .albumArtist(albumArtist) .artistNames(artists) .genres(genres) .dates(dates) .build()); } else { a.addArtists(artists); a.addGenres(genres); a.addDates(dates); } artists = new ArrayList<>(); genres = new ArrayList<>(); dates = new ArrayList<>(); albumArtist = null; album = ""; } } return hashMap.values(); } }
2,240
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAlbum.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/album/MPDAlbum.java
package org.bff.javampd.album; import java.util.ArrayList; import java.util.List; import lombok.Builder; import lombok.Data; import lombok.NonNull; /** * MPDAlbum represents an album * * @author Bill */ @Builder(builderMethodName = "internalBuilder") @Data public class MPDAlbum implements Comparable<MPDAlbum> { @NonNull private String name; private String albumArtist; @Builder.Default private List<String> artistNames = new ArrayList<>(); @Builder.Default private List<String> dates = new ArrayList<>(); @Builder.Default private List<String> genres = new ArrayList<>(); public static MPDAlbumBuilder builder(String name) { return internalBuilder().name(name); } public void addArtist(String artist) { this.artistNames.add(artist); } public void addArtists(List<String> artists) { this.artistNames.addAll(artists); } public void addDate(String date) { this.dates.add(date); } public void addDates(List<String> dates) { this.dates.addAll(dates); } public void addGenre(String genre) { this.genres.add(genre); } public void addGenres(List<String> genres) { this.genres.addAll(genres); } @Override public int compareTo(MPDAlbum album) { return this.getName().compareTo(album.getName()); } }
1,280
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AlbumConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/album/AlbumConverter.java
package org.bff.javampd.album; import java.util.Collection; import java.util.List; /** * Converts the MPD response to a {@link MPDAlbum} * * @author bill */ @FunctionalInterface public interface AlbumConverter { /** * Converts the response from the MPD server into a {@link MPDAlbum} object. * * @param list the response from the MPD server * @return a {@link MPDAlbum} object */ Collection<MPDAlbum> convertResponseToAlbum(List<String> list); }
471
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAlbumDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/album/MPDAlbumDatabase.java
package org.bff.javampd.album; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.database.TagLister; import org.bff.javampd.genre.MPDGenre; /** * MPDAlbumDatabase represents an album database to a {@link org.bff.javampd.server.MPD}. To obtain * an instance of the class you must use the {@link * org.bff.javampd.database.MusicDatabase#getAlbumDatabase()} method from the {@link * org.bff.javampd.server.MPD} connection class. * * @author Bill */ public class MPDAlbumDatabase implements AlbumDatabase { private final TagLister tagLister; private final AlbumConverter albumConverter; private static final TagLister.GroupType[] ALBUM_TAGS = { TagLister.GroupType.ARTIST, TagLister.GroupType.DATE, TagLister.GroupType.GENRE, TagLister.GroupType.ALBUM_ARTIST, }; @Inject public MPDAlbumDatabase(TagLister tagLister, AlbumConverter albumConverter) { this.tagLister = tagLister; this.albumConverter = albumConverter; } @Override public Collection<MPDAlbum> listAlbumsByAlbumArtist(MPDArtist albumArtist) { var p = new ArrayList<String>(); p.add(TagLister.ListType.ALBUM_ARTIST.getType()); p.add(albumArtist.name()); return convertResponseToAlbum(tagLister.list(TagLister.ListType.ALBUM, p, ALBUM_TAGS)); } @Override public Collection<MPDAlbum> listAlbumsByArtist(MPDArtist artist) { List<String> list = new ArrayList<>(); list.add(TagLister.ListType.ARTIST.getType()); list.add(artist.name()); return convertResponseToAlbum(tagLister.list(TagLister.ListType.ALBUM, list, ALBUM_TAGS)); } @Override public Collection<String> listAllAlbumNames() { return tagLister.list(TagLister.ListType.ALBUM).stream() .map(s -> s.substring(s.split(":")[0].length() + 1).trim()) .toList(); } @Override public Collection<MPDAlbum> listAllAlbums() { return convertResponseToAlbum(this.tagLister.list(TagLister.ListType.ALBUM, ALBUM_TAGS)); } @Override public Collection<MPDAlbum> findAlbum(String albumName) { List<String> list = new ArrayList<>(); list.add(TagLister.ListType.ALBUM.getType()); list.add(albumName); return convertResponseToAlbum(tagLister.list(TagLister.ListType.ALBUM, list, ALBUM_TAGS)); } @Override public Collection<MPDAlbum> listAlbumsByGenre(MPDGenre genre) { List<String> list = new ArrayList<>(); list.add(TagLister.ListType.GENRE.getType()); list.add(genre.name()); return convertResponseToAlbum(tagLister.list(TagLister.ListType.ALBUM, list, ALBUM_TAGS)); } @Override public Collection<MPDAlbum> listAlbumsByYear(String year) { List<String> list = new ArrayList<>(); list.add(TagLister.ListType.DATE.getType()); list.add(year); return convertResponseToAlbum(tagLister.list(TagLister.ListType.ALBUM, list, ALBUM_TAGS)); } private Collection<MPDAlbum> convertResponseToAlbum(List<String> response) { return this.albumConverter.convertResponseToAlbum(response); } }
3,109
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AlbumProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/album/AlbumProcessor.java
package org.bff.javampd.album; import java.util.HashMap; import java.util.Map; import org.bff.javampd.processor.*; public enum AlbumProcessor { ALBUM_ARTIST(new AlbumArtistTagProcessor()), ARTIST(new ArtistTagProcessor()), DATE(new DateTagProcessor()), ALBUM(new AlbumTagProcessor()), GENRE(new GenreTagProcessor()); private final transient TagResponseProcessor albumTagResponseProcessor; private static final Map<String, AlbumProcessor> lookup = new HashMap<>(); static { for (AlbumProcessor a : AlbumProcessor.values()) { lookup.put(a.getProcessor().getPrefix().toLowerCase(), a); } } AlbumProcessor(TagResponseProcessor albumTagResponseProcessor) { this.albumTagResponseProcessor = albumTagResponseProcessor; } public static AlbumProcessor lookup(String line) { return lookup.get(line.substring(0, line.indexOf(":") + 1).toLowerCase()); } public TagResponseProcessor getProcessor() { return this.albumTagResponseProcessor; } /** * Returns the line prefix that delimits songs in the response list * * @return the prefix that breaks songs in the list */ public static String getDelimitingPrefix() { return ALBUM.getProcessor().getPrefix(); } }
1,231
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDCommand.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/command/MPDCommand.java
package org.bff.javampd.command; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * MPDCommand represents a command along with optional command parameters to be sent to a MPD * server. * * @author Bill * @version 1.0 */ @Getter @EqualsAndHashCode @ToString public class MPDCommand { /** * -- GETTER -- Returns the command od this object. * * @return the command */ private final String command; /** * -- GETTER -- Returns the parameter(s) of this command as a of s. Returns null of there is no * parameter for the command. * * @return the parameters for the command */ private final List<String> params; /** * Constructor for MPD command for a command requiring more than 1 parameter. * * @param command the command to send * @param parameters the parameters to send */ public MPDCommand(String command, String... parameters) { if (command == null) { throw new IllegalArgumentException("command can't be null"); } this.command = command; this.params = new ArrayList<>(); Collections.addAll(this.params, Arrays.copyOf(parameters, parameters.length)); } }
1,287
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
CommandExecutor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/command/CommandExecutor.java
package org.bff.javampd.command; import java.util.Collection; import java.util.List; import org.bff.javampd.server.MPD; /** * @author bill */ public interface CommandExecutor { String COMMAND_TERMINATION = "OK"; /** * Sends a command with no parameters to the {@link org.bff.javampd.server.MPD} server returning * the response as a <CODE>List</CODE> of <CODE>Strings</CODE>. * * @param command the command to send * @return the response as a <CODE>Collection</CODE> of <CODE>Strings</CODE> */ List<String> sendCommand(String command); /** * Sends a command and parameters to the {@link org.bff.javampd.server.MPD} server returning the * response as a <CODE>List</CODE> of <CODE>Strings</CODE>. * * @param command the command to send * @param params the parameters for the command * @return the response as a <CODE>Collection</CODE> of <CODE>Strings</CODE> */ List<String> sendCommand(String command, String... params); /** * Sends a command and parameters to the {@link org.bff.javampd.server.MPD} server returning the * response as a <CODE>List</CODE> of <CODE>Strings</CODE>. * * @param command the command to send * @param params the parameters for the command * @return the response as a <CODE>Collection</CODE> of <CODE>Strings</CODE> */ List<String> sendCommand(String command, Integer... params); /** * Sends a {@link MPDCommand} to the {@link org.bff.javampd.server.MPD} server returning the * response as a <CODE>Collection</CODE> of <CODE>Strings</CODE>. * * @param command the command to send * @return the response as a <CODE>Collection</CODE> of <CODE>Strings</CODE> */ Collection<String> sendCommand(MPDCommand command); /** * Sends a list of {@link MPDCommand}s all at once to the MPD server and returns true if all * commands were sent successfully. If any of the commands received as error in the response false * will be returned. * * @param commandList the list of {@link MPDCommand}s */ void sendCommands(List<MPDCommand> commandList); /** * Returns the {@link org.bff.javampd.server.MPD} version * * @return the version */ String getMPDVersion(); /** * Sets the {@link org.bff.javampd.server.MPD} to run commands against * * @param mpd the {@link org.bff.javampd.server.MPD} */ void setMpd(MPD mpd); /** Authenticates to the server using the password provided by #usePassword */ void authenticate(); /** * Password for password protected mpd * * @param password the mpd password */ void usePassword(String password); /** Close the connection executor socket */ void close(); }
2,686
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDCommandExecutor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/command/MPDCommandExecutor.java
package org.bff.javampd.command; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.bff.javampd.server.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Executes commands to the {@link org.bff.javampd.server.MPD}. You <b>MUST</b> call {@link #setMpd} * before making any calls to the server * * @author bill */ @Singleton @Slf4j public class MPDCommandExecutor implements CommandExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(MPDCommandExecutor.class); private MPDSocket mpdSocket; private MPD mpd; private String password; private final ServerProperties serverProperties; /** You <b>MUST</b> call {@link #setMpd} before making any calls to the server */ public MPDCommandExecutor() { serverProperties = new ServerProperties(); } @Override public synchronized List<String> sendCommand(String command) { return sendCommand(new MPDCommand(command)); } @Override public synchronized List<String> sendCommand(String command, String... params) { return sendCommand(new MPDCommand(command, process(params))); } @Override public synchronized List<String> sendCommand(String command, Integer... params) { var intParms = new String[params.length]; for (var i = 0; i < params.length; ++i) { intParms[i] = Integer.toString(params[i]); } return new ArrayList<>(sendCommand(new MPDCommand(command, intParms))); } @Override public synchronized List<String> sendCommand(MPDCommand command) { try { checkSocket(); log.debug("Sending command: {}", command); return new ArrayList<>(mpdSocket.sendCommand(command)); } catch (MPDSecurityException se) { LOGGER.warn( "Connection exception while sending command {}, will retry", command.getCommand(), se); authenticate(); return new ArrayList<>(mpdSocket.sendCommand(command)); } } @Override public synchronized void sendCommands(List<MPDCommand> commandList) { try { checkSocket(); mpdSocket.sendCommands(commandList); } catch (MPDSecurityException se) { LOGGER.warn("Connection exception while sending commands, will retry", se); authenticate(); mpdSocket.sendCommands(commandList); } } @Override public String getMPDVersion() { checkSocket(); return mpdSocket.getVersion(); } @Override public void setMpd(MPD mpd) { this.mpd = mpd; } @Override public void authenticate() { if (password != null) { try { sendCommand(new MPDCommand(serverProperties.getPassword(), password)); } catch (Exception e) { if (e.getMessage() != null && e.getMessage().contains("incorrect password")) { throw new MPDSecurityException("Incorrect password"); } throw new MPDConnectionException("Could not authenticate", e); } } } @Override public void usePassword(String password) { if (password == null || password.isEmpty()) { throw new IllegalArgumentException("Password cannot be null or empty"); } this.password = password; } @Override public void close() { this.mpdSocket.close(); } protected MPDSocket createSocket() { return new MPDSocket(mpd.getAddress(), mpd.getPort(), mpd.getTimeout()); } private void checkSocket() { if (mpd == null) { throw new MPDConnectionException("Socket could not be established. Was mpd set?"); } if (mpdSocket == null) { mpdSocket = createSocket(); } } private String[] process(String[] params) { for (int i = 0; i < params.length; i++) { params[i] = params[i].replace("\"", "\\\""); } return params; } }
3,770
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDArtwork.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/art/MPDArtwork.java
package org.bff.javampd.art; import lombok.Builder; import lombok.Data; @Builder @Data public class MPDArtwork { private String name; private String path; private byte[] bytes; }
187
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDArtworkFinder.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/art/MPDArtworkFinder.java
package org.bff.javampd.art; import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.bff.javampd.MPDException; import org.bff.javampd.album.MPDAlbum; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.song.SongDatabase; @Singleton public class MPDArtworkFinder implements ArtworkFinder { private final SongDatabase songDatabase; @Inject public MPDArtworkFinder(SongDatabase songDatabase) { this.songDatabase = songDatabase; } @Override public List<MPDArtwork> find(MPDAlbum album) { return find(album, ""); } @Override public List<MPDArtwork> find(MPDAlbum album, String pathPrefix) { List<MPDArtwork> artworkList = new ArrayList<>(); List<String> paths = new ArrayList<>(); this.songDatabase .findAlbum(album) .forEach( song -> paths.add( pathPrefix + song.getFile().substring(0, song.getFile().lastIndexOf(File.separator)))); paths.stream().distinct().forEach(path -> artworkList.addAll(find(path))); return artworkList; } @Override public List<MPDArtwork> find(MPDArtist artist) { return find(artist, ""); } @Override public List<MPDArtwork> find(MPDArtist artist, String pathPrefix) { List<MPDArtwork> artworkList = new ArrayList<>(); List<String> paths = new ArrayList<>(); List<String> albumPaths = new ArrayList<>(); this.songDatabase .findArtist(artist) .forEach( song -> albumPaths.add( pathPrefix + song.getFile().substring(0, song.getFile().lastIndexOf(File.separator)))); albumPaths.forEach( path -> { if (path.contains(File.separator + artist.name() + File.separator)) { paths.add(path.substring(0, path.lastIndexOf(File.separator))); } }); paths.addAll(albumPaths); paths.stream().distinct().forEach(path -> artworkList.addAll(find(path))); return artworkList; } @Override public List<MPDArtwork> find(String path) { List<MPDArtwork> artworkList = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(path), "**.{jpg,jpeg,png}")) { stream.forEach(file -> artworkList.add(loadArtwork(file))); } catch (IOException e) { throw new MPDException(String.format("Could not load art in %s", path), e); } return artworkList; } private static MPDArtwork loadArtwork(Path file) { var artwork = MPDArtwork.builder() .name(file.getFileName().toString()) .path(file.toAbsolutePath().toString()) .build(); artwork.setBytes(loadFile(file)); return artwork; } private static byte[] loadFile(Path path) { try { return Files.readAllBytes(path); } catch (IOException e) { throw new MPDException(String.format("Could not read path: %s", path), e); } } }
3,217
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ArtworkFinder.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/art/ArtworkFinder.java
package org.bff.javampd.art; import java.util.List; import org.bff.javampd.album.MPDAlbum; import org.bff.javampd.artist.MPDArtist; /** * Artwork finder looks in the path of an {@link MPDArtist}, {@link MPDAlbum} or path for images. * * <p>MPD must have at least read access to this directory or nothing will be returned. */ public interface ArtworkFinder { /** * Returns a list of {@link MPDArtwork} for images in the given {@link MPDAlbum} * * @param album the album path to interrogate * @return a list of {@link MPDArtwork} */ List<MPDArtwork> find(MPDAlbum album); /** * Returns a list of {@link MPDArtwork} for images in the given {@link MPDAlbum} * * @param album the album path to interrogate * @param pathPrefix the prefix of the path if not running locally with the MPD server * @return a list of {@link MPDArtwork} */ List<MPDArtwork> find(MPDAlbum album, String pathPrefix); /** * Returns a list of {@link MPDArtwork} for images in the given {@link MPDArtist} This will search * both the artist path and all albums by the artist. This assumes you have the artist as part of * the directory structure similar to this: * * <p>'/music/artist/album/song.flac' If the artist is not there no attempt will be made to search * the artist directory. * * @param artist the artist path to interrogate * @return a list of {@link MPDArtwork} */ List<MPDArtwork> find(MPDArtist artist); /** * Returns a list of {@link MPDArtwork} for images in the given {@link MPDArtist} This will search * both the artist path and all albums by the artist. This assumes you have the artist as part of * the directory structure similar to this: * * <p>'/music/artist/album/song.flac' If the artist is not there no attempt will be made to search * the artist directory. * * @param artist the artist path to interrogate * @param pathPrefix the prefix of the path if not running locally with the MPD server * @return a list of {@link MPDArtwork} */ List<MPDArtwork> find(MPDArtist artist, String pathPrefix); /** * Returns a list of {@link MPDArtwork} for images in the given path * * @param path the path to interrogate * @return a list of {@link MPDArtwork} */ List<MPDArtwork> find(String path); }
2,321
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDFileDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/file/MPDFileDatabase.java
package org.bff.javampd.file; import com.google.inject.Inject; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.bff.javampd.MPDException; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.database.DatabaseProperties; import org.bff.javampd.database.TagLister; /** * MPDFileDatabase represents a file database controller to a {@link org.bff.javampd.server.MPD}. To * obtain an instance of the class you must use the {@link * org.bff.javampd.database.MusicDatabase#getFileDatabase()} method from the {@link * org.bff.javampd.server.MPD} connection class. * * @author Bill */ public class MPDFileDatabase implements FileDatabase { private final DatabaseProperties databaseProperties; private final CommandExecutor commandExecutor; private static final String PREFIX_FILE = TagLister.ListInfoType.FILE.getPrefix(); private static final String PREFIX_DIRECTORY = TagLister.ListInfoType.DIRECTORY.getPrefix(); private static final String PREFIX_LAST_MODIFIED = TagLister.ListInfoType.LAST_MODIFIED.getPrefix(); @Inject public MPDFileDatabase(DatabaseProperties databaseProperties, CommandExecutor commandExecutor) { this.databaseProperties = databaseProperties; this.commandExecutor = commandExecutor; } @Override public Collection<MPDFile> listRootDirectory() { return listDirectory(""); } @Override public Collection<MPDFile> listDirectory(MPDFile directory) { if (directory.isDirectory()) { return listDirectory(directory.getPath()); } else { throw new MPDException(directory.getPath() + " is not a directory."); } } private Collection<MPDFile> listDirectory(String directory) { return listDirectoryInfo(directory); } private Collection<MPDFile> listDirectoryInfo(String directory) { List<MPDFile> returnList = new ArrayList<>(); List<String> commandResponse = commandExecutor.sendCommand(databaseProperties.getListInfo(), directory); Iterator<String> iterator = commandResponse.iterator(); String line = null; while (iterator.hasNext()) { if (line == null || (!line.startsWith(PREFIX_FILE) && !line.startsWith(PREFIX_DIRECTORY))) { line = iterator.next(); } if (line.startsWith(PREFIX_FILE) || line.startsWith(PREFIX_DIRECTORY)) { var mpdFile = MPDFile.builder( line.startsWith(PREFIX_FILE) ? line.substring(PREFIX_FILE.length()).trim() : line.substring(PREFIX_DIRECTORY.length()).trim()) .build(); if (line.startsWith(PREFIX_DIRECTORY)) { mpdFile.setDirectory(true); } line = processFile(mpdFile, iterator); returnList.add(mpdFile); } } return returnList; } private static String processFile(MPDFile mpdFile, Iterator<String> iterator) { String line = iterator.next(); while (!line.startsWith(PREFIX_FILE) && !line.startsWith(PREFIX_DIRECTORY)) { if (line.startsWith(PREFIX_LAST_MODIFIED)) { mpdFile.setLastModified(processDate(line)); } if (!iterator.hasNext()) { break; } line = iterator.next(); } return line; } private static LocalDateTime processDate(String name) { return LocalDateTime.parse( name.substring(PREFIX_LAST_MODIFIED.length()).trim(), DateTimeFormatter.ISO_DATE_TIME); } }
3,557
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
FileDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/file/FileDatabase.java
package org.bff.javampd.file; import java.util.Collection; /** * Database for file related items * * @author bill */ public interface FileDatabase { /** * Lists all {@link org.bff.javampd.file.MPDFile}s for the root directory of the file system. * * @return a {@code Collection} of {@link org.bff.javampd.file.MPDFile} */ Collection<MPDFile> listRootDirectory(); /** * Lists all {@link org.bff.javampd.file.MPDFile}s for the given directory of the file system. * * @param directory the directory to list * @return a {@code Collection} of {@link org.bff.javampd.file.MPDFile} */ Collection<MPDFile> listDirectory(MPDFile directory); }
677
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDFile.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/file/MPDFile.java
package org.bff.javampd.file; import java.time.LocalDateTime; import lombok.Builder; import lombok.Data; /** * Represents a file within the mpd songs directory. * * @author Bill */ @Builder(builderMethodName = "internalBuilder") @Data public class MPDFile { private boolean directory; private String path; private LocalDateTime lastModified; public static MPDFile.MPDFileBuilder builder(String path) { return internalBuilder().path(path); } }
464
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDOutput.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/output/MPDOutput.java
package org.bff.javampd.output; import lombok.Builder; import lombok.Data; /** * Represent a MPD output. * * @author Bill */ @Builder(builderMethodName = "internalBuilder") @Data public class MPDOutput { private int id; private String name; private boolean enabled; public static MPDOutput.MPDOutputBuilder builder(int id) { return internalBuilder().id(id); } }
383
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
OutputChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/output/OutputChangeEvent.java
package org.bff.javampd.output; import lombok.Getter; /** * Represents a change in the outputs of a {@link MPDOutput}. * * @author Bill * @version 1.0 */ @Getter public class OutputChangeEvent extends java.util.EventObject { /** * -- GETTER -- Returns the for this event. * * @return the event */ private final OUTPUT_EVENT event; public enum OUTPUT_EVENT { OUTPUT_ADDED, OUTPUT_DELETED, OUTPUT_CHANGED } /** * Creates a new instance of OutputChangeEvent * * @param source the object on which the Event initially occurred * @param event the output event */ public OutputChangeEvent(Object source, OUTPUT_EVENT event) { super(source); this.event = event; } }
729
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
OutputChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/output/OutputChangeListener.java
package org.bff.javampd.output; /** * The listener interface for receiving output change events. The class that is interested in * processing a output change event implements this interface, and the object created with that * class is registered with a component using the component's <CODE>addOutputChangeListener</CODE> * method. When the event occurs, that object's <CODE>outputChanged</CODE> method is invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface OutputChangeListener { /** * Invoked when a mpd {@link OutputChangeEvent} occurs. * * @param event the event received */ void outputChanged(OutputChangeEvent event); }
681
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/PlaylistProperties.java
package org.bff.javampd.playlist; import lombok.Getter; import org.bff.javampd.server.MPDProperties; /** * @author bill */ public class PlaylistProperties extends MPDProperties { @Getter private enum Command { ADD("playlist.add"), CLEAR("playlist.clear"), CURRSONG("playlist.currsong"), DELETE("playlist.delete"), CHANGES("playlist.changes"), ID("playlist.list.id"), INFO("playlist.list"), LOAD("playlist.load"), MOVE("playlist.move"), MOVEID("playlist.move.id"), REMOVE("playlist.remove"), REMOVEID("playlist.remove.id"), SAVE("playlist.save"), SHUFFLE("playlist.shuffle"), SWAP("playlist.swap"), SWAPID("playlist.swap.id"); private final String key; Command(String key) { this.key = key; } } public String getAdd() { return getPropertyString(Command.ADD.getKey()); } public String getClear() { return getPropertyString(Command.CLEAR.getKey()); } public String getCurrentSong() { return getPropertyString(Command.CURRSONG.getKey()); } public String getDelete() { return getPropertyString(Command.DELETE.getKey()); } public String getChanges() { return getPropertyString(Command.CHANGES.getKey()); } public String getId() { return getPropertyString(Command.ID.getKey()); } public String getInfo() { return getPropertyString(Command.INFO.getKey()); } public String getLoad() { return getPropertyString(Command.LOAD.getKey()); } public String getMove() { return getPropertyString(Command.MOVE.getKey()); } public String getMoveId() { return getPropertyString(Command.MOVEID.getKey()); } public String getRemove() { return getPropertyString(Command.REMOVE.getKey()); } public String getRemoveId() { return getPropertyString(Command.REMOVEID.getKey()); } public String getSave() { return getPropertyString(Command.SAVE.getKey()); } public String getShuffle() { return getPropertyString(Command.SHUFFLE.getKey()); } public String getSwap() { return getPropertyString(Command.SWAP.getKey()); } public String getSwapId() { return getPropertyString(Command.SWAPID.getKey()); } }
2,210
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/PlaylistChangeEvent.java
package org.bff.javampd.playlist; import java.util.EventObject; import lombok.Getter; /** * Represents a change in the status of a MPD playlist. * * @author Bill */ @Getter public class PlaylistChangeEvent extends EventObject { /** * -- GETTER -- Returns the that occurred. * * @return the specific id */ private final Event event; /** * -- GETTER -- the name of the added entity * * @return name of the artist, album, song, etc */ private String name; public enum Event { SONG_ADDED, SONG_DELETED, SONG_SELECTED, PLAYLIST_ADDED, PLAYLIST_CHANGED, PLAYLIST_DELETED, PLAYLIST_LOADED, PLAYLIST_SAVED, PLAYLIST_CLEARED, ARTIST_ADDED, ALBUM_ADDED, GENRE_ADDED, YEAR_ADDED, FILE_ADDED, MULTIPLE_SONGS_ADDED } /** * Creates a new instance of PlayListChangeEvent * * @param source the object on which the Event initially occurred * @param event the specific {@link Event} that occurred */ public PlaylistChangeEvent(Object source, Event event) { super(source); this.event = event; } /** * Creates a new instance of PlayListChangeEvent * * @param source the object on which the Event initially occurred * @param event the specific {@link Event} that occurred * @param name name of the added entity */ public PlaylistChangeEvent(Object source, Event event, String name) { super(source); this.event = event; this.name = name; } }
1,491
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistSong.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/MPDPlaylistSong.java
package org.bff.javampd.playlist; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.SuperBuilder; import org.bff.javampd.song.MPDSong; @SuperBuilder @Data @EqualsAndHashCode(callSuper = true) public class MPDPlaylistSong extends MPDSong { /** Returns the position of the song in the playlist. */ @Builder.Default private final int position = -1; /** Returns the playlist song id for the song. */ @Builder.Default private final int id = -1; }
507
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylist.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/MPDPlaylist.java
package org.bff.javampd.playlist; import com.google.inject.Inject; import java.util.ArrayList; import java.util.List; import org.bff.javampd.album.MPDAlbum; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.command.MPDCommand; import org.bff.javampd.file.MPDFile; import org.bff.javampd.genre.MPDGenre; import org.bff.javampd.server.ServerStatus; import org.bff.javampd.song.MPDSong; import org.bff.javampd.song.SongDatabase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MPDPlaylist represents a playlist controller to a MPD server. To obtain an instance of the class * you must use the <code>getMPDPlaylist</code> method from the {@link org.bff.javampd.server.MPD} * connection class. * * @author Bill */ public class MPDPlaylist implements Playlist { private static final Logger LOGGER = LoggerFactory.getLogger(MPDPlaylist.class); private int oldVersion = -1; private int version = -1; private final List<PlaylistChangeListener> listeners; private final SongDatabase songDatabase; private final ServerStatus serverStatus; private final CommandExecutor commandExecutor; private final PlaylistSongConverter songConverter; private PlaylistProperties playlistProperties; /** * Playlist constructor * * @param songDatabase the song database * @param serverStatus the server status * @param playlistProperties playlist properties * @param commandExecutor command runner * @param songConverter song marshaller */ @Inject public MPDPlaylist( SongDatabase songDatabase, ServerStatus serverStatus, PlaylistProperties playlistProperties, CommandExecutor commandExecutor, PlaylistSongConverter songConverter) { this.songDatabase = songDatabase; this.serverStatus = serverStatus; this.playlistProperties = playlistProperties; this.commandExecutor = commandExecutor; this.songConverter = songConverter; this.listeners = new ArrayList<>(); this.playlistProperties = new PlaylistProperties(); } @Override public synchronized void addPlaylistChangeListener(PlaylistChangeListener pcl) { listeners.add(pcl); } @Override public synchronized void removePlaylistStatusChangedListener(PlaylistChangeListener pcl) { listeners.remove(pcl); } /** * Sends the appropriate {@link PlaylistChangeEvent} to all registered {@link * PlaylistChangeListener}. * * @param event the {@link PlaylistChangeEvent.Event} to send */ protected synchronized void firePlaylistChangeEvent(PlaylistChangeEvent.Event event) { var pce = new PlaylistChangeEvent(this, event); for (PlaylistChangeListener pcl : listeners) { pcl.playlistChanged(pce); } } /** * Sends the appropriate {@link PlaylistChangeEvent} to all registered {@link * PlaylistChangeListener}. * * @param event the {@link PlaylistChangeEvent.Event} to send * @param name name of the added entity */ protected synchronized void firePlaylistChangeEvent( PlaylistChangeEvent.Event event, String name) { var pce = new PlaylistChangeEvent(this, event, name); for (PlaylistChangeListener pcl : listeners) { pcl.playlistChanged(pce); } } @Override public void loadPlaylist(String playlistName) { String name = playlistName; if (name.endsWith(".m3u")) { name = name.substring(0, name.length() - 4); } commandExecutor.sendCommand(playlistProperties.getLoad(), name); updatePlaylist(); } @Override public void addSong(MPDSong song) { addSong(song, true); } @Override public void addSong(MPDSong song, boolean fireEvent) { addSong(song.getFile(), fireEvent); } @Override public void addSong(String file) { this.addSong(file, true); } @Override public void addSong(String file, boolean fireEvent) { commandExecutor.sendCommand(playlistProperties.getAdd(), file); updatePlaylist(); if (fireEvent) { firePlaylistChangeEvent(PlaylistChangeEvent.Event.SONG_ADDED, file); } } @Override public boolean addSongs(List<MPDSong> songList) { return addSongs(songList, true); } @Override public boolean addSongs(List<MPDSong> songList, boolean fireEvent) { commandExecutor.sendCommands( songList.stream() .map(song -> new MPDCommand(playlistProperties.getAdd(), song.getFile())) .toList()); int oldCount = songList.size(); updatePlaylist(); if (fireEvent) { firePlaylistChangeEvent( PlaylistChangeEvent.Event.MULTIPLE_SONGS_ADDED, Integer.toString(songList.size())); } return oldCount < songList.size(); } @Override public void addFileOrDirectory(MPDFile file) { commandExecutor.sendCommand(playlistProperties.getAdd(), file.getPath()); updatePlaylist(); firePlaylistChangeEvent(PlaylistChangeEvent.Event.FILE_ADDED, file.getPath()); } @Override public void removeSong(MPDPlaylistSong song) { if (song.getId() > -1) { updatePlaylist(); firePlaylistChangeEvent(PlaylistChangeEvent.Event.SONG_DELETED, song.getName()); commandExecutor.sendCommand(playlistProperties.getRemoveId(), song.getId()); } else { removeSong(song.getPosition()); } } @Override public void removeSong(int position) { if (position > -1) { commandExecutor.sendCommand(playlistProperties.getRemove(), position); updatePlaylist(); firePlaylistChangeEvent(PlaylistChangeEvent.Event.SONG_DELETED); } } @Override public MPDPlaylistSong getCurrentSong() { List<MPDPlaylistSong> songs = convertResponseToSong(commandExecutor.sendCommand(playlistProperties.getCurrentSong())); return songs.isEmpty() ? null : songs.getFirst(); } private List<MPDPlaylistSong> convertResponseToSong(List<String> response) { return songConverter.convertResponseToSongs(response); } @Override public void clearPlaylist() { commandExecutor.sendCommand(playlistProperties.getClear()); updatePlaylist(); firePlaylistChangeEvent(PlaylistChangeEvent.Event.PLAYLIST_CLEARED); } @Override public void deletePlaylist(MPDSavedPlaylist playlist) { deletePlaylist(playlist.getName()); } @Override public void deletePlaylist(String playlistName) { commandExecutor.sendCommand(playlistProperties.getDelete(), playlistName); firePlaylistChangeEvent(PlaylistChangeEvent.Event.PLAYLIST_DELETED); } @Override public void move(MPDPlaylistSong song, int to) { if (song.getId() > -1) { commandExecutor.sendCommand(playlistProperties.getMoveId(), song.getId(), to); } else if (song.getPosition() > -1) { commandExecutor.sendCommand(playlistProperties.getMove(), song.getPosition(), to); } updatePlaylist(); } @Override public void shuffle() { commandExecutor.sendCommand(playlistProperties.getShuffle()); updatePlaylist(); } @Override public void swap(MPDPlaylistSong song1, MPDPlaylistSong song2) { if (song1.getId() > -1 && song2.getId() > -1) { commandExecutor.sendCommand(playlistProperties.getSwapId(), song1.getId(), song2.getId()); } else if (song1.getPosition() > -1 && song2.getPosition() > -1) { commandExecutor.sendCommand( playlistProperties.getSwap(), song1.getPosition(), song2.getPosition()); } updatePlaylist(); } @Override public boolean savePlaylist(String playlistName) { if (playlistName != null) { commandExecutor.sendCommand(playlistProperties.getSave(), playlistName); firePlaylistChangeEvent(PlaylistChangeEvent.Event.PLAYLIST_SAVED); return true; } else { LOGGER.error("Playlist not saved since name was null"); return false; } } private void updatePlaylist() { int v = getPlaylistVersion(); setVersion(v); if (v != oldVersion) { oldVersion = getVersion(); firePlaylistChangeEvent(PlaylistChangeEvent.Event.PLAYLIST_CHANGED); } } private int getPlaylistVersion() { return serverStatus.getPlaylistVersion(); } /** * Returns the list of songs in the playlist. * * @return the list of songs */ private List<MPDPlaylistSong> listSongs() { return convertResponseToSong(commandExecutor.sendCommand(playlistProperties.getInfo())); } @Override public void insertAlbum(MPDArtist artist, MPDAlbum album) { for (MPDSong song : songDatabase.findAlbumByArtist(artist, album)) { addSong(song, false); } firePlaylistChangeEvent(PlaylistChangeEvent.Event.ALBUM_ADDED, album.getName()); } @Override public void insertAlbum(String artist, String album) { for (MPDSong song : songDatabase.findAlbumByArtist(artist, album)) { addSong(song, false); } firePlaylistChangeEvent(PlaylistChangeEvent.Event.ALBUM_ADDED, album); } @Override public void insertAlbum(MPDAlbum album) { for (MPDSong song : songDatabase.findAlbum(album)) { addSong(song, false); } firePlaylistChangeEvent(PlaylistChangeEvent.Event.ALBUM_ADDED, album.getName()); } @Override public void insertAlbum(String album) { for (MPDSong song : songDatabase.findAlbum(album)) { addSong(song, false); } firePlaylistChangeEvent(PlaylistChangeEvent.Event.ALBUM_ADDED, album); } @Override public void removeAlbum(MPDArtist artist, MPDAlbum album) { removeAlbum(artist.name(), album.getName()); } @Override public void removeAlbum(String artistName, String albumName) { List<MPDPlaylistSong> removeList = getSongList().stream() .filter( song -> song.getArtistName().equals(artistName) && song.getAlbumName().equals(albumName)) .toList(); removeList.forEach(this::removeSong); } @Override public void insertArtist(MPDArtist artist) { insertArtist(artist.name()); } @Override public void insertArtist(String artistName) { for (MPDSong song : songDatabase.findArtist(artistName)) { addSong(song, false); } firePlaylistChangeEvent(PlaylistChangeEvent.Event.ARTIST_ADDED, artistName); } @Override public void insertGenre(MPDGenre genre) { insertGenre(genre.name()); } @Override public void insertGenre(String genreName) { for (MPDSong song : songDatabase.findGenre(genreName)) { addSong(song, false); } firePlaylistChangeEvent(PlaylistChangeEvent.Event.GENRE_ADDED, genreName); } @Override public void removeGenre(MPDGenre genre) { removeGenre(genre.name()); } @Override public void removeGenre(String genreName) { List<MPDPlaylistSong> removeList = getSongList().stream().filter(song -> song.getGenre().equals(genreName)).toList(); removeList.forEach(this::removeSong); } @Override public void insertYear(String year) { for (MPDSong song : songDatabase.findYear(year)) { addSong(song, false); } firePlaylistChangeEvent(PlaylistChangeEvent.Event.YEAR_ADDED, year); } @Override public void removeYear(String year) { List<MPDPlaylistSong> removeList = new ArrayList<>(); for (MPDPlaylistSong song : getSongList()) { if (song.getDate().equals(year)) { removeList.add(song); } } removeList.forEach(this::removeSong); } @Override public void removeArtist(MPDArtist artist) { removeArtist(artist.name()); } @Override public void removeArtist(String artistName) { List<MPDPlaylistSong> removeList = new ArrayList<>(); for (MPDPlaylistSong song : getSongList()) { if (song.getArtistName().equals(artistName)) { removeList.add(song); } } removeList.forEach(this::removeSong); } @Override public int getVersion() { return version; } private void setVersion(int version) { this.version = version; } @Override public List<MPDPlaylistSong> getSongList() { return listSongs(); } @Override public void swap(MPDPlaylistSong song, int i) { commandExecutor.sendCommand(playlistProperties.getSwapId(), song.getId(), i); updatePlaylist(); } }
12,179
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistBasicChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/PlaylistBasicChangeListener.java
package org.bff.javampd.playlist; /** * The listener interface for receiving basic playlist events. The class that is interested in * processing a basic playlist event implements this interface, and the object created with that * class is registered with a component using the component's <CODE>addPlaylistChangeListener</CODE> * method. When the playlist event occurs, that object's <CODE>playlistBasicChange</CODE> method is * invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface PlaylistBasicChangeListener { /** * Invoked when a playlist event occurs. * * @param event the event fired */ void playlistBasicChange(PlaylistBasicChangeEvent event); }
707
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/PlaylistChangeListener.java
package org.bff.javampd.playlist; /** * The listener interface for receiving playlist events. The class that is interested in processing * a playlist event implements this interface, and the object created with that class is registered * with a component using the component's <CODE>addPlaylistChangeListener</CODE> method. When the * playlist event occurs, that object's <CODE>playlistChanged</CODE> method is invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface PlaylistChangeListener { /** * Invoked when a playlist event occurs. * * @param event the event fired */ void playlistChanged(PlaylistChangeEvent event); }
674
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistBasicChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/PlaylistBasicChangeEvent.java
package org.bff.javampd.playlist; import java.util.EventObject; import lombok.Getter; /** * Represents a change in the status of a MPD music playlist. * * @author Bill */ @Getter public class PlaylistBasicChangeEvent extends EventObject { /** * -- GETTER -- Returns the that occurred. * * @return the specific {@link Event} */ private final Event event; public enum Event { SONG_ADDED, SONG_DELETED, SONG_CHANGED, PLAYLIST_CHANGED, PLAYLIST_ENDED } /** * Creates a new instance of PlayListBasicChangeEvent * * @param source the object on which the Event initially occurred * @param event the specific {@link PlaylistBasicChangeEvent.Event} that occurred */ public PlaylistBasicChangeEvent(Object source, Event event) { super(source); this.event = event; } }
835
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSavedPlaylist.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/MPDSavedPlaylist.java
package org.bff.javampd.playlist; import java.util.Collection; import lombok.Builder; import lombok.Data; import org.bff.javampd.song.MPDSong; /** * MPDSavedPlaylist represents a saved playlist. * * @author Bill */ @Builder(builderMethodName = "internalBuilder") @Data public class MPDSavedPlaylist { private String name; private Collection<MPDSong> songs; public static MPDSavedPlaylist.MPDSavedPlaylistBuilder builder(String name) { return internalBuilder().name(name); } }
495
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistSongConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/MPDPlaylistSongConverter.java
package org.bff.javampd.playlist; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.bff.javampd.song.MPDTagConverter; import org.bff.javampd.song.SongProcessor; @Slf4j public class MPDPlaylistSongConverter extends MPDTagConverter<MPDPlaylistSong> implements PlaylistSongConverter { @Override public List<MPDPlaylistSong> convertResponseToSongs(List<String> list) { return super.convertResponse(list); } @Override public MPDPlaylistSong createSong(Map<String, String> props, Map<String, List<String>> tags) { return MPDPlaylistSong.builder() .file(props.get(SongProcessor.FILE.name())) .name( props.get(SongProcessor.NAME.name()) == null ? props.get(SongProcessor.TITLE.name()) : props.get(SongProcessor.NAME.name())) .title(props.get(SongProcessor.TITLE.name())) .albumArtist(props.get(SongProcessor.ALBUM_ARTIST.name())) .artistName(props.get(SongProcessor.ARTIST.name())) .genre(props.get(SongProcessor.GENRE.name())) .date(props.get(SongProcessor.DATE.name())) .comment(props.get(SongProcessor.COMMENT.name())) .discNumber(props.get(SongProcessor.DISC.name())) .albumName(props.get(SongProcessor.ALBUM.name())) .track(props.get(SongProcessor.TRACK.name())) .length(parseInt(props.get(SongProcessor.TIME.name()))) .id(parseInt(props.get(SongProcessor.ID.name()))) .position(parseInt(props.get(SongProcessor.POS.name()))) .tagMap(tags) .build(); } }
1,591
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistSongConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/PlaylistSongConverter.java
package org.bff.javampd.playlist; import java.util.List; import org.bff.javampd.song.MPDSong; /** * @author bill */ public interface PlaylistSongConverter { /** * Converts the response from the MPD server into {@link MPDSong}s. * * @param list the response from the MPD server * @return a MPDSong object */ List<MPDPlaylistSong> convertResponseToSongs(List<String> list); }
397
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/PlaylistDatabase.java
package org.bff.javampd.playlist; import java.util.Collection; import org.bff.javampd.song.MPDSong; /** * Database for playlist related items * * @author bill */ public interface PlaylistDatabase { /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.playlist.MPDSavedPlaylist}s of * all saved playlists. This is an expensive call so use it cautiously. * * @return a {@link java.util.Collection} of all {@link * org.bff.javampd.playlist.MPDSavedPlaylist}s */ Collection<MPDSavedPlaylist> listSavedPlaylists(); /** * Returns a {@link java.util.Collection} of all available playlist names on the server. * * @return a list of playlist names */ Collection<String> listPlaylists(); Collection<MPDSong> listPlaylistSongs(String playlistName); int countPlaylistSongs(String playlistName); }
859
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/MPDPlaylistDatabase.java
package org.bff.javampd.playlist; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.database.DatabaseProperties; import org.bff.javampd.database.MusicDatabase; import org.bff.javampd.database.TagLister; import org.bff.javampd.server.MPD; import org.bff.javampd.song.MPDSong; import org.bff.javampd.song.SongConverter; import org.bff.javampd.song.SongDatabase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MPDPlaylistDatabase represents a playlist database to a {@link MPD}. To obtain an instance of the * class you must use the {@link MusicDatabase#getPlaylistDatabase()} method from the {@link MPD} * connection class. * * @author Bill */ public class MPDPlaylistDatabase implements PlaylistDatabase { private final SongDatabase songDatabase; private final CommandExecutor commandExecutor; private final DatabaseProperties databaseProperties; private final TagLister tagLister; private final SongConverter songConverter; private static final Logger LOGGER = LoggerFactory.getLogger(MPDPlaylistDatabase.class); @Inject public MPDPlaylistDatabase( SongDatabase songDatabase, CommandExecutor commandExecutor, DatabaseProperties databaseProperties, TagLister tagLister, SongConverter songConverter) { this.songDatabase = songDatabase; this.commandExecutor = commandExecutor; this.databaseProperties = databaseProperties; this.tagLister = tagLister; this.songConverter = songConverter; } @Override public Collection<MPDSavedPlaylist> listSavedPlaylists() { List<MPDSavedPlaylist> playlists = new ArrayList<>(); listPlaylists() .forEach( s -> { MPDSavedPlaylist playlist = MPDSavedPlaylist.builder(s).build(); playlist.setSongs(listPlaylistSongs(s)); playlists.add(playlist); }); return playlists; } @Override public Collection<String> listPlaylists() { return tagLister.listInfo(TagLister.ListInfoType.PLAYLIST); } @Override public Collection<MPDSong> listPlaylistSongs(String playlistName) { List<String> response = commandExecutor.sendCommand(databaseProperties.getListSongs(), playlistName); List<MPDSong> songList = songConverter.getSongFileNameList(response).stream() .map( song -> { Optional<MPDSong> mpdSong = Optional.empty(); try { mpdSong = Optional.of(new ArrayList<>(songDatabase.searchFileName(song)).getFirst()); } catch (IndexOutOfBoundsException e) { LOGGER.error("Could not find file: {}", song); } return mpdSong; }) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); // Handle web radio streams songList.addAll( songConverter.getSongFileNameList(response).stream() .filter(stream -> Pattern.compile("http.+").matcher(stream.toLowerCase()).matches()) .map(song -> MPDPlaylistSong.builder().file(song).title(song).build()) .toList()); return songList; } @Override public int countPlaylistSongs(String playlistName) { List<String> response = commandExecutor.sendCommand(databaseProperties.getListSongs(), playlistName); return response.size(); } }
3,668
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
Playlist.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/playlist/Playlist.java
package org.bff.javampd.playlist; import java.util.List; import org.bff.javampd.album.MPDAlbum; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.file.MPDFile; import org.bff.javampd.genre.MPDGenre; import org.bff.javampd.song.MPDSong; /** * @author bill */ public interface Playlist { /** * Adds a {@link PlaylistChangeListener} to this object to receive {@link PlaylistChangeEvent}s. * * @param pcl the PlaylistChangeListener to add */ void addPlaylistChangeListener(PlaylistChangeListener pcl); /** * Removes a {@link PlaylistChangeListener} from this object. * * @param pcl the PlaylistChangeListener to remove */ void removePlaylistStatusChangedListener(PlaylistChangeListener pcl); /** * Loads the songs in the given playlist to the current playlist. The playlist name can be givin * with or without the .m3u extension. * * @param playlistName the playlist name */ void loadPlaylist(String playlistName); /** * Adds a {@link org.bff.javampd.song.MPDSong} to the playlist and fires a {@link * PlaylistChangeEvent} for event listeners * * @param song the song to add */ void addSong(MPDSong song); /** * Adds a file to the playlist and fires a {@link PlaylistChangeEvent} for event listeners * * @param file the file to add */ void addSong(String file); /** * Adds a file to the playlist. * * @param file the song to add * @param fireEvent whether to fire song added event for the event listeners */ void addSong(String file, boolean fireEvent); /** * Adds a {@link org.bff.javampd.playlist.MPDPlaylistSong} to the playlist. * * @param song the song to add * @param fireEvent whether to fire song added event for the event listeners */ void addSong(MPDSong song, boolean fireEvent); /** * Adds a <CODE>List</CODE> of {@link org.bff.javampd.song.MPDSong}s to the playlist. * * @param songList the list of songs to add * @return true if the songs are added successfully; false otherwise */ boolean addSongs(List<MPDSong> songList); /** * Adds a <CODE>List</CODE> of {@link org.bff.javampd.song.MPDSong}s to the playlist. * * @param songList the list of songs to add * @param fireEvent true if a playlist event should be fired after adding * @return true if the songs are added successfully; false otherwise */ boolean addSongs(List<MPDSong> songList, boolean fireEvent); /** * Adds a directory of songs to the playlist. * * @param file the directory to add */ void addFileOrDirectory(MPDFile file); /** * Removes a {@link org.bff.javampd.playlist.MPDPlaylistSong} from the playlist. * * @param song the song to remove */ void removeSong(MPDPlaylistSong song); /** * Removes a {@link org.bff.javampd.playlist.MPDPlaylistSong} from the playlist. * * @param position the playlist position to remove */ void removeSong(int position); /** * Returns the current song. * * @return the current song */ MPDPlaylistSong getCurrentSong(); /** Removes all songs from the playlist. */ void clearPlaylist(); /** * Deletes a {@link org.bff.javampd.playlist.MPDSavedPlaylist} * * @param playlist the {@link org.bff.javampd.playlist.MPDSavedPlaylist} */ void deletePlaylist(MPDSavedPlaylist playlist); /** * Deletes the playlist from the MPD server. * * @param playlistName the playlist to delete */ void deletePlaylist(String playlistName); /** * Moves the desired song to the given position in the playlist. * * @param song the song to move * @param to the position to move the song to */ void move(MPDPlaylistSong song, int to); /** Shuffles the songs in the playlist. */ void shuffle(); /** * Swaps the given two songs in the playlist. * * @param song1 first song to swap * @param song2 second song to swap */ void swap(MPDPlaylistSong song1, MPDPlaylistSong song2); /** * Saves the current playlist as the passed playlist name. * * @param playlistName the playlist name for the playlist * @return true if the playlist is saved; otherwise false */ boolean savePlaylist(String playlistName); /** * Adds a {@link org.bff.javampd.album.MPDAlbum} by a {@link org.bff.javampd.artist.MPDArtist} to * the playlist. * * @param artist the {@link org.bff.javampd.artist.MPDArtist} for the album to add * @param album the {@link org.bff.javampd.album.MPDAlbum} to add */ void insertAlbum(MPDArtist artist, MPDAlbum album); /** * Adds a album by a artist to the playlist. * * @param artistName the album's artist * @param albumName the album name */ void insertAlbum(String artistName, String albumName); /** * Adds a {@link org.bff.javampd.album.MPDAlbum} to the playlist. * * @param album the {@link org.bff.javampd.album.MPDAlbum} to add */ void insertAlbum(MPDAlbum album); /** * Adds a album to the playlist. * * @param albumName the album to add */ void insertAlbum(String albumName); /** * Removes a {@link org.bff.javampd.album.MPDAlbum} by a {@link org.bff.javampd.artist.MPDArtist} * from the playlist. * * @param artist the {@link org.bff.javampd.artist.MPDArtist} for the album to remove * @param album the {@link org.bff.javampd.album.MPDAlbum} to remove */ void removeAlbum(MPDArtist artist, MPDAlbum album); /** * Removes a album by a artist from the playlist. * * @param artistName the artist for the album to remove * @param albumName the album to remove */ void removeAlbum(String artistName, String albumName); /** * Adds a {@link org.bff.javampd.artist.MPDArtist} to the playlist. * * @param artist the {@link org.bff.javampd.artist.MPDArtist} to add */ void insertArtist(MPDArtist artist); /** * Adds a artist to the playlist. * * @param artistName the artist to add */ void insertArtist(String artistName); /** * Adds a {@link org.bff.javampd.genre.MPDGenre} to the playlist. * * @param genre the {@link org.bff.javampd.genre.MPDGenre} to add */ void insertGenre(MPDGenre genre); /** * Adds a genre to the playlist. * * @param genreName the genre to add */ void insertGenre(String genreName); /** * Removes a {@link org.bff.javampd.genre.MPDGenre} from the playlist. * * @param genre the {@link org.bff.javampd.genre.MPDGenre} to remove */ void removeGenre(MPDGenre genre); /** * Removes a genre from the playlist. * * @param genreName the artist to remove */ void removeGenre(String genreName); /** * Adds a year to the playlist. * * @param year the {@link org.bff.javampd.genre.MPDGenre} to add */ void insertYear(String year); /** * Removes a year from the playlist. * * @param year the artist to remove */ void removeYear(String year); /** * Removes a {@link org.bff.javampd.artist.MPDArtist} from the playlist. * * @param artist the {@link org.bff.javampd.artist.MPDArtist} to remove */ void removeArtist(MPDArtist artist); /** * Removes a artist from the playlist. * * @param artistName the artist to remove */ void removeArtist(String artistName); /** * Returns the playlist version. * * @return the playlist version */ int getVersion(); /** * Returns the list of songs in the playlist. This does query the MPD server for the list so care * should be taken not to call it excessively. * * @return the song list */ List<MPDPlaylistSong> getSongList(); /** * Returns the string representation of this playlist. * * @return the string representation */ @Override String toString(); void swap(MPDPlaylistSong song, int i); }
7,839
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDServerStatistics.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/statistics/MPDServerStatistics.java
package org.bff.javampd.statistics; import com.google.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.server.ServerProperties; /** * @author bill */ @Slf4j public class MPDServerStatistics implements ServerStatistics { private final ServerProperties serverProperties; private final CommandExecutor commandExecutor; private final StatsConverter converter; @Inject public MPDServerStatistics( ServerProperties serverProperties, CommandExecutor commandExecutor, StatsConverter converter) { this.serverProperties = serverProperties; this.commandExecutor = commandExecutor; this.converter = converter; } @Override public MPDStatistics getStatistics() { return converter.convertResponseToStats( commandExecutor.sendCommand(serverProperties.getStats())); } }
891
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ServerStatistics.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/statistics/ServerStatistics.java
package org.bff.javampd.statistics; /** * @author bill */ public interface ServerStatistics { MPDStatistics getStatistics(); }
132
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
StatsConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/statistics/StatsConverter.java
package org.bff.javampd.statistics; import java.util.List; @FunctionalInterface public interface StatsConverter { MPDStatistics convertResponseToStats(List<String> list); }
177
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDStatsConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/statistics/MPDStatsConverter.java
package org.bff.javampd.statistics; import static org.bff.javampd.command.CommandExecutor.COMMAND_TERMINATION; import static org.bff.javampd.statistics.Statistic.*; import java.util.EnumMap; import java.util.List; import lombok.extern.slf4j.Slf4j; @Slf4j public class MPDStatsConverter implements StatsConverter { @Override public MPDStatistics convertResponseToStats(List<String> list) { var iterator = list.iterator(); var props = new EnumMap<Statistic, String>(Statistic.class); String line; while (iterator.hasNext()) { line = iterator.next(); if (!isStreamTerminated(line)) { props.put(lookup(line), line.split(":")[1]); } } return MPDStatistics.builder() .artists(Integer.parseInt(checkProp((props.get(ARTISTS))))) .albums(Integer.parseInt(checkProp(props.get(ALBUMS)))) .tracks(Integer.parseInt(checkProp(props.get(SONGS)))) .databasePlaytime(Long.parseLong(checkProp(props.get(DBPLAYTIME)))) .lastUpdateTime(Long.parseLong(checkProp(props.get(DBUPDATE)))) .playtime(Long.parseLong(checkProp(props.get(PLAYTIME)))) .uptime(Long.parseLong(checkProp(props.get(UPTIME)))) .build(); } private String checkProp(String s) { return s == null ? "0" : s.trim(); } private boolean isStreamTerminated(String line) { return line == null || COMMAND_TERMINATION.equalsIgnoreCase(line); } }
1,428
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
Statistic.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/statistics/Statistic.java
package org.bff.javampd.statistics; import java.util.HashMap; import java.util.Map; import lombok.Getter; @Getter public enum Statistic { ALBUMS("albums:"), ARTISTS("artists:"), SONGS("songs:"), DBPLAYTIME("db_playtime:"), DBUPDATE("db_update:"), PLAYTIME("playtime:"), UPTIME("uptime:"); private static final Map<String, Statistic> lookup = new HashMap<>(); static { for (Statistic s : Statistic.values()) { lookup.put(s.getPrefix().toLowerCase(), s); } } /** * -- GETTER -- Returns the <CODE>String</CODE> prefix of the response. * * @return the prefix of the response */ private final String prefix; /** * Default constructor for Statistics * * @param prefix the prefix of the line in the response */ Statistic(String prefix) { this.prefix = prefix; } public static Statistic lookup(String line) { return lookup.get(line.substring(0, line.indexOf(":") + 1)); } }
953
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDStatistics.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/statistics/MPDStatistics.java
package org.bff.javampd.statistics; import lombok.Builder; import lombok.Data; @Data @Builder public class MPDStatistics { private long playtime; private long uptime; private int artists; private int albums; private int tracks; private long lastUpdateTime; private long databasePlaytime; }
306
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAdmin.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/admin/MPDAdmin.java
package org.bff.javampd.admin; import static org.bff.javampd.output.OutputChangeEvent.OUTPUT_EVENT; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.output.MPDOutput; import org.bff.javampd.output.OutputChangeEvent; import org.bff.javampd.output.OutputChangeListener; /** * MPDAdmin represents an administrative controller to a MPD server. To obtain an instance of the * class you must use the <code>getMPDAdmin</code> method from the {@link * org.bff.javampd.server.MPD} connection class. This class does not have a public constructor * (singleton model) so the object must be obtained from the connection object. * * @author Bill */ @Slf4j public class MPDAdmin implements Admin { private final List<MPDChangeListener> listeners = new ArrayList<>(); private final List<OutputChangeListener> outputListeners = new ArrayList<>(); protected static final String OUTPUT_PREFIX_ID = "outputid:"; protected static final String OUTPUT_PREFIX_NAME = "outputname:"; protected static final String OUTPUT_PREFIX_ENABLED = "outputenabled:"; protected static final String UPDATE_PREFIX = "updating_db:"; private final AdminProperties adminProperties; private final CommandExecutor commandExecutor; @Inject public MPDAdmin(AdminProperties adminProperties, CommandExecutor commandExecutor) { this.adminProperties = adminProperties; this.commandExecutor = commandExecutor; } @Override public Collection<MPDOutput> getOutputs() { return new ArrayList<>(parseOutputs(commandExecutor.sendCommand(adminProperties.getOutputs()))); } @Override public boolean disableOutput(MPDOutput output) { fireOutputChangeEvent(OUTPUT_EVENT.OUTPUT_CHANGED); return commandExecutor .sendCommand(adminProperties.getOutputDisable(), output.getId()) .isEmpty(); } @Override public boolean enableOutput(MPDOutput output) { fireOutputChangeEvent(OUTPUT_EVENT.OUTPUT_CHANGED); return commandExecutor.sendCommand(adminProperties.getOutputEnable(), output.getId()).isEmpty(); } @Override public synchronized void addMPDChangeListener(MPDChangeListener mcl) { listeners.add(mcl); } @Override public synchronized void removeMPDChangeListener(MPDChangeListener mcl) { listeners.remove(mcl); } /** * Sends the appropriate {@link MPDChangeEvent} to all registered {@link MPDChangeListener}s. * * @param event the {@link MPDChangeEvent.Event} to send */ protected synchronized void fireMPDChangeEvent(MPDChangeEvent.Event event) { var mce = new MPDChangeEvent(this, event); for (MPDChangeListener mcl : listeners) { mcl.mpdChanged(mce); } } @Override public void killMPD() { commandExecutor.sendCommand(adminProperties.getKill()); fireMPDChangeEvent(MPDChangeEvent.Event.KILLED); } @Override public int updateDatabase() { var response = commandExecutor.sendCommand(adminProperties.getRefresh()); fireMPDChangeEvent(MPDChangeEvent.Event.REFRESHED); return parseUpdate(response); } @Override public int updateDatabase(String path) { var response = commandExecutor.sendCommand(adminProperties.getRefresh(), path); fireMPDChangeEvent(MPDChangeEvent.Event.REFRESHED); return parseUpdate(response); } @Override public int rescan() { var response = commandExecutor.sendCommand(adminProperties.getRescan()); fireMPDChangeEvent(MPDChangeEvent.Event.REFRESHED); return parseUpdate(response); } @Override public synchronized void addOutputChangeListener(OutputChangeListener pcl) { outputListeners.add(pcl); } @Override public synchronized void removeOutputChangeListener(OutputChangeListener pcl) { outputListeners.remove(pcl); } /** * Sends the appropriate {@link org.bff.javampd.playlist.PlaylistChangeEvent} to all registered * {@link org.bff.javampd.playlist.PlaylistChangeListener}. * * @param event the event id to send */ protected synchronized void fireOutputChangeEvent(OUTPUT_EVENT event) { var oce = new OutputChangeEvent(this, event); for (OutputChangeListener pcl : outputListeners) { pcl.outputChanged(oce); } } private int parseUpdate(List<String> response) { var iterator = response.iterator(); String line = null; while (iterator.hasNext()) { if (line == null || (!line.startsWith(UPDATE_PREFIX))) { line = iterator.next(); } if (line.startsWith(UPDATE_PREFIX)) { try { return Integer.parseInt(line.replace(UPDATE_PREFIX, "").trim()); } catch (NumberFormatException e) { log.error("Unable to parse jod id from update", e); } } } log.warn("No update jod id returned"); return -1; } private static Collection<MPDOutput> parseOutputs(List<String> response) { List<MPDOutput> outputs = new ArrayList<>(); var iterator = response.iterator(); String line = null; while (iterator.hasNext()) { if (line == null || (!line.startsWith(OUTPUT_PREFIX_ID))) { line = iterator.next(); } if (line.startsWith(OUTPUT_PREFIX_ID)) { line = parseOutput(line, iterator, outputs); } } return outputs; } private static String parseOutput( String startingLine, Iterator<String> iterator, List<MPDOutput> outputs) { var output = MPDOutput.builder( Integer.parseInt(startingLine.substring(OUTPUT_PREFIX_ID.length()).trim())) .build(); String line = iterator.next(); while (!line.startsWith(OUTPUT_PREFIX_ID)) { if (line.startsWith(OUTPUT_PREFIX_NAME)) { output.setName(line.replace(OUTPUT_PREFIX_NAME, "").trim()); } else if (line.startsWith(OUTPUT_PREFIX_ENABLED)) { output.setEnabled("1".equals(line.replace(OUTPUT_PREFIX_ENABLED, "").trim())); } if (!iterator.hasNext()) { break; } line = iterator.next(); } outputs.add(output); return line; } }
6,193
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
Admin.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/admin/Admin.java
package org.bff.javampd.admin; import java.util.Collection; import org.bff.javampd.output.MPDOutput; import org.bff.javampd.output.OutputChangeListener; /** * Performs {@link org.bff.javampd.server.MPD} administrative tasks * * @author bill */ public interface Admin { /** * Returns the information about all outputs * * @return a <code>Collection</code> of {@link org.bff.javampd.output.MPDOutput} */ Collection<MPDOutput> getOutputs(); /** * Disables the passed {@link MPDOutput} * * @param output the output to disable * @return true if the output is disabled */ boolean disableOutput(MPDOutput output); /** * Enables the passed {@link MPDOutput} * * @param output the output to enable * @return true if the output is enabled */ boolean enableOutput(MPDOutput output); /** * Adds a {@link MPDChangeListener} to this object to receive {@link MPDChangeEvent}s. * * @param mcl the MPDChangeListener to add */ void addMPDChangeListener(MPDChangeListener mcl); /** * Removes a {@link MPDChangeListener} from this object. * * @param mcl the MPDChangeListener to remove */ void removeMPDChangeListener(MPDChangeListener mcl); /** Kills the mpd connection. */ void killMPD(); /** * Updates the music database: finds new files, removes deleted files, updates modified files. * * @return a positive number identifying the update job. You can read the current job id in the * * {@link org.bff.javampd.server.Status} response. */ int updateDatabase(); /** * Updates the music database: finds new files, removes deleted files, updates modified files. * * @param path a particular directory or song/file to update * @return a positive number identifying the update job. You can read the current job id in the * {@link org.bff.javampd.server.Status} response. */ int updateDatabase(String path); /** * Same as {@link #updateDatabase()}, but also rescans unmodified files. * * @return a positive number identifying the update job. You can read the current job id in the * {@link org.bff.javampd.server.Status} response. */ int rescan(); /** * Adds a {@link OutputChangeListener} to this object to receive {@link * org.bff.javampd.playlist.PlaylistChangeEvent}s. * * @param pcl the PlaylistChangeListener to add */ void addOutputChangeListener(OutputChangeListener pcl); /** * Removes a {@link OutputChangeListener} from this object. * * @param pcl the PlaylistChangeListener to remove */ void removeOutputChangeListener(OutputChangeListener pcl); }
2,649
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/admin/MPDChangeEvent.java
package org.bff.javampd.admin; import lombok.Getter; /** * An event used to identify an administrative action. * * @author Bill * @version 1.0 */ @Getter public class MPDChangeEvent extends java.util.EventObject { /** * -- GETTER -- Returns the specific that occurred. * * @return the specific {@link Event} */ private final Event event; public enum Event { KILLED, REFRESHED } /** * Creates a new instance of MusicPlayerStatusChangedEvent * * @param source the object on which the Event initially occurred * @param event the specific {@link Event} that occurred */ public MPDChangeEvent(Object source, Event event) { super(source); this.event = event; } }
723
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/admin/MPDChangeListener.java
package org.bff.javampd.admin; /** * The listener interface for receiving MPD administrative change events. The class that is * interested in processing a change event implements this interface, and the object created with * that class is registered with a component using the component's <CODE>addMPDChangeListener</CODE> * method. When the change event occurs, that object's connectionChangeEventReceived method is * invoked. * * @author Bill */ @FunctionalInterface public interface MPDChangeListener { /** * Invoked when a mpd administrative change event occurs. * * @param event the {@link MPDChangeEvent} received */ void mpdChanged(MPDChangeEvent event); }
689
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AdminProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/admin/AdminProperties.java
package org.bff.javampd.admin; import lombok.Getter; import org.bff.javampd.server.MPDProperties; public class AdminProperties extends MPDProperties { @Getter private enum Command { KILL("admin.kill"), REFRESH("admin.update"), RESCAN("admin.rescan"), OUTPUTS("admin.outputs"), OUTPUT_ENABLE("admin.enable.out"), OUTPUT_DISABLE("admin.disable.out"); private final String key; Command(String key) { this.key = key; } } public String getKill() { return getPropertyString(Command.KILL.getKey()); } public String getRefresh() { return getPropertyString(Command.REFRESH.getKey()); } public String getRescan() { return getPropertyString(Command.RESCAN.getKey()); } public String getOutputs() { return getPropertyString(Command.OUTPUTS.getKey()); } public String getOutputEnable() { return getPropertyString(Command.OUTPUT_ENABLE.getKey()); } public String getOutputDisable() { return getPropertyString(Command.OUTPUT_DISABLE.getKey()); } }
1,040
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TimeTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/TimeTagProcessor.java
package org.bff.javampd.processor; public class TimeTagProcessor extends TagResponseProcessor implements ResponseProcessor { public TimeTagProcessor() { super("Time:"); } @Override public TagType getType() { return TagType.TIME; } }
254
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
NameTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/NameTagProcessor.java
package org.bff.javampd.processor; public class NameTagProcessor extends TagResponseProcessor implements ResponseProcessor { public NameTagProcessor() { super("Name:"); } @Override public TagType getType() { return TagType.NAME; } }
254
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AlbumArtistTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/AlbumArtistTagProcessor.java
package org.bff.javampd.processor; public class AlbumArtistTagProcessor extends TagResponseProcessor implements ResponseProcessor { public AlbumArtistTagProcessor() { super("AlbumArtist:"); } @Override public TagType getType() { return TagType.ALBUM_ARTIST; } }
283
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
IdTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/IdTagProcessor.java
package org.bff.javampd.processor; import lombok.extern.slf4j.Slf4j; @Slf4j public class IdTagProcessor extends TagResponseProcessor implements ResponseProcessor { public IdTagProcessor() { super("Id:"); } @Override public TagType getType() { return TagType.ID; } }
288
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ResponseProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/ResponseProcessor.java
package org.bff.javampd.processor; public interface ResponseProcessor { enum TagType { ALBUM_ARTIST, ALBUM, ARTIST, COMMENT, DATE, DISC, FILE, ID, NAME, POSITION, TIME, TITLE, TRACK, GENRE } /** * Returns the {@link TagType} of the processor * * @return the {@link TagType} */ TagType getType(); /** * Returns the line prefix that delimits songs in the response list * * @return the prefix that breaks songs in the list */ String getPrefix(); /** * Process the response line and set the appropriate @{link MPDSong} property * * @param line the line to process */ String processTag(String line); }
709
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TrackTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/TrackTagProcessor.java
package org.bff.javampd.processor; public class TrackTagProcessor extends TagResponseProcessor implements ResponseProcessor { public TrackTagProcessor() { super("Track:"); } @Override public TagType getType() { return TagType.TRACK; } }
258
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PositionTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/PositionTagProcessor.java
package org.bff.javampd.processor; public class PositionTagProcessor extends TagResponseProcessor implements ResponseProcessor { public PositionTagProcessor() { super("Pos:"); } @Override public TagType getType() { return TagType.POSITION; } }
265
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ArtistTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/ArtistTagProcessor.java
package org.bff.javampd.processor; public class ArtistTagProcessor extends TagResponseProcessor implements ResponseProcessor { public ArtistTagProcessor() { super("Artist:"); } @Override public TagType getType() { return TagType.ARTIST; } }
262
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
FileTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/FileTagProcessor.java
package org.bff.javampd.processor; public class FileTagProcessor extends TagResponseProcessor implements ResponseProcessor { public FileTagProcessor() { super("file:"); } @Override public TagType getType() { return TagType.FILE; } }
254
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TagResponseProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/TagResponseProcessor.java
package org.bff.javampd.processor; import lombok.Getter; @Getter public abstract class TagResponseProcessor implements ResponseProcessor { private final String prefix; protected TagResponseProcessor(String prefix) { this.prefix = prefix; } protected boolean startsWith(String line) { return line.startsWith(getPrefix()); } @Override public String processTag(String line) { if (startsWith(line)) { return line.substring(getPrefix().length()).trim(); } return null; } }
517
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
DateTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/DateTagProcessor.java
package org.bff.javampd.processor; public class DateTagProcessor extends TagResponseProcessor implements ResponseProcessor { public DateTagProcessor() { super("Date:"); } @Override public TagType getType() { return TagType.DATE; } }
254
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AlbumTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/AlbumTagProcessor.java
package org.bff.javampd.processor; public class AlbumTagProcessor extends TagResponseProcessor implements ResponseProcessor { public AlbumTagProcessor() { super("Album:"); } @Override public TagType getType() { return TagType.ALBUM; } }
258
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TitleTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/TitleTagProcessor.java
package org.bff.javampd.processor; public class TitleTagProcessor extends TagResponseProcessor implements ResponseProcessor { public TitleTagProcessor() { super("Title:"); } @Override public TagType getType() { return TagType.TITLE; } }
258
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
DiscTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/DiscTagProcessor.java
package org.bff.javampd.processor; public class DiscTagProcessor extends TagResponseProcessor implements ResponseProcessor { public DiscTagProcessor() { super("Disc:"); } @Override public TagType getType() { return TagType.DISC; } }
254
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
CommentTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/CommentTagProcessor.java
package org.bff.javampd.processor; public class CommentTagProcessor extends TagResponseProcessor implements ResponseProcessor { public CommentTagProcessor() { super("Comment:"); } @Override public TagType getType() { return TagType.COMMENT; } }
266
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
GenreTagProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/processor/GenreTagProcessor.java
package org.bff.javampd.processor; public class GenreTagProcessor extends TagResponseProcessor implements ResponseProcessor { public GenreTagProcessor() { super("Genre:"); } @Override public TagType getType() { return TagType.GENRE; } }
258
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSocket.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/MPDSocket.java
package org.bff.javampd.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.List; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.bff.javampd.MPDException; import org.bff.javampd.command.MPDCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author bill */ @Slf4j public class MPDSocket { private static final Logger LOGGER = LoggerFactory.getLogger(MPDSocket.class); private Socket socket; private BufferedReader reader; private final ResponseProperties responseProperties; private final ServerProperties serverProperties; private final String encoding; private String lastError; @Getter private String version; private final String server; private final int port; private boolean closed; private static final int TRIES = 3; public MPDSocket(InetAddress server, int port, int timeout) { this.server = server.getHostAddress(); this.port = port; this.responseProperties = new ResponseProperties(); this.serverProperties = new ServerProperties(); this.encoding = serverProperties.getEncoding(); connect(timeout); } /** * If MPD is already connected no attempt will be made to connect and the mpdVersion is returned. * * <p>A timeout of 0 means an infinite wait. * * @param timeout socket timeout, 0 for infinite wait * @throws MPDConnectionException if there is a socked io problem */ private synchronized void connect(int timeout) { connectSocket(timeout); } private void readVersion() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new MPDConnectionException(e); } if (isResponseOK(line)) { this.version = stripResponse(responseProperties.getOk(), line).trim(); } else { throw new MPDConnectionException( "Command from server: " + ((line == null) ? "null" : stripResponse(responseProperties.getError(), line))); } } private void connectSocket(int timeout) { log.debug("attempting to connect socket to {} with timeout of {}", server, timeout); this.socket = createSocket(); SocketAddress socketAddress = new InetSocketAddress(server, port); try { this.socket.connect(socketAddress, timeout); setReader(new BufferedReader(new InputStreamReader(socket.getInputStream(), encoding))); readVersion(); } catch (Exception ioe) { log.error("failed to connect socket to {}", server); throw new MPDConnectionException(ioe); } } protected void setReader(BufferedReader reader) { this.reader = reader; } protected Socket createSocket() { return new Socket(); } public synchronized Collection<String> sendCommand(MPDCommand command) { checkConnection(); var count = 0; while (count < TRIES) { try { return sendBytes(convertCommand(command.getCommand(), command.getParams())); } catch (MPDException mpdException) { logCommandError(command, mpdException); throw mpdException; } catch (Exception ex) { logCommandError(command, ex); try { connect(); } catch (Exception exc) { log.error("Unable to connect to {} on port {}", server, port, exc); } ++count; log.warn("Retrying command {} for the {} time", command.getCommand(), count); } } log.error("Unable to send command {} after {} tries", command, TRIES); throw new MPDConnectionException("Unable to send command " + command); } private static void logCommandError(MPDCommand command, Exception se) { log.error("Error from: {}", command.getCommand(), se); for (String str : command.getParams()) { log.error("\tparam: {}", str); } } /** * Attempts to connect to MPD with an infinite timeout value. If MPD is already connected no * attempt will be made to connect and the mpdVersion is returned. */ private synchronized void connect() { connect(0); } private boolean isResponseOK(final String line) { if (line == null) { log.info("Response check failed. Line is null"); return false; } return line.startsWith(responseProperties.getOk()) || line.startsWith(responseProperties.getListOk()); } private boolean isResponseError(final String line) { if (line.startsWith(responseProperties.getError())) { log.warn("line contained an error: {}", line); this.lastError = line.substring(responseProperties.getError().length()).trim(); return true; } else { return false; } } private static String stripResponse(String response, String line) { return line.substring(response.length()); } private static String convertCommand(String command) { return convertCommand(command, new ArrayList<>()); } private static String convertCommand(String command, List<String> params) { var sb = new StringBuilder(command); for (String param : params) { param = param.replace("\"", "\\\\\""); sb.append(" \"").append(param).append("\""); } return sb.append("\n").toString(); } public synchronized void sendCommands(List<MPDCommand> commandList) { var sb = new StringBuilder(convertCommand(serverProperties.getStartBulk())); for (MPDCommand command : commandList) { sb.append(convertCommand(command.getCommand(), command.getParams())); } sb.append(convertCommand(serverProperties.getEndBulk())); checkConnection(); try { sendBytes(sb.toString()); String line = reader.readLine(); while (line != null) { if (!isResponseOK(line)) { log.warn("some command from a command list failed: {}", line); } if (reader.ready()) { line = reader.readLine(); log.warn("unexpected response line {}", line); } else { line = null; } } } catch (MPDSecurityException se) { throw se; } catch (Exception e) { commandList.forEach(s -> log.error(s.getCommand())); throw new MPDConnectionException(e.getMessage(), e); } } private List<String> sendBytes(String command) throws IOException { log.debug("start command: {}", command); var response = new ArrayList<String>(); writeToStream(command); var inLine = reader.readLine(); log.debug("first response line is: {}", inLine); while (inLine != null) { if (isResponseOK(inLine)) { log.debug("the response was ok"); break; } if (isResponseError(inLine)) { if (lastError.contains("you don't have permission")) { throw new MPDSecurityException(lastError, command); } else { log.error("Got error from command {}", command); throw new MPDConnectionException(lastError); } } response.add(inLine); inLine = reader.readLine(); } response.forEach(LOGGER::debug); return response; } private void checkConnection() { boolean connected; if (this.closed) { throw new MPDConnectionException("Close has been called on MPD. Create a new MPD."); } if (!socket.isConnected()) { log.warn("socket hasn't been connected yet"); connected = false; } else { if (!socket.isClosed()) { connected = checkPing(); } else { log.warn("socket is closed"); connected = false; } } if (!connected) { log.info("we've lost connectivity, attempting to connect"); try { connect(); } catch (Exception e) { throw new MPDConnectionException("Connection to server lost: " + e.getMessage(), e); } } } public void close() { this.closed = true; if (!this.socket.isClosed()) { try { this.reader.close(); } catch (IOException e) { throw new MPDConnectionException("Unable to close socket", e); } try { this.socket.close(); } catch (IOException e) { throw new MPDConnectionException("Unable to close socket", e); } } } private void writeToStream(String command) throws IOException { socket.getOutputStream().write(command.getBytes(serverProperties.getEncoding())); } private boolean checkPing() { var connected = true; try { writeToStream(convertCommand(serverProperties.getPing())); String inLine = reader.readLine(); if (!isResponseOK(inLine)) { connected = false; } } catch (Exception e) { connected = false; log.error("lost socket connection", e); } return connected; } }
8,874
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ResponseProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/ResponseProperties.java
package org.bff.javampd.server; import lombok.Getter; /** * Properties for {@link org.bff.javampd.server.MPD} responses * * @author bill */ public class ResponseProperties extends MPDProperties { @Getter private enum Command { OK("cmd.response.ok"), LIST_OK("cmd.response.list.ok"), ERR("cmd.response.err"); private final String key; Command(String key) { this.key = key; } } public String getOk() { return getPropertyString(Command.OK.getKey()); } public String getListOk() { return getPropertyString(Command.LIST_OK.getKey()); } public String getError() { return getPropertyString(Command.ERR.getKey()); } }
682
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDServerStatus.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/MPDServerStatus.java
package org.bff.javampd.server; import static java.lang.Integer.parseInt; import com.google.inject.Inject; import java.time.LocalDateTime; import java.util.Collection; import java.util.List; import java.util.Optional; import lombok.Getter; import org.bff.javampd.Clock; import org.bff.javampd.command.CommandExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MPDServerStatus implements ServerStatus { private static final Logger LOGGER = LoggerFactory.getLogger(MPDServerStatus.class); private long expiryInterval = 5; private List<String> cachedResponse; private final Clock clock; private LocalDateTime responseDate; private final ServerProperties serverProperties; private final CommandExecutor commandExecutor; @Getter private enum TimeType { ELAPSED(0), TOTAL(1); private final int index; TimeType(int index) { this.index = index; } } @Inject public MPDServerStatus( ServerProperties serverProperties, CommandExecutor commandExecutor, Clock clock) { this.serverProperties = serverProperties; this.commandExecutor = commandExecutor; this.clock = clock; responseDate = clock.min(); } /** * Returns the current status of the requested status element. See {@link Status} for a list of * possible items returned by getStatus. If the status isn't part of the response "" is returned. * * @param status the status desired * @return the desired status information */ protected String getStatus(Status status) { LocalDateTime now = clock.now(); if (now.minusSeconds(expiryInterval).isAfter(responseDate)) { responseDate = now; cachedResponse = commandExecutor.sendCommand(serverProperties.getStatus()); } for (String line : cachedResponse) { if (line.toLowerCase().startsWith(status.getStatusPrefix())) { return line.substring(status.getStatusPrefix().length()).trim(); } } LOGGER.warn("Response did not contain status {}", status.getStatusPrefix()); return ""; } @Override public Collection<String> getStatus() { return commandExecutor.sendCommand(serverProperties.getStatus()); } @Override public int getPlaylistVersion() { String version = getStatus(Status.PLAYLIST); try { return parseInt("".equals(version) ? "0" : version); } catch (NumberFormatException nfe) { LOGGER.error("Could not format playlist version response {}", version, nfe); return 0; } } @Override public String getState() { return getStatus(Status.STATE); } @Override public int getXFade() { String xFade = getStatus(Status.XFADE); try { return parseInt("".equals(xFade) ? "0" : xFade); } catch (NumberFormatException nfe) { LOGGER.error("Could not format xfade response {}", xFade, nfe); return 0; } } @Override public String getAudio() { return getStatus(Status.AUDIO); } @Override public boolean isError() { return !"".equals(getStatus(Status.ERROR)); } @Override public String getError() { return getStatus(Status.ERROR); } @Override public long getElapsedTime() { return lookupTime(TimeType.ELAPSED); } @Override public long getTotalTime() { return lookupTime(TimeType.TOTAL); } @Override public int getBitrate() { String bitrate = getStatus(Status.BITRATE); try { return parseInt("".equals(bitrate) ? "0" : bitrate); } catch (NumberFormatException nfe) { LOGGER.error("Could not format bitrate response {}", bitrate, nfe); return 0; } } @Override public int getVolume() { String volume = getStatus(Status.VOLUME); try { return parseInt("".equals(volume) ? "0" : volume); } catch (NumberFormatException nfe) { LOGGER.error("Could not format volume response {}", volume, nfe); return 0; } } @Override public boolean isRepeat() { return "1".equals(getStatus(Status.REPEAT)); } @Override public boolean isRandom() { return "1".equals(getStatus(Status.RANDOM)); } @Override public boolean isDatabaseUpdating() { return !"".equals(getStatus(Status.UPDATINGDB)); } @Override public boolean isConsume() { return "1".equals(getStatus(Status.CONSUME)); } @Override public boolean isSingle() { return "1".equals(getStatus(Status.SINGLE)); } @Override public Optional<Integer> playlistSongNumber() { var songNumber = getStatus(Status.CURRENTSONG); return "".equals(songNumber) ? Optional.empty() : Optional.of(parseInt(songNumber)); } @Override public Optional<String> playlistSongId() { var id = getStatus(Status.CURRENTSONGID); return "".equals(id) ? Optional.empty() : Optional.ofNullable(id); } @Override public Optional<Integer> playlistNextSongNumber() { var songNumber = getStatus(Status.NEXT_SONG); return "".equals(songNumber) ? Optional.empty() : Optional.of(parseInt(songNumber)); } @Override public Optional<String> playlistNextSongId() { var id = getStatus(Status.NEXT_SONG_ID); return "".equals(id) ? Optional.empty() : Optional.ofNullable(id); } @Override public Optional<Integer> durationCurrentSong() { var duration = getStatus(Status.DURATION); return "".equals(duration) ? Optional.empty() : Optional.of(parseInt(duration)); } @Override public Optional<Integer> elapsedCurrentSong() { var elapsed = getStatus(Status.ELAPSED); return "".equals(elapsed) ? Optional.empty() : Optional.of(parseInt(elapsed)); } @Override public Optional<Integer> getMixRampDb() { var db = getStatus(Status.MIX_RAMP_DB); return "".equals(db) ? Optional.empty() : Optional.of((int) Float.parseFloat(db)); } @Override public Optional<Integer> getMixRampDelay() { var delay = getStatus(Status.MIX_RAMP_DELAY); return "".equals(delay) ? Optional.empty() : Optional.of(parseInt(delay)); } @Override public void setExpiryInterval(long seconds) { expiryInterval = seconds; } @Override public void forceUpdate() { responseDate = clock.min(); } private long lookupTime(TimeType type) { String time = getStatus(Status.TIME); if ("".equals(time) || !time.contains(":")) { return 0; } else { try { return parseInt(time.trim().split(":")[type.getIndex()]); } catch (NumberFormatException nfe) { LOGGER.error("Could not format time {}", time, nfe); return 0; } } } }
6,526
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSecurityException.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/MPDSecurityException.java
package org.bff.javampd.server; import org.bff.javampd.MPDException; /** * Represents a security or permission issue when trying to execute commands * * @author bill */ public class MPDSecurityException extends MPDException { /** * Class constructor specifying the message. * * @param message the exception message */ public MPDSecurityException(String message) { super(message); } /** * Class constructor specifying the message and command generating the error. * * @param message the exception message * @param command the command generating the exception */ public MPDSecurityException(String message, String command) { super(message, command); } }
707
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ServerProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/ServerProperties.java
package org.bff.javampd.server; import lombok.Getter; /** * @author bill */ public class ServerProperties extends MPDProperties { @Getter private enum Command { SERVERENCODING("server.encoding"), CLEARERROR("cmd.clear.error"), CLOSE("cmd.close"), KILL("cmd.kill"), STATUS("cmd.status"), STATS("cmd.statistics"), STARTBULK("cmd.start.bulk"), ENDBULK("cmd.end.bulk"), PASSWORD("cmd.password"), PING("cmd.ping"); private final String key; Command(String key) { this.key = key; } } public String getClearError() { return getResponseCommand(Command.CLEARERROR); } public String getStatus() { return getResponseCommand(Command.STATUS); } public String getStats() { return getResponseCommand(Command.STATS); } public String getPing() { return getResponseCommand(Command.PING); } public String getPassword() { return getResponseCommand(Command.PASSWORD); } public String getClose() { return getResponseCommand(Command.CLOSE); } public String getStartBulk() { return getResponseCommand(Command.STARTBULK); } public String getEndBulk() { return getResponseCommand(Command.ENDBULK); } private String getResponseCommand(Command command) { return getPropertyString(command.getKey()); } public String getEncoding() { return getResponseCommand(Command.SERVERENCODING); } }
1,419
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ConnectionChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/ConnectionChangeListener.java
package org.bff.javampd.server; /** * The listener interface for receiving connection change events. The class that is interested in * processing a connection event implements this interface, and the object created with that class * is registered with a component using the component's <CODE>addConnectionChangeListener</CODE> * method. When the connection event occurs, that object's <CODE>connectionChangeEventReceived * </CODE> method is invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface ConnectionChangeListener { /** * Invoked when a connection change event occurs. * * @param event the event received */ void connectionChangeEventReceived(ConnectionChangeEvent event); }
735
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
Status.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/Status.java
package org.bff.javampd.server; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; /** Enumeration of the available information from the MPD server status. */ @Slf4j public enum Status { /** The current volume (0-100) */ VOLUME("volume:"), /** is the song repeating (0 or 1) */ REPEAT("repeat:"), /** is the song playing in random order (0 or 1) */ RANDOM("random:"), /** the playlist version number (31-bit unsigned integer) */ PLAYLIST("playlist:"), /** the length of the playlist */ PLAYLISTLENGTH("playlistlength:"), /** the current state (play, stop, or pause) */ STATE("state:"), /** playlist song number of the current song stopped on or playing */ CURRENTSONG("song:"), /** playlist song id of the current song stopped on or playing */ CURRENTSONGID("songid:"), /** playlist next song number of the next song to be played */ NEXT_SONG("nextsong:"), /** playlist song id of the next song to be played */ NEXT_SONG_ID("nextsongid:"), /** duration of the current song in seconds */ DURATION("duration:"), /** total time elapsed within the current song in seconds, but with higher resolution */ ELAPSED("elapsed:"), /** the time of the current playing/paused song */ TIME("time:"), /** instantaneous bitrate in kbps */ BITRATE("bitrate:"), /** crossfade in seconds */ XFADE("xfade:"), /** the cuurent samplerate, bits, and channels */ AUDIO("audio:"), /** job id */ UPDATINGDB("updating_db:"), /** if there is an error, returns message here */ ERROR("error:"), /** if 'consume' mode is enabled */ CONSUME("consume:"), /** if 'single' mode is enabled */ SINGLE("single:"), /** if 'single' mode is enabled */ MIX_RAMP_DB("mixrampdb:"), /** if 'single' mode is enabled */ MIX_RAMP_DELAY("mixrampdelay:"), /** if the status is unknown */ UNKNOWN("unknown"); /** the prefix associated with the status */ private final String prefix; private static final Map<String, Status> lookup = new HashMap<>(); static { for (Status s : Status.values()) { lookup.put(s.prefix, s); } } /** * Enum constructor * * @param prefix the prefix of the line in the response */ Status(String prefix) { this.prefix = prefix; } /** * Returns the <CODE>String</CODE> prefix of the response. * * @return the prefix of the response */ public String getStatusPrefix() { return prefix; } /** * Returns the {@link Status} the status line starts with. If no status is found {@link #UNKNOWN} * is returned * * @param line the line to process * @return the {@link Status} the lines starts with. <code>null</code> if there isn't a match */ public static Status lookup(String line) { var status = lookup.get(line.substring(0, line.indexOf(":") + 1)); if (status != null) { return status; } log.warn("Unknown status {} returned", line); return UNKNOWN; } }
2,970
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/MPDProperties.java
package org.bff.javampd.server; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.bff.javampd.MPDException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * I handle loading the properties from the properties file * * @author bill */ public abstract class MPDProperties implements PropertyLoader { private static final Logger LOGGER = LoggerFactory.getLogger(MPDProperties.class); private final Properties prop; private static final String PROP_FILE = "/mpd.properties"; private static final String PROP_OVERRIDE_FILE = "/javampd.properties"; protected MPDProperties() { prop = new Properties(); loadValues(PROP_FILE); loadOverrideValues(); } @Override public String getPropertyString(String property) { return prop.getProperty(property); } protected void loadValues(String propertiesResourceLocation) { try (InputStream is = MPDProperties.class.getResourceAsStream(propertiesResourceLocation)) { loadProperties(is); } catch (NullPointerException | IOException e) { throw new MPDException("Could not load mpd properties", e); } } protected void loadOverrideValues() { try (InputStream is = MPDProperties.class.getResourceAsStream(MPDProperties.PROP_OVERRIDE_FILE)) { loadProperties(is); } catch (NullPointerException | IOException e) { LOGGER.info("Override properties file not on classpath"); } } protected void loadProperties(InputStream inputStream) throws IOException { prop.load(inputStream); } }
1,581
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ConnectionChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/ConnectionChangeEvent.java
package org.bff.javampd.server; import java.util.EventObject; import lombok.Getter; /** * An event used to identify a change in connection status. * * @author Bill * @version 1.0 */ @Getter public class ConnectionChangeEvent extends EventObject { /** * -- GETTER -- Returns true if there is a connection with the MPD server. If there is no * connection returns false. * * @return true if connected; false otherwise */ private final boolean connected; /** * Creates a new instance of ConnectionChangeEvent * * @param source the object on which the Event initially occurred * @param isConnected the connection status */ public ConnectionChangeEvent(Object source, boolean isConnected) { super(source); this.connected = isConnected; } }
790
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
Server.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/Server.java
package org.bff.javampd.server; import org.bff.javampd.admin.Admin; import org.bff.javampd.art.ArtworkFinder; import org.bff.javampd.database.MusicDatabase; import org.bff.javampd.monitor.StandAloneMonitor; import org.bff.javampd.player.Player; import org.bff.javampd.playlist.Playlist; import org.bff.javampd.song.SongSearcher; import org.bff.javampd.statistics.ServerStatistics; /** * @author bill */ public interface Server { /** * Clears the current error message in the MPD status * * @throws MPDConnectionException if there is a problem sending the command to the server */ void clearError(); /** * Closes the connection to the MPD server. * * @throws MPDConnectionException if there is a problem sending the command to the server */ void close(); /** * Returns the MPD version running on the server. * * @return the version of the MPD */ String getVersion(); /** * Determines if there is a connection to the MPD server. * * @return true if connected to server , false if not */ boolean isConnected(); ArtworkFinder getArtworkFinder(); /** * Returns true if {@link #close()} has been called. Once closed a new {@link MPD} will need to be * created. Automatic reconnections will not be attempted after close is called. * * @return true if {@link #close()} has been called */ boolean isClosed(); Player getPlayer(); Playlist getPlaylist(); Admin getAdmin(); MusicDatabase getMusicDatabase(); SongSearcher getSongSearcher(); ServerStatistics getServerStatistics(); ServerStatus getServerStatus(); StandAloneMonitor getStandAloneMonitor(); }
1,662
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PropertyLoader.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/PropertyLoader.java
package org.bff.javampd.server; /** * Loads properties from the mpd.properties resource bundle * * @author bill */ @FunctionalInterface public interface PropertyLoader { /** * Returns the properties value * * @param property the property string key * @return the value from the properties file */ String getPropertyString(String property); }
366
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ServerStatus.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/ServerStatus.java
package org.bff.javampd.server; import java.util.Collection; import java.util.Optional; /** * ServerStatus represents the server's status at the time it is called. The status has a default * expiry interval of 5 seconds. This can be overridden by using {@link #setExpiryInterval(long)}. * You can also force an update from the server by calling {@link #forceUpdate()} * * @author bill */ public interface ServerStatus { /** * Returns the full status of the MPD server as a <CODE>Collection</CODE> of Strings. * * @return the desired status information */ Collection<String> getStatus(); /** * Returns the current playlist version * * @return the playlist version */ int getPlaylistVersion(); /** * Returns the current player state * * @return the current state */ String getState(); /** * Returns the cross fade value * * @return the crossfade value */ int getXFade(); /** * Returns the audio format (sampleRate:bits:channels) * * @return the audio format */ String getAudio(); /** * Returns the error description. If there is no error null is returned. You might want to first * check the error status with {@link #isError} * * @return the error string, null if none */ String getError(); /** * Returns the elapsed time of the currently playing song * * @return elapsed time of the song */ long getElapsedTime(); /** * Returns the total time of the currently playing song * * @return total time of the song */ long getTotalTime(); /** * Returns the current bitrate of the {@link org.bff.javampd.song.MPDSong} playing * * @return the current bitrate */ int getBitrate(); /** * Returns the current volume * * @return the current volume */ int getVolume(); /** * Returns true if the MPD status contains an error. {@link #getError} to get the error * description. * * @return true if there is an error */ boolean isError(); /** * Returns if the playlist is repeating * * @return playlist repeating */ boolean isRepeat(); /** * Returns if the playlist is randomized * * @return true if playlist is random */ boolean isRandom(); /** * Returns if the database is currently updating * * @return true if the db is updating */ boolean isDatabaseUpdating(); /** * Sets the length of time that the status is considered expired. Set to 0 to always call the * server * * @param seconds the number of seconds before the loaded status is considered expired */ void setExpiryInterval(long seconds); /** Forces a server update */ void forceUpdate(); /** * Returns if the player is in consuming mode. If true, each song played is removed from playlist. * * @return true if the player is in consuming mode. */ boolean isConsume(); /** * Returns if the player plays a single track. If true, activated, playback is stopped after * current song, or song is repeated if the 'repeat' mode is enabled. * * @return true if the player plays a single track; */ boolean isSingle(); /** * Returns the playlist song number of the current song stopped on or playing * * @return the playlist song number of the current song stopped on or playing */ Optional<Integer> playlistSongNumber(); /** * Returns the playlist song id of the current song stopped on or playing, null if not known * * @return the playlist song id of the current song stopped on or playing, null if not known */ Optional<String> playlistSongId(); /** * The playlist song number of the next song to be played * * @return the playlist song number of the next song to be played */ Optional<Integer> playlistNextSongNumber(); /** * The playlist song id of the next song to be played * * @return the playlist song id of the next song to be played */ Optional<String> playlistNextSongId(); /** * Duration of the current song in seconds * * @return duration of the current song in seconds */ Optional<Integer> durationCurrentSong(); /** * Total time elapsed within the current song in seconds, but with higher resolution * * @return total time elapsed within the current song in seconds, but with higher resolution */ Optional<Integer> elapsedCurrentSong(); /** * The threshold at which songs will be overlapped. Like crossfading but doesn’t fade the track * volume, just overlaps. * * @return the threshold at which songs will be overlapped. Like crossfading but doesn’t fade the * track volume, just overlaps. */ Optional<Integer> getMixRampDb(); /** * Additional time subtracted from the overlap calculated by mixrampdb. * * @return additional time subtracted from the overlap calculated by mixrampdb */ Optional<Integer> getMixRampDelay(); }
4,939
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ErrorEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/ErrorEvent.java
package org.bff.javampd.server; import lombok.Getter; /** * An event used to identify a MPD error. * * @author Bill * @version 1.0 */ @Getter public class ErrorEvent extends java.util.EventObject { /** * -- GETTER -- Returns the message attached to this event. If there is no message null is * returned. * * @return the optional message */ private String message; /** * Creates a new instance of ErrorEvent * * @param source the object on which the Event initially occurred */ public ErrorEvent(Object source) { super(source); } /** * Creates a new instance of ErrorEvent * * @param message an optional message * @param source the object on which the Event initially occurred */ public ErrorEvent(Object source, String message) { super(source); this.message = message; } }
852
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPD.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/MPD.java
package org.bff.javampd.server; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Singleton; import java.net.InetAddress; import java.util.Optional; import lombok.Builder; import lombok.Getter; import org.bff.javampd.MPDDatabaseModule; import org.bff.javampd.MPDModule; import org.bff.javampd.MPDMonitorModule; import org.bff.javampd.admin.Admin; import org.bff.javampd.art.ArtworkFinder; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.database.MusicDatabase; import org.bff.javampd.monitor.ConnectionMonitor; import org.bff.javampd.monitor.StandAloneMonitor; import org.bff.javampd.player.Player; import org.bff.javampd.playlist.Playlist; import org.bff.javampd.song.SongSearcher; import org.bff.javampd.statistics.ServerStatistics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MPD represents a connection to a MPD server. The commands are maintained in a properties file * called mpd.properties. * * <p>Uses the builder pattern for construction. * * <p>Defaults are: * * <p>server - localhost port - 6600 no timeout no password * * @author Bill */ @Getter @Singleton public class MPD extends MPDServer { private static final Logger LOGGER = LoggerFactory.getLogger(MPD.class); private int port = 6600; private String server = "localhost"; private final int timeout; private final String password; private final InetAddress address; @Builder public MPD(String server, Integer port, int timeout, String password) { this.server = Optional.ofNullable(server).orElse(this.server); this.port = Optional.ofNullable(port).orElse(this.port); this.timeout = timeout; this.password = password; try { this.address = InetAddress.getByName(this.server); init(); authenticate(); } catch (Exception e) { throw new MPDConnectionException(e); } } void init() { var injector = Guice.createInjector(new MPDModule(), new MPDDatabaseModule(), new MPDMonitorModule()); bind(injector); setMpd(this); authenticate(); injector.getInstance(ConnectionMonitor.class).setServer(this); } private void bind(Injector injector) { serverProperties = injector.getInstance(ServerProperties.class); player = injector.getInstance(Player.class); playlist = injector.getInstance(Playlist.class); admin = injector.getInstance(Admin.class); serverStatistics = injector.getInstance(ServerStatistics.class); serverStatus = injector.getInstance(ServerStatus.class); musicDatabase = injector.getInstance(MusicDatabase.class); songSearcher = injector.getInstance(SongSearcher.class); commandExecutor = injector.getInstance(CommandExecutor.class); artworkFinder = injector.getInstance(ArtworkFinder.class); standAloneMonitor = injector.getInstance(StandAloneMonitor.class); } void authenticate() { if (usingPassword()) { super.authenticate(this.password); } } private boolean usingPassword() { return this.password != null && !this.password.isEmpty(); } }
3,091
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDServer.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/MPDServer.java
package org.bff.javampd.server; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.bff.javampd.MPDException; import org.bff.javampd.admin.Admin; import org.bff.javampd.art.ArtworkFinder; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.database.MusicDatabase; import org.bff.javampd.monitor.StandAloneMonitor; import org.bff.javampd.player.Player; import org.bff.javampd.playlist.Playlist; import org.bff.javampd.song.SongSearcher; import org.bff.javampd.statistics.ServerStatistics; @Getter @NoArgsConstructor @Slf4j public abstract class MPDServer implements Server { protected ServerProperties serverProperties; protected CommandExecutor commandExecutor; protected Player player; protected Playlist playlist; protected Admin admin; protected ServerStatistics serverStatistics; protected ServerStatus serverStatus; protected StandAloneMonitor standAloneMonitor; protected MusicDatabase musicDatabase; protected SongSearcher songSearcher; protected ArtworkFinder artworkFinder; protected boolean closed; @Override public void clearError() { commandExecutor.sendCommand(serverProperties.getClearError()); } @Override public void close() { try { commandExecutor.sendCommand(serverProperties.getClose()); this.closed = true; } finally { commandExecutor.close(); } } @Override public String getVersion() { return commandExecutor.getMPDVersion(); } @Override public boolean isConnected() { return ping(); } private boolean ping() { try { commandExecutor.sendCommand(serverProperties.getPing()); } catch (MPDException e) { log.error("Could not ping MPD", e); return false; } return true; } public void authenticate(String password) { commandExecutor.usePassword(password); commandExecutor.authenticate(); } public void setMpd(MPD mpd) { this.commandExecutor.setMpd(mpd); } @Override public ArtworkFinder getArtworkFinder() { return this.artworkFinder; } @Override public boolean isClosed() { return this.closed; } @Override public Player getPlayer() { return this.player; } @Override public Playlist getPlaylist() { return this.playlist; } @Override public Admin getAdmin() { return this.admin; } @Override public MusicDatabase getMusicDatabase() { return this.musicDatabase; } @Override public SongSearcher getSongSearcher() { return this.songSearcher; } @Override public ServerStatistics getServerStatistics() { return this.serverStatistics; } @Override public ServerStatus getServerStatus() { return this.serverStatus; } @Override public StandAloneMonitor getStandAloneMonitor() { return this.standAloneMonitor; } }
2,852
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ErrorListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/ErrorListener.java
package org.bff.javampd.server; /** * The listener interface for receiving MPD error events. The class that is interested in processing * a error event implements this interface, and the object created with that class is registered * with a component using the component's <CODE>addErrorListener</CODE> method. When the error event * occurs, that object's <CODE> errorEventReceived</CODE> method is invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface ErrorListener { /** * Invoked when a MPD error occurs. * * @param event the event received */ void errorEventReceived(ErrorEvent event); }
646
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDConnectionException.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/server/MPDConnectionException.java
package org.bff.javampd.server; import org.bff.javampd.MPDException; /** * Represents an error with the MPD connection. * * @author Bill * @version 1.0 */ public class MPDConnectionException extends MPDException { /** Constructor. */ public MPDConnectionException() { super(); } /** * Class constructor specifying the message. * * @param message the exception message */ public MPDConnectionException(String message) { super(message); } /** * Class constructor specifying the cause. * * @param cause the cause of this exception */ public MPDConnectionException(Throwable cause) { super(cause); } /** * Class constructor specifying the message and cause. * * @param message the exception message * @param cause the cause of this exception */ public MPDConnectionException(String message, Throwable cause) { super(message, cause); } }
923
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDTagLister.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/database/MPDTagLister.java
package org.bff.javampd.database; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bff.javampd.command.CommandExecutor; /** * Implementation of {@link TagLister} for the MPD database * * @author Bill */ public class MPDTagLister implements TagLister { private final DatabaseProperties databaseProperties; private final CommandExecutor commandExecutor; @Inject public MPDTagLister(DatabaseProperties databaseProperties, CommandExecutor commandExecutor) { this.databaseProperties = databaseProperties; this.commandExecutor = commandExecutor; } @Override public List<String> listInfo(ListInfoType... types) { List<String> returnList = new ArrayList<>(); List<String> list = commandExecutor.sendCommand(databaseProperties.getListInfo()); for (String s : list) { for (ListInfoType type : types) { if (s.startsWith(type.getPrefix())) { returnList.add(s.substring(type.getPrefix().length()).trim()); } } } return returnList; } @Override public List<String> list(ListType listType) { return list(listType, new ArrayList<>()); } @Override public List<String> list(ListType listType, List<String> params, GroupType... groupTypes) { addGroupParams(params, groupTypes); return commandExecutor.sendCommand( databaseProperties.getList(), generateParamList(listType, params)); } @Override public List<String> list(ListType listType, GroupType... groupTypes) { List<String> params = new ArrayList<>(); addGroupParams(params, groupTypes); return commandExecutor.sendCommand( databaseProperties.getList(), generateParamList(listType, params)); } private void addGroupParams(List<String> params, GroupType... groupTypes) { if (groupTypes.length > 0) { Arrays.stream(groupTypes) .forEach( group -> { params.add(databaseProperties.getGroup()); params.add(group.getType()); }); } } private static String[] generateParamList(ListType listType, List<String> params) { String[] paramList; var i = 0; if (params != null) { paramList = new String[params.size() + 1]; } else { paramList = new String[1]; } paramList[i++] = listType.getType(); if (params != null) { for (String s : params) { paramList[i++] = s; } } return paramList; } }
2,502
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDMusicDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/database/MPDMusicDatabase.java
package org.bff.javampd.database; import com.google.inject.Inject; import com.google.inject.Singleton; import org.bff.javampd.album.AlbumDatabase; import org.bff.javampd.artist.ArtistDatabase; import org.bff.javampd.file.FileDatabase; import org.bff.javampd.genre.GenreDatabase; import org.bff.javampd.playlist.PlaylistDatabase; import org.bff.javampd.song.SongDatabase; import org.bff.javampd.year.DateDatabase; @Singleton public class MPDMusicDatabase implements MusicDatabase { private final ArtistDatabase artistDatabase; private final AlbumDatabase albumDatabase; private final GenreDatabase genreDatabase; private final PlaylistDatabase playlistDatabase; private final FileDatabase fileDatabase; private final DateDatabase dateDatabase; private final SongDatabase songDatabase; @Inject public MPDMusicDatabase( ArtistDatabase artistDatabase, AlbumDatabase albumDatabase, GenreDatabase genreDatabase, PlaylistDatabase playlistDatabase, FileDatabase fileDatabase, DateDatabase dateDatabase, SongDatabase songDatabase) { this.artistDatabase = artistDatabase; this.albumDatabase = albumDatabase; this.genreDatabase = genreDatabase; this.playlistDatabase = playlistDatabase; this.fileDatabase = fileDatabase; this.dateDatabase = dateDatabase; this.songDatabase = songDatabase; } @Override public ArtistDatabase getArtistDatabase() { return artistDatabase; } @Override public AlbumDatabase getAlbumDatabase() { return albumDatabase; } @Override public GenreDatabase getGenreDatabase() { return genreDatabase; } @Override public PlaylistDatabase getPlaylistDatabase() { return playlistDatabase; } @Override public FileDatabase getFileDatabase() { return fileDatabase; } @Override public DateDatabase getDateDatabase() { return dateDatabase; } @Override public SongDatabase getSongDatabase() { return songDatabase; } }
1,987
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MusicDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/database/MusicDatabase.java
package org.bff.javampd.database; import org.bff.javampd.album.AlbumDatabase; import org.bff.javampd.artist.ArtistDatabase; import org.bff.javampd.file.FileDatabase; import org.bff.javampd.genre.GenreDatabase; import org.bff.javampd.playlist.PlaylistDatabase; import org.bff.javampd.song.SongDatabase; import org.bff.javampd.year.DateDatabase; /** * Central location for getting MPD database access * * @author Bill */ public interface MusicDatabase { ArtistDatabase getArtistDatabase(); AlbumDatabase getAlbumDatabase(); GenreDatabase getGenreDatabase(); PlaylistDatabase getPlaylistDatabase(); FileDatabase getFileDatabase(); DateDatabase getDateDatabase(); SongDatabase getSongDatabase(); }
720
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
DatabaseProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/database/DatabaseProperties.java
package org.bff.javampd.database; import lombok.Getter; import org.bff.javampd.server.MPDProperties; /** * @author bill */ public class DatabaseProperties extends MPDProperties { @Getter private enum Command { FIND("db.find"), LIST("db.list.tag"), GROUP("db.group"), LIST_INFO("db.list.info"), SEARCH("db.search"), LIST_SONGS("db.list.songs"); private final String key; Command(String key) { this.key = key; } } public String getFind() { return getPropertyString(Command.FIND.getKey()); } public String getList() { return getPropertyString(Command.LIST.getKey()); } public String getGroup() { return getPropertyString(Command.GROUP.getKey()); } public String getListInfo() { return getPropertyString(Command.LIST_INFO.getKey()); } public String getSearch() { return getPropertyString(Command.SEARCH.getKey()); } public String getListSongs() { return getPropertyString(Command.LIST_SONGS.getKey()); } }
1,010
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TagLister.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/database/TagLister.java
package org.bff.javampd.database; import java.util.List; import lombok.Getter; /** * Performs list operations against the MPD database. * * @author Bill */ public interface TagLister { @Getter enum ListType { ALBUM("album"), ALBUM_ARTIST("albumartist"), ARTIST("artist"), GENRE("genre"), DATE("date"); private final String type; ListType(String type) { this.type = type; } } @Getter enum GroupType { ALBUM("album"), ALBUM_ARTIST("albumartist"), ARTIST("artist"), GENRE("genre"), DATE("date"); private final String type; GroupType(String type) { this.type = type; } } @Getter enum ListInfoType { PLAYLIST("playlist:"), DIRECTORY("directory:"), FILE("file:"), LAST_MODIFIED("Last-Modified:"); private final String prefix; ListInfoType(String prefix) { this.prefix = prefix; } } List<String> listInfo(ListInfoType... types); List<String> list(ListType listType); List<String> list(ListType listType, GroupType... groupTypes); List<String> list(ListType listType, List<String> params, GroupType... groupTypes); }
1,163
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
DateDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/year/DateDatabase.java
package org.bff.javampd.year; import java.util.Collection; /** * Database for year related items * * @author bill */ @FunctionalInterface public interface DateDatabase { /** * Returns a {@code Collection} of dates for songs in the database. The dates are sorted from * least to greatest. * * @return a {@link java.util.Collection} of years */ Collection<String> listAllDates(); }
406
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDDateDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/year/MPDDateDatabase.java
package org.bff.javampd.year; import com.google.inject.Inject; import java.util.Collection; import org.bff.javampd.database.TagLister; /** * MPDDateDatabase represents a date database controller to a {@link org.bff.javampd.server.MPD}. To * obtain an instance of the class you must use the {@link * org.bff.javampd.database.MusicDatabase#getDateDatabase} method from the {@link * org.bff.javampd.server.MPD} connection class. * * @author Bill */ public class MPDDateDatabase implements DateDatabase { private final TagLister tagLister; @Inject public MPDDateDatabase(TagLister tagLister) { this.tagLister = tagLister; } @Override public Collection<String> listAllDates() { return tagLister.list(TagLister.ListType.DATE).stream() .map(s -> s.substring(s.split(":")[0].length() + 1).trim()) .distinct() .sorted() .toList(); } }
893
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDArtist.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/artist/MPDArtist.java
package org.bff.javampd.artist; /** * String represents an artist. * * @author Bill */ public record MPDArtist(String name) {}
132
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ArtistDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/artist/ArtistDatabase.java
package org.bff.javampd.artist; import java.util.Collection; import org.bff.javampd.genre.MPDGenre; /** * Database for artist related items * * @author bill */ public interface ArtistDatabase { /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.artist.MPDArtist}s of all * artists. * * @return a {@link java.util.Collection} of {@link org.bff.javampd.artist.MPDArtist}s containing * the album names */ Collection<MPDArtist> listAllArtists(); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.artist.MPDArtist}s of all * album artists. * * @return a {@link java.util.Collection} of {@link org.bff.javampd.artist.MPDArtist}s containing * the album names */ Collection<MPDArtist> listAllAlbumArtists(); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.artist.MPDArtist}s of all * artists by a particular genre. * * @param genre the genre to find artists * @return a {@link java.util.Collection} of {@link org.bff.javampd.artist.MPDArtist}s of all * artists */ Collection<MPDArtist> listArtistsByGenre(MPDGenre genre); /** * Returns a {@link org.bff.javampd.artist.MPDArtist} with the passed name. * * @param name the name of the artist * @return a {@link org.bff.javampd.artist.MPDArtist} */ MPDArtist listArtistByName(String name); }
1,404
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDArtistDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/artist/MPDArtistDatabase.java
package org.bff.javampd.artist; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.bff.javampd.database.TagLister; import org.bff.javampd.genre.MPDGenre; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MPDArtistDatabase represents a artist database controller to a {@link * org.bff.javampd.server.MPD}. To obtain an instance of the class you must use the {@link * org.bff.javampd.database.MusicDatabase#getArtistDatabase} method from the {@link * org.bff.javampd.server.MPD} connection class. * * @author Bill */ public class MPDArtistDatabase implements ArtistDatabase { private static final Logger LOGGER = LoggerFactory.getLogger(MPDArtistDatabase.class); private final TagLister tagLister; @Inject public MPDArtistDatabase(TagLister tagLister) { this.tagLister = tagLister; } @Override public Collection<MPDArtist> listAllArtists() { return tagLister.list(TagLister.ListType.ARTIST).stream() .map(s -> new MPDArtist(convertResponse(s))) .toList(); } @Override public Collection<MPDArtist> listAllAlbumArtists() { return tagLister.list(TagLister.ListType.ALBUM_ARTIST).stream() .map(s -> new MPDArtist(convertResponse(s))) .toList(); } @Override public Collection<MPDArtist> listArtistsByGenre(MPDGenre genre) { List<String> list = new ArrayList<>(); list.add(TagLister.ListType.GENRE.getType()); list.add(genre.name()); return tagLister.list(TagLister.ListType.ARTIST, list).stream() .map(s -> new MPDArtist(convertResponse(s))) .toList(); } @Override public MPDArtist listArtistByName(String name) { List<String> list = new ArrayList<>(); list.add(TagLister.ListType.ARTIST.getType()); list.add(name); MPDArtist artist = null; List<MPDArtist> artists = tagLister.list(TagLister.ListType.ARTIST, list).stream() .map(s -> new MPDArtist(convertResponse(s))) .toList(); if (artists.size() > 1) { LOGGER.warn("Multiple artists returned for name {}", name); } if (!artists.isEmpty()) { artist = artists.getFirst(); } return artist; } private static String convertResponse(String s) { return s.substring(s.split(":")[0].length() + 1).trim(); } }
2,356
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAudioInfo.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/audioinfo/MPDAudioInfo.java
package org.bff.javampd.audioinfo; import lombok.Builder; import lombok.Data; /** Represents audio information about MPD */ @Builder @Data public class MPDAudioInfo { private int sampleRate; private int bits; private int channels; }
241
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlayerChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/PlayerChangeListener.java
package org.bff.javampd.player; /** * The listener interface for receiving player events. The class that is interested in processing a * player event implements this interface, and the object created with that class is registered with * a component using the component's <CODE>addPlayerChangeListener</CODE> method. When the player * event occurs, that object's <CODE>playerChanged</CODE> method is invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface PlayerChangeListener { /** * Invoked when a player change event occurs. * * @param event the {@link PlayerChangeEvent} fired */ void playerChanged(PlayerChangeEvent event); }
681
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlayer.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/MPDPlayer.java
package org.bff.javampd.player; import com.google.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.bff.javampd.audioinfo.MPDAudioInfo; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.playlist.MPDPlaylistSong; import org.bff.javampd.playlist.PlaylistSongConverter; import org.bff.javampd.server.ServerStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MPDPlayer represents a player controller to a MPD server. To obtain an instance of the class you * must use the <code>getMPDPlayer</code> method from the {@link org.bff.javampd.server.MPD} * connection class. This class does not have a public constructor (singleton model) so the object * must be obtained from the connection object. * * @author Bill */ public class MPDPlayer implements Player { private static final Logger LOGGER = LoggerFactory.getLogger(MPDPlayer.class); private int oldVolume; private final List<PlayerChangeListener> listeners = new ArrayList<>(); private final VolumeChangeDelegate volumeChangeDelegate; private Status status = Status.STATUS_STOPPED; private final ServerStatus serverStatus; private final PlayerProperties playerProperties; private final CommandExecutor commandExecutor; private final PlaylistSongConverter playlistSongConverter; @Inject public MPDPlayer( ServerStatus serverStatus, PlayerProperties playerProperties, CommandExecutor commandExecutor, PlaylistSongConverter playlistSongConverter) { this.serverStatus = serverStatus; this.playerProperties = playerProperties; this.commandExecutor = commandExecutor; this.playlistSongConverter = playlistSongConverter; this.volumeChangeDelegate = new VolumeChangeDelegate(); } @Override public Optional<MPDPlaylistSong> getCurrentSong() { List<MPDPlaylistSong> songList = playlistSongConverter.convertResponseToSongs( commandExecutor.sendCommand(playerProperties.getCurrentSong())); if (songList.isEmpty()) { return Optional.empty(); } else { return Optional.ofNullable(songList.getFirst()); } } @Override public synchronized void addPlayerChangeListener(PlayerChangeListener pcl) { listeners.add(pcl); } @Override public synchronized void removePlayerChangedListener(PlayerChangeListener pcl) { listeners.remove(pcl); } /** * Sends the appropriate {@link PlayerChangeEvent} to all registered {@link * PlayerChangeListener}s. * * @param event the {@link PlayerChangeEvent.Event} to send */ protected synchronized void firePlayerChangeEvent(PlayerChangeEvent.Event event) { var pce = new PlayerChangeEvent(this, event); for (PlayerChangeListener pcl : listeners) { pcl.playerChanged(pce); } } @Override public synchronized void addVolumeChangeListener(VolumeChangeListener vcl) { volumeChangeDelegate.addVolumeChangeListener(vcl); } @Override public synchronized void removeVolumeChangedListener(VolumeChangeListener vcl) { volumeChangeDelegate.removeVolumeChangedListener(vcl); } /** * Sends the appropriate {@link VolumeChangeEvent} to all registered {@link VolumeChangeListener}. * * @param volume the new volume */ protected synchronized void fireVolumeChangeEvent(int volume) { volumeChangeDelegate.fireVolumeChangeEvent(this, volume); } @Override public void play() { playSong(null); } @Override public void playSong(MPDPlaylistSong song) { if (song == null) { commandExecutor.sendCommand(playerProperties.getPlay()); } else { commandExecutor.sendCommand(playerProperties.getPlayId(), song.getId()); } if (status == Status.STATUS_STOPPED || status == Status.STATUS_PAUSED) { status = Status.STATUS_PLAYING; firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_STARTED); } else { firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_SONG_SET); } } @Override public void seek(long secs) { seekSong(null, secs); } @Override public void seekSong(MPDPlaylistSong song, long secs) { if (song == null) { getCurrentSong() .ifPresent( s -> { if (s.getLength() > secs) { seekMPDSong(s, secs); } }); } else { if (song.getLength() >= secs) { seekMPDSong(song, secs); } } } @Override public void stop() { commandExecutor.sendCommand(playerProperties.getStop()); status = Status.STATUS_STOPPED; firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_STOPPED); } @Override public void pause() { commandExecutor.sendCommand(playerProperties.getPause()); status = Status.STATUS_PAUSED; firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_PAUSED); } @Override public void playNext() { commandExecutor.sendCommand(playerProperties.getNext()); firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_NEXT); } @Override public void playPrevious() { commandExecutor.sendCommand(playerProperties.getPrevious()); firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_PREVIOUS); } @Override public void mute() { oldVolume = getVolume(); setVolume(0); firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_MUTED); } @Override public void unMute() { setVolume(oldVolume); firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_UNMUTED); } @Override public int getBitrate() { return serverStatus.getBitrate(); } @Override public int getVolume() { return serverStatus.getVolume(); } @Override public void setVolume(int volume) { if (volume < 0 || volume > 100) { LOGGER.warn("Not changing volume to {}", volume); } else { commandExecutor.sendCommand(playerProperties.getSetVolume(), volume); fireVolumeChangeEvent(volume); } } @Override public boolean isRepeat() { return serverStatus.isRepeat(); } @Override public void setRepeat(boolean shouldRepeat) { String repeat; if (shouldRepeat) { repeat = "1"; } else { repeat = "0"; } commandExecutor.sendCommand(playerProperties.getRepeat(), repeat); } @Override public boolean isRandom() { return serverStatus.isRandom(); } @Override public void setRandom(boolean shouldRandom) { String random; if (shouldRandom) { random = "1"; } else { random = "0"; } commandExecutor.sendCommand(playerProperties.getRandom(), random); } @Override public void randomizePlay() { setRandom(true); } @Override public void unRandomizePlay() { setRandom(false); } @Override public int getXFade() { return serverStatus.getXFade(); } @Override public void setXFade(int xFade) { commandExecutor.sendCommand(playerProperties.getXFade(), xFade); } @Override public long getElapsedTime() { return serverStatus.getElapsedTime(); } @Override public long getTotalTime() { return serverStatus.getTotalTime(); } @Override public void setConsume(boolean consume) { commandExecutor.sendCommand(playerProperties.getConsume(), consume ? "1" : "0"); } @Override public void setSingle(boolean single) { commandExecutor.sendCommand(playerProperties.getSingle(), single ? "1" : "0"); } @Override public Optional<Integer> getMixRampDb() { return this.serverStatus.getMixRampDb(); } @Override public void setMixRampDb(int db) { commandExecutor.sendCommand(playerProperties.getMixRampDb(), db); } @Override public Optional<Integer> getMixRampDelay() { return this.serverStatus.getMixRampDelay(); } @Override public void setMixRampDelay(int delay) { commandExecutor.sendCommand( playerProperties.getMixRampDelay(), delay < 0 ? "nan" : Integer.toString(delay)); } @Override public MPDAudioInfo getAudioDetails() { MPDAudioInfo info = null; String response = serverStatus.getAudio(); if (!"".equals(response)) { String[] split = response.split(":"); info = MPDAudioInfo.builder() .sampleRate(parseSampleRate(split[0])) .bits(parseBitRate(split[1])) .channels(parseChannels(split[2])) .build(); } return info; } private static int parseSampleRate(String sampleRate) { try { return Integer.parseInt(sampleRate); } catch (NumberFormatException nfe) { LOGGER.error("Could not format sample rate", nfe); return -1; } } @Override public Status getStatus() { String currentStatus = serverStatus.getState(); if (currentStatus.equalsIgnoreCase(Status.STATUS_PLAYING.getPrefix())) { return Status.STATUS_PLAYING; } else if (currentStatus.equalsIgnoreCase(Status.STATUS_PAUSED.getPrefix())) { return Status.STATUS_PAUSED; } else { return Status.STATUS_STOPPED; } } private static int parseChannels(String channels) { try { return Integer.parseInt(channels); } catch (NumberFormatException nfe) { LOGGER.error("Could not format channels", nfe); return -1; } } private static int parseBitRate(String bitRate) { try { return Integer.parseInt(bitRate); } catch (NumberFormatException nfe) { LOGGER.error("Could not format bits", nfe); return -1; } } private void seekMPDSong(MPDPlaylistSong song, long secs) { var params = new String[2]; params[1] = Long.toString(secs); params[0] = Integer.toString(song.getId()); commandExecutor.sendCommand(playerProperties.getSeekId(), params); firePlayerChangeEvent(PlayerChangeEvent.Event.PLAYER_SEEKING); } }
9,786
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
BitrateChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/BitrateChangeListener.java
package org.bff.javampd.player; /** * The listener interface for receiving bitrate events. The class that is interested in processing a * bitrate event implements this interface, and the object created with that class is registered * with a component using the component's <CODE>addBitrateChangeListener</CODE> method. When the * bitrate event occurs, that object's <CODE>bitrateChanged</CODE> method is invoked. * * @author Bill */ @FunctionalInterface public interface BitrateChangeListener { /** * Invoked when a bitrate change event occurs. * * @param event the {@link BitrateChangeEvent} fired */ void bitrateChanged(BitrateChangeEvent event); }
675
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
BitrateChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/BitrateChangeEvent.java
package org.bff.javampd.player; import lombok.Getter; /** * Represents a bitrate change when playing a song. * * @author Bill */ @Getter public class BitrateChangeEvent extends java.util.EventObject { /** * -- GETTER -- the old bitrate * * @return the from bitrate */ private final int oldBitrate; /** * -- GETTER -- the new bitrate * * @return the new bitrate */ private final int newBitrate; /** * Creates a new instance of BitrateChangeEvent * * @param source the object on which the Event initially occurred * @param oldBitrate the from bitrate * @param newBitrate the new bitrate */ public BitrateChangeEvent(Object source, int oldBitrate, int newBitrate) { super(source); this.oldBitrate = oldBitrate; this.newBitrate = newBitrate; } }
818
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z