Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid read(URL) throwing NPE for invalid URLs #1272

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions core/src/main/java/tech/tablesaw/io/DataFrameReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,13 @@ public Table url(String url) {
* mime-type Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table url(URL url) {
URLConnection connection = null;
try {
connection = url.openConnection();
URLConnection connection = url.openConnection();
String contentType = connection.getContentType();
return url(url, getCharset(contentType), getMimeType(contentType));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeIOException(e);
}
String contentType = connection.getContentType();
return url(url, getCharset(contentType), getMimeType(contentType));
}

private Table url(URL url, Charset charset, String mimeType) {
Expand All @@ -87,11 +86,17 @@ private Table readUrl(URL url, Charset charset, DataReader<?> reader) {
}

private String getMimeType(String contentType) {
if (contentType == null) {
return null;
}
String[] pair = contentType.split(";");
return pair[0].trim();
}

private Charset getCharset(String contentType) {
if (contentType == null) {
return Charset.defaultCharset();
}
String[] pair = contentType.split(";");
return pair.length == 1
? Charset.defaultCharset()
Expand Down
13 changes: 13 additions & 0 deletions core/src/test/java/tech/tablesaw/io/DataFrameReaderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.Files;
Expand Down Expand Up @@ -81,4 +82,16 @@ public void readUrlUnknownMimeTypeNoExtension() throws Exception {
.getMessage()
.contains("No reader registered for mime-type application/octet-stream"));
}

@Test
void readInvalidURL() throws MalformedURLException {
URL url = new URL("ftp://not-a-host/data.csv");
assertThrows(RuntimeIOException.class, () -> Table.read().url(url));
}

@Test
void readInvalidURLNoExtension() throws MalformedURLException {
URL url = new URL("ftp://not-a-host/data/csv");
assertThrows(IllegalArgumentException.class, () -> Table.read().url(url));
}
}
Loading