Java Code Examples for java.net.HttpURLConnection#HTTP_NOT_MODIFIED

The following examples show how to use java.net.HttpURLConnection#HTTP_NOT_MODIFIED . 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: ResponseHeaders.java    From phonegapbootcampsite with MIT License 6 votes vote down vote up
/**
 * Returns true if this cached response should be used; false if the
 * network response should be used.
 */
public boolean validate(ResponseHeaders networkResponse) {
  if (networkResponse.headers.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
    return true;
  }

  // The HTTP spec says that if the network's response is older than our
  // cached response, we may return the cache's response. Like Chrome (but
  // unlike Firefox), this client prefers to return the newer response.
  if (lastModified != null
      && networkResponse.lastModified != null
      && networkResponse.lastModified.getTime() < lastModified.getTime()) {
    return true;
  }

  return false;
}
 
Example 2
Source File: ResponseHeaders.java    From L.TileLayer.Cordova with MIT License 6 votes vote down vote up
/**
 * Returns true if this cached response should be used; false if the
 * network response should be used.
 */
public boolean validate(ResponseHeaders networkResponse) {
  if (networkResponse.headers.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
    return true;
  }

  // The HTTP spec says that if the network's response is older than our
  // cached response, we may return the cache's response. Like Chrome (but
  // unlike Firefox), this client prefers to return the newer response.
  if (lastModified != null
      && networkResponse.lastModified != null
      && networkResponse.lastModified.getTime() < lastModified.getTime()) {
    return true;
  }

  return false;
}
 
Example 3
Source File: ResponseHeaders.java    From bluemix-parking-meter with MIT License 6 votes vote down vote up
/**
 * Returns true if this cached response should be used; false if the
 * network response should be used.
 */
public boolean validate(ResponseHeaders networkResponse) {
  if (networkResponse.headers.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
    return true;
  }

  // The HTTP spec says that if the network's response is older than our
  // cached response, we may return the cache's response. Like Chrome (but
  // unlike Firefox), this client prefers to return the newer response.
  if (lastModified != null
      && networkResponse.lastModified != null
      && networkResponse.lastModified.getTime() < lastModified.getTime()) {
    return true;
  }

  return false;
}
 
Example 4
Source File: ResponseHeaders.java    From cordova-android-chromeview with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if this cached response should be used; false if the
 * network response should be used.
 */
public boolean validate(ResponseHeaders networkResponse) {
  if (networkResponse.headers.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
    return true;
  }

  // The HTTP spec says that if the network's response is older than our
  // cached response, we may return the cache's response. Like Chrome (but
  // unlike Firefox), this client prefers to return the newer response.
  if (lastModified != null
      && networkResponse.lastModified != null
      && networkResponse.lastModified.getTime() < lastModified.getTime()) {
    return true;
  }

  return false;
}
 
Example 5
Source File: ResponseHeaders.java    From wildfly-samples with MIT License 6 votes vote down vote up
/**
 * Returns true if this cached response should be used; false if the
 * network response should be used.
 */
public boolean validate(ResponseHeaders networkResponse) {
  if (networkResponse.headers.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
    return true;
  }

  // The HTTP spec says that if the network's response is older than our
  // cached response, we may return the cache's response. Like Chrome (but
  // unlike Firefox), this client prefers to return the newer response.
  if (lastModified != null
      && networkResponse.lastModified != null
      && networkResponse.lastModified.getTime() < lastModified.getTime()) {
    return true;
  }

  return false;
}
 
Example 6
Source File: HttpClientUtil.java    From Dragonfly with Apache License 2.0 5 votes vote down vote up
public static boolean isExpired(String fileUrl, long lastModified, String[] headers) throws MalformedURLException {
    if (lastModified <= 0) {
        return true;
    }
    int times = 2;
    HttpURLConnection conn = null;
    URL url = new URL(fileUrl);
    int code;
    while (times-- > 0) {
        try {
            conn = openConnection(url);
            fillHeaders(conn, headers);
            conn.setUseCaches(false);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(1000);
            conn.setIfModifiedSince(lastModified);

            conn.connect();
            code = conn.getResponseCode();
            if (REDIRECTED_CODE.contains(code)) {
                fileUrl = conn.getHeaderField("Location");
                if (StringUtils.isNotBlank(fileUrl)) {
                    return isExpired(fileUrl, lastModified, null);
                }
            }
            if (code == HttpURLConnection.HTTP_NOT_MODIFIED) {
                return false;
            }
            break;
        } catch (Exception e) {
            logger.warn("url:{} isExpired error", fileUrl, e);
        } finally {
            closeConn(conn);
            conn = null;
        }
    }
    return true;
}
 
Example 7
Source File: BasicNetworkTest.java    From volley with Apache License 2.0 5 votes vote down vote up
@Test
public void notModified() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    List<Header> headers = new ArrayList<>();
    headers.add(new Header("ServerKeyA", "ServerValueA"));
    headers.add(new Header("ServerKeyB", "ServerValueB"));
    headers.add(new Header("SharedKey", "ServerValueShared"));
    headers.add(new Header("sharedcaseinsensitivekey", "ServerValueShared1"));
    headers.add(new Header("SharedCaseInsensitiveKey", "ServerValueShared2"));
    HttpResponse fakeResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_MODIFIED, headers);
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    Entry entry = new Entry();
    entry.allResponseHeaders = new ArrayList<>();
    entry.allResponseHeaders.add(new Header("CachedKeyA", "CachedValueA"));
    entry.allResponseHeaders.add(new Header("CachedKeyB", "CachedValueB"));
    entry.allResponseHeaders.add(new Header("SharedKey", "CachedValueShared"));
    entry.allResponseHeaders.add(new Header("SHAREDCASEINSENSITIVEKEY", "CachedValueShared1"));
    entry.allResponseHeaders.add(new Header("shAREDcaSEinSENSITIVEkeY", "CachedValueShared2"));
    request.setCacheEntry(entry);
    NetworkResponse response = httpNetwork.performRequest(request);
    List<Header> expectedHeaders = new ArrayList<>();
    // Should have all server headers + cache headers that didn't show up in server response.
    expectedHeaders.add(new Header("ServerKeyA", "ServerValueA"));
    expectedHeaders.add(new Header("ServerKeyB", "ServerValueB"));
    expectedHeaders.add(new Header("SharedKey", "ServerValueShared"));
    expectedHeaders.add(new Header("sharedcaseinsensitivekey", "ServerValueShared1"));
    expectedHeaders.add(new Header("SharedCaseInsensitiveKey", "ServerValueShared2"));
    expectedHeaders.add(new Header("CachedKeyA", "CachedValueA"));
    expectedHeaders.add(new Header("CachedKeyB", "CachedValueB"));
    assertThat(expectedHeaders, containsInAnyOrder(response.allHeaders.toArray(new Header[0])));
}
 
Example 8
Source File: BasicNetworkTest.java    From volley with Apache License 2.0 5 votes vote down vote up
@Test
public void notModified_legacyCache() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    List<Header> headers = new ArrayList<>();
    headers.add(new Header("ServerKeyA", "ServerValueA"));
    headers.add(new Header("ServerKeyB", "ServerValueB"));
    headers.add(new Header("SharedKey", "ServerValueShared"));
    headers.add(new Header("sharedcaseinsensitivekey", "ServerValueShared1"));
    headers.add(new Header("SharedCaseInsensitiveKey", "ServerValueShared2"));
    HttpResponse fakeResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_MODIFIED, headers);
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    Entry entry = new Entry();
    entry.responseHeaders = new HashMap<>();
    entry.responseHeaders.put("CachedKeyA", "CachedValueA");
    entry.responseHeaders.put("CachedKeyB", "CachedValueB");
    entry.responseHeaders.put("SharedKey", "CachedValueShared");
    entry.responseHeaders.put("SHAREDCASEINSENSITIVEKEY", "CachedValueShared1");
    entry.responseHeaders.put("shAREDcaSEinSENSITIVEkeY", "CachedValueShared2");
    request.setCacheEntry(entry);
    NetworkResponse response = httpNetwork.performRequest(request);
    List<Header> expectedHeaders = new ArrayList<>();
    // Should have all server headers + cache headers that didn't show up in server response.
    expectedHeaders.add(new Header("ServerKeyA", "ServerValueA"));
    expectedHeaders.add(new Header("ServerKeyB", "ServerValueB"));
    expectedHeaders.add(new Header("SharedKey", "ServerValueShared"));
    expectedHeaders.add(new Header("sharedcaseinsensitivekey", "ServerValueShared1"));
    expectedHeaders.add(new Header("SharedCaseInsensitiveKey", "ServerValueShared2"));
    expectedHeaders.add(new Header("CachedKeyA", "CachedValueA"));
    expectedHeaders.add(new Header("CachedKeyB", "CachedValueB"));
    assertThat(expectedHeaders, containsInAnyOrder(response.allHeaders.toArray(new Header[0])));
}
 
Example 9
Source File: UrlModuleSourceProvider.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
private boolean isResourceChanged(URLConnection urlConnection)
throws IOException {
    if(urlConnection instanceof HttpURLConnection) {
        return ((HttpURLConnection)urlConnection).getResponseCode() ==
            HttpURLConnection.HTTP_NOT_MODIFIED;
    }
    return lastModified == urlConnection.getLastModified();
}
 
Example 10
Source File: Showcase.java    From yandex-money-sdk-java with MIT License 5 votes vote down vote up
@Override
public ShowcaseContext parse(HttpClientResponse response) throws Exception {
    InputStream inputStream = null;
    try {
        switch (response.getCode()) {
            case HttpURLConnection.HTTP_MULT_CHOICE:
                DateTime dateModified = parseDateHeader(response, HttpHeaders.LAST_MODIFIED);
                final String location = response.getHeader(HttpHeaders.LOCATION);

                inputStream = response.getByteStream();
                Showcase showcase = ShowcaseTypeAdapter.getInstance().fromJson(inputStream);
                ShowcaseContext showcaseContext = new ShowcaseContext(showcase, location, dateModified);
                showcaseContext.setState(ShowcaseContext.State.HAS_NEXT_STEP);
                return showcaseContext;
            case HttpURLConnection.HTTP_NOT_MODIFIED: {
                return new ShowcaseContext(ShowcaseContext.State.NOT_MODIFIED);
            }
            case HttpURLConnection.HTTP_MOVED_PERM:
                // todo create new request and call it
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new ResourceNotFoundException(response.getUrl());
            default:
                throw new IOException(processError(response));
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}
 
Example 11
Source File: AbstractQuery.java    From AndroidStarter with Apache License 2.0 5 votes vote down vote up
protected <T> boolean isCached(@NonNull final Response<T> poResponse) {
    if (poResponse.isSuccessful() &&
            (
                    (poResponse.raw().networkResponse() != null && poResponse.raw().networkResponse().code() == HttpURLConnection.HTTP_NOT_MODIFIED)
                            ||
                            (poResponse.raw().networkResponse() == null && poResponse.raw().cacheResponse() != null))
            ) {
        return true;
    }
    return false;
}
 
Example 12
Source File: GeoIpService.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Downloads the archive to the destination file if it's newer than the locally version.
 *
 * @param lastModified modification timestamp of the already present file
 * @param destination save file
 * @return null if no updates were found, the MD5 hash of the downloaded archive if successful
 * @throws IOException if failed during downloading and writing to destination file
 */
private String downloadDatabaseArchive(Instant lastModified, Path destination) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(ARCHIVE_URL).openConnection();

    String clientId = settings.getProperty(ProtectionSettings.MAXMIND_API_CLIENT_ID);
    String licenseKey = settings.getProperty(ProtectionSettings.MAXMIND_API_LICENSE_KEY);
    if (clientId.isEmpty() || licenseKey.isEmpty()) {
        logger.warning("No MaxMind credentials found in the configuration file!"
            + " GeoIp protections will be disabled.");
        return null;
    }
    String basicAuth = "Basic " + new String(Base64.getEncoder().encode((clientId + ":" + licenseKey).getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);

    if (lastModified != null) {
        // Only download if we actually need a newer version - this field is specified in GMT zone
        ZonedDateTime zonedTime = lastModified.atZone(ZoneId.of("GMT"));
        String timeFormat = DateTimeFormatter.RFC_1123_DATE_TIME.format(zonedTime);
        connection.addRequestProperty("If-Modified-Since", timeFormat);
    }

    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
        //we already have the newest version
        connection.getInputStream().close();
        return null;
    }

    String hash = connection.getHeaderField("X-Database-MD5");
    String rawModifiedDate = connection.getHeaderField("Last-Modified");
    Instant modifiedDate = Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rawModifiedDate));
    Files.copy(connection.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING);
    Files.setLastModifiedTime(destination, FileTime.from(modifiedDate));
    return hash;
}
 
Example 13
Source File: URICertStore.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a <code>Collection</code> of <code>X509Certificate</code>s that
 * match the specified selector. If no <code>X509Certificate</code>s
 * match the selector, an empty <code>Collection</code> will be returned.
 *
 * @param selector a <code>CertSelector</code> used to select which
 *  <code>X509Certificate</code>s should be returned. Specify
 *  <code>null</code> to return all <code>X509Certificate</code>s.
 * @return a <code>Collection</code> of <code>X509Certificate</code>s that
 *         match the specified selector
 * @throws CertStoreException if an exception occurs
 */
@Override
@SuppressWarnings("unchecked")
public synchronized Collection<X509Certificate> engineGetCertificates
    (CertSelector selector) throws CertStoreException {

    // if ldap URI we wrap the CertSelector in an LDAPCertSelector to
    // avoid LDAP DN matching issues (see LDAPCertSelector for more info)
    if (ldap) {
        X509CertSelector xsel = (X509CertSelector) selector;
        try {
            xsel = ldapHelper.wrap(xsel, xsel.getSubject(), ldapPath);
        } catch (IOException ioe) {
            throw new CertStoreException(ioe);
        }
        // Fetch the certificates via LDAP. LDAPCertStore has its own
        // caching mechanism, see the class description for more info.
        // Safe cast since xsel is an X509 certificate selector.
        return (Collection<X509Certificate>)
            ldapCertStore.getCertificates(xsel);
    }

    // Return the Certificates for this entry. It returns the cached value
    // if it is still current and fetches the Certificates otherwise.
    // For the caching details, see the top of this class.
    long time = System.currentTimeMillis();
    if (time - lastChecked < CHECK_INTERVAL) {
        if (debug != null) {
            debug.println("Returning certificates from cache");
        }
        return getMatchingCerts(certs, selector);
    }
    lastChecked = time;
    try {
        URLConnection connection = uri.toURL().openConnection();
        if (lastModified != 0) {
            connection.setIfModifiedSince(lastModified);
        }
        long oldLastModified = lastModified;
        try (InputStream in = connection.getInputStream()) {
            lastModified = connection.getLastModified();
            if (oldLastModified != 0) {
                if (oldLastModified == lastModified) {
                    if (debug != null) {
                        debug.println("Not modified, using cached copy");
                    }
                    return getMatchingCerts(certs, selector);
                } else if (connection instanceof HttpURLConnection) {
                    // some proxy servers omit last modified
                    HttpURLConnection hconn = (HttpURLConnection)connection;
                    if (hconn.getResponseCode()
                                == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        if (debug != null) {
                            debug.println("Not modified, using cached copy");
                        }
                        return getMatchingCerts(certs, selector);
                    }
                }
            }
            if (debug != null) {
                debug.println("Downloading new certificates...");
            }
            // Safe cast since factory is an X.509 certificate factory
            certs = (Collection<X509Certificate>)
                factory.generateCertificates(in);
        }
        return getMatchingCerts(certs, selector);
    } catch (IOException | CertificateException e) {
        if (debug != null) {
            debug.println("Exception fetching certificates:");
            e.printStackTrace();
        }
    }
    // exception, forget previous values
    lastModified = 0;
    certs = Collections.emptySet();
    return certs;
}
 
Example 14
Source File: URICertStore.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
     * Returns a <code>Collection</code> of <code>X509Certificate</code>s that
     * match the specified selector. If no <code>X509Certificate</code>s
     * match the selector, an empty <code>Collection</code> will be returned.
     *
     * @param selector a <code>CertSelector</code> used to select which
     *  <code>X509Certificate</code>s should be returned. Specify
     *  <code>null</code> to return all <code>X509Certificate</code>s.
     * @return a <code>Collection</code> of <code>X509Certificate</code>s that
     *         match the specified selector
     * @throws CertStoreException if an exception occurs
     */
    @Override
    @SuppressWarnings("unchecked")
    public synchronized Collection<X509Certificate> engineGetCertificates
        (CertSelector selector) throws CertStoreException {

        // if ldap URI we wrap the CertSelector in an LDAPCertSelector to
        // avoid LDAP DN matching issues (see LDAPCertSelector for more info)
//        if (ldap) {
//            X509CertSelector xsel = (X509CertSelector) selector;
//            try {
//                xsel = ldapHelper.wrap(xsel, xsel.getSubject(), ldapPath);
//            } catch (IOException ioe) {
//                throw new CertStoreException(ioe);
//            }
//            // Fetch the certificates via LDAP. LDAPCertStore has its own
//            // caching mechanism, see the class description for more info.
//            // Safe cast since xsel is an X509 certificate selector.
//            return (Collection<X509Certificate>)
//                ldapCertStore.getCertificates(xsel);
//        }

        // Return the Certificates for this entry. It returns the cached value
        // if it is still current and fetches the Certificates otherwise.
        // For the caching details, see the top of this class.
        long time = System.currentTimeMillis();
        if (time - lastChecked < CHECK_INTERVAL) {
            if (debug != null) {
                debug.println("Returning certificates from cache");
            }
            return getMatchingCerts(certs, selector);
        }
        lastChecked = time;
        try {
            URLConnection connection = uri.toURL().openConnection();
            if (lastModified != 0) {
                connection.setIfModifiedSince(lastModified);
            }
            long oldLastModified = lastModified;
            try (InputStream in = connection.getInputStream()) {
                lastModified = connection.getLastModified();
                if (oldLastModified != 0) {
                    if (oldLastModified == lastModified) {
                        if (debug != null) {
                            debug.println("Not modified, using cached copy");
                        }
                        return getMatchingCerts(certs, selector);
                    } else if (connection instanceof HttpURLConnection) {
                        // some proxy servers omit last modified
                        HttpURLConnection hconn = (HttpURLConnection)connection;
                        if (hconn.getResponseCode()
                                    == HttpURLConnection.HTTP_NOT_MODIFIED) {
                            if (debug != null) {
                                debug.println("Not modified, using cached copy");
                            }
                            return getMatchingCerts(certs, selector);
                        }
                    }
                }
                if (debug != null) {
                    debug.println("Downloading new certificates...");
                }
                // Safe cast since factory is an X.509 certificate factory
                certs = (Collection<X509Certificate>)
                    factory.generateCertificates(in);
            }
            return getMatchingCerts(certs, selector);
        } catch (IOException | CertificateException e) {
            if (debug != null) {
                debug.println("Exception fetching certificates:");
                e.printStackTrace();
            }
        }
        // exception, forget previous values
        lastModified = 0;
        certs = Collections.emptySet();
        return certs;
    }
 
Example 15
Source File: URICertStore.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a <code>Collection</code> of <code>X509Certificate</code>s that
 * match the specified selector. If no <code>X509Certificate</code>s
 * match the selector, an empty <code>Collection</code> will be returned.
 *
 * @param selector a <code>CertSelector</code> used to select which
 *  <code>X509Certificate</code>s should be returned. Specify
 *  <code>null</code> to return all <code>X509Certificate</code>s.
 * @return a <code>Collection</code> of <code>X509Certificate</code>s that
 *         match the specified selector
 * @throws CertStoreException if an exception occurs
 */
@Override
@SuppressWarnings("unchecked")
public synchronized Collection<X509Certificate> engineGetCertificates
    (CertSelector selector) throws CertStoreException {

    // if ldap URI we wrap the CertSelector in an LDAPCertSelector to
    // avoid LDAP DN matching issues (see LDAPCertSelector for more info)
    if (ldap) {
        X509CertSelector xsel = (X509CertSelector) selector;
        try {
            xsel = ldapHelper.wrap(xsel, xsel.getSubject(), ldapPath);
        } catch (IOException ioe) {
            throw new CertStoreException(ioe);
        }
        // Fetch the certificates via LDAP. LDAPCertStore has its own
        // caching mechanism, see the class description for more info.
        // Safe cast since xsel is an X509 certificate selector.
        return (Collection<X509Certificate>)
            ldapCertStore.getCertificates(xsel);
    }

    // Return the Certificates for this entry. It returns the cached value
    // if it is still current and fetches the Certificates otherwise.
    // For the caching details, see the top of this class.
    long time = System.currentTimeMillis();
    if (time - lastChecked < CHECK_INTERVAL) {
        if (debug != null) {
            debug.println("Returning certificates from cache");
        }
        return getMatchingCerts(certs, selector);
    }
    lastChecked = time;
    try {
        URLConnection connection = uri.toURL().openConnection();
        if (lastModified != 0) {
            connection.setIfModifiedSince(lastModified);
        }
        long oldLastModified = lastModified;
        try (InputStream in = connection.getInputStream()) {
            lastModified = connection.getLastModified();
            if (oldLastModified != 0) {
                if (oldLastModified == lastModified) {
                    if (debug != null) {
                        debug.println("Not modified, using cached copy");
                    }
                    return getMatchingCerts(certs, selector);
                } else if (connection instanceof HttpURLConnection) {
                    // some proxy servers omit last modified
                    HttpURLConnection hconn = (HttpURLConnection)connection;
                    if (hconn.getResponseCode()
                                == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        if (debug != null) {
                            debug.println("Not modified, using cached copy");
                        }
                        return getMatchingCerts(certs, selector);
                    }
                }
            }
            if (debug != null) {
                debug.println("Downloading new certificates...");
            }
            // Safe cast since factory is an X.509 certificate factory
            certs = (Collection<X509Certificate>)
                factory.generateCertificates(in);
        }
        return getMatchingCerts(certs, selector);
    } catch (IOException | CertificateException e) {
        if (debug != null) {
            debug.println("Exception fetching certificates:");
            e.printStackTrace();
        }
    }
    // exception, forget previous values
    lastModified = 0;
    certs = Collections.emptySet();
    return certs;
}
 
Example 16
Source File: URICertStore.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a <code>Collection</code> of <code>X509Certificate</code>s that
 * match the specified selector. If no <code>X509Certificate</code>s
 * match the selector, an empty <code>Collection</code> will be returned.
 *
 * @param selector a <code>CertSelector</code> used to select which
 *  <code>X509Certificate</code>s should be returned. Specify
 *  <code>null</code> to return all <code>X509Certificate</code>s.
 * @return a <code>Collection</code> of <code>X509Certificate</code>s that
 *         match the specified selector
 * @throws CertStoreException if an exception occurs
 */
@Override
@SuppressWarnings("unchecked")
public synchronized Collection<X509Certificate> engineGetCertificates
    (CertSelector selector) throws CertStoreException {

    if (ldap) {
        // caching mechanism, see the class description for more info.
        return (Collection<X509Certificate>)
            ldapCertStore.getCertificates(selector);
    }

    // Return the Certificates for this entry. It returns the cached value
    // if it is still current and fetches the Certificates otherwise.
    // For the caching details, see the top of this class.
    long time = System.currentTimeMillis();
    if (time - lastChecked < CHECK_INTERVAL) {
        if (debug != null) {
            debug.println("Returning certificates from cache");
        }
        return getMatchingCerts(certs, selector);
    }
    lastChecked = time;
    try {
        URLConnection connection = uri.toURL().openConnection();
        if (lastModified != 0) {
            connection.setIfModifiedSince(lastModified);
        }
        long oldLastModified = lastModified;
        try (InputStream in = connection.getInputStream()) {
            lastModified = connection.getLastModified();
            if (oldLastModified != 0) {
                if (oldLastModified == lastModified) {
                    if (debug != null) {
                        debug.println("Not modified, using cached copy");
                    }
                    return getMatchingCerts(certs, selector);
                } else if (connection instanceof HttpURLConnection) {
                    // some proxy servers omit last modified
                    HttpURLConnection hconn = (HttpURLConnection)connection;
                    if (hconn.getResponseCode()
                                == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        if (debug != null) {
                            debug.println("Not modified, using cached copy");
                        }
                        return getMatchingCerts(certs, selector);
                    }
                }
            }
            if (debug != null) {
                debug.println("Downloading new certificates...");
            }
            // Safe cast since factory is an X.509 certificate factory
            certs = (Collection<X509Certificate>)
                factory.generateCertificates(in);
        }
        return getMatchingCerts(certs, selector);
    } catch (IOException | CertificateException e) {
        if (debug != null) {
            debug.println("Exception fetching certificates:");
            e.printStackTrace();
        }
    }
    // exception, forget previous values
    lastModified = 0;
    certs = Collections.emptySet();
    return certs;
}
 
Example 17
Source File: Sentry.java    From Sentry-Android with MIT License 4 votes vote down vote up
/**
 * Map from HTTP status code to reason description.
 * Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
 * This function implements a look-up table with a default value for unknown status-codes.
 * @param statusCode an integer HTTP status code, expected to be in the range [200,505].
 * @return a non-empty string in all cases.
 */
private static String httpReason(int statusCode) {
    switch (statusCode) {
        // 2xx
        case HttpURLConnection.HTTP_OK: return "OK";
        case HttpURLConnection.HTTP_CREATED: return "Created";
        case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
        case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
        case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
        case HttpURLConnection.HTTP_RESET: return "Reset Content";
        case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";

        // 3xx
        case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
        case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
        case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
        case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
        case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
        case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";

        // 4xx
        case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
        case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
        case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
        case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
        case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
        case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
        case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
        case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
        case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
        case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
        case HttpURLConnection.HTTP_GONE: return "Gone";
        case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
        case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
        case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
        case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";

        // 5xx
        case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
        case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
        case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
        case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
        case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";

        default: return "unknown";
    }
}
 
Example 18
Source File: URICertStore.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a <code>Collection</code> of <code>X509Certificate</code>s that
 * match the specified selector. If no <code>X509Certificate</code>s
 * match the selector, an empty <code>Collection</code> will be returned.
 *
 * @param selector a <code>CertSelector</code> used to select which
 *  <code>X509Certificate</code>s should be returned. Specify
 *  <code>null</code> to return all <code>X509Certificate</code>s.
 * @return a <code>Collection</code> of <code>X509Certificate</code>s that
 *         match the specified selector
 * @throws CertStoreException if an exception occurs
 */
@Override
@SuppressWarnings("unchecked")
public synchronized Collection<X509Certificate> engineGetCertificates
    (CertSelector selector) throws CertStoreException {

    if (ldap) {
        // caching mechanism, see the class description for more info.
        return (Collection<X509Certificate>)
            ldapCertStore.getCertificates(selector);
    }

    // Return the Certificates for this entry. It returns the cached value
    // if it is still current and fetches the Certificates otherwise.
    // For the caching details, see the top of this class.
    long time = System.currentTimeMillis();
    if (time - lastChecked < CHECK_INTERVAL) {
        if (debug != null) {
            debug.println("Returning certificates from cache");
        }
        return getMatchingCerts(certs, selector);
    }
    lastChecked = time;
    try {
        URLConnection connection = uri.toURL().openConnection();
        if (lastModified != 0) {
            connection.setIfModifiedSince(lastModified);
        }
        long oldLastModified = lastModified;
        try (InputStream in = connection.getInputStream()) {
            lastModified = connection.getLastModified();
            if (oldLastModified != 0) {
                if (oldLastModified == lastModified) {
                    if (debug != null) {
                        debug.println("Not modified, using cached copy");
                    }
                    return getMatchingCerts(certs, selector);
                } else if (connection instanceof HttpURLConnection) {
                    // some proxy servers omit last modified
                    HttpURLConnection hconn = (HttpURLConnection)connection;
                    if (hconn.getResponseCode()
                                == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        if (debug != null) {
                            debug.println("Not modified, using cached copy");
                        }
                        return getMatchingCerts(certs, selector);
                    }
                }
            }
            if (debug != null) {
                debug.println("Downloading new certificates...");
            }
            // Safe cast since factory is an X.509 certificate factory
            certs = (Collection<X509Certificate>)
                factory.generateCertificates(in);
        }
        return getMatchingCerts(certs, selector);
    } catch (IOException | CertificateException e) {
        if (debug != null) {
            debug.println("Exception fetching certificates:");
            e.printStackTrace();
        }
    }
    // exception, forget previous values
    lastModified = 0;
    certs = Collections.emptySet();
    return certs;
}
 
Example 19
Source File: URICertStore.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a <code>Collection</code> of <code>X509Certificate</code>s that
 * match the specified selector. If no <code>X509Certificate</code>s
 * match the selector, an empty <code>Collection</code> will be returned.
 *
 * @param selector a <code>CertSelector</code> used to select which
 *  <code>X509Certificate</code>s should be returned. Specify
 *  <code>null</code> to return all <code>X509Certificate</code>s.
 * @return a <code>Collection</code> of <code>X509Certificate</code>s that
 *         match the specified selector
 * @throws CertStoreException if an exception occurs
 */
@Override
@SuppressWarnings("unchecked")
public synchronized Collection<X509Certificate> engineGetCertificates
    (CertSelector selector) throws CertStoreException {

    // if ldap URI we wrap the CertSelector in an LDAPCertSelector to
    // avoid LDAP DN matching issues (see LDAPCertSelector for more info)
    if (ldap) {
        X509CertSelector xsel = (X509CertSelector) selector;
        try {
            xsel = ldapHelper.wrap(xsel, xsel.getSubject(), ldapPath);
        } catch (IOException ioe) {
            throw new CertStoreException(ioe);
        }
        // Fetch the certificates via LDAP. LDAPCertStore has its own
        // caching mechanism, see the class description for more info.
        // Safe cast since xsel is an X509 certificate selector.
        return (Collection<X509Certificate>)
            ldapCertStore.getCertificates(xsel);
    }

    // Return the Certificates for this entry. It returns the cached value
    // if it is still current and fetches the Certificates otherwise.
    // For the caching details, see the top of this class.
    long time = System.currentTimeMillis();
    if (time - lastChecked < CHECK_INTERVAL) {
        if (debug != null) {
            debug.println("Returning certificates from cache");
        }
        return getMatchingCerts(certs, selector);
    }
    lastChecked = time;
    try {
        URLConnection connection = uri.toURL().openConnection();
        if (lastModified != 0) {
            connection.setIfModifiedSince(lastModified);
        }
        long oldLastModified = lastModified;
        try (InputStream in = connection.getInputStream()) {
            lastModified = connection.getLastModified();
            if (oldLastModified != 0) {
                if (oldLastModified == lastModified) {
                    if (debug != null) {
                        debug.println("Not modified, using cached copy");
                    }
                    return getMatchingCerts(certs, selector);
                } else if (connection instanceof HttpURLConnection) {
                    // some proxy servers omit last modified
                    HttpURLConnection hconn = (HttpURLConnection)connection;
                    if (hconn.getResponseCode()
                                == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        if (debug != null) {
                            debug.println("Not modified, using cached copy");
                        }
                        return getMatchingCerts(certs, selector);
                    }
                }
            }
            if (debug != null) {
                debug.println("Downloading new certificates...");
            }
            // Safe cast since factory is an X.509 certificate factory
            certs = (Collection<X509Certificate>)
                factory.generateCertificates(in);
        }
        return getMatchingCerts(certs, selector);
    } catch (IOException | CertificateException e) {
        if (debug != null) {
            debug.println("Exception fetching certificates:");
            e.printStackTrace();
        }
    }
    // exception, forget previous values
    lastModified = 0;
    certs = Collections.emptySet();
    return certs;
}
 
Example 20
Source File: HurlStack.java    From volley with Apache License 2.0 3 votes vote down vote up
/**
 * Checks if a response message contains a body.
 *
 * @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
 * @param requestMethod request method
 * @param responseCode response status code
 * @return whether the response has a body
 */
private static boolean hasResponseBody(int requestMethod, int responseCode) {
    return requestMethod != Request.Method.HEAD
            && !(HTTP_CONTINUE <= responseCode && responseCode < HttpURLConnection.HTTP_OK)
            && responseCode != HttpURLConnection.HTTP_NO_CONTENT
            && responseCode != HttpURLConnection.HTTP_NOT_MODIFIED;
}