Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package uk.co.everywheremusic.model; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import uk.co.everywheremusic.viewcontroller.ServerScene; /** * * @author kyle */ public class RestApi { private static final String INIT = "/init"; private static final String UPDATE = "/update"; private static final String SONG = "/song"; private static final String CURRENT_TIME = "/timestamp"; private String path; private String queryString; private String installFolder; private String musicFolder; /** * * @param path * @param queryString */ public RestApi(String path, String queryString) { this.path = path; this.queryString = queryString; String[] config = LibraryManager.readConfigFile("." + Globals.INSTALL_EXT + Globals.SETTINGS_FILENAME); if (config != null) { this.installFolder = config[0]; this.musicFolder = config[1]; } } /** * * @param request * @param response * @throws ServletException * @throws IOException */ public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*if(path.equals(SONG)){ handleSongRequest(request, response); }else{ handleJsonRequest(request, response); }*/ // string support >= java v7 switch (path) { case SONG: handleSongRequest(request, response); break; case INIT: handleJsonRequest(request, response); break; case UPDATE: handleJsonRequest(request, response); break; case CURRENT_TIME: handleTimeRequest(request, response); break; default: handleJsonRequest(request, response); } } /** * * @param request * @param response * @throws ServletException * @throws IOException */ public void handleJsonRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String result = null; int status; boolean auth = false; switch (path) { case INIT: if (queryString != null) { String[] args = queryString.split(Pattern.quote("&")); if (args != null && args.length == 1) { String[] keyValueOne = args[0].split(Pattern.quote("=")); if (keyValueOne != null && keyValueOne.length == 2) { if (keyValueOne[0].equals("auth")) { DBManager dbm = new DBManager(installFolder); PasswordDAO pdao = dbm.getPasswordDAO(); auth = pdao.authenticatePassword(keyValueOne[1]); } } } } if (auth) { result = getUpdate(-1); status = 200; } else { status = 401; } break; case UPDATE: long lastUpdated = Long.MAX_VALUE; // will make DB return no update by default as no updates in the future if (queryString != null) { String[] args = queryString.split(Pattern.quote("&")); if (args != null && args.length == 2) { String[] keyValueOne = args[0].split(Pattern.quote("=")); if (keyValueOne != null && keyValueOne.length == 2) { if (keyValueOne[0].equals("lastUpdated")) { lastUpdated = Long.parseLong(keyValueOne[1]); } } String[] keyValueTwo = args[1].split(Pattern.quote("=")); if (keyValueTwo != null && keyValueTwo.length == 2) { if (keyValueTwo[0].equals("auth")) { DBManager dbm = new DBManager(installFolder); PasswordDAO pdao = dbm.getPasswordDAO(); auth = pdao.authenticatePassword(keyValueTwo[1]); } } } } if (auth) { result = getUpdate(lastUpdated); status = 200; } else { status = 401; } break; default: status = 404; result = null; break; } switch (status) { case 200: response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(result); break; case 401: response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().println("<h1>Error 401: Forbidden</h1>"); break; case 404: response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().println("<h1>Error 404: Not Found</h1>"); break; default: response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().println("<h1>Error 404: Not Found</h1>"); break; } } /** * * @param request * @param response * @throws ServletException * @throws IOException */ public void handleSongRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = ""; boolean auth = false; if (queryString != null) { String[] args = queryString.split(Pattern.quote("&")); if (args != null && args.length == 2) { String[] keyValueOne = args[0].split(Pattern.quote("=")); if (keyValueOne != null && keyValueOne.length == 2) { if (keyValueOne[0].equals("path")) { path = keyValueOne[1]; } } String[] keyValueTwo = args[1].split(Pattern.quote("=")); if (keyValueTwo != null && keyValueTwo.length == 2) { if (keyValueTwo[0].equals("auth")) { DBManager dbm = new DBManager(installFolder); PasswordDAO pdao = dbm.getPasswordDAO(); auth = pdao.authenticatePassword(keyValueTwo[1]); } } } } if (auth) { // check if valid song DBManager dbm = new DBManager(installFolder); SongDAO sdao = dbm.getSongDAO(); SongBean song = sdao.getSongFromPath(path); if (song != null) { File file = new File(path); String mime = Files.probeContentType(Paths.get(file.getAbsolutePath())); response.setStatus(HttpServletResponse.SC_OK); response.setContentType(mime); response.setHeader("Content-Disposition", "filename=\"" + file.getName() + "\""); response.setContentLengthLong(file.length()); FileUtils.copyFile(file, response.getOutputStream()); } else { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("<h1>Error 400: Bad request</h1><br />Invalid song"); } } else { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().println("<h1>Error 401: Forbidden</h1>"); } } private String getUpdate(long lastUpdate) { String result = null; DBManager dbm = new DBManager(installFolder); SongDAO sdao = dbm.getSongDAO(); DeletedSongDAO dsdao = dbm.getDeletedSongDAO(); ArrayList<SongBean> songs = sdao.getSongsUpdate(lastUpdate); JSONArray songsList = new JSONArray(); for (int i = 0; i < songs.size(); i++) { SongBean song = songs.get(i); JSONObject obj = LibraryManager.makeSongJsonObject(song.getFilePath(), song.getArtist(), song.getAlbum(), song.getTitle(), song.getAlbumArtist(), song.getComposer(), song.getGenre(), song.getTrackNo(), song.getDiscNo(), song.getYear(), song.getComment()); songsList.add(songsList.size(), obj); } JSONArray deletedSongsList = new JSONArray(); ArrayList<DeletedSongBean> deletedSongs = dsdao.getDeletedSongsUpdate(lastUpdate); for (int i = 0; i < deletedSongs.size(); i++) { DeletedSongBean deletedSong = deletedSongs.get(i); JSONObject obj = LibraryManager.makeDeletedSongJsonObject(deletedSong.getId(), deletedSong.getTimestamp(), deletedSong.getFilePath()); deletedSongsList.add(deletedSongsList.size(), obj); } JSONObject finalJSON = new JSONObject(); finalJSON.put(Globals.JSON_SONGS_INIT, songsList); finalJSON.put("DeletedSongs", deletedSongsList); result = finalJSON.toJSONString(); return result; } /** * * @param request * @param response * @throws ServletException * @throws IOException */ public void handleTimeRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean auth = false; if (queryString != null) { String[] args = queryString.split(Pattern.quote("&")); if (args != null && args.length == 1) { String[] keyValueOne = args[0].split(Pattern.quote("=")); if (keyValueOne != null && keyValueOne.length == 2) { if (keyValueOne[0].equals("auth")) { DBManager dbm = new DBManager(installFolder); PasswordDAO pdao = dbm.getPasswordDAO(); auth = pdao.authenticatePassword(keyValueOne[1]); } } } } if (auth) { JSONObject objTime = new JSONObject(); objTime.put("ServerTimestamp", System.currentTimeMillis()); String result = objTime.toString(); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(result); } else { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().println("<h1>Error 401: Forbidden</h1>"); } } }