Skip to content

Commit

Permalink
Retrieve resource bytes from map as URLStreamHandler can be shared to…
Browse files Browse the repository at this point in the history
… other resources (#1)

Co-authored-by: jose.pereda <[email protected]>
  • Loading branch information
José Pereda and jperedadnr authored Apr 12, 2021
1 parent 4a3a4e7 commit 34f8793
Showing 1 changed file with 25 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
package com.oracle.svm.core.jdk;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
Expand Down Expand Up @@ -125,8 +126,26 @@ public static List<byte[]> get(String name) {

public static URL createURL(String name, byte[] resourceBytes) {
class Conn extends URLConnection {

private InputStream in;
private long length = -1L;

Conn(URL url) {
super(url);

// remove "resource:" from url to get the resource name
String resName = url.toString().substring(1 + JavaNetSubstitutions.RESOURCE_PROTOCOL.length());
if (resName.equals(name)) {
in = new ByteArrayInputStream(resourceBytes);
length = resourceBytes.length;
} else {
final List<byte[]> bytes = singleton().resources.get(resName);
if (bytes != null && !bytes.isEmpty()) {
byte[] resBytes = bytes.get(0);
in = new ByteArrayInputStream(resBytes);
length = resBytes.length;
}
}
}

@Override
Expand All @@ -135,17 +154,20 @@ public void connect() throws IOException {

@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(resourceBytes);
if (in == null) {
throw new FileNotFoundException(url.toString());
}
return in;
}

@Override
public long getContentLengthLong() {
return resourceBytes.length;
return length;
}
}

try {
return new URL("resource", null, -1, name, new URLStreamHandler() {
return new URL(JavaNetSubstitutions.RESOURCE_PROTOCOL, null, -1, name, new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new Conn(u);
Expand Down

0 comments on commit 34f8793

Please sign in to comment.