Skip to content

Instantly share code, notes, and snippets.

@siordache
Last active June 2, 2016 20:21
Show Gist options
  • Save siordache/6586ace06fdb4f56f374daa0e3f1e1b1 to your computer and use it in GitHub Desktop.
Save siordache/6586ace06fdb4f56f374daa0e3f1e1b1 to your computer and use it in GitHub Desktop.
URL protocol for in-memory resources
class InMemoryProtocol {
static final String PROTOCOL_NAME = 'inmemory'
static final Map inMemoryMap = [:]
static int inMemoryIndex = 0
static {
URL.URLStreamHandlerFactory = new URLStreamHandlerFactory() {
@Override URLStreamHandler createURLStreamHandler(String protocol) {
(protocol == PROTOCOL_NAME) ? new URLStreamHandler() {
@Override protected URLConnection openConnection(URL url) throws IOException {
new URLConnection(url) {
@Override void connect() throws IOException {}
@Override InputStream getInputStream() throws IOException {
int index = url.path.substring(1) as int
String catalog = InMemoryProtocol.inMemoryMap[index]
new ByteArrayInputStream(catalog.bytes)
}
}
}
} : null
}
}
}
private static String createUrlString(String text) {
inMemoryIndex++
inMemoryMap[inMemoryIndex] = text
"$PROTOCOL_NAME://beryx.org/$inMemoryIndex"
}
static URL createUrl(String text) {
new URL(createUrlString(text))
}
}
import spock.lang.Shared
import spock.lang.Specification
class InMemoryProtocolSpec extends Specification {
def "should correctly retrieve the content of in-memory URLs"() {
given:
def content1 = '''
host = www.beryx.org
port = 80
'''
def content2 = '''
{
"host": "www.beryx.org",
"port": "80"
}
'''
when:
def url1 = InMemoryProtocol.createUrl(content1)
def url2 = InMemoryProtocol.createUrl(content2)
then:
url1.text == content1
url2.text == content2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment