From f4f658a7f7c24e79d00d69562ee4991b4098612c Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sun, 6 May 2012 23:25:22 -0400 Subject: [PATCH] goofing around with URLs in java --- digressions/Makefile | 5 +++- digressions/URLParts.java | 52 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 digressions/URLParts.java diff --git a/digressions/Makefile b/digressions/Makefile index 1884913..3da0974 100644 --- a/digressions/Makefile +++ b/digressions/Makefile @@ -1,5 +1,8 @@ CFLAGS += -g -Wall -Wextra -all: temperatures +%.class:%.java + javac -d $(PWD) $^ + +all: temperatures URLParts.class .PHONY: all diff --git a/digressions/URLParts.java b/digressions/URLParts.java new file mode 100644 index 0000000..09dafff --- /dev/null +++ b/digressions/URLParts.java @@ -0,0 +1,52 @@ +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 defaultPorts; + static { + Map tmpMap = new HashMap(); + 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); + } +}