Example usage for java.net URLConnection setUseCaches

List of usage examples for java.net URLConnection setUseCaches

Introduction

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

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:org.jahia.services.render.scripting.bundle.BundleSourceResourceResolver.java

private boolean urlExists(URL url) {
    // Try a URL connection content-length header...
    try {//from   w  w w .ja  v  a 2s .  c  o  m
        URLConnection con = null;
        con = url.openConnection();
        con.setUseCaches(false);
        HttpURLConnection httpCon = (con instanceof HttpURLConnection ? (HttpURLConnection) con : null);
        if (httpCon != null) {
            httpCon.setRequestMethod("HEAD");
            if (httpCon.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return true;
            }
        }
        if (con.getContentLength() > 0) {
            return true;
        }
        if (httpCon != null) {
            // no HTTP OK status, and no content-length header: give up
            httpCon.disconnect();
            return false;
        } else {
            // Fall back to stream existence: can we open the stream?
            InputStream is = getInputStream(url);
            is.close();
            return true;
        }
    } catch (IOException e) {
        logger.debug("Testing existence of resource " + url, e);
        return false;
    }
}

From source file:ome.system.UpgradeCheck.java

/**
 * If the {@link #url} has been set to null or the empty string, then no
 * upgrade check will be performed (silently). If however the string is an
 * invalid URL, a warning will be printed.
 * /*  ww  w . ja  v a 2  s. com*/
 * This method should <em>never</em> throw an exception.
 */
public void run() {

    // If null or empty, the upgrade check is disabled.
    if (url == null || url.length() == 0) {
        return; // EARLY EXIT!
    }

    StringBuilder query = new StringBuilder();
    try {
        query.append(url);
        query.append("?version=");
        query.append(URLEncoder.encode(version, "UTF-8"));
        query.append(";os.name=");
        query.append(URLEncoder.encode(System.getProperty("os.name"), "UTF-8"));
        query.append(";os.arch=");
        query.append(URLEncoder.encode(System.getProperty("os.arch"), "UTF-8"));
        query.append(";os.version=");
        query.append(URLEncoder.encode(System.getProperty("os.version"), "UTF-8"));
        query.append(";java.runtime.version=");
        query.append(URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8"));
        query.append(";java.vm.vendor=");
        query.append(URLEncoder.encode(System.getProperty("java.vm.vendor"), "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        // Internal issue
        set(null, uee);
        return;
    }

    URL _url;
    try {
        _url = new URL(query.toString());
    } catch (Exception e) {
        set(null, e);
        log.error("Invalid URL: " + query.toString());
        return;
    }

    BufferedInputStream bufIn = null;
    try {
        URLConnection conn = _url.openConnection();
        conn.setUseCaches(false);
        conn.addRequestProperty("User-Agent", agent);
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        conn.connect();

        log.debug("Attempting to connect to " + query);

        InputStream in = conn.getInputStream();
        bufIn = new BufferedInputStream(in);

        StringBuilder sb = new StringBuilder();
        while (true) {
            int data = bufIn.read();
            if (data == -1) {
                break;
            } else {
                sb.append((char) data);
            }
        }
        String result = sb.toString();
        if (result.length() == 0) {
            log.info("no update needed");
            set(null, null);
        } else {
            log.warn("UPGRADE AVAILABLE:" + result);
            set(result, null);
        }
    } catch (UnknownHostException uhe) {
        log.error("Unknown host:" + url);
        set(null, uhe);
    } catch (IOException ioe) {
        log.error(String.format("Error reading from url: %s \"%s\"", query, ioe.getMessage()));
        set(null, ioe);
    } catch (Exception ex) {
        log.error("Unknown exception thrown on UpgradeCheck", ex);
        set(null, ex);
    } finally {
        Utils.closeQuietly(bufIn);
    }
}

From source file:rbcp.XMLResourceBundleControl.java

@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
        boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    if (baseName == null || locale == null || format == null || loader == null) {
        throw new NullPointerException();
    }/*from w  w w . j  a  va 2  s.  c  o m*/
    ResourceBundle bundle = null;
    if (format.equals("xml")) {
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, format);
        URL url = loader.getResource(resourceName);
        if (url != null) {
            URLConnection connection = url.openConnection();
            if (connection != null) {
                if (reload) {
                    // disable caches if reloading
                    connection.setUseCaches(false);
                }
                try (InputStream stream = connection.getInputStream()) {
                    if (stream != null) {
                        BufferedInputStream bis = new BufferedInputStream(stream);
                        bundle = new XMLResourceBundle(bis);
                    }
                }
            }
        }
    }
    return bundle;
}

From source file:eu.europa.ec.markt.dss.validation.tsp.OnlineTSPSource.java

/**
 * Get timestamp token - communications layer
 * // ww  w .  ja  v a2s . c  om
 * @return - byte[] - TSA response, raw bytes (RFC 3161 encoded)
 */
protected byte[] getTSAResponse(byte[] requestBytes) throws IOException {
    // Setup the TSA connection

    URL tspUrl = new URL(tspServer);
    URLConnection tsaConnection = tspUrl.openConnection();

    tsaConnection.setDoInput(true);
    tsaConnection.setDoOutput(true);
    tsaConnection.setUseCaches(false);
    tsaConnection.setRequestProperty("Content-Type", "application/timestamp-query");
    // tsaConnection.setRequestProperty("Content-Transfer-Encoding",
    // "base64");
    tsaConnection.setRequestProperty("Content-Transfer-Encoding", "binary");

    OutputStream out = tsaConnection.getOutputStream();
    out.write(requestBytes);
    out.close();

    // Get TSA response as a byte array
    InputStream inp = tsaConnection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = inp.read(buffer, 0, buffer.length)) >= 0) {
        baos.write(buffer, 0, bytesRead);
    }
    byte[] respBytes = baos.toByteArray();

    String encoding = tsaConnection.getContentEncoding();
    if (encoding != null && encoding.equalsIgnoreCase("base64")) {
        respBytes = new Base64().decode(respBytes);
    }
    return respBytes;
}

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

/**
 * Recupere la date du fichier dont le chemin est l'url
 * //from w  w  w  .  j a  v  a 2 s  .  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:de.xaniox.simpletrading.i18n.YMLControl.java

@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
        boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    Validate.notNull(baseName);//ww w. j  a va  2  s . c  om
    Validate.notNull(locale);
    Validate.notNull(format);
    Validate.notNull(loader);

    ResourceBundle bundle = null;

    if (YML_FORMAT.equals(format)) {
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, format);

        URL url = null;

        if (mode == I18N.LoadingMode.CLASSPATH) {
            //The mode forces us to load the resource from classpath
            url = getClass().getResource(classpathDir + resourceName);
        } else if (mode == I18N.LoadingMode.FILE_SYSTEM) {
            //If we use the file system mode, try to load the resource from file first
            //and load it from classpath if it fails
            File resourceFile = new File(localeDir, resourceName);

            if (resourceFile.exists() && resourceFile.isFile()) {
                url = resourceFile.toURI().toURL();
            } else {
                url = getClass().getResource(classpathDir + resourceName);
            }
        }

        if (url == null) {
            return null;
        }

        URLConnection connection = url.openConnection();
        if (reload) {
            connection.setUseCaches(false);
        }

        InputStream stream = connection.getInputStream();

        if (stream != null) {
            Reader reader = new InputStreamReader(stream, I18N.UTF8_CHARSET);
            YamlConfiguration config = new YamlConfiguration();

            StringBuilder builder;

            try (BufferedReader bufferedReader = new BufferedReader(reader)) {
                builder = new StringBuilder();

                String read;
                while ((read = bufferedReader.readLine()) != null) {
                    builder.append(read);
                    builder.append('\n');
                }
            }

            try {
                config.loadFromString(builder.toString());
            } catch (InvalidConfigurationException e) {
                throw new InstantiationException(e.getMessage());
            }

            bundle = new YMLResourceBundle(config);
        }
    } else {
        bundle = super.newBundle(baseName, locale, format, loader, reload);
    }

    return bundle;
}

From source file:de.xaniox.heavyspleef.core.i18n.YMLControl.java

@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
        boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    Validate.notNull(baseName);//from w w  w  . jav  a  2  s . c o  m
    Validate.notNull(locale);
    Validate.notNull(format);
    Validate.notNull(loader);

    ResourceBundle bundle = null;

    if (YML_FORMAT.equals(format)) {
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, format);

        URL url = null;

        if (mode == LoadingMode.CLASSPATH) {
            //The mode forces us to load the resource from classpath
            url = getClass().getResource(classpathDir + resourceName);
        } else if (mode == LoadingMode.FILE_SYSTEM) {
            //If we use the file system mode, try to load the resource from file first
            //and load it from classpath if it fails
            File resourceFile = new File(localeDir, resourceName);

            if (resourceFile.exists() && resourceFile.isFile()) {
                url = resourceFile.toURI().toURL();
            } else {
                url = getClass().getResource(classpathDir + resourceName);
            }
        }

        if (url == null) {
            return null;
        }

        URLConnection connection = url.openConnection();
        if (reload) {
            connection.setUseCaches(false);
        }

        InputStream stream = connection.getInputStream();

        if (stream != null) {
            Reader reader = new InputStreamReader(stream, I18N.UTF8_CHARSET);
            YamlConfiguration config = new YamlConfiguration();

            StringBuilder builder;

            try (BufferedReader bufferedReader = new BufferedReader(reader)) {
                builder = new StringBuilder();

                String read;
                while ((read = bufferedReader.readLine()) != null) {
                    builder.append(read);
                    builder.append('\n');
                }
            }

            try {
                config.loadFromString(builder.toString());
            } catch (InvalidConfigurationException e) {
                throw new InstantiationException(e.getMessage());
            }

            bundle = new YMLResourceBundle(config);
        }
    } else {
        bundle = super.newBundle(baseName, locale, format, loader, reload);
    }

    return bundle;
}

From source file:eu.europa.esig.dss.client.http.NativeHTTPDataLoader.java

@Override
public byte[] post(String url, byte[] content) {
    OutputStream out = null;//from  w  w  w.  j  a v a2  s . c o  m
    InputStream inputStream = null;
    byte[] result = null;
    try {
        URLConnection connection = new URL(url).openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        out = connection.getOutputStream();
        IOUtils.write(content, out);
        inputStream = connection.getInputStream();
        result = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        throw new DSSException("An error occured while HTTP POST for url '" + url + "' : " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(inputStream);
    }
    return result;
}

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

/**
 * @param url : URL//from  w ww.  j  av a 2 s .co m
 * @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;
}

From source file:de.matzefratze123.heavyspleef.core.i18n.YMLControl.java

@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
        boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    Validate.notNull(baseName);//from   ww w  .  j  ava  2s  .c  o  m
    Validate.notNull(locale);
    Validate.notNull(format);
    Validate.notNull(loader);

    ResourceBundle bundle = null;

    if (YML_FORMAT.equals(format)) {
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, format);

        URL url = null;

        if (classpath) {
            url = getClass().getResource(classpathDir + resourceName);
        } else {
            File resourceFile = new File(localeDir, resourceName);

            if (resourceFile.exists() && resourceFile.isFile()) {
                url = resourceFile.toURI().toURL();
            } else {
                url = getClass().getResource(classpathDir + resourceName);
            }
        }

        URLConnection connection = url.openConnection();
        if (reload) {
            connection.setUseCaches(false);
        }

        InputStream stream = connection.getInputStream();

        if (stream != null) {
            Reader reader = new InputStreamReader(stream, I18N.UTF8_CHARSET);
            YamlConfiguration config = new YamlConfiguration();

            StringBuilder builder;

            try (BufferedReader bufferedReader = new BufferedReader(reader)) {
                builder = new StringBuilder();

                String read;
                while ((read = bufferedReader.readLine()) != null) {
                    builder.append(read);
                    builder.append('\n');
                }
            }

            try {
                config.loadFromString(builder.toString());
            } catch (InvalidConfigurationException e) {
                throw new InstantiationException(e.getMessage());
            }

            bundle = new YMLResourceBundle(config, loadParent);
        }
    } else {
        bundle = super.newBundle(baseName, locale, format, loader, reload);
    }

    return bundle;
}