ch.trustserv.soundbox.plugins.portals.jamendoplugin.JamendoPlugin.java Source code

Java tutorial

Introduction

Here is the source code for ch.trustserv.soundbox.plugins.portals.jamendoplugin.JamendoPlugin.java

Source

package ch.trustserv.soundbox.plugins.portals.jamendoplugin;

import static ch.trustserv.soundbox.abstr.communication.message.IMsgIdentifier.FOUNDSONG;
import static ch.trustserv.soundbox.abstr.communication.message.IMsgIdentifier.GETSTREAMFROMSONGFORDOWNLOADER;
import static ch.trustserv.soundbox.abstr.communication.message.IMsgIdentifier.GETSTREAMFROMSONGFORPLAYER;
import static ch.trustserv.soundbox.abstr.communication.message.IMsgIdentifier.SEARCHALBUMFORBROWSER;
import static ch.trustserv.soundbox.abstr.communication.message.IMsgIdentifier.SEARCHARTISTFORBROWSER;
import static ch.trustserv.soundbox.abstr.communication.message.IMsgIdentifier.SEARCHSONGFORBROWSER;
import static ch.trustserv.soundbox.abstr.communication.message.IMsgIdentifier.STREAMFROMSONGFORDOWNLOADER;
import static ch.trustserv.soundbox.abstr.communication.message.IMsgIdentifier.STREAMFROMSONGFORPLAYER;
import ch.trustserv.soundbox.interfaces.portal.AbstractPortal;
import ch.trustserv.soundbox.interfaces.portal.Author;
import ch.trustserv.soundbox.interfaces.portal.License;
import ch.trustserv.soundbox.interfaces.portal.PluginInformation;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;

/**
 *
 * @author Oliver Zemann
 */
public class JamendoPlugin extends AbstractPortal {

    /**
     *
     */
    private final String _version = "0.0.0";
    /**
     *
     */
    private final BundleContext cx;
    /**
     *
     */
    PluginInformation infos;
    /**
     *
     */
    private Date lastTimeCommandSend;

    /**
     *
     * @param cx
     */
    public JamendoPlugin(final BundleContext cx) {
        this.cx = cx;
    }

    /**
     *
     * @return
     */
    @Override
    public boolean init() {
        setInfos(new PluginInformation("Jamendo Plugin " + _version, new Author("Oliver", "Zemann"),
                new License("LGPL 1.0")));
        return true;
    }

    /**
     *
     * @param searchString
     * @return
     */
    @Override
    public Object searchSong(final String searchString) {

        URI link = null;
        try {
            link = new URI("http://api.jamendo.com/get2/id+name+album_name+"
                    + "artist_name+duration/track/json/track_album+album_artist"
                    + "?order=searchweight_desc&n=all&searchquery=" + searchString.replaceAll(" ", "%20"));
        } catch (URISyntaxException ex) {
            Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
        }
        HttpGet get = new HttpGet(link);
        HttpClient client = new DefaultHttpClient();
        Dictionary l = new Hashtable<>();
        ArrayList songArrayList = new ArrayList();
        JSONParser parser = new JSONParser();
        Object obj = null;
        try {
            HttpEntity entity = client.execute(get).getEntity();
            String entityAsString = EntityUtils.toString(entity);
            entity.getContent().close();
            if (entityAsString.isEmpty()) // something went wrong...
            {
                return null;
            }
            obj = parser.parse(entityAsString);

        } catch (IOException | IllegalStateException | ParseException | org.json.simple.parser.ParseException ex) {
            Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
        }

        JSONArray songs = (JSONArray) obj;
        Iterator iter = songs.iterator();
        JSONObject rawSong = null;
        while (iter.hasNext()) {
            try {
                rawSong = (JSONObject) parser.parse(iter.next().toString());
            } catch (org.json.simple.parser.ParseException ex) {
                Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
            }

            JamendoSong song = new JamendoSong(rawSong);
            songArrayList.add(song);
        }

        l.put("songList", songArrayList);
        l.put("portalName", "Jamendo");
        ServiceReference ref = cx.getServiceReference(EventAdmin.class.getName());
        if (ref != null) {
            EventAdmin eventAdmin = (EventAdmin) cx.getService(ref);
            Event reportGeneratedEvent = new Event(FOUNDSONG, l);

            eventAdmin.sendEvent(reportGeneratedEvent);
        }
        return null;
    }

    /**
     *
     */
    @Override
    public void showPluginInformation() {
        new PluginInformationFrame(this).setVisible(true);
    }

    /**
     *
     */
    @Override
    public void showConfig() {
        ConfigurationFrame frame = new ConfigurationFrame();
        frame.setVisible(true);
    }

    /**
     *
     * @param event
     */
    @Override
    public void handleEvent(final Event event) {

        if (event == null) {
            return;
        }

        switch (event.getTopic()) {
        case SEARCHSONGFORBROWSER:
            searchSong(event.getProperty("songTitle").toString());
            break;
        case SEARCHALBUMFORBROWSER:
            searchAlbum(event.getProperty("albumTitle").toString());
            break;
        case SEARCHARTISTFORBROWSER:
            searchArtist(event.getProperty("artistName").toString());
            break;
        case GETSTREAMFROMSONGFORPLAYER: {
            Object song = event.getProperty("song");
            if (song instanceof JamendoSong) {
                getStreamFromSong((JamendoSong) song, GETSTREAMFROMSONGFORPLAYER);
            }
            break;
        }
        case GETSTREAMFROMSONGFORDOWNLOADER: {
            Object song = event.getProperty("song");
            if (song instanceof JamendoSong) {
                getStreamFromSong((JamendoSong) song, GETSTREAMFROMSONGFORDOWNLOADER);
            }
            break;
        }
        }
    }

    /**
     *
     * @return
     */
    private String getVersion() {
        return _version;
    }

    /**
     *
     * @return
     */
    @Override
    public PluginInformation getInfos() {
        return infos;
    }

    /**
     *
     * @param infos
     */
    @Override
    public void setInfos(final PluginInformation infos) {
        this.infos = infos;
    }

    /**
     *
     * @param toString
     */
    private void searchAlbum(final String toString) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     *
     * @param toString
     */
    private void searchArtist(final String toString) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     *
     * @param jamendoSong
     * @param reciever
     */
    private void getStreamFromSong(final JamendoSong jamendoSong, final String reciever) {
        URL streamLink = null;
        try {
            streamLink = new URL("http://api.jamendo.com/get2/stream/track/redirect/?id=" + jamendoSong.getId()
                    + "&streamencoding=mp31");
        } catch (MalformedURLException ex) {
            Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
        }
        ServiceReference ref = cx.getServiceReference(EventAdmin.class.getName());

        if (ref != null) {
            EventAdmin eventAdmin = (EventAdmin) cx.getService(ref);
            Dictionary properties = new Hashtable();
            try {
                URLConnection con = streamLink.openConnection();
                jamendoSong.setContentLength(con.getContentLength());
                properties.put("stream", new BufferedInputStream(con.getInputStream()));
                properties.put("song", jamendoSong);
            } catch (IOException ex) {
                Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
            }
            Event reportGeneratedEvent = null;
            switch (reciever) {
            case GETSTREAMFROMSONGFORDOWNLOADER:
                reportGeneratedEvent = new Event(STREAMFROMSONGFORDOWNLOADER, properties);
                break;
            case GETSTREAMFROMSONGFORPLAYER:
                reportGeneratedEvent = new Event(STREAMFROMSONGFORPLAYER, properties);
                break;
            }
            eventAdmin.sendEvent(reportGeneratedEvent);
        }
    }
}