Example usage for java.net URLConnection getLastModified

List of usage examples for java.net URLConnection getLastModified

Introduction

In this page you can find the example usage for java.net URLConnection getLastModified.

Prototype

public long getLastModified() 

Source Link

Document

Returns the value of the last-modified header field.

Usage

From source file:ninja.AssetsController.java

private void streamOutUrlEntity(URL url, Context context, Result result) {
    // check if stream exists. if not print a notfound exception
    if (url == null) {
        context.finalizeHeadersWithoutFlashAndSessionCookie(Results.notFound());
    } else {//from w ww.jav a2s.co m
        try {
            URLConnection urlConnection = url.openConnection();
            Long lastModified = urlConnection.getLastModified();
            httpCacheToolkit.addEtag(context, result, lastModified);

            if (result.getStatusCode() == Result.SC_304_NOT_MODIFIED) {
                // Do not stream anything out. Simply return 304
                context.finalizeHeadersWithoutFlashAndSessionCookie(result);
            } else {
                result.status(200);

                // Try to set the mimetype:
                String mimeType = mimeTypes.getContentType(context, url.getFile());

                if (mimeType != null && !mimeType.isEmpty()) {
                    result.contentType(mimeType);
                }

                ResponseStreams responseStreams = context.finalizeHeadersWithoutFlashAndSessionCookie(result);

                try (InputStream inputStream = urlConnection.getInputStream();
                        OutputStream outputStream = responseStreams.getOutputStream()) {
                    ByteStreams.copy(inputStream, outputStream);
                }

            }

        } catch (IOException e) {
            logger.error("error streaming file", e);
        }

    }

}

From source file:org.mycore.common.xml.MCRXMLResource.java

public long getLastModified(String name, ClassLoader classLoader) throws IOException {
    URLConnection con = getResourceURLConnection(name, classLoader);
    try {//from  w w w .  j a  va 2 s . c om
        return con == null ? -1 : con.getLastModified();
    } finally {
        closeURLConnection(con);
    }
}

From source file:org.geoserver.wfs.notification.AbstractFileWatcher.java

public T load() throws IOException {
    if (shouldCheck()) {
        URLConnection conn = u.openConnection();
        nextCheckTime = System.currentTimeMillis() + CHECK_PERIOD;
        if (shouldUpdate(conn)) {
            T newData;/* ww  w  . j  a  va2 s. c  om*/
            try {
                newData = doLoad(conn);
                lastModTime = conn.getLastModified(); // Don't update until successful
            } catch (IOException e) {
                if (data == null || !oldDataAcceptable) {
                    // Check right away if we're throwing exceptions
                    nextCheckTime = 0;
                    throw e;
                }
                newData = data; // Use old data, but warn
                LOG.warn("Loading new data failed, using old data", e);
            }
            return data = newData;
        }
    }

    return data;
}

From source file:org.solmix.runtime.support.spring.ContainerXmlBeanDefinitionReader.java

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();
    }//ww w .j av  a  2s .  c  o m
    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 = null;
        URLConnection fixCon = null;
        resCon = resUrl.openConnection();
        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);
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.web.StaticContentServlet.java

private void prepareResponse(HttpServletResponse response, URL[] resources, String rawResourcePath)
        throws IOException {
    long lastModified = -1;
    int contentLength = 0;
    String mimeType = null;//  w  ww .j  a  v a  2s  .com
    for (int i = 0; i < resources.length; i++) {
        final URLConnection resourceConn = resources[i].openConnection();
        //Setting the last modified http for the requested resource
        if (resourceConn.getLastModified() > lastModified) {
            lastModified = resourceConn.getLastModified();
        }
        //Setting the mime type of the resource requested
        String currentMimeType = getServletContext().getMimeType(resources[i].getPath());
        if (log.isDebugEnabled()) {
            log.debug("Current MimeType: " + currentMimeType);
        }
        if (currentMimeType == null) {
            int index = resources[i].getPath().lastIndexOf('.');
            if (index > 0) {
                String extension = resources[i].getPath().substring(resources[i].getPath().lastIndexOf('.'));
                currentMimeType = (String) defaultMimeTypes.get(extension);
            } else {
                currentMimeType = "text/html"; //html will be the default mime.
            }
        }
        if (mimeType == null) {
            mimeType = currentMimeType;
        } else if (!mimeType.equals(currentMimeType)) {
            //This does not apply to us yet since we don't use combined resource url but maybe in the future ...
            throw new MalformedURLException("Combined resource path: " + rawResourcePath
                    + " is invalid. All resources in a combined resource path must be of the same mime type.");
        }
        contentLength += resourceConn.getContentLength();
    }
    response.setContentType(mimeType);
    response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(contentLength));
    response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified);
    if (cacheTimeout > 0) {
        configureCaching(response, cacheTimeout);
    }
}

From source file:org.squale.welcom.struts.webServer.URLManager.java

/**
 * Recupere la date du fichier dont le chemin est l'url
 * //  www  .  ja va2s  . c  o m
 * @param pUrl : L'url
 * @return : Date dir URL OK
 * @throws IOException Probleme sur l'ouverture de la connection
 */
public Date getURLDate(final URL pUrl) throws IOException {

    final URLConnection urlcon = pUrl.openConnection();
    urlcon.setUseCaches(true);
    urlcon.connect();
    return new Date(urlcon.getLastModified());

}

From source file:org.apache.tiles.definition.dao.BaseLocaleUrlDefinitionDAO.java

/** {@inheritDoc} */
public boolean refreshRequired() {
    boolean status = false;

    Set<String> urls = lastModifiedDates.keySet();

    try {/*ww w.j av  a 2 s  . com*/
        for (String urlPath : urls) {
            Long lastModifiedDate = lastModifiedDates.get(urlPath);
            URL url = new URL(urlPath);
            URLConnection connection = url.openConnection();
            connection.connect();
            long newModDate = connection.getLastModified();
            if (newModDate != lastModifiedDate) {
                status = true;
                break;
            }
        }
    } catch (Exception e) {
        log.warn("Exception while monitoring update times.", e);
        return true;
    }
    return status;
}

From source file:org.nmdp.service.epitope.task.URLProcessor.java

private long refreshFromUrl(URL url, Consumer<InputStream> consumer, long lastModified)
        throws MalformedURLException, IOException {
    logger.debug("trying url: " + url);
    long sourceLastModified = 0;
    final URLConnection urlConnection = url.openConnection();
    if (url.getProtocol().equalsIgnoreCase("ftp")) {
        sourceLastModified = getFtpLastModifiedTime(url);
    } else {//from ww w.j  a v a2 s.  co m
        sourceLastModified = urlConnection.getLastModified();
    }
    String sourceLastModifiedStr = dateFormat.format(sourceLastModified);
    String lastModifiedStr = dateFormat.format(lastModified);
    if (sourceLastModified == 0) {
        logger.warn("resource has no modification date, forcing refresh...");
    } else if (sourceLastModified < lastModified) {
        logger.warn("resource is older than last modification date (source: " + sourceLastModifiedStr
                + ", last: " + lastModifiedStr + "), leaving it");
        return lastModified;
    } else if (sourceLastModified == lastModified) {
        logger.debug("resource is current (modified: " + lastModifiedStr + ")");
        return lastModified;
    } else {
        logger.info("resource is newer than last modification date, refreshing (source: "
                + sourceLastModifiedStr + ", cache: " + lastModifiedStr + ")");
    }
    urlConnection.connect();
    InputStream is = urlConnection.getInputStream();
    if (unzip) {
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry = zis.getNextEntry();
        logger.info("unzipping, got zip entry: {}", entry.getName());
        is = zis;
    }
    consumer.accept(is);
    is.close();
    return sourceLastModified;
}

From source file:com.threewks.thundr.route.staticResource.StaticResourceRouteResolver.java

protected void serve(StaticResource action, Request request, Response response)
        throws ServletException, IOException {
    String resource = request.getRequestPath();
    URL resourceUrl = servletContext.getResource(resource);
    boolean allowed = isAllowed(resource);
    if (resourceUrl == null || !allowed) {
        response.withStatusCode(StatusCode.NotFound);
        Logger.info("%s -> %s not resolved: %s", resource, action, allowed ? "Not found" : "Not Permitted");
        return;/*from   w w w  .  j ava2s  . c  o  m*/
    }

    URLConnection urlConnection = resourceUrl.openConnection();
    String mimeType = deriveMimeType(resource);
    long contentLength = urlConnection.getContentLength();
    long lastModified = urlConnection.getLastModified();
    String acceptEncoding = request.getHeader(Header.AcceptEncoding);
    long cacheTimeSeconds = deriveCacheDuration(resource, mimeType);

    // TODO - v3 - Validate objects written to headers are serialized correctly - ints and dates mostly.
    // @formatter:off
    response.withContentType(mimeType)
            //response.setDateHeader(Header.Expires, System.currentTimeMillis() + cacheTimeSeconds * 1000L); // HTTP 1.0
            .withHeader(Header.Expires, System.currentTimeMillis() + cacheTimeSeconds * 1000L) // HTTP 1.0
            .withHeader(Header.CacheControl, String.format("max-age=%d, public", cacheTimeSeconds)) // HTTP 1.1
            .withHeader(Header.LastModified, lastModified);
    // @formatter:on

    OutputStream os = null;
    InputStream is = urlConnection.getInputStream();

    if (shouldZip(acceptEncoding, mimeType)) {
        HttpServletResponse resp = response.getRawResponse(HttpServletResponse.class);
        GzipResponseWrapper wrapper = new GzipResponseWrapper(resp);
        os = wrapper.getOutputStream();
        StreamUtil.copy(is, os);
        wrapper.finishResponse();
    } else {
        response.withHeader(Header.ContentLength, Long.toString(contentLength));
        os = response.getOutputStream();
        StreamUtil.copy(is, os);
        os.close();
    }

    response.withStatusCode(StatusCode.OK);
    Logger.debug("%s -> %s resolved as %s(%d bytes)", resource, action, mimeType, contentLength);
}

From source file:org.squale.welcom.addons.access.excel.UpdateAccessManager.java

/**
 * @param url : URL//from   www .  ja v a  2  s .com
 * @return La date de dernier emodification de l'url
 */
private Date getTimeUrl(final URL url) {
    try {
        final URLConnection urlCon = url.openConnection();
        urlCon.setUseCaches(false);
        urlCon.connect();
        return new Date(urlCon.getLastModified());
    } catch (final IOException e) {
        logStartup.error(e, e);
    }
    return null;
}