Java Code Examples for java.net.URLConnection#getLastModified()

The following examples show how to use java.net.URLConnection#getLastModified() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DocumentCache.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the time-stamp for a document's last update
 */
private final long getLastModified(String uri) {
    try {
        URL url = new URL(uri);
        URLConnection connection = url.openConnection();
        long timestamp = connection.getLastModified();
        // Check for a "file:" URI (courtesy of Brian Ewins)
        if (timestamp == 0){ // get 0 for local URI
            if ("file".equals(url.getProtocol())){
                File localfile = new File(URLDecoder.decode(url.getFile()));
                timestamp = localfile.lastModified();
            }
        }
        return(timestamp);
    }
    // Brutal handling of all exceptions
    catch (Exception e) {
        return(System.currentTimeMillis());
    }
}
 
Example 2
Source File: GetLastModified.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    try {
        File f = File.createTempFile("test", null);
        f.deleteOnExit();
        String s = f.getAbsolutePath();
        s = s.startsWith("/") ? s : "/" + s;
        URL url = new URL("file://localhost"+s);
        URLConnection conn = null;
        conn = url.openConnection();
        conn.connect();
        if (f.lastModified() != conn.getLastModified())
            throw new RuntimeException("file.lastModified() & FileURLConnection.getLastModified() should be equal");
        f.delete();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 3
Source File: DocumentCache.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the time-stamp for a document's last update
 */
private final long getLastModified(String uri) {
    try {
        URL url = new URL(uri);
        URLConnection connection = url.openConnection();
        long timestamp = connection.getLastModified();
        // Check for a "file:" URI (courtesy of Brian Ewins)
        if (timestamp == 0){ // get 0 for local URI
            if ("file".equals(url.getProtocol())){
                File localfile = new File(URLDecoder.decode(url.getFile()));
                timestamp = localfile.lastModified();
            }
        }
        return(timestamp);
    }
    // Brutal handling of all exceptions
    catch (Exception e) {
        return(System.currentTimeMillis());
    }
}
 
Example 4
Source File: GetLastModified.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    try {
        File f = File.createTempFile("test", null);
        f.deleteOnExit();
        String s = f.getAbsolutePath();
        s = s.startsWith("/") ? s : "/" + s;
        URL url = new URL("file://localhost"+s);
        URLConnection conn = null;
        conn = url.openConnection();
        conn.connect();
        if (f.lastModified() != conn.getLastModified())
            throw new RuntimeException("file.lastModified() & FileURLConnection.getLastModified() should be equal");
        f.delete();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 5
Source File: GetLastModified.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    try {
        File f = File.createTempFile("test", null);
        f.deleteOnExit();
        String s = f.getAbsolutePath();
        s = s.startsWith("/") ? s : "/" + s;
        URL url = new URL("file://localhost"+s);
        URLConnection conn = null;
        conn = url.openConnection();
        conn.connect();
        if (f.lastModified() != conn.getLastModified())
            throw new RuntimeException("file.lastModified() & FileURLConnection.getLastModified() should be equal");
        f.delete();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 6
Source File: GetLastModified.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    try {
        File f = File.createTempFile("test", null);
        f.deleteOnExit();
        String s = f.getAbsolutePath();
        s = s.startsWith("/") ? s : "/" + s;
        URL url = new URL("file://localhost"+s);
        URLConnection conn = null;
        conn = url.openConnection();
        conn.connect();
        if (f.lastModified() != conn.getLastModified())
            throw new RuntimeException("file.lastModified() & FileURLConnection.getLastModified() should be equal");
        f.delete();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 7
Source File: UrlModuleSourceProvider.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public URLValidator(URI uri, URLConnection urlConnection,
        long request_time, UrlConnectionExpiryCalculator
        urlConnectionExpiryCalculator) {
    this.uri = uri;
    this.lastModified = urlConnection.getLastModified();
    this.entityTags = getEntityTags(urlConnection);
    expiry = calculateExpiry(urlConnection, request_time,
            urlConnectionExpiryCalculator);
}
 
Example 8
Source File: Source.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
protected void loadMeta() throws IOException {
    if (length == 0 && lastModified == 0) {
        final URLConnection c = url.openConnection();
        length = c.getContentLength();
        lastModified = c.getLastModified();
        debug("loaded metadata for ", url);
    }
}
 
Example 9
Source File: Source.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
protected void load() throws IOException {
    if (array == null) {
        final URLConnection c = url.openConnection();
        try (InputStream in = c.getInputStream()) {
            array = cs == null ? readFully(in) : readFully(in, cs);
            length = array.length;
            lastModified = c.getLastModified();
            debug("loaded content for ", url);
        }
    }
}
 
Example 10
Source File: UrlTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void headers() throws IOException {
  byte[] bytes = {1, 2, 3};
  Files.write(path, bytes);
  FileTime lastModified = Files.getLastModifiedTime(path);

  URL url = path.toUri().toURL();
  URLConnection conn = url.openConnection();

  // read header fields directly
  assertThat(conn.getHeaderFields()).containsEntry("content-length", ImmutableList.of("3"));
  assertThat(conn.getHeaderFields())
      .containsEntry("content-type", ImmutableList.of("application/octet-stream"));

  if (lastModified != null) {
    assertThat(conn.getHeaderFields()).containsKey("last-modified");
    assertThat(conn.getHeaderFields()).hasSize(3);
  } else {
    assertThat(conn.getHeaderFields()).hasSize(2);
  }

  // use the specific methods for reading the expected headers
  assertThat(conn.getContentLengthLong()).isEqualTo(Files.size(path));
  assertThat(conn.getContentType()).isEqualTo("application/octet-stream");

  if (lastModified != null) {
    // The HTTP date format does not include milliseconds, which means that the last modified time
    // returned from the connection may not be exactly the same as that of the file system itself.
    // The difference should less than 1000ms though, and should never be greater.
    long difference = lastModified.toMillis() - conn.getLastModified();
    assertThat(difference).isIn(Range.closedOpen(0L, 1000L));
  } else {
    assertThat(conn.getLastModified()).isEqualTo(0L);
  }
}
 
Example 11
Source File: GetLastModified.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void test(String s) throws Exception {
    URL url = new URL(s);
    URLConnection conn = url.openConnection();
    if (conn.getLastModified() == 0) {
        System.out.println("Failed: getLastModified returned 0 for URL: " + s);
        testFailed = true;
    }
}
 
Example 12
Source File: GetLastModified.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void test(String s) throws Exception {
    URL url = new URL(s);
    URLConnection conn = url.openConnection();
    if (conn.getLastModified() == 0) {
        System.out.println("Failed: getLastModified returned 0 for URL: " + s);
        testFailed = true;
    }
}
 
Example 13
Source File: ControlledValidationXmlBeanDefinitionReader.java    From cxf with Apache License 2.0 5 votes vote down vote up
private int fastInfosetLoadBeanDefinitions(EncodedResource encodedResource)
    throws IOException, StaleFastinfosetException,
    ParserConfigurationException, XMLStreamException {

    URL resUrl = encodedResource.getResource().getURL();
    // There are XML files scampering around that don't end in .xml.
    // We don't apply the optimization to them.
    if (!resUrl.getPath().endsWith(".xml")) {
        throw new StaleFastinfosetException();
    }
    String fixmlPath = resUrl.getPath().replaceFirst("\\.xml$", ".fixml");
    String protocol = resUrl.getProtocol();
    // beware of the relative URL rules for jar:, which are surprising.
    if ("jar".equals(protocol)) {
        fixmlPath = fixmlPath.replaceFirst("^.*!", "");
    }

    URL fixmlUrl = new URL(resUrl, fixmlPath);

    // if we are in unpacked files, we take some extra time
    // to ensure that we aren't using a stale Fastinfoset file.
    if ("file".equals(protocol)) {
        URLConnection resCon = resUrl.openConnection();
        URLConnection fixCon = fixmlUrl.openConnection();
        if (resCon.getLastModified() > fixCon.getLastModified()) {
            throw new StaleFastinfosetException();
        }
    }

    Resource newResource = new UrlResource(fixmlUrl);
    Document doc = TunedDocumentLoader.loadFastinfosetDocument(fixmlUrl);
    if (doc == null) {
        //something caused FastinfoSet to not be able to read the doc
        throw new StaleFastinfosetException();
    }
    return registerBeanDefinitions(doc, newResource);
}
 
Example 14
Source File: FileUtil.java    From ECTester with MIT License 5 votes vote down vote up
public static boolean isNewer(URLConnection jarConn, Path realPath) throws IOException {
    if (realPath.toFile().isFile()) {
        long jarModified = jarConn.getLastModified();
        long realModified = Files.getLastModifiedTime(realPath).toMillis();
        return jarModified > realModified;
    }
    return true;
}
 
Example 15
Source File: GetLastModified.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static void test(String s) throws Exception {
    URL url = new URL(s);
    URLConnection conn = url.openConnection();
    if (conn.getLastModified() == 0) {
        System.out.println("Failed: getLastModified returned 0 for URL: " + s);
        testFailed = true;
    }
}
 
Example 16
Source File: MCRLayoutUtilities.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
private long getLastModified() throws IOException {
    URLConnection urlConnection = docURL.openConnection();
    return urlConnection.getLastModified();
}
 
Example 17
Source File: HttpResponseUtils.java    From enkan with Eclipse Public License 1.0 4 votes vote down vote up
public static Date connectionLastModified(URLConnection conn) {
    long lastMod = conn.getLastModified();
    return lastMod > 0 ? new Date(lastMod) : null;
}
 
Example 18
Source File: ResourceBundle.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Determines if the expired <code>bundle</code> in the cache needs
 * to be reloaded based on the loading time given by
 * <code>loadTime</code> or some other criteria. The method returns
 * <code>true</code> if reloading is required; <code>false</code>
 * otherwise. <code>loadTime</code> is a millisecond offset since
 * the <a href="Calendar.html#Epoch"> <code>Calendar</code>
 * Epoch</a>.
 *
 * <p>
 * The calling <code>ResourceBundle.getBundle</code> factory method
 * calls this method on the <code>ResourceBundle.Control</code>
 * instance used for its current invocation, not on the instance
 * used in the invocation that originally loaded the resource
 * bundle.
 *
 * <p>The default implementation compares <code>loadTime</code> and
 * the last modified time of the source data of the resource
 * bundle. If it's determined that the source data has been modified
 * since <code>loadTime</code>, <code>true</code> is
 * returned. Otherwise, <code>false</code> is returned. This
 * implementation assumes that the given <code>format</code> is the
 * same string as its file suffix if it's not one of the default
 * formats, <code>"java.class"</code> or
 * <code>"java.properties"</code>.
 *
 * @param baseName
 *        the base bundle name of the resource bundle, a
 *        fully qualified class name
 * @param locale
 *        the locale for which the resource bundle
 *        should be instantiated
 * @param format
 *        the resource bundle format to be loaded
 * @param loader
 *        the <code>ClassLoader</code> to use to load the bundle
 * @param bundle
 *        the resource bundle instance that has been expired
 *        in the cache
 * @param loadTime
 *        the time when <code>bundle</code> was loaded and put
 *        in the cache
 * @return <code>true</code> if the expired bundle needs to be
 *        reloaded; <code>false</code> otherwise.
 * @exception NullPointerException
 *        if <code>baseName</code>, <code>locale</code>,
 *        <code>format</code>, <code>loader</code>, or
 *        <code>bundle</code> is <code>null</code>
 */
public boolean needsReload(String baseName, Locale locale,
                           String format, ClassLoader loader,
                           ResourceBundle bundle, long loadTime) {
    if (bundle == null) {
        throw new NullPointerException();
    }
    if (format.equals("java.class") || format.equals("java.properties")) {
        format = format.substring(5);
    }
    boolean result = false;
    try {
        String resourceName = toResourceName0(toBundleName(baseName, locale), format);
        if (resourceName == null) {
            return result;
        }
        URL url = loader.getResource(resourceName);
        if (url != null) {
            long lastModified = 0;
            URLConnection connection = url.openConnection();
            if (connection != null) {
                // disable caches to get the correct data
                connection.setUseCaches(false);
                if (connection instanceof JarURLConnection) {
                    JarEntry ent = ((JarURLConnection)connection).getJarEntry();
                    if (ent != null) {
                        lastModified = ent.getTime();
                        if (lastModified == -1) {
                            lastModified = 0;
                        }
                    }
                } else {
                    lastModified = connection.getLastModified();
                }
            }
            result = lastModified >= loadTime;
        }
    } catch (NullPointerException npe) {
        throw npe;
    } catch (Exception e) {
        // ignore other exceptions
    }
    return result;
}
 
Example 19
Source File: ResourceBundle.java    From openjdk-8-source with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Determines if the expired <code>bundle</code> in the cache needs
 * to be reloaded based on the loading time given by
 * <code>loadTime</code> or some other criteria. The method returns
 * <code>true</code> if reloading is required; <code>false</code>
 * otherwise. <code>loadTime</code> is a millisecond offset since
 * the <a href="Calendar.html#Epoch"> <code>Calendar</code>
 * Epoch</a>.
 *
 * The calling <code>ResourceBundle.getBundle</code> factory method
 * calls this method on the <code>ResourceBundle.Control</code>
 * instance used for its current invocation, not on the instance
 * used in the invocation that originally loaded the resource
 * bundle.
 *
 * <p>The default implementation compares <code>loadTime</code> and
 * the last modified time of the source data of the resource
 * bundle. If it's determined that the source data has been modified
 * since <code>loadTime</code>, <code>true</code> is
 * returned. Otherwise, <code>false</code> is returned. This
 * implementation assumes that the given <code>format</code> is the
 * same string as its file suffix if it's not one of the default
 * formats, <code>"java.class"</code> or
 * <code>"java.properties"</code>.
 *
 * @param baseName
 *        the base bundle name of the resource bundle, a
 *        fully qualified class name
 * @param locale
 *        the locale for which the resource bundle
 *        should be instantiated
 * @param format
 *        the resource bundle format to be loaded
 * @param loader
 *        the <code>ClassLoader</code> to use to load the bundle
 * @param bundle
 *        the resource bundle instance that has been expired
 *        in the cache
 * @param loadTime
 *        the time when <code>bundle</code> was loaded and put
 *        in the cache
 * @return <code>true</code> if the expired bundle needs to be
 *        reloaded; <code>false</code> otherwise.
 * @exception NullPointerException
 *        if <code>baseName</code>, <code>locale</code>,
 *        <code>format</code>, <code>loader</code>, or
 *        <code>bundle</code> is <code>null</code>
 */
public boolean needsReload(String baseName, Locale locale,
                           String format, ClassLoader loader,
                           ResourceBundle bundle, long loadTime) {
    if (bundle == null) {
        throw new NullPointerException();
    }
    if (format.equals("java.class") || format.equals("java.properties")) {
        format = format.substring(5);
    }
    boolean result = false;
    try {
        String resourceName = toResourceName(toBundleName(baseName, locale), format);
        URL url = loader.getResource(resourceName);
        if (url != null) {
            long lastModified = 0;
            URLConnection connection = url.openConnection();
            if (connection != null) {
                // disable caches to get the correct data
                connection.setUseCaches(false);
                if (connection instanceof JarURLConnection) {
                    JarEntry ent = ((JarURLConnection)connection).getJarEntry();
                    if (ent != null) {
                        lastModified = ent.getTime();
                        if (lastModified == -1) {
                            lastModified = 0;
                        }
                    }
                } else {
                    lastModified = connection.getLastModified();
                }
            }
            result = lastModified >= loadTime;
        }
    } catch (NullPointerException npe) {
        throw npe;
    } catch (Exception e) {
        // ignore other exceptions
    }
    return result;
}
 
Example 20
Source File: ResourceBundle.java    From jdk8u_jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Determines if the expired <code>bundle</code> in the cache needs
 * to be reloaded based on the loading time given by
 * <code>loadTime</code> or some other criteria. The method returns
 * <code>true</code> if reloading is required; <code>false</code>
 * otherwise. <code>loadTime</code> is a millisecond offset since
 * the <a href="Calendar.html#Epoch"> <code>Calendar</code>
 * Epoch</a>.
 *
 * The calling <code>ResourceBundle.getBundle</code> factory method
 * calls this method on the <code>ResourceBundle.Control</code>
 * instance used for its current invocation, not on the instance
 * used in the invocation that originally loaded the resource
 * bundle.
 *
 * <p>The default implementation compares <code>loadTime</code> and
 * the last modified time of the source data of the resource
 * bundle. If it's determined that the source data has been modified
 * since <code>loadTime</code>, <code>true</code> is
 * returned. Otherwise, <code>false</code> is returned. This
 * implementation assumes that the given <code>format</code> is the
 * same string as its file suffix if it's not one of the default
 * formats, <code>"java.class"</code> or
 * <code>"java.properties"</code>.
 *
 * @param baseName
 *        the base bundle name of the resource bundle, a
 *        fully qualified class name
 * @param locale
 *        the locale for which the resource bundle
 *        should be instantiated
 * @param format
 *        the resource bundle format to be loaded
 * @param loader
 *        the <code>ClassLoader</code> to use to load the bundle
 * @param bundle
 *        the resource bundle instance that has been expired
 *        in the cache
 * @param loadTime
 *        the time when <code>bundle</code> was loaded and put
 *        in the cache
 * @return <code>true</code> if the expired bundle needs to be
 *        reloaded; <code>false</code> otherwise.
 * @exception NullPointerException
 *        if <code>baseName</code>, <code>locale</code>,
 *        <code>format</code>, <code>loader</code>, or
 *        <code>bundle</code> is <code>null</code>
 */
public boolean needsReload(String baseName, Locale locale,
                           String format, ClassLoader loader,
                           ResourceBundle bundle, long loadTime) {
    if (bundle == null) {
        throw new NullPointerException();
    }
    if (format.equals("java.class") || format.equals("java.properties")) {
        format = format.substring(5);
    }
    boolean result = false;
    try {
        String resourceName = toResourceName0(toBundleName(baseName, locale), format);
        if (resourceName == null) {
            return result;
        }
        URL url = loader.getResource(resourceName);
        if (url != null) {
            long lastModified = 0;
            URLConnection connection = url.openConnection();
            if (connection != null) {
                // disable caches to get the correct data
                connection.setUseCaches(false);
                if (connection instanceof JarURLConnection) {
                    JarEntry ent = ((JarURLConnection)connection).getJarEntry();
                    if (ent != null) {
                        lastModified = ent.getTime();
                        if (lastModified == -1) {
                            lastModified = 0;
                        }
                    }
                } else {
                    lastModified = connection.getLastModified();
                }
            }
            result = lastModified >= loadTime;
        }
    } catch (NullPointerException npe) {
        throw npe;
    } catch (Exception e) {
        // ignore other exceptions
    }
    return result;
}