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:org.openhab.binding.maxcul.internal.MaxCulBinding.java

/**
 * @{inheritDoc/* w  w  w  .j a  v a2s . com*/
 */
@Override
protected void internalReceiveCommand(final String itemName, Command command) {
    Timer pairModeTimer = null;

    MaxCulBindingConfig bindingConfig = null;
    for (MaxCulBindingProvider provider : super.providers) {
        bindingConfig = provider.getConfigForItemName(itemName);
        if (bindingConfig != null) {
            break;
        }
    }
    logger.debug("Received command " + command.toString() + " for item " + itemName);
    if (bindingConfig != null) {
        logger.debug("Found config for " + itemName);

        switch (bindingConfig.getDeviceType()) {
        case PAIR_MODE:
            if ((command instanceof OnOffType)) {
                switch ((OnOffType) command) {
                case ON:
                    /*
                     * turn on pair mode and schedule disabling of pairing
                     * mode
                     */
                    pairMode = true;
                    TimerTask task = new TimerTask() {
                        public void run() {
                            logger.debug(itemName + " pairMode time out executed");
                            pairMode = false;
                            eventPublisher.postUpdate(itemName, OnOffType.OFF);
                        }
                    };
                    pairModeTimer = timers.get(itemName);
                    if (pairModeTimer != null) {
                        pairModeTimer.cancel();
                        timers.remove(itemName);
                    }
                    pairModeTimer = new Timer();
                    timers.put(itemName, pairModeTimer);
                    pairModeTimer.schedule(task, pairModeTimeout);
                    logger.debug(itemName + " pairMode enabled & timeout scheduled");
                    break;
                case OFF:
                    /*
                     * we are manually disabling, so clear the timer and the
                     * flag
                     */
                    pairMode = false;
                    pairModeTimer = timers.get(itemName);
                    if (pairModeTimer != null) {
                        logger.debug(itemName + " pairMode timer cancelled");
                        pairModeTimer.cancel();
                        timers.remove(itemName);
                    }
                    logger.debug(itemName + " pairMode cleared");
                    break;
                }
            } else
                logger.warn(
                        "Command not handled for " + bindingConfig.getDeviceType() + " that is not OnOffType");
            break;
        case LISTEN_MODE:
            if (command instanceof OnOffType) {
                this.messageHandler.setListenMode(((OnOffType) command == OnOffType.ON));
            } else
                logger.warn(
                        "Command not handled for " + bindingConfig.getDeviceType() + " that is not OnOffType");
            break;
        case RADIATOR_THERMOSTAT:
        case RADIATOR_THERMOSTAT_PLUS:
        case WALL_THERMOSTAT:
            if (bindingConfig.getFeature() == MaxCulFeature.THERMOSTAT) {
                /* clear out old pacing timer */
                if (pacedBindingTransmitTimers.containsKey(bindingConfig)) {
                    pacedBindingTransmitTimers.get(bindingConfig).cancel();
                    pacedBindingTransmitTimers.remove(bindingConfig);
                }
                /* schedule new timer */
                Timer pacingTimer = new Timer();
                pacedBindingTransmitTimers.put(bindingConfig, pacingTimer);
                pacingTimer.schedule(new MaxCulPacedThermostatTransmitTask(command, bindingConfig,
                        messageHandler, super.providers), PACED_TRANSMIT_TIME);
            } else if (bindingConfig.getFeature() == MaxCulFeature.RESET) {
                messageHandler.sendReset(bindingConfig.getDevAddr());
            } else {
                logger.warn("Command not handled for " + bindingConfig.getDeviceType()
                        + " that is not OnOffType or DecimalType");
            }
            break;
        default:
            logger.warn("Command not handled for " + bindingConfig.getDeviceType());
            break;
        }
    }
    updateCreditMonitors();
}

From source file:self.philbrown.javaQuery.$.java

/**
 * Schedule a task for single execution after a specified delay.
 * @param function the task to schedule. Receives no args. Note that the function will be
 * run on a Timer thread, and not the UI Thread.
 * @param delay amount of time in milliseconds before execution.
 * @return the created Timer/*from   w  ww  .j  av a 2s  .  com*/
 */
public static Timer setTimeout(final Function function, long delay) {
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        @Override
        public void run() {
            function.invoke(null);
        }

    }, delay);
    return t;
}

From source file:org.rifidi.edge.adapter.llrp.LLRPReaderSession.java

/**
 * /*from w w  w.j  a v  a 2  s . c  o m*/
 * @param llrpOperationTracker
 * @param isSynchronous
 *            if operations are going to be executed in synchronous mode,
 *            otherwise they execute in asynchronous mode
 * @throws TimeoutException
 * @throws InvalidLLRPMessageException
 */
private LLRPEncodeMessageDto startRequestedOperations(LLRPOperationTracker llrpOperationTracker)
        throws TimeoutException, InvalidLLRPMessageException, Exception {

    // Start the requested operations
    setRunningLLRPEncoding(true);

    // Variable to return asynchronous response
    LLRPEncodeMessageDto llrpEncodeMessageDto = new LLRPEncodeMessageDto();

    // Call the operations in tracker
    for (LLRPOperationDto llrpOperationDto : llrpOperationTracker.getOperationList()) {

        ADD_ACCESSSPEC_RESPONSE response = executeLLRPOperation(llrpOperationDto.getAccessSpecId(),
                llrpOperationDto.getEpc());

        llrpOperationDto.setAccessSpecResponse(response);

        // Check if response is failure, and return synchronous message
        if (response.getLLRPStatus().getStatusCode().intValue() != StatusCode.M_Success) {
            throw new Exception(response.toXMLString());
        }

    }

    if (isExecuteOperationsInAsynchronousMode()) {

        llrpOperationTracker.initializeMqttParameters();

        // Check the operation status in asynchronous mode
        // Add a timer to control
        Timer timer = new Timer(true);
        timer.schedule(llrpOperationTracker, new Date());
        logger.info("TimerTask begins! :" + new Date());

        //TODO change Success hard coded value
        llrpEncodeMessageDto.setStatus("Success");

    } else {

        // Check the operation status in synchronous mode
        llrpEncodeMessageDto = llrpOperationTracker.checkOperationStatus();

    }

    return llrpEncodeMessageDto;
}

From source file:com.lenovo.tensorhusky.common.utils.Shell.java

/**
 * Run a command//w ww  .  j  a  v a  2  s  .  c o  m
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        // One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));
    final BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    } catch (OutOfMemoryError oe) {
        LOG.error("Caught " + oe + ". One possible reason is that ulimit"
                + " setting of 'max user processes' is too low. If so, do"
                + " 'ulimit -u <largerNum>' and try again.");
        throw oe;
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        // the timeout thread handling
        // taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled. the stream draining thread will attempt to
            // drain that fd!! it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            // issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.monotonicNow();
    }
}

From source file:com.delphix.session.test.ServiceTest.java

@Test
public void testLoginAborted() {
    // Create the session
    ClientConfig spec = initServiceSpec(new HelloService(helloService));

    // Connect to an invalid address
    try {/*from www .ja v  a 2  s  . c  o  m*/
        List<TransportAddress> addresses = new ArrayList<TransportAddress>();
        addresses.add(new TransportAddress(InetAddress.getByName("169.0.0.1")));
        spec.setAddresses(addresses);
    } catch (UnknownHostException e) {
        fail("failed to get invalid address", e);
    }

    final ClientNexus client = clientManager.create(spec);

    // Schedule a timer to close the nexus before it is established
    Timer timer = new Timer();

    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            client.close();
        }
    }, 1000);

    Throwable t = loginFail(client);

    assertTrue(t instanceof LoginAbortedException);

    timer.cancel();
}

From source file:com.delphix.session.test.ServiceTest.java

@Test
public void testSessionReset() {
    int numThreads = 4;

    // Configure the server
    Server server = serverManager.locate(helloService.getServiceName());

    final Timer timer = new Timer();

    server.addListener(new SessionEventListener(new SessionEventRunnable() {

        @Override//from w w  w  .j  av a  2  s . com
        public void work() {
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    nexus.close();
                }
            }, 500);
        }
    }));

    // Create the session
    ClientConfig spec = initServiceSpec(new HelloService(helloService));
    ClientNexus client = clientManager.create(spec);

    login(client);

    // Issue commands over the fore channel
    issueCommands(client, numThreads, 32, 0);

    // Wait for the login to complete
    awaitDone(numThreads + 1);

    timer.cancel();
}

From source file:com.delphix.session.test.ServiceTest.java

@Test
public void testSyncDispatchReset() {
    int numThreads = 8;

    // Configure the server
    Server server = serverManager.locate(delayService.getServiceName());

    HelloDelayService delay = (HelloDelayService) server.getService();
    delay.setDelay(1000);//from  www .  j a va  2  s.  c om

    final Timer timer = new Timer();

    server.addListener(new SessionEventListener(new SessionEventRunnable() {

        @Override
        public void work() {
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    nexus.close();
                }
            }, 500);
        }
    }));

    // Create the session
    ClientConfig spec = initServiceSpec(new HelloDelayService(delayService));

    // Set a small fore channel queue depth to test sync dispatch
    ServiceOptions proposal = spec.getOptions();
    proposal.setOption(FORE_QUEUE_DEPTH, 2);
    proposal.setOption(SYNC_DISPATCH, true);

    ClientNexus client = clientManager.create(spec);

    login(client);

    // Issue commands over the fore channel
    issueCommands(client, numThreads, 4096, 0);

    // Wait for the test to complete
    awaitDone(numThreads + 1);

    timer.cancel();
}

From source file:com.eveningoutpost.dexdrip.Home.java

private void processIncomingBundle(Bundle bundle) {
    Log.d(TAG, "Processing incoming bundle");
    if (bundle != null) {
        String receivedText = bundle.getString(WatchUpdaterService.WEARABLE_VOICE_PAYLOAD);
        if (receivedText != null) {
            voiceRecognitionText.setText(receivedText);
            voiceRecognitionText.setVisibility(View.VISIBLE);
            last_speech_time = JoH.ts();
            naturalLanguageRecognition(receivedText);
        }//from ww  w . ja  va  2 s  . c o  m
        if (bundle.getString(WatchUpdaterService.WEARABLE_APPROVE_TREATMENT) != null)
            processAndApproveTreatment();
        else if (bundle.getString(WatchUpdaterService.WEARABLE_CANCEL_TREATMENT) != null)
            cancelTreatment();
        else if (bundle.getString(Home.START_SPEECH_RECOGNITION) != null)
            promptSpeechInput();
        else if (bundle.getString(Home.START_TEXT_RECOGNITION) != null)
            promptTextInput_old();
        else if (bundle.getString(Home.CREATE_TREATMENT_NOTE) != null) {
            try {
                showNoteTextInputDialog(null, Long.parseLong(bundle.getString(Home.CREATE_TREATMENT_NOTE)),
                        JoH.tolerantParseDouble(bundle.getString(Home.CREATE_TREATMENT_NOTE + "2")));
            } catch (NullPointerException e) {
                Log.d(TAG, "Got null point exception during CREATE_TREATMENT_NOTE Intent");
            }
        } else if (bundle.getString(Home.HOME_FULL_WAKEUP) != null) {
            if (!JoH.isScreenOn()) {
                final int timeout = 60000;
                final PowerManager.WakeLock wl = JoH.getWakeLock("full-wakeup", timeout + 1000);
                final Window win = getWindow();
                win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        JoH.releaseWakeLock(wl);
                        finish();
                    }
                }, timeout);
            } else {
                Log.d(TAG, "Screen is already on so not turning on");
            }
        } else if (bundle.getString(Home.GCM_RESOLUTION_ACTIVITY) != null) {
            GcmActivity.checkPlayServices(this, this);
        } else if (bundle.getString(Home.SNOOZE_CONFIRM_DIALOG) != null) {
            GcmActivity.sendSnoozeToRemoteWithConfirm(this);
        }
    }
}

From source file:org.wso2.emm.system.service.api.OTAServerManager.java

public void startDownloadUpgradePackage(final OTAServerManager serverManager) {
    if (asyncTask != null) {
        asyncTask.cancel(true);//from   w  w  w. j  ava2 s  . com
    }
    asyncTask = new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... unused) {
            Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                    Constants.Status.OTA_UPGRADE_ONGOING);
            File targetFile = new File(FileUtils.getUpgradePackageFilePath());
            if (targetFile.exists()) {
                targetFile.delete();
            }
            try {
                boolean fileStatus = targetFile.createNewFile();
                if (!fileStatus) {
                    Log.e(TAG, "Update package file creation failed.");
                }
            } catch (IOException e) {
                String message = "Update package file retrieval error.";
                Log.e(TAG, message + e);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.INTERNAL_ERROR, message);
            }

            try {
                wakeLock.acquire();

                URL url = serverConfig.getPackageURL();
                Log.d(TAG, "Start downloading package:" + url.toString());
                URLConnection connection = url.openConnection();
                connection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT);
                connection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                lengthOfFile = connection.getContentLength();
                downloadedLength = 0;
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(targetFile);
                Timer timeoutTimer = new Timer();
                Log.d(TAG, "Update package file size:" + lengthOfFile);
                if (getFreeDiskSpace() < lengthOfFile) {
                    String message = "Device does not have enough memory to download the OTA" + " update";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.LOW_DISK_SPACE, 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 null;
                }
                byte data[] = new byte[DEFAULT_BYTES];
                long count;
                isProgressUpdateTerminated = false;
                executor = new DownloadProgressUpdateExecutor();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        while (lengthOfFile > downloadedLength && !isProgressUpdateTerminated) {
                            Preference.putString(context,
                                    context.getResources().getString(R.string.upgrade_download_status),
                                    Constants.Status.OTA_UPGRADE_ONGOING);
                            publishDownloadProgress(lengthOfFile, downloadedLength);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException ignored) {
                            }
                        }
                    }
                });
                while ((count = input.read(data)) >= 0) {
                    downloadedLength += count;
                    output.write(data, DEFAULT_OFFSET, (int) count);
                    timeoutTimer.cancel();
                    timeoutTimer = new Timer();
                    timeoutTimer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                }
                publishDownloadProgress(lengthOfFile, downloadedLength);
                isProgressUpdateTerminated = true;
                timeoutTimer.cancel();
                output.flush();
                output.close();
                input.close();
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        context.getResources().getString(R.string.status_success));
                if (serverManager.stateChangeListener != null) {
                    serverManager.stateChangeListener.onStateOrProgress(
                            OTAStateChangeListener.STATE_IN_DOWNLOADING, DEFAULT_STATE_ERROR_CODE, null,
                            DEFAULT_STATE_INFO_CODE);
                }
            } catch (SocketTimeoutException e) {
                String message = "Connection failure (Socket timeout) when downloading update package.";
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.CONNECTION_FAILED, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0,
                        null);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.CONNECTION_FAILED);
            } catch (IOException e) {
                String message = "Unable to find firmware upgrade package "
                        + serverConfig.getPackageURL().toString();
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.FILE_NOT_FOUND, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0,
                        null);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.FILE_NOT_FOUND);
            } finally {
                wakeLock.release();
                wakeLock.acquire(2);
                if (targetFile.exists() && lengthOfFile != downloadedLength) {
                    targetFile.delete();
                    String status = Preference.getString(context,
                            context.getResources().getString(R.string.upgrade_download_status));
                    if (!Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.OTA_DOWNLOAD_FAILED);
                    }
                }
            }
            return null;
        }
    }.executeOnExecutor(threadPoolExecutor);
}

From source file:org.wso2.iot.system.service.api.OTAServerManager.java

public void startDownloadUpgradePackage(final OTAServerManager serverManager) {
    if (asyncTask != null) {
        asyncTask.cancel(true);/* w ww.j  a v  a 2  s  .  c o m*/
    }
    asyncTask = new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... unused) {
            Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                    Constants.Status.OTA_UPGRADE_ONGOING);
            File targetFile = new File(FileUtils.getUpgradePackageFilePath());
            if (targetFile.exists()) {
                targetFile.delete();
            }
            try {
                boolean fileStatus = targetFile.createNewFile();
                if (!fileStatus) {
                    Log.e(TAG, "Update package file creation failed.");
                }
            } catch (IOException e) {
                String message = "Update package file retrieval error.";
                Log.e(TAG, message + e);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.INTERNAL_ERROR, message);
            }

            try {
                wakeLock.acquire();

                URL url = serverConfig.getPackageURL();
                Log.d(TAG, "Start downloading package:" + url.toString());
                URLConnection connection = url.openConnection();
                connection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT);
                connection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                lengthOfFile = connection.getContentLength();
                downloadedLength = 0;
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(targetFile);
                Timer timeoutTimer = new Timer();
                Log.d(TAG, "Update package file size:" + lengthOfFile);
                if (getFreeDiskSpace() < lengthOfFile) {
                    String message = "Device does not have enough memory to download the OTA" + " update";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.LOW_DISK_SPACE, 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 null;
                }
                byte data[] = new byte[DEFAULT_BYTES];
                long count;
                isProgressUpdateTerminated = false;
                executor = new DownloadProgressUpdateExecutor();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        while (lengthOfFile > downloadedLength && !isProgressUpdateTerminated) {
                            Preference.putString(context,
                                    context.getResources().getString(R.string.upgrade_download_status),
                                    Constants.Status.OTA_UPGRADE_ONGOING);
                            publishDownloadProgress(lengthOfFile, downloadedLength);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException ignored) {
                            }
                        }
                    }
                });
                while ((count = input.read(data)) >= 0) {
                    downloadedLength += count;
                    output.write(data, DEFAULT_OFFSET, (int) count);
                    timeoutTimer.cancel();
                    timeoutTimer = new Timer();
                    timeoutTimer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                }
                publishDownloadProgress(lengthOfFile, downloadedLength);
                isProgressUpdateTerminated = true;
                timeoutTimer.cancel();
                output.flush();
                output.close();
                input.close();
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        context.getResources().getString(R.string.status_success));
                if (serverManager.stateChangeListener != null) {
                    serverManager.stateChangeListener.onStateOrProgress(
                            OTAStateChangeListener.STATE_IN_DOWNLOADING, DEFAULT_STATE_ERROR_CODE, null,
                            DEFAULT_STATE_INFO_CODE);
                }
            } catch (SocketTimeoutException e) {
                String message = "Connection failure (Socket timeout) when downloading update package.";
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.CONNECTION_FAILED, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                        Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                        message);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.CONNECTION_FAILED);
            } catch (IOException e) {
                String message = "Unable to find firmware upgrade package "
                        + serverConfig.getPackageURL().toString();
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.FILE_NOT_FOUND, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                        Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                        message);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.FILE_NOT_FOUND);
            } finally {
                wakeLock.release();
                wakeLock.acquire(2);
                if (targetFile.exists() && lengthOfFile != downloadedLength) {
                    targetFile.delete();
                    String status = Preference.getString(context,
                            context.getResources().getString(R.string.upgrade_download_status));
                    if (!Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.OTA_DOWNLOAD_FAILED);
                    }
                }
            }
            return null;
        }
    }.executeOnExecutor(threadPoolExecutor);
}