1 19 20 package org.netbeans.modules.uihandler; 21 22 import java.io.ByteArrayInputStream ; 23 import java.io.ByteArrayOutputStream ; 24 import java.io.IOException ; 25 import java.io.InputStream ; 26 import java.io.OutputStream ; 27 import java.net.URL ; 28 import java.net.URLConnection ; 29 import java.net.URLStreamHandler ; 30 import java.net.URLStreamHandlerFactory ; 31 import java.util.HashMap ; 32 import java.util.Map ; 33 import junit.framework.Assert; 34 35 39 public class MemoryURL extends URLStreamHandler { 40 41 static { 42 class F implements URLStreamHandlerFactory { 43 public URLStreamHandler createURLStreamHandler(String protocol) { 44 if (protocol.startsWith("memory")) { 45 return new MemoryURL(); 46 } 47 return null; 48 } 49 } 50 F f = new F(); 51 URL.setURLStreamHandlerFactory(f); 52 } 53 54 private static Map <String ,InputStream > contents = new HashMap <String ,InputStream >(); 55 private static Map <String ,MC> outputs = new HashMap <String ,MC>(); 56 public static void registerURL(String u, String content) { 57 contents.put(u, new ByteArrayInputStream (content.getBytes())); 58 } 59 public static void registerURL(String u, InputStream content) { 60 contents.put(u, content); 61 } 62 63 public static byte[] getOutputForURL(String u) { 64 MC out = outputs.get(u); 65 Assert.assertNotNull("No output for " + u, out); 66 return out.out.toByteArray(); 67 } 68 69 public static String getRequestParameter(String u, String param) { 70 MC out = outputs.get(u); 71 Assert.assertNotNull("No output for " + u, out); 72 return out.params.get(param.toLowerCase()); 73 } 74 75 protected URLConnection openConnection(URL u) throws IOException { 76 return new MC(u); 77 } 78 79 private static final class MC extends URLConnection { 80 private InputStream values; 81 private ByteArrayOutputStream out; 82 private Map <String ,String > params; 83 84 public MC(URL u) { 85 super(u); 86 outputs.put(u.toExternalForm(), this); 87 params = new HashMap <String ,String >(); 88 } 89 90 public void connect() throws IOException { 91 if (values != null) { 92 return; 93 } 94 values = contents.remove(url.toExternalForm()); 95 if (values == null) { 96 throw new IOException ("No such content: " + url); 97 } 98 } 99 100 public InputStream getInputStream() throws IOException { 101 connect(); 102 return values; 103 } 104 105 public OutputStream getOutputStream() throws IOException { 106 if (out == null) { 107 out = new ByteArrayOutputStream (); 108 } 109 return out; 110 } 111 112 public void setRequestProperty(String key, String value) { 113 super.setRequestProperty(key, value); 114 params.put(key.toLowerCase(), value); 115 } 116 117 118 } 119 } 120 | Popular Tags |