Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

In this page you can find the example usage for java.util Timer schedule.

Prototype

public void schedule(TimerTask task, Date time) 

Source Link

Document

Schedules the specified task for execution at the specified time.

Usage

From source file:be.ac.ua.comp.scarletnebula.core.Server.java

private ServerStatisticsManager getNewServerStatistics(final boolean retry) {
    serverStatisticsManager = new ServerStatisticsManager(this);
    serverStatisticsManager.addNoStatisticsListener(new ServerStatisticsManager.NoStatisticsListener() {

        @Override/*from www .j  ava  2  s.  c  om*/
        public void connectionFailed(final ServerStatisticsManager manager) {
            log.info("Being notified of server statistics failure.");
            noConnection = true;
            serverChanged();

            if (!retry)
                return;

            log.info("Starting timer that will retry statistics in 120 sec");
            final java.util.Timer twoMin = new java.util.Timer();
            twoMin.schedule(new java.util.TimerTask() {
                @Override
                public void run() {
                    if (getServerStatistics() != null
                            && getServerStatistics().getAvailableDatastreams().size() > 0)
                        return;

                    log.info("Retrying statistics (after 120 sec)");
                    noConnection = false;
                    serverStatisticsManager = getNewServerStatistics(false);
                    serverChanged();
                    cancel();
                }
            }, (120 * 1000));

            log.info("Starting timer that will retry statistics in 30 sec");
            final java.util.Timer thirtySecs = new java.util.Timer();
            thirtySecs.schedule(new java.util.TimerTask() {
                @Override
                public void run() {
                    log.info("Retrying statistics (after 30 sec)");
                    noConnection = false;
                    serverStatisticsManager = getNewServerStatistics(false);
                    serverChanged();
                    cancel();
                }
            }, (30 * 1000));

        }
    });
    return serverStatisticsManager;
}

From source file:cc.kune.core.server.manager.impl.UserManagerDefault.java

@Override
public User login(final String nickOrEmail, final String passwd) {
    User user;/*from   ww  w .j a v  a 2 s  .com*/
    try {
        user = userFinder.findByShortName(nickOrEmail);
    } catch (final NoResultException e) {
        try {
            user = userFinder.findByEmail(nickOrEmail);
        } catch (final NoResultException e2) {
            return null;
        }
    }
    if (PasswordDigest.from(user.getSalt(), user.getDiggest()).verify(passwd.toCharArray())) {
        final I18nLanguage lang = user.getLanguage();
        if (user.getLastLogin() == null) {
            final String userName = user.getShortName();
            final Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // FIXME: Use notifyService!
                    xmppManager.sendMessage(userName, i18n.tWithNT(lang, "This is the chat window. "
                            + "Here you can communicate with other users of [%s] but also with other users with compatible accounts (such as Gmail accounts). "
                            + "Just add a buddy and start chatting.", "",
                            i18n.tWithNT(lang, properties.getSiteCommonName(), "")));
                }
            }, 5000);
        }
        user.setLastLogin(System.currentTimeMillis());
        return user;
    } else {
        return null;
    }
}

From source file:org.powertac.visualizer.services.VisualizerServiceTournament.java

@Override
public void afterPropertiesSet() throws Exception {
    Timer initTimer = new Timer(true);
    // delay to let deployment complete
    initTimer.schedule(new TimerTask() {
        @Override/*from   w  w  w. j av  a2s .  c  o m*/
        public void run() {
            init();
        }
    }, 20000l);
}

From source file:jahirfiquitiva.iconshowcase.activities.WallpaperViewerActivity.java

private void showApplyWallpaperDialog(final String wallUrl) {
    ISDialogs.showApplyWallpaperDialog(this, new MaterialDialog.SingleButtonCallback() {
        @Override//ww  w  .j  av  a  2s  .com
        public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
            if (dialogApply != null) {
                dialogApply.dismiss();
            }

            if (toHide1 != null && toHide2 != null) {
                toHide1.setVisibility(View.GONE);
                toHide2.setVisibility(View.GONE);
            }

            final ApplyWallpaper[] applyTask = new ApplyWallpaper[1];

            final boolean[] enteredApplyTask = { false };

            dialogApply = new MaterialDialog.Builder(WallpaperViewerActivity.this)
                    .content(R.string.downloading_wallpaper).progress(true, 0).cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            if (applyTask[0] != null) {
                                applyTask[0].cancel(true);
                            }
                            dialogApply.dismiss();

                            if (toHide1 != null && toHide2 != null) {
                                toHide1.setVisibility(View.VISIBLE);
                                toHide2.setVisibility(View.VISIBLE);
                            }

                        }
                    }).show();

            Glide.with(context).load(wallUrl).asBitmap().dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(final Bitmap resource,
                                GlideAnimation<? super Bitmap> glideAnimation) {
                            if (resource != null && dialogApply.isShowing()) {
                                enteredApplyTask[0] = true;

                                if (dialogApply != null) {
                                    dialogApply.dismiss();
                                }

                                dialogApply = new MaterialDialog.Builder(context)
                                        .content(R.string.setting_wall_title).progress(true, 0)
                                        .cancelable(false).show();

                                applyTask[0] = new ApplyWallpaper(context, resource,
                                        new ApplyWallpaper.ApplyCallback() {
                                            @Override
                                            public void afterApplied() {
                                                runOnUIThread(context, new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (dialogApply != null) {
                                                            dialogApply.dismiss();
                                                        }

                                                        dialogApply = new MaterialDialog.Builder(context)
                                                                .content(R.string.set_as_wall_done)
                                                                .positiveText(android.R.string.ok).show();

                                                        dialogApply.setOnDismissListener(
                                                                new DialogInterface.OnDismissListener() {
                                                                    @Override
                                                                    public void onDismiss(
                                                                            DialogInterface dialogInterface) {
                                                                        if (toHide1 != null
                                                                                && toHide2 != null) {
                                                                            toHide1.setVisibility(View.VISIBLE);
                                                                            toHide2.setVisibility(View.VISIBLE);
                                                                        }
                                                                    }
                                                                });
                                                    }
                                                });
                                            }
                                        });
                                applyTask[0].execute();
                            }
                        }
                    });

            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUIThread(WallpaperViewerActivity.this, new Runnable() {
                        @Override
                        public void run() {
                            if (!enteredApplyTask[0]) {
                                String newContent = context.getString(R.string.downloading_wallpaper) + "\n"
                                        + context.getString(R.string.download_takes_longer);
                                dialogApply.setContent(newContent);
                                dialogApply.setActionButton(DialogAction.POSITIVE, android.R.string.cancel);
                            }
                        }
                    });
                }
            }, 10000);
        }
    }, new MaterialDialog.SingleButtonCallback() {
        @Override
        public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
            if (!PermissionUtils.canAccessStorage(WallpaperViewerActivity.this)) {
                PermissionUtils.setViewerActivityAction("crop");
                PermissionUtils.requestStoragePermission(WallpaperViewerActivity.this);
            } else {
                cropWallpaper(wallUrl);
            }
        }
    }, new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialogInterface) {
            if (toHide1 != null && toHide2 != null) {
                toHide1.setVisibility(View.VISIBLE);
                toHide2.setVisibility(View.VISIBLE);
            }
        }
    });
    // WallpaperDialog.show(this, wallUrl);
}

From source file:cz.dasnet.dasik.Dasik.java

@Override
protected void onConnect() {
    log.info("Connected on " + getServer());
    auth();/*  ww w  . j a  va 2 s.c o  m*/
    if (authed) {
        requestInvites();
    }
    final Dasik bot = this;
    try {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                bot.joinChannels();
            }
        }, 1000);

        TimerTask dumpTask = new TimerTask() {

            @Override
            public void run() {
                Document document = DocumentHelper.createDocument();
                Element channelinfo = document.addElement("channelinfo");

                for (String c : activeChannels.keySet()) {
                    Element channel = channelinfo.addElement("channel");
                    Element name = channel.addElement("name");
                    name.setText(c);
                    Element size = channel.addElement("size");
                    size.setText("" + getUsers(c).length);
                }

                Element updatetime = channelinfo.addElement("updatetime");
                updatetime.setText(new Long(new Date().getTime() / 1000).toString());

                try {
                    XMLWriter writer = new XMLWriter(new FileWriter("channelinfo.xml"));
                    writer.write(document);
                    writer.close();
                } catch (IOException ex) {
                    log.error("Unable to dump channel info", ex);
                }
            }
        };

        Timer dump = new Timer("dump", true);
        dump.schedule(dumpTask, 10000, 60000);
    } catch (Exception ex) {
        this.joinChannels();
        log.error("Channel autojoin timer failed to schedule the task.", ex);
    }
}

From source file:jahirfiquitiva.iconshowcase.activities.AltWallpaperViewerActivity.java

private void saveWallpaperAction(final String name, String url) {

    if (downloadDialog != null) {
        downloadDialog.dismiss();/* ww  w . jav a  2 s . co m*/
    }

    if (fabOpened) {
        closeMenu();
        fabOpened = false;
    }

    hideFab(fab);

    final boolean[] enteredDownloadTask = { false };

    downloadDialog = new MaterialDialog.Builder(this).content(R.string.downloading_wallpaper).progress(true, 0)
            .cancelable(false).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (downloadDialog != null) {
                        downloadDialog.dismiss();
                        reshowFab(fab);
                        setupFullScreen();
                    }
                }
            }).show();

    Glide.with(this).load(url).asBitmap().dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE)
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    if (resource != null && downloadDialog.isShowing()) {
                        enteredDownloadTask[0] = true;
                        saveWallpaper(AltWallpaperViewerActivity.this, name, downloadDialog, resource);
                    }
                }
            });

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUIThread(AltWallpaperViewerActivity.this, new Runnable() {
                @Override
                public void run() {
                    if (!enteredDownloadTask[0]) {
                        String newContent = getString(R.string.downloading_wallpaper) + "\n"
                                + getString(R.string.download_takes_longer);
                        downloadDialog.setContent(newContent);
                        downloadDialog.setActionButton(DialogAction.POSITIVE, android.R.string.cancel);
                    }
                }
            });
        }
    }, 10000);
}

From source file:dhtaccess.benchmark.ThroughputMeasure.java

private void start(boolean details, int repeats, int queryFreq, boolean doPut, String[] args) {
    this.repeats = repeats;

    // prepare for RPC
    int numAccessor = args.length;
    DHTAccessor[] accessorArray = new DHTAccessor[numAccessor];
    try {/*from   w  w  w . j a  v  a  2s  .c om*/
        for (int i = 0; i < numAccessor; i++) {
            accessorArray[i] = new DHTAccessor(args[i]);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // generate key prefix
    Random rnd = new Random(System.currentTimeMillis());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < KEY_PREFIX_LENGTH; i++) {
        sb.append((char) ('a' + rnd.nextInt(26)));
    }
    String keyPrefix = sb.toString();
    String valuePrefix = VALUE_PREFIX;

    // benchmarking
    System.out.println("Repeats " + repeats + " times.");
    System.out.println("Query frequency (times/sec): " + queryFreq);

    if (doPut) {
        System.out.println("Putting: " + keyPrefix + "<number>");

        for (int i = 0; i < repeats; i++) {
            byte[] key = null, value = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
                value = (valuePrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            acc.put(key, value, TTL);
        }
    }

    System.out.println("Benchmarking by getting.");
    System.out.println("(Start getting " + INITIAL_SLEEP + " msec later.)");

    Timer timer = new Timer("Benchmark driving timer", false /* isDaemon */);
    this.count = this.repeats;

    this.startTime = System.currentTimeMillis() + INITIAL_SLEEP;

    for (int i = 0; i < repeats; i++) {
        byte[] key = null;
        try {
            key = (keyPrefix + i).getBytes(ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.exit(1);
        }

        int accIndex = rnd.nextInt(numAccessor);
        DHTAccessor acc = accessorArray[accIndex];

        TimerTask task = new GetQuerier(acc, key, details);
        timer.schedule(task, new Date(this.startTime + (long) (1000.0 * i / queryFreq)));
    }
}

From source file:org.openhab.persistence.rrd4j.internal.RRD4jService.java

/**
 * @{inheritDoc}/*  www .  j  a  va  2  s.  co m*/
 */
public synchronized void store(final Item item, final String alias) {
    final String name = alias == null ? item.getName() : alias;
    RrdDb db = getDB(name);
    if (db != null) {
        ConsolFun function = getConsolidationFunction(db);
        long now = System.currentTimeMillis() / 1000;
        if (function != ConsolFun.AVERAGE) {
            try {
                // we store the last value again, so that the value change in the database is not interpolated, but
                // happens right at this spot
                if (now - 1 > db.getLastUpdateTime()) {
                    // only do it if there is not already a value
                    double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
                    if (!Double.isNaN(lastValue)) {
                        Sample sample = db.createSample();
                        sample.setTime(now - 1);
                        sample.setValue(DATASOURCE_STATE, lastValue);
                        sample.update();
                        logger.debug("Stored '{}' with state '{}' in rrd4j database (again)", name,
                                mapToState(lastValue, item.getName()));
                    }
                }
            } catch (IOException e) {
                logger.debug("Error storing last value (again): {}", e.getMessage());
            }
        }
        try {
            Sample sample = db.createSample();
            sample.setTime(now);

            DecimalType state = (DecimalType) item.getStateAs(DecimalType.class);
            if (state != null) {
                double value = state.toBigDecimal().doubleValue();
                if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) { // counter values must be adjusted by stepsize
                    value = value * db.getRrdDef().getStep();
                }
                sample.setValue(DATASOURCE_STATE, value);
                sample.update();
                logger.debug("Stored '{}' with state '{}' in rrd4j database", name, state);
            }
        } catch (IllegalArgumentException e) {
            if (e.getMessage().contains("at least one second step is required")) {

                // we try to store the value one second later
                TimerTask task = new TimerTask() {
                    public void run() {
                        store(item, name);
                    }
                };
                Timer timer = timers.get(name);
                if (timer != null) {
                    timer.cancel();
                    timers.remove(name);
                }
                timer = new Timer();
                timers.put(name, timer);
                timer.schedule(task, 1000);
            } else {
                logger.warn("Could not persist '{}' to rrd4j database: {}",
                        new String[] { name, e.getMessage() });
            }
        } catch (Exception e) {
            logger.warn("Could not persist '{}' to rrd4j database: {}", new String[] { name, e.getMessage() });
        }
        try {
            db.close();
        } catch (IOException e) {
            logger.debug("Error closing rrd4j database: {}", e.getMessage());
        }
    }
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Does a subtree search for an element given a pattern. Only the first
 * element found is considered, and all references are searched in order
 * until either a match is found or no more references are left to search.
 * @param ldap/*w  w  w  . j a  v  a 2  s . c o  m*/
 *            A prepared LDAP context.
 * @param pattern
 *            The search pattern. Must not include the character '*' or the
 *            substring '\2a' to prevent possible LDAP exploits.
 * @return The element's relative DN, or <code>null</code> if none was
 *         found. <code>null</code> is also returned if the search pattern
 *         contains an illegal character or substring.
 * @throws BackendException
 *             If there was a problem accessing the backend. Typical causes
 *             include timeouts.
 */
private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException {

    // Check pattern for illegal content.
    String[] illegals = { "*", "\\2a" };
    for (int i = 0; i < illegals.length; i++) {
        if (pattern.indexOf(illegals[i]) > -1)
            return null;
    }

    // The context provider URL, for later logging.
    String url = "unknown backend";

    // Start counting the (milli)seconds and prepare for timeouts.
    long searchStart = System.currentTimeMillis();
    JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket);
    NamingEnumeration results;
    try {

        // Remember the URL, for later logging.
        url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
        interruptTask.setURL(url);

        // Start timeout interruptor and perform the search.
        Timer interruptTimer = new Timer();
        interruptTimer.schedule(interruptTask, (1000 * myTimeout));
        results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout,
                new String[] {}, false, false));
        interruptTimer.cancel();
        if (!results.hasMore())
            return null;

    } catch (TimeLimitExceededException e) {

        // The search timed out.
        log.logWarn("Search on " + url + " for " + pattern + " timed out after ~"
                + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket);
        return null;

    } catch (SizeLimitExceededException e) {

        // The search returned too many results.
        log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket);
        return null;

    } catch (NameNotFoundException e) {

        // Element not found. Possibly non-existing reference.
        log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary?
        return null;

    } catch (AuthenticationException e) {

        // Search failed authentication; check non-anonymous search config.
        try {
            final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL);
            final String errorMessage;
            if ((searchUser == null) || searchUser.equals(""))
                errorMessage = "Anonymous search failed authentication on " + url;
            else
                errorMessage = "Could not authenticate search user " + searchUser + " on " + url;
            log.logDebug(errorMessage, mySessionTicket);
            throw new BackendException(errorMessage, e);
        } catch (NamingException f) {

            // Should not happen!
            log.logCritical("Unable to read LDAP environment", mySessionTicket, f);
            throw new BackendException("Unable to read LDAP environment", f);

        }

    } catch (NamingException e) {

        // Did we interrupt the search ourselves?
        if (interruptTask.finished()) {
            final long elapsed = System.currentTimeMillis() - searchStart;
            log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms",
                    mySessionTicket);
            throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed
                    + "ms; connection terminated");
        }

        // All other exceptions.
        log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e);
        return null;

    }

    // We just found at least one element. Did we get an ambigious result?
    SearchResult entry = null;
    try {
        entry = (SearchResult) results.next();
        String buffer = new String();
        while (results.hasMoreElements())
            buffer = buffer + ", " + ((SearchResult) results.next()).getName();
        if (!buffer.equals(""))
            log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName()
                    + buffer + "]", mySessionTicket);
        // TODO: Throw BackendException, or a subclass, or just (as now)
        // pick the first and hope for the best?
        buffer = null;
    } catch (NamingException e) {
        throw new BackendException("Unable to read search results", e);
    }
    return entry.getName(); // Relative DN (to the reference).

}

From source file:org.wso2.iot.system.service.SystemService.java

/**
 * Upgrading device firmware over the air (OTA).
 *///from  w  w  w  .j  ava 2s  . c o m
public void upgradeFirmware(final boolean isStatusCheck) {
    Log.i(TAG, "An upgrade has been requested");

    Preference.putBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress),
            isStatusCheck);
    Preference.putString(context, context.getResources().getString(R.string.firmware_download_progress),
            String.valueOf(DEFAULT_STATE_INFO_CODE));
    Preference.putInt(context, context.getResources().getString(R.string.operation_id), operationId);

    String schedule = null;
    String server;
    if (command != null && !command.trim().isEmpty()) {
        try {
            JSONObject upgradeData = new JSONObject(command);
            if (!upgradeData.isNull(context.getResources().getString(R.string.alarm_schedule))) {
                schedule = (String) upgradeData.get(context.getResources().getString(R.string.alarm_schedule));
            }

            boolean isAutomaticRetry = !Preference.hasPreferenceKey(context,
                    context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                    || Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry));
            if (!upgradeData
                    .isNull(context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                isAutomaticRetry = upgradeData.getBoolean(
                        context.getResources().getString(R.string.firmware_upgrade_automatic_retry));
                if (!isAutomaticRetry) {
                    Log.i(TAG, "Automatic retry on firmware upgrade failure is disabled.");
                }
            }

            Preference.putBoolean(context,
                    context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                    isAutomaticRetry);

            if (!upgradeData.isNull(context.getResources().getString(R.string.firmware_server))) {
                server = (String) upgradeData.get(context.getResources().getString(R.string.firmware_server));
                // When the server is empty, that means it is indicating to download from default server
                if (!server.isEmpty() && !Patterns.WEB_URL.matcher(server).matches()) {
                    String message = "Firmware upgrade URL provided is not valid.";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.MALFORMED_OTA_URL, message);
                    CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                            Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                            message);
                    Log.e(TAG, message);
                    return;
                } else {
                    Preference.putString(context, context.getResources().getString(R.string.firmware_server),
                            server);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Firmware upgrade payload parsing failed." + e);
            return;
        }
    }
    if (schedule != null && !schedule.trim().isEmpty()) {
        Log.i(TAG, "Upgrade scheduled received: " + schedule);
        Preference.putString(context, context.getResources().getString(R.string.alarm_schedule), schedule);
        try {
            AlarmUtils.setOneTimeAlarm(context, schedule, Constants.Operation.UPGRADE_FIRMWARE, null);
        } catch (ParseException e) {
            CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                    Constants.Status.MALFORMED_REQUEST, e.getMessage());
        }
    } else {
        if (isStatusCheck) {
            Log.i(TAG, "Firmware status check is initiated by admin.");
        } else {
            Log.i(TAG, "Upgrade request initiated by admin.");

            String status = Preference.getString(context,
                    context.getResources().getString(R.string.upgrade_download_status));
            boolean isAutomaticUpgrade = Preference.getBoolean(context,
                    context.getResources().getString(R.string.firmware_upgrade_automatic_retry));

            if (Constants.Status.WIFI_OFF.equals(status) && isAutomaticUpgrade && !checkNetworkOnline()) {
                String msg = "Ignoring request as service waiting for WiFi to start upgrade.";
                Log.d(TAG, msg);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING,
                        Constants.Status.OTA_UPGRADE_PENDING, msg);
                return;
            } else if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                String msg = "Checking for existing download. Will proceed this request if current download is no longer ongoing.";
                Log.d(TAG, msg);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING,
                        Constants.Status.OTA_UPGRADE_ONGOING, msg);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.REQUEST_PLACED);
                Timer timeoutTimer = new Timer();
                timeoutTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context,
                                context.getResources().getString(R.string.upgrade_download_status)))) {
                            Log.d(TAG,
                                    "Download is no longer ongoing. Proceeding download request from the agent.");
                            OTADownload otaDownload = new OTADownload(context);
                            otaDownload.startOTA();
                        } else {
                            String msg = "Request ignored because another download is ongoing.";
                            Log.d(TAG, msg);
                            CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                    Constants.Code.FAILURE, Constants.Status.OTA_UPGRADE_ONGOING, msg);
                        }
                    }
                }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                return;
            }
        }

        //Prepare for upgrade
        OTADownload otaDownload = new OTADownload(context);
        otaDownload.startOTA();
    }
}