1 16 17 package org.springframework.core.io; 18 19 import java.io.File ; 20 import java.io.IOException ; 21 import java.io.InputStream ; 22 import java.net.MalformedURLException ; 23 import java.net.URL ; 24 import java.net.URLConnection ; 25 26 import org.springframework.util.Assert; 27 import org.springframework.util.ResourceUtils; 28 import org.springframework.util.StringUtils; 29 30 39 public class UrlResource extends AbstractResource { 40 41 44 private final URL url; 45 46 49 private final URL cleanedUrl; 50 51 52 56 public UrlResource(URL url) { 57 Assert.notNull(url, "URL must not be null"); 58 this.url = url; 59 this.cleanedUrl = getCleanedUrl(this.url, url.toString()); 60 } 61 62 67 public UrlResource(String path) throws MalformedURLException { 68 Assert.notNull(path, "Path must not be null"); 69 this.url = new URL (path); 70 this.cleanedUrl = getCleanedUrl(this.url, path); 71 } 72 73 80 private URL getCleanedUrl(URL originalUrl, String originalPath) { 81 try { 82 return new URL (StringUtils.cleanPath(originalPath)); 83 } 84 catch (MalformedURLException ex) { 85 return originalUrl; 88 } 89 } 90 91 92 100 public InputStream getInputStream() throws IOException { 101 URLConnection con = this.url.openConnection(); 102 con.setUseCaches(false); 103 return con.getInputStream(); 104 } 105 106 109 public URL getURL() throws IOException { 110 return this.url; 111 } 112 113 118 public File getFile() throws IOException { 119 return ResourceUtils.getFile(this.url, getDescription()); 120 } 121 122 127 public Resource createRelative(String relativePath) throws MalformedURLException { 128 if (relativePath.startsWith("/")) { 129 relativePath = relativePath.substring(1); 130 } 131 return new UrlResource(new URL (this.url, relativePath)); 132 } 133 134 139 public String getFilename() { 140 return new File (this.url.getFile()).getName(); 141 } 142 143 146 public String getDescription() { 147 return "URL [" + this.url + "]"; 148 } 149 150 151 154 public boolean equals(Object obj) { 155 return (obj == this || 156 (obj instanceof UrlResource && this.cleanedUrl.equals(((UrlResource) obj).cleanedUrl))); 157 } 158 159 162 public int hashCode() { 163 return this.cleanedUrl.hashCode(); 164 } 165 166 } 167 | Popular Tags |