box-o-sand/digressions/URLParts.java
2012-05-06 23:25:22 -04:00

53 lines
1.5 KiB
Java

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Collections;
/**
* A crappy little toy exercise not intended for actual usage.
* Given a URL as first argument, prints the component parts on separate lines
* all fancy-like. Also does some silly guessing when there's no port
* provided. Unmazing.
*/
public class URLParts {
public static final Map<String, Integer> defaultPorts;
static {
Map<String, Integer> tmpMap = new HashMap<String, Integer>();
tmpMap.put("http", 80);
tmpMap.put("https", 443);
tmpMap.put("file", -1);
defaultPorts = Collections.unmodifiableMap(tmpMap);
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < args.length; i++) {
showParts(new URL(args[i]));
}
}
public static void showParts(URL url) {
String protocol = url.getProtocol();
int port = url.getPort();
if (port == -1) {
port = getDefaultPortForProtocol(protocol);
}
showPart("protocol", protocol);
showPart("host", url.getHost());
showPart("port", Integer.toString(port));
}
public static void showPart(String name, String value) {
System.out.println(String.format("%s: %s", name, value));
}
public static int getDefaultPortForProtocol(String protocol) {
if (protocol == null) {
protocol = "http";
} else {
protocol = protocol.toLowerCase();
}
return defaultPorts.get(protocol);
}
}