package com.oracle.avatar.util; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import jdk.nashorn.internal.runtime.Source; /** * A map that supports {@link Class} storage and lookup by either {@link URL} or {@link Source}. * @author Bryan Atsatt. Copyright (c) 2013 Oracle. * @since 7/29/13 */ public interface ClassMap { /** * A ClassMap entry. */ public static class Entry { private final Source src; private final Class cls; private final long last; /** * Constructor. * @param source The {@link Source}. * @param cls The {@link Class}; */ Entry(final Source source, final Class cls) { this.src = source; this.cls = cls; final URL u = source.getURL(); long lastMod = -1; if (u != null) { final URLConnection c = connectionFor(u); if (c != null) { lastMod = c.getLastModified(); } } this.last = lastMod; } /** * Test if this entry represents the same content * as that of the specified {@code URL}. The default * implementation compares only content length and * last modified time, not the actual content. * @param other The {@code URL} to compare against. * @return {@code true} if equivalent. */ public boolean equals(final URL other) { final URL ours = src.getURL(); if (ours != null && other != null) { if (ours == other) { return true; } else if (ours.sameFile(other)) { final URLConnection otherConn = connectionFor(other); if (otherConn != null) { if (src.getLength() == otherConn.getContentLength()) { if (last == otherConn.getLastModified()) { return true; } } } } } return false; } /** * Returns the {@code URL}. * @return the URL, or {@code null} if none. */ public URL toURL() { return src.getURL(); } /** * Returns the {@link Source}. * @return The source. */ public Source toSource() { return src; } /** * Returns the {@link Source}. * @return The source. */ public Class toClass() { return cls; } private static URLConnection connectionFor(URL url) { try { return url.openConnection(); } catch (IOException e) { return null; } } } /** * Lookup an entry by {@code URL}. * @param key The url. * @return The entry or {@code null} if not found. */ public Entry get(final URL key); /** * Lookup an entry by {@link Source}. * @param key The source. * @return The entry or {@code null} if none. */ public Entry get(final Source key); /** * Add an entry. * @param source The {@link Source}. * @param cls The {@link Class}; * @return Any previous {@link Entry}. */ public Entry put(final Source source, final Class cls); /** * Return the current size. * @return The size. */ public int size(); }