Created
July 5, 2015 23:51
-
-
Save TheJoshGriffith/5f3550417bc189c5c508 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package uk.me.jig.jrmp; | |
import org.json.*; | |
import java.net.URL; | |
import java.util.LinkedHashMap; | |
import java.util.Map; | |
import java.util.Scanner; | |
/** | |
* Created by Joshua on 05/07/2015. | |
*/ | |
public class spotifyGrabber { | |
private static Map<String, String> replaceMap; | |
private static Map<String, String> replaceRegexMap; | |
private static void prepareReplaceMap() | |
{ | |
replaceMap = new LinkedHashMap<String, String>(); | |
replaceRegexMap = new LinkedHashMap<String, String>(); | |
replaceRegexMap.put("^[0-9]*\\. ", ""); | |
replaceRegexMap.put("^[0-9]* -", ""); | |
replaceRegexMap.put("^[0-9]* ", ""); | |
replaceRegexMap.put("^[0-9]*_-_", ""); | |
replaceMap.put(".mp3", ""); | |
replaceMap.put(" ", "%20"); | |
replaceMap.put("-", "%20"); | |
replaceMap.put("_", "%20"); | |
replaceMap.put("(", "%20"); | |
replaceMap.put(")", "%20"); | |
replaceMap.put("'", "%27"); | |
} | |
private static String prepareTitleForAPI(String title) | |
{ | |
prepareReplaceMap(); | |
for (Map.Entry<String, String> entry : replaceRegexMap.entrySet()) { | |
System.out.println(entry.getKey()); | |
title = title.replaceAll(entry.getKey(), entry.getValue()); | |
} | |
for (Map.Entry<String, String> entry : replaceMap.entrySet()) { | |
System.out.println(entry.getKey()); | |
title = title.replace(entry.getKey(), entry.getValue()); | |
} | |
return title; | |
} | |
public static SongData getSongData(String songName) { | |
try { | |
String tempSongName = prepareTitleForAPI(songName); | |
String s = "https://api.spotify.com/v1/search?q=" + tempSongName + "&type=track"; | |
System.out.println(s); | |
URL url = new URL(s); | |
Scanner scanner = new Scanner(url.openStream()); | |
String result = new String(); | |
while (scanner.hasNext()) { | |
String tmp = scanner.nextLine(); | |
result += tmp; | |
//System.out.println(tmp); | |
} | |
JSONObject obj = new JSONObject(result); | |
JSONObject res = obj.getJSONObject("tracks").getJSONArray("items").getJSONObject(0); | |
String artistName = obj.getJSONObject("tracks").getJSONArray("items").getJSONObject(0).getJSONArray("artists").getJSONObject(0).getString("name"); | |
System.out.println("Artist: " + artistName/* + ". Track: " + res.getString("name") + "."*/); | |
return new SongData("", artistName); | |
} | |
catch (Exception ex) { | |
System.err.println("Failed to get JSON data" + ex.getMessage()); | |
System.out.println("Failed to get JSON data" + ex.getMessage()); | |
} | |
return new SongData("", ""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment