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

The following examples show how to use java.net.URLConnection#getLastModified() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * 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
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
/**
 * 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
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
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
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
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 8
Source Project: ECTester   File: FileUtil.java    License: 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 9
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 10
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 11
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
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 Project: jimfs   File: UrlTest.java    License: 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 14
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 15
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 16
Source Project: enkan   File: HttpResponseUtils.java    License: 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 17
private long getLastModified() throws IOException {
    URLConnection urlConnection = docURL.openConnection();
    return urlConnection.getLastModified();
}
 
Example 18
/**
 * 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
/**
 * 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
/**
 * 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;
}