├── lib └── jdom-2.0.6.jar ├── src └── wseemann │ └── media │ └── jplaylistparser │ ├── exception │ └── JPlaylistParserException.java │ ├── parser │ ├── Parser.java │ ├── AbstractParser.java │ ├── m3u │ │ └── M3UPlaylistParser.java │ ├── pls │ │ └── PLSPlaylistParser.java │ ├── m3u8 │ │ └── M3U8PlaylistParser.java │ ├── xspf │ │ └── XSPFPlaylistParser.java │ ├── AutoDetectParser.java │ └── asx │ │ └── ASXPlaylistParser.java │ ├── playlist │ ├── Playlist.java │ └── PlaylistEntry.java │ └── mime │ └── MediaType.java ├── README.md ├── examples └── ParsePlaylist.java └── LICENSE-2.0.txt /lib/jdom-2.0.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wseemann/JavaPlaylistParser/HEAD/lib/jdom-2.0.6.jar -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/exception/JPlaylistParserException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.exception; 18 | 19 | public class JPlaylistParserException extends Exception { 20 | 21 | private static final long serialVersionUID = 1L; 22 | 23 | public JPlaylistParserException(String msg) { 24 | super(msg); 25 | } 26 | 27 | public JPlaylistParserException(String msg, Throwable cause) { 28 | super(msg, cause); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/parser/Parser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.parser; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | import java.util.Set; 22 | 23 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 24 | import wseemann.media.jplaylistparser.mime.MediaType; 25 | import wseemann.media.jplaylistparser.playlist.Playlist; 26 | 27 | import org.xml.sax.SAXException; 28 | 29 | public interface Parser { 30 | 31 | Set getSupportedTypes(); 32 | 33 | void parse( 34 | String uri, InputStream stream, Playlist playlist) 35 | throws IOException, SAXException, JPlaylistParserException; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/parser/AbstractParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.parser; 18 | 19 | import java.io.IOException; 20 | 21 | import org.xml.sax.SAXException; 22 | 23 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 24 | import wseemann.media.jplaylistparser.playlist.Playlist; 25 | import wseemann.media.jplaylistparser.playlist.PlaylistEntry; 26 | 27 | public abstract class AbstractParser implements Parser { 28 | 29 | protected void parseEntry(PlaylistEntry playlistEntry, Playlist playlist) { 30 | try { 31 | AutoDetectParser parser = new AutoDetectParser(); // Should auto-detect! 32 | parser.parse(playlistEntry.get(PlaylistEntry.URI), playlist); 33 | return; 34 | } catch (IOException e) { 35 | } catch (SAXException e) { 36 | } catch (JPlaylistParserException e) { 37 | } 38 | 39 | playlist.add(playlistEntry); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/playlist/Playlist.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.playlist; 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | 22 | public class Playlist { 23 | 24 | private List mPlaylistEntries = null; 25 | 26 | /** 27 | * Constructs a new, empty playlist. 28 | */ 29 | public Playlist() { 30 | setPlaylistEntries(new ArrayList()); 31 | } 32 | 33 | public void add(PlaylistEntry playlistEntry) { 34 | mPlaylistEntries.add(playlistEntry); 35 | } 36 | 37 | /** 38 | * @return the mPlaylistEntries 39 | */ 40 | public List getPlaylistEntries() { 41 | return mPlaylistEntries; 42 | } 43 | 44 | /** 45 | * @param mPlaylistEntries the mPlaylistEntries to set 46 | */ 47 | protected void setPlaylistEntries(List mPlaylistEntries) { 48 | this.mPlaylistEntries = mPlaylistEntries; 49 | } 50 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | JavaPlaylistParser 2 | ============================ 3 | 4 | View the project page here. 5 | 6 | Donate 7 | ------------ 8 | 9 | Donations can be made via PayPal: 10 | 11 | 12 | 13 | 14 | 15 | Overview 16 | -------- 17 | 18 | JavaPlaylistParser is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries. 19 | 20 | Using JPP in your application 21 | ------------ 22 | 23 | Extract and copy the following JAR file and prebuilt native libraries into your projects "libs" folder: 24 | 25 | Installation 26 | ------------ 27 | 28 | ### Ant 29 | 30 | Java Playlist Parser is based on Java 6 and uses the Apache Ant 31 | build system. To build Java Playlist sParser, use the following command in this directory: 32 | 33 | ant jar 34 | 35 | Usage 36 | ------------ 37 | 38 | 39 | 40 | License 41 | ------------ 42 | 43 | ``` 44 | JavaPlaylistParser: A toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries. 45 | 46 | Copyright 2014 William Seemann 47 | 48 | Licensed under the Apache License, Version 2.0 (the "License"); 49 | you may not use this file except in compliance with the License. 50 | You may obtain a copy of the License at 51 | 52 | http://www.apache.org/licenses/LICENSE-2.0 53 | 54 | Unless required by applicable law or agreed to in writing, software 55 | distributed under the License is distributed on an "AS IS" BASIS, 56 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 57 | See the License for the specific language governing permissions and 58 | limitations under the License. 59 | 60 | -------------------------------------------------------------------------------- /examples/ParsePlaylist.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.io.IOException; 18 | import java.io.InputStream; 19 | import java.net.HttpURLConnection; 20 | import java.net.MalformedURLException; 21 | import java.net.URL; 22 | 23 | import org.xml.sax.SAXException; 24 | 25 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 26 | import wseemann.media.jplaylistparser.parser.AutoDetectParser; 27 | import wseemann.media.jplaylistparser.playlist.Playlist; 28 | import wseemann.media.jplaylistparser.playlist.PlaylistEntry; 29 | 30 | public class ParsePlaylist { 31 | 32 | public static void main(String [] args) throws SAXException, JPlaylistParserException { 33 | URL url; 34 | HttpURLConnection conn = null; 35 | InputStream is = null; 36 | 37 | try { 38 | url = new URL("Enter playlist URL here"); 39 | conn = (HttpURLConnection) url.openConnection(); 40 | conn.setConnectTimeout(6000); 41 | conn.setReadTimeout(6000); 42 | conn.setRequestMethod("GET"); 43 | 44 | String contentType = conn.getContentType(); 45 | is = conn.getInputStream(); 46 | 47 | AutoDetectParser parser = new AutoDetectParser(); // Should auto-detect! 48 | Playlist playlist = new Playlist(); 49 | parser.parse(url.toString(), contentType, is, playlist); 50 | 51 | for (int i = 0; i < playlist.getPlaylistEntries().size(); i++) { 52 | PlaylistEntry entry = playlist.getPlaylistEntries().get(i); 53 | System.out.println(entry.get(PlaylistEntry.URI)); 54 | } 55 | } catch (MalformedURLException e) { 56 | e.printStackTrace(); 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } finally { 60 | if (conn != null) { 61 | conn.disconnect(); 62 | } 63 | 64 | if (is != null) { 65 | try { 66 | is.close(); 67 | } catch (IOException e) { 68 | } 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/parser/m3u/M3UPlaylistParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.parser.m3u; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.util.Collections; 24 | import java.util.Set; 25 | 26 | import org.xml.sax.SAXException; 27 | 28 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 29 | import wseemann.media.jplaylistparser.mime.MediaType; 30 | import wseemann.media.jplaylistparser.parser.AbstractParser; 31 | import wseemann.media.jplaylistparser.playlist.Playlist; 32 | import wseemann.media.jplaylistparser.playlist.PlaylistEntry; 33 | 34 | public class M3UPlaylistParser extends AbstractParser { 35 | public final static String EXTENSION = ".m3u"; 36 | 37 | private final static String EXTENDED_INFO_TAG = "#EXTM3U"; 38 | private final static String RECORD_TAG = "^[#][E|e][X|x][T|t][I|i][N|n][F|f].*"; 39 | 40 | private static int mNumberOfFiles = 0; 41 | private boolean processingEntry = false; 42 | 43 | private static final Set SUPPORTED_TYPES = 44 | Collections.singleton(MediaType.audio("x-mpegurl")); 45 | 46 | public Set getSupportedTypes() { 47 | return SUPPORTED_TYPES; 48 | } 49 | 50 | /** 51 | * Retrieves the files listed in a .m3u file 52 | * @throws IOException 53 | */ 54 | private void parsePlaylist(InputStream stream, Playlist playlist) throws IOException { 55 | String line = null; 56 | BufferedReader reader = null; 57 | PlaylistEntry playlistEntry = null; 58 | 59 | // Start the query 60 | reader = new BufferedReader(new InputStreamReader(stream)); 61 | 62 | while ((line = reader.readLine()) != null) { 63 | if (!(line.equalsIgnoreCase(EXTENDED_INFO_TAG) || line.trim().equals(""))) { 64 | if (line.matches(RECORD_TAG)) { 65 | playlistEntry = new PlaylistEntry(); 66 | playlistEntry.set(PlaylistEntry.PLAYLIST_METADATA, line.replaceAll("^(.*?),", "")); 67 | processingEntry = true; 68 | } else { 69 | if (!processingEntry) { 70 | playlistEntry = new PlaylistEntry(); 71 | } 72 | 73 | playlistEntry.set(PlaylistEntry.URI, line.trim()); 74 | savePlaylistFile(playlistEntry, playlist); 75 | } 76 | } 77 | } 78 | } 79 | 80 | private void savePlaylistFile(PlaylistEntry playlistEntry, Playlist playlist) { 81 | mNumberOfFiles = mNumberOfFiles + 1; 82 | playlistEntry.set(PlaylistEntry.TRACK, String.valueOf(mNumberOfFiles)); 83 | parseEntry(playlistEntry, playlist); 84 | processingEntry = false; 85 | } 86 | 87 | @Override 88 | public void parse(String uri, InputStream stream, Playlist playlist) 89 | throws IOException, SAXException, JPlaylistParserException { 90 | parsePlaylist(stream, playlist); 91 | } 92 | } 93 | 94 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/parser/pls/PLSPlaylistParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.parser.pls; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.util.Collections; 24 | import java.util.Set; 25 | 26 | import org.xml.sax.SAXException; 27 | 28 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 29 | import wseemann.media.jplaylistparser.mime.MediaType; 30 | import wseemann.media.jplaylistparser.parser.AbstractParser; 31 | import wseemann.media.jplaylistparser.playlist.Playlist; 32 | import wseemann.media.jplaylistparser.playlist.PlaylistEntry; 33 | 34 | public class PLSPlaylistParser extends AbstractParser { 35 | public final static String EXTENSION = ".pls"; 36 | 37 | private static int mNumberOfFiles = 0; 38 | private boolean processingEntry = false; 39 | 40 | private static final Set SUPPORTED_TYPES = 41 | Collections.singleton(MediaType.audio("x-scpls")); 42 | 43 | public Set getSupportedTypes() { 44 | return SUPPORTED_TYPES; 45 | } 46 | 47 | /** 48 | * Retrieves the files listed in a .pls file 49 | * @throws IOException 50 | */ 51 | private void parsePlaylist(InputStream stream, Playlist playlist) throws IOException { 52 | String line = null; 53 | BufferedReader reader = null; 54 | PlaylistEntry playlistEntry = null; 55 | 56 | reader = new BufferedReader(new InputStreamReader(stream)); 57 | 58 | playlistEntry = new PlaylistEntry(); 59 | processingEntry = false; 60 | 61 | while ((line = reader.readLine()) != null) { 62 | if (line.trim().equals("")) { 63 | if (processingEntry) { 64 | savePlaylistFile(playlistEntry, playlist); 65 | } 66 | 67 | playlistEntry = new PlaylistEntry(); 68 | processingEntry = false; 69 | } else { 70 | int index = line.indexOf('='); 71 | String [] parsedLine = new String[0]; 72 | 73 | if (index != -1) { 74 | parsedLine = new String[2]; 75 | parsedLine[0] = line.substring(0, index); 76 | parsedLine[1] = line.substring(index + 1); 77 | } 78 | 79 | if (parsedLine.length == 2) { 80 | if (parsedLine[0].trim().matches("[Ff][Ii][Ll][Ee].*")) { 81 | processingEntry = true; 82 | playlistEntry.set(PlaylistEntry.URI, parsedLine[1].trim()); 83 | } else if (parsedLine[0].trim().contains("Title")) { 84 | playlistEntry.set(PlaylistEntry.PLAYLIST_METADATA, parsedLine[1].trim()); 85 | } else if (parsedLine[0].trim().contains("Length")) { 86 | if (processingEntry) { 87 | savePlaylistFile(playlistEntry, playlist); 88 | } 89 | 90 | playlistEntry = new PlaylistEntry(); 91 | processingEntry = false; 92 | } 93 | } 94 | } 95 | } 96 | 97 | // added in case the file doesn't follow the standard pls 98 | // structure: 99 | // FileX: 100 | // TitleX: 101 | // LengthX: 102 | if (processingEntry) { 103 | savePlaylistFile(playlistEntry, playlist); 104 | } 105 | } 106 | 107 | private void savePlaylistFile(PlaylistEntry playlistEntry, Playlist playlist) { 108 | mNumberOfFiles = mNumberOfFiles + 1; 109 | playlistEntry.set(PlaylistEntry.TRACK, String.valueOf(mNumberOfFiles)); 110 | parseEntry(playlistEntry, playlist); 111 | processingEntry = false; 112 | } 113 | 114 | @Override 115 | public void parse(String uri, InputStream stream, Playlist playlist) 116 | throws IOException, SAXException, JPlaylistParserException { 117 | parsePlaylist(stream, playlist); 118 | } 119 | } 120 | 121 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/parser/m3u8/M3U8PlaylistParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.parser.m3u8; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.net.URI; 24 | import java.net.URISyntaxException; 25 | import java.util.Collections; 26 | import java.util.Set; 27 | 28 | import org.xml.sax.SAXException; 29 | 30 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 31 | import wseemann.media.jplaylistparser.mime.MediaType; 32 | import wseemann.media.jplaylistparser.parser.AbstractParser; 33 | import wseemann.media.jplaylistparser.playlist.Playlist; 34 | import wseemann.media.jplaylistparser.playlist.PlaylistEntry; 35 | 36 | public class M3U8PlaylistParser extends AbstractParser { 37 | public final static String EXTENSION = ".m3u8"; 38 | 39 | private final static String EXTENDED_INFO_TAG = "#EXTM3U"; 40 | private final static String INFO_TAG = "^[#][E|e][X|x][T|t][-][X|x][-].*"; 41 | private final static String RECORD_TAG = "^[#][E|e][X|x][T|t][I|i][N|n][F|f].*"; 42 | 43 | private final static String PROTOCOL = "^[H|h][T|t][T|t][P|p].*"; 44 | 45 | private static int mNumberOfFiles = 0; 46 | private boolean processingEntry = false; 47 | 48 | private static final Set SUPPORTED_TYPES = 49 | Collections.singleton(MediaType.audio("x-mpegurl")); 50 | 51 | public Set getSupportedTypes() { 52 | return SUPPORTED_TYPES; 53 | } 54 | 55 | /** 56 | * Retrieves the files listed in a .m3u file 57 | * @throws IOException 58 | * @throws JPlaylistParserException 59 | */ 60 | private void parsePlaylist(String uri, InputStream stream, Playlist playlist) throws IOException, JPlaylistParserException { 61 | String line = null; 62 | BufferedReader reader = null; 63 | PlaylistEntry playlistEntry = null; 64 | 65 | String host = getHost(uri); 66 | 67 | // Start the query 68 | reader = new BufferedReader(new InputStreamReader(stream)); 69 | 70 | while ((line = reader.readLine()) != null) { 71 | if (!(line.equalsIgnoreCase(EXTENDED_INFO_TAG) || 72 | line.matches(INFO_TAG) || 73 | line.trim().equals(""))) { 74 | if (line.matches(RECORD_TAG)) { 75 | playlistEntry = new PlaylistEntry(); 76 | playlistEntry.set(PlaylistEntry.PLAYLIST_METADATA, line.replaceAll("^(.*?),", "")); 77 | processingEntry = true; 78 | } else { 79 | if (!processingEntry) { 80 | playlistEntry = new PlaylistEntry(); 81 | } 82 | 83 | playlistEntry.set(PlaylistEntry.URI, generateUri(line.trim(), host)); 84 | savePlaylistFile(playlistEntry, playlist); 85 | } 86 | } 87 | } 88 | } 89 | 90 | private void savePlaylistFile(PlaylistEntry playlistEntry, Playlist playlist) { 91 | mNumberOfFiles = mNumberOfFiles + 1; 92 | playlistEntry.set(PlaylistEntry.TRACK, String.valueOf(mNumberOfFiles)); 93 | parseEntry(playlistEntry, playlist); 94 | processingEntry = false; 95 | } 96 | 97 | private String getHost(String uri) throws JPlaylistParserException { 98 | try { 99 | URI host = new URI(uri); 100 | 101 | String path; 102 | 103 | if ((path = host.getPath()) == null || path.trim().equals("")) { 104 | return uri + '/'; 105 | } 106 | 107 | int index = path.lastIndexOf('/'); 108 | 109 | if (index > -1) { 110 | host = new URI(host.getScheme(), null, host.getHost(), host.getPort(), path.substring(0, index + 1), null, null); 111 | } 112 | 113 | return host.toString(); 114 | } catch (URISyntaxException e) { 115 | throw new JPlaylistParserException(e.getMessage()); 116 | } 117 | } 118 | 119 | private String generateUri(String uri, String host) { 120 | if (uri.matches(PROTOCOL)) { 121 | return uri; 122 | } 123 | 124 | return host + uri; 125 | } 126 | 127 | @Override 128 | public void parse(String uri, InputStream stream, Playlist playlist) 129 | throws IOException, SAXException, JPlaylistParserException { 130 | parsePlaylist(uri, stream, playlist); 131 | } 132 | } 133 | 134 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/parser/xspf/XSPFPlaylistParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.parser.xspf; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.io.Reader; 24 | import java.io.StringReader; 25 | import java.util.ArrayList; 26 | import java.util.Collections; 27 | import java.util.List; 28 | import java.util.Set; 29 | 30 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 31 | import wseemann.media.jplaylistparser.mime.MediaType; 32 | import wseemann.media.jplaylistparser.parser.AbstractParser; 33 | import wseemann.media.jplaylistparser.playlist.Playlist; 34 | import wseemann.media.jplaylistparser.playlist.PlaylistEntry; 35 | 36 | import org.jdom2.Document; 37 | import org.jdom2.Element; 38 | import org.jdom2.JDOMException; 39 | import org.jdom2.input.SAXBuilder; 40 | import org.xml.sax.SAXException; 41 | 42 | public class XSPFPlaylistParser extends AbstractParser { 43 | public final static String EXTENSION = ".xspf"; 44 | 45 | private final String LOCATION_ELEMENT = "LOCATION"; 46 | private final String TITLE_ELEMENT = "TITLE"; 47 | private final String TRACK_ELEMENT = "TRACK"; 48 | private final String TRACKLIST_ELEMENT = "TRACKLIST"; 49 | 50 | private static int mNumberOfFiles = 0; 51 | 52 | private static final Set SUPPORTED_TYPES = 53 | Collections.singleton(MediaType.video("application/xspf+xml")); 54 | 55 | public Set getSupportedTypes() { 56 | return SUPPORTED_TYPES; 57 | } 58 | 59 | /** 60 | * Retrieves the files listed in a .asx file 61 | * @throws IOException 62 | */ 63 | private void parsePlaylist(InputStream stream, Playlist playlist) throws IOException { 64 | String xml = ""; 65 | String line = null; 66 | BufferedReader reader = null; 67 | 68 | // Start the query 69 | reader = new BufferedReader(new InputStreamReader(stream)); 70 | 71 | while ((line = reader.readLine()) != null) { 72 | xml = xml + line; 73 | } 74 | 75 | parseXML(xml, playlist); 76 | } 77 | 78 | private void parseXML(String xml, Playlist playlist) { 79 | SAXBuilder builder = new SAXBuilder(); 80 | Reader in; 81 | Document doc = null; 82 | Element root = null; 83 | 84 | try { 85 | in = new StringReader(xml); 86 | 87 | doc = builder.build(in); 88 | root = doc.getRootElement(); 89 | List children = castList(Element.class, root.getChildren()); 90 | 91 | for (int i = 0; i < children.size(); i++) { 92 | String tag = children.get(i).getName(); 93 | 94 | if (tag != null && tag.equalsIgnoreCase(TRACKLIST_ELEMENT)) { 95 | List children2 = castList(Element.class, children.get(i).getChildren()); 96 | 97 | for (int j = 0; j < children2.size(); j++) { 98 | String attributeName = children2.get(j).getName(); 99 | 100 | if (attributeName.equalsIgnoreCase(TRACK_ELEMENT)) { 101 | List children3 = castList(Element.class, children2.get(j).getChildren()); 102 | buildPlaylistEntry(children3, playlist); 103 | } 104 | } 105 | } 106 | } 107 | } catch (JDOMException e) { 108 | } catch (IOException e) { 109 | } catch (Exception e) { 110 | } 111 | } 112 | 113 | private void buildPlaylistEntry(List children, Playlist playlist) { 114 | PlaylistEntry playlistEntry = new PlaylistEntry(); 115 | 116 | for(int i = 0; i < children.size(); i++) { 117 | String attributeName = children.get(i).getName(); 118 | 119 | if (attributeName.equalsIgnoreCase(LOCATION_ELEMENT)) { 120 | String href = children.get(i).getValue(); 121 | 122 | // TODO: add trim? 123 | playlistEntry.set(PlaylistEntry.URI, href); 124 | } else if (attributeName.equalsIgnoreCase(TITLE_ELEMENT)) { 125 | String title = children.get(i).getValue(); 126 | 127 | if (title != null) { 128 | playlistEntry.set(PlaylistEntry.PLAYLIST_METADATA, title); 129 | } 130 | } 131 | } 132 | 133 | mNumberOfFiles = mNumberOfFiles + 1; 134 | playlistEntry.set(PlaylistEntry.TRACK, String.valueOf(mNumberOfFiles)); 135 | parseEntry(playlistEntry, playlist); 136 | } 137 | 138 | private List castList(Class castClass, List c) { 139 | List list = new ArrayList(c.size()); 140 | 141 | for(Object o: c) { 142 | list.add(castClass.cast(o)); 143 | } 144 | 145 | return list; 146 | } 147 | 148 | @Override 149 | public void parse(String uri, InputStream stream, Playlist playlist) 150 | throws IOException, SAXException, JPlaylistParserException{ 151 | parsePlaylist(stream, playlist); 152 | } 153 | } 154 | 155 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/parser/AutoDetectParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.parser; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | import java.net.HttpURLConnection; 22 | import java.net.MalformedURLException; 23 | import java.net.URL; 24 | import java.net.URLDecoder; 25 | 26 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 27 | import wseemann.media.jplaylistparser.mime.MediaType; 28 | import wseemann.media.jplaylistparser.parser.asx.ASXPlaylistParser; 29 | import wseemann.media.jplaylistparser.parser.m3u.M3UPlaylistParser; 30 | import wseemann.media.jplaylistparser.parser.m3u8.M3U8PlaylistParser; 31 | import wseemann.media.jplaylistparser.parser.pls.PLSPlaylistParser; 32 | import wseemann.media.jplaylistparser.parser.xspf.XSPFPlaylistParser; 33 | import wseemann.media.jplaylistparser.playlist.Playlist; 34 | 35 | import org.xml.sax.SAXException; 36 | 37 | public class AutoDetectParser { 38 | 39 | public void parse( 40 | String uri, 41 | String mimeType, 42 | InputStream stream, 43 | Playlist playlist) 44 | throws IOException, SAXException, JPlaylistParserException { 45 | Parser parser = null; 46 | String extension = null; 47 | 48 | if (uri == null) { 49 | throw new IllegalArgumentException("URI cannot be NULL"); 50 | } 51 | 52 | if (stream == null) { 53 | throw new IllegalArgumentException("stream cannot be NULL"); 54 | } 55 | 56 | if (mimeType == null) { 57 | mimeType = ""; 58 | } 59 | 60 | if (mimeType.split("\\;").length > 0) { 61 | mimeType = mimeType.split("\\;")[0]; 62 | } 63 | 64 | ASXPlaylistParser asxPlaylistParser = new ASXPlaylistParser(); 65 | M3UPlaylistParser m3uPlaylistParser = new M3UPlaylistParser(); 66 | M3U8PlaylistParser m3u8PlaylistParser = new M3U8PlaylistParser(); 67 | PLSPlaylistParser plsPlaylistParser = new PLSPlaylistParser(); 68 | XSPFPlaylistParser xspfPlaylistParser = new XSPFPlaylistParser(); 69 | 70 | extension = getFileExtension(uri); 71 | 72 | if (extension.equalsIgnoreCase(ASXPlaylistParser.EXTENSION) 73 | || asxPlaylistParser.getSupportedTypes().contains(MediaType.parse(mimeType))) { 74 | parser = asxPlaylistParser; 75 | } else if (extension.equalsIgnoreCase(M3UPlaylistParser.EXTENSION) 76 | || (m3uPlaylistParser.getSupportedTypes().contains(MediaType.parse(mimeType)) && 77 | !extension.equalsIgnoreCase(M3U8PlaylistParser.EXTENSION))) { 78 | parser = m3uPlaylistParser; 79 | } else if (extension.equalsIgnoreCase(M3U8PlaylistParser.EXTENSION) 80 | || m3uPlaylistParser.getSupportedTypes().contains(MediaType.parse(mimeType))) { 81 | parser = m3u8PlaylistParser; 82 | } else if (extension.equalsIgnoreCase(PLSPlaylistParser.EXTENSION) 83 | || plsPlaylistParser.getSupportedTypes().contains(MediaType.parse(mimeType))) { 84 | parser = plsPlaylistParser; 85 | } else if (extension.equalsIgnoreCase(XSPFPlaylistParser.EXTENSION) 86 | || xspfPlaylistParser.getSupportedTypes().contains(MediaType.parse(mimeType))) { 87 | parser = xspfPlaylistParser; 88 | } else { 89 | throw new JPlaylistParserException("Unsupported format"); 90 | } 91 | 92 | parser.parse(uri, stream, playlist); 93 | } 94 | 95 | public void parse( 96 | String uri, 97 | Playlist playlist) 98 | throws IOException, SAXException, JPlaylistParserException { 99 | Parser parser = null; 100 | String extension = null; 101 | 102 | if (uri == null) { 103 | throw new IllegalArgumentException("URI cannot be NULL"); 104 | } 105 | 106 | ASXPlaylistParser asxPlaylistParser = new ASXPlaylistParser(); 107 | M3UPlaylistParser m3uPlaylistParser = new M3UPlaylistParser(); 108 | M3U8PlaylistParser m3u8PlaylistParser = new M3U8PlaylistParser(); 109 | PLSPlaylistParser plsPlaylistParser = new PLSPlaylistParser(); 110 | XSPFPlaylistParser xspfPlaylistParser = new XSPFPlaylistParser(); 111 | 112 | extension = getFileExtension(uri); 113 | 114 | if (extension.equalsIgnoreCase(ASXPlaylistParser.EXTENSION)) { 115 | parser = asxPlaylistParser; 116 | } else if (extension.equalsIgnoreCase(M3UPlaylistParser.EXTENSION) 117 | && !extension.equalsIgnoreCase(M3U8PlaylistParser.EXTENSION)) { 118 | parser = m3uPlaylistParser; 119 | } else if (extension.equalsIgnoreCase(M3U8PlaylistParser.EXTENSION)) { 120 | parser = m3u8PlaylistParser; 121 | } else if (extension.equalsIgnoreCase(PLSPlaylistParser.EXTENSION)) { 122 | parser = plsPlaylistParser; 123 | } else if (extension.equalsIgnoreCase(XSPFPlaylistParser.EXTENSION)) { 124 | parser = xspfPlaylistParser; 125 | } else { 126 | throw new JPlaylistParserException("Unsupported format"); 127 | } 128 | 129 | URL url; 130 | HttpURLConnection conn = null; 131 | InputStream is = null; 132 | 133 | try { 134 | url = new URL(URLDecoder.decode(uri, "UTF-8")); 135 | conn = (HttpURLConnection) url.openConnection(); 136 | conn.setConnectTimeout(6000); 137 | conn.setReadTimeout(6000); 138 | conn.setRequestMethod("GET"); 139 | 140 | is = conn.getInputStream(); 141 | 142 | parser.parse(url.toString(), is, playlist); 143 | } catch (MalformedURLException e) { 144 | e.printStackTrace(); 145 | } catch (IOException e) { 146 | e.printStackTrace(); 147 | } finally { 148 | if (conn != null) { 149 | conn.disconnect(); 150 | } 151 | 152 | if (is != null) { 153 | try { 154 | is.close(); 155 | } catch (IOException e) { 156 | } 157 | } 158 | } 159 | } 160 | 161 | private String getFileExtension(String uri) { 162 | String fileExtention = ""; 163 | 164 | int index = uri.lastIndexOf("."); 165 | 166 | if (index != -1) { 167 | fileExtention = uri.substring(index, uri.length()); 168 | } 169 | 170 | return fileExtention; 171 | } 172 | } -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/playlist/PlaylistEntry.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.playlist; 18 | 19 | import java.util.Enumeration; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.Properties; 23 | 24 | /** 25 | * A multi-valued metadata container. 26 | */ 27 | public class PlaylistEntry { 28 | // Message, MSOffice, ClimateForcast, TIFF, TikaMetadataKeys, TikaMimeKeys, 29 | // Serializable { 30 | 31 | /** 32 | * A map of all metadata attributes. 33 | */ 34 | private Map metadata = null; 35 | 36 | /** 37 | * The common delimiter used between the namespace abbreviation and the property name 38 | */ 39 | public static final String NAMESPACE_PREFIX_DELIMITER = ":"; 40 | 41 | @Deprecated public static final String FORMAT = "format"; 42 | @Deprecated public static final String IDENTIFIER = "identifier"; 43 | @Deprecated public static final String MODIFIED = "modified"; 44 | @Deprecated public static final String CONTRIBUTOR = "contributor"; 45 | @Deprecated public static final String COVERAGE = "coverage"; 46 | @Deprecated public static final String CREATOR = "creator"; 47 | @Deprecated public static final String DESCRIPTION = "description"; 48 | @Deprecated public static final String LANGUAGE = "language"; 49 | @Deprecated public static final String PUBLISHER = "publisher"; 50 | @Deprecated public static final String RELATION = "relation"; 51 | @Deprecated public static final String RIGHTS = "rights"; 52 | @Deprecated public static final String SOURCE = "source"; 53 | @Deprecated public static final String SUBJECT = "subject"; 54 | public static final String TITLE = "title"; 55 | @Deprecated public static final String TYPE = "type"; 56 | public static final String TRACK = "track"; 57 | public static final String URI = "uri"; 58 | public static final String PLAYLIST_METADATA = "playlist_metadata"; 59 | 60 | /** 61 | * Constructs a new, empty playlist entry. 62 | */ 63 | public PlaylistEntry() { 64 | metadata = new HashMap(); 65 | } 66 | 67 | /** 68 | * Returns true if named value is multivalued. 69 | * 70 | * @param name 71 | * name of metadata 72 | * @return true is named value is multivalued, false if single value or null 73 | */ 74 | public boolean isMultiValued(final String name) { 75 | return metadata.get(name) != null && metadata.get(name).length > 1; 76 | } 77 | 78 | /** 79 | * Returns an array of the names contained in the metadata. 80 | * 81 | * @return Metadata names 82 | */ 83 | public String[] names() { 84 | return metadata.keySet().toArray(new String[metadata.keySet().size()]); 85 | } 86 | 87 | /** 88 | * Get the value associated to a metadata name. If many values are assiociated 89 | * to the specified name, then the first one is returned. 90 | * 91 | * @param name 92 | * of the metadata. 93 | * @return the value associated to the specified metadata name. 94 | */ 95 | public String get(final String name) { 96 | String[] values = metadata.get(name); 97 | if (values == null) { 98 | return null; 99 | } else { 100 | return values[0]; 101 | } 102 | } 103 | 104 | /** 105 | * Get the values associated to a metadata name. 106 | * 107 | * @param name 108 | * of the metadata. 109 | * @return the values associated to a metadata name. 110 | */ 111 | public String[] getValues(final String name) { 112 | return _getValues(name); 113 | } 114 | 115 | private String[] _getValues(final String name) { 116 | String[] values = metadata.get(name); 117 | if (values == null) { 118 | values = new String[0]; 119 | } 120 | return values; 121 | } 122 | 123 | private String[] appendedValues(String[] values, final String value) { 124 | String[] newValues = new String[values.length + 1]; 125 | System.arraycopy(values, 0, newValues, 0, values.length); 126 | newValues[newValues.length - 1] = value; 127 | return newValues; 128 | } 129 | 130 | /** 131 | * Add a metadata name/value mapping. Add the specified value to the list of 132 | * values associated to the specified metadata name. 133 | * 134 | * @param name 135 | * the metadata name. 136 | * @param value 137 | * the metadata value. 138 | */ 139 | public void add(final String name, final String value) { 140 | String[] values = metadata.get(name); 141 | if (values == null) { 142 | set(name, value); 143 | } else { 144 | metadata.put(name, appendedValues(values, value)); 145 | } 146 | } 147 | 148 | /** 149 | * Copy All key-value pairs from properties. 150 | * 151 | * @param properties 152 | * properties to copy from 153 | */ 154 | @SuppressWarnings("unchecked") 155 | public void setAll(Properties properties) { 156 | Enumeration names = 157 | (Enumeration) properties.propertyNames(); 158 | while (names.hasMoreElements()) { 159 | String name = names.nextElement(); 160 | metadata.put(name, new String[] { properties.getProperty(name) }); 161 | } 162 | } 163 | 164 | /** 165 | * Set metadata name/value. Associate the specified value to the specified 166 | * metadata name. If some previous values were associated to this name, they 167 | * are removed. 168 | * 169 | * @param name 170 | * the metadata name. 171 | * @param value 172 | * the metadata value. 173 | */ 174 | public void set(String name, String value) { 175 | metadata.put(name, new String[] { value }); 176 | } 177 | 178 | /** 179 | * Remove a metadata and all its associated values. 180 | * 181 | * @param name 182 | * metadata name to remove 183 | */ 184 | public void remove(String name) { 185 | metadata.remove(name); 186 | } 187 | 188 | /** 189 | * Returns the number of metadata names in this metadata. 190 | * 191 | * @return number of metadata names 192 | */ 193 | public int size() { 194 | return metadata.size(); 195 | } 196 | 197 | public boolean equals(Object o) { 198 | 199 | if (o == null) { 200 | return false; 201 | } 202 | 203 | PlaylistEntry other = null; 204 | try { 205 | other = (PlaylistEntry) o; 206 | } catch (ClassCastException cce) { 207 | return false; 208 | } 209 | 210 | if (other.size() != size()) { 211 | return false; 212 | } 213 | 214 | String[] names = names(); 215 | for (int i = 0; i < names.length; i++) { 216 | String[] otherValues = other._getValues(names[i]); 217 | String[] thisValues = _getValues(names[i]); 218 | if (otherValues.length != thisValues.length) { 219 | return false; 220 | } 221 | for (int j = 0; j < otherValues.length; j++) { 222 | if (!otherValues[j].equals(thisValues[j])) { 223 | return false; 224 | } 225 | } 226 | } 227 | return true; 228 | } 229 | 230 | public String toString() { 231 | StringBuffer buf = new StringBuffer(); 232 | String[] names = names(); 233 | for (int i = 0; i < names.length; i++) { 234 | String[] values = _getValues(names[i]); 235 | for (int j = 0; j < values.length; j++) { 236 | buf.append(names[i]).append("=").append(values[j]).append(" "); 237 | } 238 | } 239 | return buf.toString(); 240 | } 241 | 242 | } 243 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/parser/asx/ASXPlaylistParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.parser.asx; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.io.Reader; 24 | import java.io.StringReader; 25 | import java.net.HttpURLConnection; 26 | import java.net.MalformedURLException; 27 | import java.net.URL; 28 | import java.util.ArrayList; 29 | import java.util.Collections; 30 | import java.util.List; 31 | import java.util.Set; 32 | 33 | import wseemann.media.jplaylistparser.exception.JPlaylistParserException; 34 | import wseemann.media.jplaylistparser.mime.MediaType; 35 | import wseemann.media.jplaylistparser.parser.AbstractParser; 36 | import wseemann.media.jplaylistparser.parser.AutoDetectParser; 37 | import wseemann.media.jplaylistparser.playlist.Playlist; 38 | import wseemann.media.jplaylistparser.playlist.PlaylistEntry; 39 | 40 | import org.jdom2.Document; 41 | import org.jdom2.Element; 42 | import org.jdom2.JDOMException; 43 | import org.jdom2.input.JDOMParseException; 44 | import org.jdom2.input.SAXBuilder; 45 | import org.xml.sax.SAXException; 46 | 47 | public class ASXPlaylistParser extends AbstractParser { 48 | public final static String EXTENSION = ".asx"; 49 | 50 | private final String ABSTRACT_ELEMENT = "ABSTRACT"; 51 | private final String ASX_ELEMENT = "ASX"; 52 | private final String AUTHOR_ELEMENT = "AUTHOR"; 53 | private final String BASE_ELEMENT = "BASE"; 54 | private final String COPYRIGHT_ELEMENT = "COPYRIGHT"; 55 | private final String DURATION_ELEMENT = "DURATION"; 56 | private final String ENDMARKER_ELEMENT = "ENDMARKER"; 57 | private final String ENTRY_ELEMENT = "ENTRY"; 58 | private final String ENTRYREF_ELEMENT = "ENTRYREF"; 59 | private final String EVENT_ELEMENT = "EVENT"; 60 | private final String MOREINFO_ELEMENT = "MOREINFO"; 61 | private final String PARAM_ELEMENT = "PARAM"; 62 | private final String REF_ELEMENT = "REF"; 63 | private final String REPEAT_ELEMENT = "REPEAT"; 64 | private final String STARTMARKER_ELEMENT = "STARTMARKER"; 65 | private final String STARTTIME_ELEMENT = "STARTTIME"; 66 | private final String TITLE_ELEMENT = "TITLE"; 67 | 68 | private final String HREF_ATTRIBUTE = "href"; 69 | 70 | private static int mNumberOfFiles = 0; 71 | 72 | private static final Set SUPPORTED_TYPES = 73 | Collections.singleton(MediaType.video("x-ms-asf")); 74 | 75 | public Set getSupportedTypes() { 76 | return SUPPORTED_TYPES; 77 | } 78 | 79 | /** 80 | * Retrieves the files listed in a .asx file 81 | * @throws IOException 82 | */ 83 | private void parsePlaylist(InputStream stream, Playlist playlist) throws IOException { 84 | String xml = ""; 85 | String line = null; 86 | BufferedReader reader = null; 87 | 88 | // Start the query 89 | reader = new BufferedReader(new InputStreamReader(stream)); 90 | 91 | while ((line = reader.readLine()) != null) { 92 | xml = xml + line; 93 | } 94 | 95 | parseXML(xml, playlist); 96 | } 97 | 98 | private String validateXML(String xml, SAXBuilder builder) throws JDOMException, IOException { 99 | Reader in; 100 | int i = 0; 101 | 102 | xml = xml.replaceAll("\\&", "&"); 103 | 104 | while (i < 5) { 105 | in = new StringReader(xml); 106 | 107 | try { 108 | builder.build(in); 109 | break; 110 | } catch (JDOMParseException e) { 111 | String message = e.getMessage(); 112 | if (message.matches("^.*.The element type.*.must be terminated by the matching end-tag.*")) { 113 | String tag = message.substring(message.lastIndexOf("type") + 6, message.lastIndexOf("must") - 2); 114 | xml = xml.replaceAll("(?i)" , ""); 115 | } else { 116 | break; 117 | } 118 | 119 | i++; 120 | } 121 | } 122 | 123 | return xml; 124 | } 125 | 126 | private void parseXML(String xml, Playlist playlist) { 127 | SAXBuilder builder = new SAXBuilder(); 128 | Reader in; 129 | Document doc = null; 130 | Element root = null; 131 | 132 | try { 133 | xml = validateXML(xml, builder); 134 | in = new StringReader(xml); 135 | 136 | doc = builder.build(in); 137 | root = doc.getRootElement(); 138 | List children = castList(Element.class, root.getChildren()); 139 | 140 | for (int i = 0; i < children.size(); i++) { 141 | String tag = children.get(i).getName(); 142 | 143 | if (tag != null && tag.equalsIgnoreCase(ENTRY_ELEMENT)) { 144 | List children2 = castList(Element.class, children.get(i).getChildren()); 145 | 146 | buildPlaylistEntry(children2, playlist); 147 | } else if (tag != null && tag.equalsIgnoreCase(ENTRYREF_ELEMENT)) { 148 | URL url; 149 | HttpURLConnection conn = null; 150 | InputStream is = null; 151 | 152 | try { 153 | String href = children.get(i).getAttributeValue(HREF_ATTRIBUTE); 154 | 155 | if (href == null) { 156 | href = children.get(i).getAttributeValue(HREF_ATTRIBUTE.toUpperCase()); 157 | } 158 | 159 | if (href == null) { 160 | href = children.get(i).getValue(); 161 | } 162 | 163 | url = new URL(href); 164 | conn = (HttpURLConnection) url.openConnection(); 165 | conn.setConnectTimeout(6000); 166 | conn.setReadTimeout(6000); 167 | conn.setRequestMethod("GET"); 168 | 169 | String contentType = conn.getContentType(); 170 | is = conn.getInputStream(); 171 | 172 | AutoDetectParser parser = new AutoDetectParser(); 173 | parser.parse(url.toString(), contentType, is, playlist); 174 | } catch (MalformedURLException e) { 175 | } catch (IOException e) { 176 | } finally { 177 | if (conn != null) { 178 | conn.disconnect(); 179 | } 180 | 181 | if (is != null) { 182 | try { 183 | is.close(); 184 | } catch (IOException e) { 185 | } 186 | } 187 | } 188 | } 189 | } 190 | } catch (JDOMException e) { 191 | } catch (IOException e) { 192 | } catch (Exception e) { 193 | } 194 | } 195 | 196 | private void buildPlaylistEntry(List children, Playlist playlist) { 197 | PlaylistEntry playlistEntry = new PlaylistEntry(); 198 | 199 | for(int i = 0; i < children.size(); i++) { 200 | String attributeName = children.get(i).getName(); 201 | 202 | if (attributeName.equalsIgnoreCase(ABSTRACT_ELEMENT)) { 203 | } else if (attributeName.equalsIgnoreCase(ASX_ELEMENT)) { 204 | } else if (attributeName.equalsIgnoreCase(AUTHOR_ELEMENT)) { 205 | } else if (attributeName.equalsIgnoreCase(BASE_ELEMENT)) { 206 | } else if (attributeName.equalsIgnoreCase(COPYRIGHT_ELEMENT)) { 207 | } else if (attributeName.equalsIgnoreCase(DURATION_ELEMENT)) { 208 | } else if (attributeName.equalsIgnoreCase(ENDMARKER_ELEMENT)) { 209 | } else if (attributeName.equalsIgnoreCase(ENTRY_ELEMENT)) { 210 | } else if (attributeName.equalsIgnoreCase(ENTRYREF_ELEMENT)) { 211 | } else if (attributeName.equalsIgnoreCase(EVENT_ELEMENT)) { 212 | } else if (attributeName.equalsIgnoreCase(MOREINFO_ELEMENT)) { 213 | } else if (attributeName.equalsIgnoreCase(PARAM_ELEMENT)) { 214 | } else if (attributeName.equalsIgnoreCase(REF_ELEMENT)) { 215 | String href = children.get(i).getAttributeValue(HREF_ATTRIBUTE); 216 | 217 | if (href == null) { 218 | href = children.get(i).getAttributeValue(HREF_ATTRIBUTE.toUpperCase()); 219 | } 220 | 221 | if (href == null) { 222 | href = children.get(i).getValue(); 223 | } 224 | 225 | // TODO: add trim? 226 | playlistEntry.set(PlaylistEntry.URI, href); 227 | } else if (attributeName.equalsIgnoreCase(REPEAT_ELEMENT)) { 228 | } else if (attributeName.equalsIgnoreCase(STARTMARKER_ELEMENT)) { 229 | } else if (attributeName.equalsIgnoreCase(STARTTIME_ELEMENT)) { 230 | } else if (attributeName.equalsIgnoreCase(TITLE_ELEMENT)) { 231 | String title = children.get(i).getValue(); 232 | 233 | if (title != null) { 234 | playlistEntry.set(PlaylistEntry.PLAYLIST_METADATA, title); 235 | } 236 | } 237 | } 238 | 239 | mNumberOfFiles = mNumberOfFiles + 1; 240 | playlistEntry.set(PlaylistEntry.TRACK, String.valueOf(mNumberOfFiles)); 241 | parseEntry(playlistEntry, playlist); 242 | } 243 | 244 | private List castList(Class castClass, List c) { 245 | List list = new ArrayList(c.size()); 246 | 247 | for(Object o: c) { 248 | list.add(castClass.cast(o)); 249 | } 250 | 251 | return list; 252 | } 253 | 254 | @Override 255 | public void parse(String uri, InputStream stream, Playlist playlist) 256 | throws IOException, SAXException, JPlaylistParserException{ 257 | parsePlaylist(stream, playlist); 258 | } 259 | } 260 | 261 | -------------------------------------------------------------------------------- / LICENSE-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | -------------------------------------------------------------------------------- /src/wseemann/media/jplaylistparser/mime/MediaType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 William Seemann 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package wseemann.media.jplaylistparser.mime; 18 | 19 | import java.util.Collections; 20 | import java.util.HashMap; 21 | import java.util.Locale; 22 | import java.util.Map; 23 | import java.util.SortedMap; 24 | import java.util.TreeMap; 25 | import java.util.regex.Matcher; 26 | import java.util.regex.Pattern; 27 | 28 | /** 29 | * Internet media type. 30 | */ 31 | public final class MediaType implements Comparable { 32 | 33 | private static final Pattern SPECIAL = 34 | Pattern.compile("[\\(\\)<>@,;:\\\\\"/\\[\\]\\?=]"); 35 | 36 | private static final Pattern SPECIAL_OR_WHITESPACE = 37 | Pattern.compile("[\\(\\)<>@,;:\\\\\"/\\[\\]\\?=\\s]"); 38 | 39 | /** 40 | * See http://www.ietf.org/rfc/rfc2045.txt for valid mime-type characters. 41 | */ 42 | private static final String VALID_CHARS = 43 | "([^\\c\\(\\)<>@,;:\\\\\"/\\[\\]\\?=\\s]+)"; 44 | 45 | private static final Pattern TYPE_PATTERN = Pattern.compile( 46 | "(?s)\\s*" + VALID_CHARS + "\\s*/\\s*" + VALID_CHARS 47 | + "\\s*($|;.*)"); 48 | 49 | private static final Pattern CHARSET_FIRST_PATTERN = Pattern.compile( 50 | "(?is)\\s*(charset\\s*=\\s*[^\\c;\\s]+)\\s*;\\s*" 51 | + VALID_CHARS + "\\s*/\\s*" + VALID_CHARS + "\\s*"); 52 | 53 | /** 54 | * Set of basic types with normalized "type/subtype" names. 55 | * Used to optimize type lookup and to avoid having too many 56 | * {@link MediaType} instances in memory. 57 | */ 58 | private static final Map SIMPLE_TYPES = 59 | new HashMap(); 60 | 61 | public static final MediaType OCTET_STREAM = 62 | parse("application/octet-stream"); 63 | 64 | public static final MediaType TEXT_PLAIN = parse("text/plain"); 65 | 66 | public static final MediaType APPLICATION_XML = parse("application/xml"); 67 | 68 | public static final MediaType APPLICATION_ZIP = parse("application/zip"); 69 | 70 | public static MediaType application(String type) { 71 | return MediaType.parse("application/" + type); 72 | } 73 | 74 | public static MediaType audio(String type) { 75 | return MediaType.parse("audio/" + type); 76 | } 77 | 78 | public static MediaType image(String type) { 79 | return MediaType.parse("image/" + type); 80 | } 81 | 82 | public static MediaType text(String type) { 83 | return MediaType.parse("text/" + type); 84 | } 85 | 86 | public static MediaType video(String type) { 87 | return MediaType.parse("video/" + type); 88 | } 89 | 90 | /** 91 | * Parses the given string to a media type. The string is expected 92 | * to be of the form "type/subtype(; parameter=...)*" as defined in 93 | * RFC 2045, though we also handle "charset=xxx; type/subtype" for 94 | * broken web servers. 95 | * 96 | * @param string media type string to be parsed 97 | * @return parsed media type, or null if parsing fails 98 | */ 99 | public static MediaType parse(String string) { 100 | if (string == null) { 101 | return null; 102 | } 103 | 104 | // Optimization for the common cases 105 | synchronized (SIMPLE_TYPES) { 106 | MediaType type = SIMPLE_TYPES.get(string); 107 | if (type == null) { 108 | int slash = string.indexOf('/'); 109 | if (slash == -1) { 110 | return null; 111 | } else if (SIMPLE_TYPES.size() < 10000 112 | && isSimpleName(string.substring(0, slash)) 113 | && isSimpleName(string.substring(slash + 1))) { 114 | type = new MediaType(string, slash); 115 | SIMPLE_TYPES.put(string, type); 116 | } 117 | } 118 | if (type != null) { 119 | return type; 120 | } 121 | } 122 | 123 | Matcher matcher; 124 | matcher = TYPE_PATTERN.matcher(string); 125 | if (matcher.matches()) { 126 | return new MediaType( 127 | matcher.group(1), matcher.group(2), 128 | parseParameters(matcher.group(3))); 129 | } 130 | matcher = CHARSET_FIRST_PATTERN.matcher(string); 131 | if (matcher.matches()) { 132 | return new MediaType( 133 | matcher.group(2), matcher.group(3), 134 | parseParameters(matcher.group(1))); 135 | } 136 | 137 | return null; 138 | } 139 | 140 | private static boolean isSimpleName(String name) { 141 | for (int i = 0; i < name.length(); i++) { 142 | char c = name.charAt(i); 143 | if (c != '-' && c != '+' && c != '.' && c != '_' 144 | && !('0' <= c && c <= '9') 145 | && !('a' <= c && c <= 'z')) { 146 | return false; 147 | } 148 | } 149 | return name.length() > 0; 150 | } 151 | 152 | private static Map parseParameters(String string) { 153 | if (string.length() == 0) { 154 | return Collections.emptyMap(); 155 | } 156 | 157 | // Extracts k1=v1, k2=v2 from mime/type; k1=v1; k2=v2 158 | // Note - this logic isn't fully RFC2045 compliant yet, as it 159 | // doesn't fully handle quoted keys or values (eg containing ; or =) 160 | Map parameters = new HashMap(); 161 | while (string.length() > 0) { 162 | String key = string; 163 | String value = ""; 164 | 165 | int semicolon = string.indexOf(';'); 166 | if (semicolon != -1) { 167 | key = string.substring(0, semicolon); 168 | string = string.substring(semicolon + 1); 169 | } else { 170 | string = ""; 171 | } 172 | 173 | int equals = key.indexOf('='); 174 | if (equals != -1) { 175 | value = key.substring(equals + 1); 176 | key = key.substring(0, equals); 177 | } 178 | 179 | key = key.trim(); 180 | if (key.length() > 0) { 181 | parameters.put(key, unquote(value.trim())); 182 | } 183 | } 184 | return parameters; 185 | } 186 | 187 | private static String unquote(String s) { 188 | if( s.startsWith("\"") && s.endsWith("\"")) { 189 | return s.substring(1, s.length() - 1); 190 | } 191 | if( s.startsWith("'") && s.endsWith("'")) { 192 | return s.substring(1, s.length() - 1); 193 | } 194 | 195 | return s; 196 | } 197 | 198 | /** 199 | * Canonical string representation of this media type. 200 | */ 201 | private final String string; 202 | 203 | /** 204 | * Location of the "/" character separating the type and the subtype 205 | * tokens in {@link #string}. 206 | */ 207 | private final int slash; 208 | 209 | /** 210 | * Location of the first ";" character separating the type part of 211 | * {@link #string} from possible parameters. Length of {@link #string} 212 | * in case there are no parameters. 213 | */ 214 | private final int semicolon; 215 | 216 | /** 217 | * Immutable sorted map of media type parameters. 218 | */ 219 | private final Map parameters; 220 | 221 | public MediaType( 222 | String type, String subtype, Map parameters) { 223 | type = type.trim().toLowerCase(Locale.ENGLISH); 224 | subtype = subtype.trim().toLowerCase(Locale.ENGLISH); 225 | 226 | this.slash = type.length(); 227 | this.semicolon = slash + 1 + subtype.length(); 228 | 229 | if (parameters.isEmpty()) { 230 | this.parameters = Collections.emptyMap(); 231 | this.string = type + '/' + subtype; 232 | } else { 233 | StringBuilder builder = new StringBuilder(); 234 | builder.append(type); 235 | builder.append('/'); 236 | builder.append(subtype); 237 | 238 | SortedMap map = new TreeMap(); 239 | for (Map.Entry entry : parameters.entrySet()) { 240 | String key = entry.getKey().trim().toLowerCase(Locale.ENGLISH); 241 | map.put(key, entry.getValue()); 242 | } 243 | for (Map.Entry entry : map.entrySet()) { 244 | builder.append("; "); 245 | builder.append(entry.getKey()); 246 | builder.append("="); 247 | String value = entry.getValue(); 248 | if (SPECIAL_OR_WHITESPACE.matcher(value).find()) { 249 | builder.append('"'); 250 | builder.append(SPECIAL.matcher(value).replaceAll("\\\\$0")); 251 | builder.append('"'); 252 | } else { 253 | builder.append(value); 254 | } 255 | } 256 | 257 | this.string = builder.toString(); 258 | this.parameters = Collections.unmodifiableSortedMap(map); 259 | } 260 | } 261 | 262 | public MediaType(String type, String subtype) { 263 | this(type, subtype, Collections.emptyMap()); 264 | } 265 | 266 | private MediaType(String string, int slash) { 267 | assert slash != -1; 268 | assert string.charAt(slash) == '/'; 269 | assert isSimpleName(string.substring(0, slash)); 270 | assert isSimpleName(string.substring(slash + 1)); 271 | this.string = string; 272 | this.slash = slash; 273 | this.semicolon = string.length(); 274 | this.parameters = Collections.emptyMap(); 275 | } 276 | 277 | private static Map union( 278 | Map a, Map b) { 279 | if (a.isEmpty()) { 280 | return b; 281 | } else if (b.isEmpty()) { 282 | return a; 283 | } else { 284 | Map union = new HashMap(); 285 | union.putAll(a); 286 | union.putAll(b); 287 | return union; 288 | } 289 | } 290 | 291 | public MediaType(MediaType type, Map parameters) { 292 | this(type.getType(), type.getSubtype(), 293 | union(type.parameters, parameters)); 294 | } 295 | 296 | /** 297 | * Returns the base form of the MediaType, excluding 298 | * any parameters, such as "text/plain" for 299 | * "text/plain; charset=utf-8" 300 | */ 301 | public MediaType getBaseType() { 302 | if (parameters.isEmpty()) { 303 | return this; 304 | } else { 305 | return MediaType.parse(string.substring(0, semicolon)); 306 | } 307 | } 308 | 309 | /** 310 | * Return the Type of the MediaType, such as 311 | * "text" for "text/plain" 312 | */ 313 | public String getType() { 314 | return string.substring(0, slash); 315 | } 316 | 317 | /** 318 | * Return the Sub-Type of the MediaType, 319 | * such as "plain" for "text/plain" 320 | */ 321 | public String getSubtype() { 322 | return string.substring(slash + 1, semicolon); 323 | } 324 | 325 | /** 326 | * Checks whether this media type contains parameters. 327 | * 328 | * @return true if this type has one or more parameters, 329 | * false otherwise 330 | */ 331 | public boolean hasParameters() { 332 | return !parameters.isEmpty(); 333 | } 334 | 335 | /** 336 | * Returns an immutable sorted map of the parameters of this media type. 337 | * The parameter names are guaranteed to be trimmed and in lower case. 338 | * 339 | * @return sorted map of parameters 340 | */ 341 | public Map getParameters() { 342 | return parameters; 343 | } 344 | 345 | public String toString() { 346 | return string; 347 | } 348 | 349 | public boolean equals(Object object) { 350 | if (object instanceof MediaType) { 351 | MediaType that = (MediaType) object; 352 | return string.equals(that.string); 353 | } else { 354 | return false; 355 | } 356 | } 357 | 358 | public int hashCode() { 359 | return string.hashCode(); 360 | } 361 | 362 | public int compareTo(MediaType that) { 363 | return string.compareTo(that.string); 364 | } 365 | 366 | } 367 | --------------------------------------------------------------------------------