AbstractUpdateOperation.java

  1. /*******************************************************************************
  2.  * Copyright 2013 André Rouél
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *   http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  ******************************************************************************/
  16. package net.sf.uadetector.datastore;

  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.InputStreamReader;
  20. import java.io.LineNumberReader;
  21. import java.net.URL;
  22. import java.nio.charset.Charset;
  23. import java.util.concurrent.ExecutorService;
  24. import java.util.regex.Pattern;

  25. import javax.annotation.Nonnull;
  26. import javax.annotation.Nullable;

  27. import net.sf.qualitycheck.Check;
  28. import net.sf.uadetector.internal.util.ExecutorServices;

  29. import org.slf4j.Logger;
  30. import org.slf4j.LoggerFactory;

  31. /**
  32.  * Provides a basic implementation to update UAS data in the background when calling {@link #run()}.
  33.  *
  34.  * @author André Rouél
  35.  */
  36. public abstract class AbstractUpdateOperation implements UpdateOperation {

  37.     /**
  38.      * Defines an empty version string
  39.      */
  40.     private static final String EMPTY_VERSION = "";

  41.     /**
  42.      * Corresponding default logger for this class
  43.      */
  44.     private static final Logger LOG = LoggerFactory.getLogger(AbstractUpdateOperation.class);

  45.     /**
  46.      * Message for the log when no update is available.<br>
  47.      * <br>
  48.      * <b>Message sample</b>: No update available. Current version is '<em>20120301-01</em>'.<br>
  49.      * <b>First placeholder</b>: current version
  50.      */
  51.     private static final String MSG_NO_UPDATE_AVAILABLE = "No update available. Current version is '%s'.";

  52.     /**
  53.      * Message for the log when an online update check is not possible.<br>
  54.      * <br>
  55.      * <b>Message sample</b>: Can not check for an updated version. Are you sure you have an established internet
  56.      * connection?
  57.      */
  58.     private static final String MSG_NO_UPDATE_CHECK_POSSIBLE = "Can not check for an updated version. Are you sure you have an established internet connection?";

  59.     /**
  60.      * Message for the log when an exception occur during the update check.<br>
  61.      * <br>
  62.      * <b>Message sample</b>: Can not check for an updated version: <em>java.net.ConnectException</em>:
  63.      * <em>Connection refused</em><br>
  64.      * <b>First placeholder</b>: class name of exception<br>
  65.      * <b>Second placeholder</b>: exception message
  66.      */
  67.     private static final String MSG_NO_UPDATE_CHECK_POSSIBLE__DEBUG = "Can not check for an updated version: %s: %s";

  68.     /**
  69.      * Message for the log when an update is available.<br>
  70.      * <br>
  71.      * <b>Message sample</b>: An update is available. Current version is '<em>20120301-01</em>' and remote version is '
  72.      * <em>20120401-01</em>'.<br>
  73.      * <b>First placeholder</b>: current version<br>
  74.      * <b>Second placeholder</b>: new remote version
  75.      */
  76.     private static final String MSG_UPDATE_AVAILABLE = "An update is available. Current version is '%s' and remote version is '%s'.";

  77.     /**
  78.      * Pattern of a typical version of <i>UAS data</i>
  79.      */
  80.     private static final Pattern VERSION_PATTERN = Pattern.compile("\\d{8}\\-\\d{2}");

  81.     /**
  82.      * Checks a given newer version against an older one.
  83.      *
  84.      * @param newer
  85.      *            possible newer version
  86.      * @param older
  87.      *            possible older version
  88.      * @return {@code true} if the first argument is newer than the second argument, otherwise {@code false}
  89.      */
  90.     static boolean hasUpdate(final String newer, final String older) {
  91.         return VERSION_PATTERN.matcher(newer).matches() && VERSION_PATTERN.matcher(older).matches() ? newer.compareTo(older) > 0 : false;
  92.     }

  93.     /**
  94.      * Reads the current User-Agent data version from <a
  95.      * href="http://user-agent-string.info">http://user-agent-string.info</a>.
  96.      *
  97.      * @param url
  98.      *            a URL which the version information can be loaded
  99.      * @return a version string or {@code null}
  100.      * @throws IOException
  101.      *             if an I/O exception occurs
  102.      */
  103.     @Nullable
  104.     private static String retrieveRemoteVersion(@Nonnull final URL url, @Nonnull final Charset charset) throws IOException {
  105.         final InputStream stream = url.openStream();
  106.         final InputStreamReader reader = new InputStreamReader(stream, charset);
  107.         final LineNumberReader lnr = new LineNumberReader(reader);
  108.         final String line = lnr.readLine();
  109.         lnr.close();
  110.         reader.close();
  111.         stream.close();
  112.         return line;
  113.     }

  114.     /**
  115.      * {@link ExecutorService} to run the update operation of the UAS data in background
  116.      */
  117.     private final ExecutorService executorService = ExecutorServices.createBackgroundExecutor();

  118.     /**
  119.      * Time of last update check in milliseconds
  120.      */
  121.     private long lastUpdateCheck = 0;

  122.     /**
  123.      * The data store for instances that implements {@link net.sf.uadetector.internal.data.Data}
  124.      */
  125.     private final RefreshableDataStore store;

  126.     public AbstractUpdateOperation(@Nonnull final RefreshableDataStore dataStore) {
  127.         Check.notNull(dataStore, "dataStore");
  128.         store = dataStore;
  129.     }

  130.     /**
  131.      * Shortcut to get the current version of the UAS data in the {@link net.sf.uadetector.datastore.DataStore}.
  132.      *
  133.      * @return current version of UAS data
  134.      */
  135.     @Nonnull
  136.     private String getCurrentVersion() {
  137.         return store.getData().getVersion();
  138.     }

  139.     /**
  140.      * Gets the time of the last update check in milliseconds.
  141.      *
  142.      * @return time of the last update check in milliseconds
  143.      */
  144.     @Override
  145.     public long getLastUpdateCheck() {
  146.         return lastUpdateCheck;
  147.     }

  148.     /**
  149.      * Fetches the current version information over HTTP and compares it with the last version of the most recently
  150.      * imported data.
  151.      *
  152.      * @return {@code true} if an update exists, otherwise {@code false}
  153.      */
  154.     protected boolean isUpdateAvailable() {
  155.         boolean result = false;
  156.         String version = EMPTY_VERSION;
  157.         try {
  158.             version = retrieveRemoteVersion(store.getVersionUrl(), store.getCharset());
  159.         } catch (final IOException e) {
  160.             LOG.info(MSG_NO_UPDATE_CHECK_POSSIBLE);
  161.             LOG.debug(String.format(MSG_NO_UPDATE_CHECK_POSSIBLE__DEBUG, e.getClass().getName(), e.getLocalizedMessage()));
  162.         }
  163.         if (hasUpdate(version, getCurrentVersion())) {
  164.             LOG.debug(String.format(MSG_UPDATE_AVAILABLE, getCurrentVersion(), version));
  165.             result = true;
  166.         } else {
  167.             LOG.debug(String.format(MSG_NO_UPDATE_AVAILABLE, getCurrentVersion()));
  168.         }
  169.         lastUpdateCheck = System.currentTimeMillis();
  170.         return result;
  171.     }

  172.     /**
  173.      * Executes the update at some time in the future (as soon as possible) within a new thread.
  174.      */
  175.     @Override
  176.     public void run() {
  177.         executorService.execute(new Runnable() {
  178.             @Override
  179.             public void run() {
  180.                 call();
  181.             }
  182.         });
  183.     }

  184.     /**
  185.      * Shuts down the corresponding background executor as soon as possible, but at the latest specified default time.
  186.      *
  187.      * @see ExecutorServices#shutdown(ExecutorService)
  188.      */
  189.     @Override
  190.     public void shutdown() {
  191.         ExecutorServices.shutdown(executorService);
  192.     }

  193. }