1.1 --- a/samples/exceptions/test/org/apidesign/exceptions/trycatchredo/MemoryURL.java Sun Feb 01 16:03:37 2009 +0100
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,95 +0,0 @@
1.4 -
1.5 -package org.apidesign.exceptions.trycatchredo;
1.6 -
1.7 -import java.io.ByteArrayInputStream;
1.8 -import java.io.ByteArrayOutputStream;
1.9 -import java.io.IOException;
1.10 -import java.io.InputStream;
1.11 -import java.io.OutputStream;
1.12 -import java.net.MalformedURLException;
1.13 -import java.net.URL;
1.14 -import java.net.URLConnection;
1.15 -import java.net.URLStreamHandler;
1.16 -import java.net.URLStreamHandlerFactory;
1.17 -import java.util.HashMap;
1.18 -import java.util.Map;
1.19 -import junit.framework.Assert;
1.20 -
1.21 -/**
1.22 - *
1.23 - * @author Jaroslav Tulach
1.24 - */
1.25 -public final class MemoryURL extends URLStreamHandler {
1.26 - private MemoryURL() {
1.27 - }
1.28 -
1.29 - static void initialize() {
1.30 - }
1.31 - static {
1.32 - class F implements URLStreamHandlerFactory {
1.33 - public URLStreamHandler createURLStreamHandler(String protocol) {
1.34 - if (protocol.startsWith("memory")) {
1.35 - return new MemoryURL();
1.36 - }
1.37 - return null;
1.38 - }
1.39 - }
1.40 - F f = new F();
1.41 - URL.setURLStreamHandlerFactory(f);
1.42 - }
1.43 -
1.44 - private static Map<String,InputStream> contents = new HashMap<String,InputStream>();
1.45 - private static Map<String,OutputStream> outputs = new HashMap<String,OutputStream>();
1.46 - public static void registerURL(String u, String content, OutputStream out) throws MalformedURLException {
1.47 - contents.put(u, new ByteArrayInputStream(content.getBytes()));
1.48 - outputs.put(u, out);
1.49 - }
1.50 -
1.51 - public static String getOutputForURL(String u) {
1.52 - OutputStream out = outputs.get(u);
1.53 - Assert.assertNotNull("No output for " + u, out);
1.54 - return out.toString();
1.55 - }
1.56 -
1.57 - protected URLConnection openConnection(URL u) throws IOException {
1.58 - return new MC(u);
1.59 - }
1.60 -
1.61 - private static final class MC extends URLConnection {
1.62 - private InputStream values;
1.63 - private OutputStream out;
1.64 -
1.65 - public MC(URL u) {
1.66 - super(u);
1.67 - out = outputs.get(u.toExternalForm());
1.68 - if (out == null) {
1.69 - out = new ByteArrayOutputStream();
1.70 - outputs.put(u.toExternalForm(), out);
1.71 - }
1.72 - }
1.73 -
1.74 - public void connect() throws IOException {
1.75 - if (values != null) {
1.76 - return;
1.77 - }
1.78 - values = contents.remove(url.toExternalForm());
1.79 - if (values == null) {
1.80 - throw new IOException("No such content: " + url);
1.81 - }
1.82 - }
1.83 -
1.84 - @Override
1.85 - public InputStream getInputStream() throws IOException {
1.86 - connect();
1.87 - return values;
1.88 - }
1.89 -
1.90 - @Override
1.91 - public OutputStream getOutputStream() throws IOException {
1.92 - if (out == null) {
1.93 - out = new ByteArrayOutputStream();
1.94 - }
1.95 - return out;
1.96 - }
1.97 - }
1.98 -}