// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UrlCaseTester {
    private static boolean test(URL url) {
        try {
            // TODO: clode connection
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            return con.getResponseCode() == HttpURLConnection.HTTP_OK;
        } catch (IOException e) {
            return false;
        }
    }
    private static final Pattern p = Pattern.compile("<DT><A HREF=\"([^\"]+://[^\"]+)\" ADD_DATE");
    public static void main(String[] args) throws Exception {
        int problem = 0;
        int impossible = 0;
        int sensitive = 0;
        int insensitive = 0;
        for(String line : Files.readAllLines(Paths.get("/work/bookmarks.html"))) {
            Matcher m = p.matcher(line);
            if(m.find()) {
                String urlstr = m.group(1);
                URL url = new URL(urlstr);
                if(url.getProtocol().equals("http")) {
                    boolean ok1 = test(url);
                    if(ok1) {
                        String path = url.getPath();
                        char[] path2 = path.toCharArray();
                        if(path2.length >= 3  && Character.isLetter(path2[2])) {
                            if(Character.isLowerCase(path2[2])) {
                                path2[2] = Character.toUpperCase(path2[2]);
                            } else if(Character.isUpperCase(path2[2])) {
                                path2[2] = Character.toLowerCase(path2[2]);
                            }
                            path = new String(path2);
                            urlstr = url.getProtocol() + "://" + url.getHost() + (url.getPort() > 0 ? ":" + url.getPort() : "") + path + (url.getQuery() != null ? "?" + url.getQuery() : "");
                            url = new URL(urlstr);
                            boolean ok2 = test(url);
                            if(ok2) {
                                insensitive++;
                            } else {
                                sensitive++;
                            }
                        } else {
                            impossible++;
                        }
                    } else {
                        problem++;
                    }
                }
            }
            System.out.printf("problem: %d, impossible: %d, sensitive: %d, insensitive: %d\n", problem, impossible, sensitive, insensitive);
            if(sensitive + insensitive >= 100) break;
        }
    }
}
