Example usage for java.util Timer cancel

List of usage examples for java.util Timer cancel

Introduction

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

Prototype

public void cancel() 

Source Link

Document

Terminates this timer, discarding any currently scheduled tasks.

Usage

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 {/*w w  w  . j  a  v a2s .  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.shengtao.chat.chatUI.adapter.MessageAdapter.java

/**
 * ?//from www.j a v a2 s  .co  m
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleVideoMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {

    VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
    // final File image=new File(PathUtil.getInstance().getVideoPath(),
    // videoBody.getFileName());
    String localThumb = videoBody.getLocalThumb();

    holder.iv.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult(new Intent(activity, ContextMenu.class)
                    .putExtra("position", position).putExtra("type", Type.VIDEO.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    if (localThumb != null) {

        showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
    }
    if (videoBody.getLength() > 0) {
        String time = DateUtils.toTimeBySecond(videoBody.getLength());
        holder.timeLength.setText(time);
    }
    holder.playBtn.setImageResource(drawable.video_download_btn_nor);

    if (message.direct == Direct.RECEIVE) {
        if (videoBody.getVideoFileLength() > 0) {
            String size = TextFormater.getDataSize(videoBody.getVideoFileLength());
            holder.size.setText(size);
        }
    } else {
        if (videoBody.getLocalUrl() != null && new File(videoBody.getLocalUrl()).exists()) {
            String size = TextFormater.getDataSize(new File(videoBody.getLocalUrl()).length());
            holder.size.setText(size);
        }
    }

    if (message.direct == Direct.RECEIVE) {

        // System.err.println("it is receive msg");
        if (message.status == EMMessage.Status.INPROGRESS) {
            // System.err.println("!!!! back receive");
            holder.iv.setImageResource(drawable.default_image);
            showDownloadImageProgress(message, holder);

        } else {
            // System.err.println("!!!! not back receive, show image directly");
            holder.iv.setImageResource(drawable.default_image);
            if (localThumb != null) {
                showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
            }

        }

        return;
    }
    holder.pb.setTag(position);

    // until here ,deal with send video msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity, activity.getString(string.send_fail)
                                    + activity.getString(string.connect_failuer_toast), 0).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        // sendMsgInBackground(message, holder);
        sendPictureMessage(message, holder);

    }

}

From source file:com.com.easemob.chatuidemo.adapter.MessageAdapter.java

/**
 * ?//from w w  w  .j a  va 2  s  .co m
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleImageMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {
    holder.pb.setTag(position);
    holder.iv.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult((new Intent(activity, ContextMenu.class))
                    .putExtra("position", position).putExtra("type", EMMessage.Type.IMAGE.ordinal()),
                    ChatMessage.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    // ??
    if (message.direct == EMMessage.Direct.RECEIVE) {
        // "it is receive msg";
        if (message.status == EMMessage.Status.INPROGRESS) {
            // "!!!! back receive";
            holder.iv.setImageResource(R.drawable.default_image);
            showDownloadImageProgress(message, holder);
            // downloadImage(message, holder);
        } else {
            // "!!!! not back receive, show image directly");
            holder.pb.setVisibility(View.GONE);
            holder.tv.setVisibility(View.GONE);
            holder.iv.setImageResource(R.drawable.default_image);
            ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
            if (imgBody.getLocalUrl() != null) {
                // String filePath = imgBody.getLocalUrl();
                String remotePath = imgBody.getRemoteUrl();
                String filePath = ImageUtils.getImagePath(remotePath);
                String thumbRemoteUrl = imgBody.getThumbnailUrl();
                if (TextUtils.isEmpty(thumbRemoteUrl) && !TextUtils.isEmpty(remotePath)) {
                    thumbRemoteUrl = remotePath;
                }
                String thumbnailPath = ImageUtils.getThumbnailImagePath(thumbRemoteUrl);
                showImageView(thumbnailPath, holder.iv, filePath, imgBody.getRemoteUrl(), message);
            }
        }
        return;
    }

    // ???
    // process send message
    // send pic, show the pic directly
    ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
    String filePath = imgBody.getLocalUrl();
    if (filePath != null && new File(filePath).exists()) {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, null, message);
    } else {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, IMAGE_DIR, message);
    }

    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        holder.staus_iv.setVisibility(View.GONE);
        holder.pb.setVisibility(View.VISIBLE);
        holder.tv.setVisibility(View.VISIBLE);
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity, activity.getString(R.string.send_fail)
                                    + activity.getString(R.string.connect_failuer_toast), 0).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        sendPictureMessage(message, holder);
    }
}

From source file:gtu._work.etc.EnglishTester.java

void startNow() {
    final StringBuilder currentTime = new StringBuilder();
    currentTime.append(System.currentTimeMillis());

    wordsList = new ArrayList<String>();
    pickProp = new Properties();

    if (picOnly.isSelected()) {
        filterHasPicProp();//from ww w. ja v  a 2  s  . c  o  m
    }

    for (Enumeration<?> enu = englishProp.propertyNames(); enu.hasMoreElements();) {
        String key = (String) enu.nextElement();
        String value = englishProp.getProperty(key);
        wordsList.add(key);
    }
    wordsList = RandomUtil.randomList(wordsList);

    if (sortChkBox.isSelected()) {
        Collections.sort(wordsList);
        ifIsNumberSort(wordsList);
    }

    propCountLabel.setText(String.valueOf(englishProp.size()));
    questionCountLabel.setText(String.valueOf(wordsList.size()));

    // ?
    inputTestTrainer.initQuestion();

    setVisible(false);

    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            // jTabbedPane1.setSelectedIndex(tabSelectedCombo.getSelectedIndex());//
            // 

            if (!EnglishTester.gtu.swing.util.JFrameUtil.isVisible(this)) {
                setVisible(true);
            }

            // ??
            if (currentWordIndex == wordsList.get(0)) {
                return;
            }

            // System.out.println(wordsList);
            if (!wordsList.isEmpty()) {
                String word = wordsList.get(0);

                // 
                setCurrentWord(word);
                // 

                scanPic();
                if (showChineseOption.isSelected()) {
                    setPictureDialogShow(true);
                }

                // 
                resetAnswers(word);
                // 
            } else {
                JCommonUtil._jOptionPane_showMessageDialog_info("words is over");
                timer.cancel();
            }
        }
    }, 0, DELAY_TIME);
}

From source file:com.com.easemob.chatuidemo.adapter.MessageAdapter.java

/**
 * ?/*  w w w  . j  a  va2s . co  m*/
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleVideoMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {

    VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
    // final File image=new File(PathUtil.getInstance().getVideoPath(),
    // videoBody.getFileName());
    String localThumb = videoBody.getLocalThumb();

    holder.iv.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult(new Intent(activity, ContextMenu.class)
                    .putExtra("position", position).putExtra("type", EMMessage.Type.VIDEO.ordinal()),
                    ChatMessage.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    if (localThumb != null) {

        showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
    }
    if (videoBody.getLength() > 0) {
        String time = DateUtils.toTimeBySecond(videoBody.getLength());
        holder.timeLength.setText(time);
    }
    holder.playBtn.setImageResource(R.drawable.video_download_btn_nor);

    if (message.direct == EMMessage.Direct.RECEIVE) {
        if (videoBody.getVideoFileLength() > 0) {
            String size = TextFormater.getDataSize(videoBody.getVideoFileLength());
            holder.size.setText(size);
        }
    } else {
        if (videoBody.getLocalUrl() != null && new File(videoBody.getLocalUrl()).exists()) {
            String size = TextFormater.getDataSize(new File(videoBody.getLocalUrl()).length());
            holder.size.setText(size);
        }
    }

    if (message.direct == EMMessage.Direct.RECEIVE) {

        // System.err.println("it is receive msg");
        if (message.status == EMMessage.Status.INPROGRESS) {
            // System.err.println("!!!! back receive");
            holder.iv.setImageResource(R.drawable.default_image);
            showDownloadImageProgress(message, holder);

        } else {
            // System.err.println("!!!! not back receive, show image directly");
            holder.iv.setImageResource(R.drawable.default_image);
            if (localThumb != null) {
                showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
            }

        }

        return;
    }
    holder.pb.setTag(position);

    // until here ,deal with send video msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(R.string.send_fail)
                                            + activity.getString(R.string.connect_failuer_toast),
                                    Toast.LENGTH_LONG).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        // sendMsgInBackground(message, holder);
        sendPictureMessage(message, holder);

    }

}

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

public void startDownloadUpgradePackage(final OTAServerManager serverManager) {
    if (asyncTask != null) {
        asyncTask.cancel(true);/*w  w  w.  ja  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, 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 w w .  j a va2s. co 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);
}

From source file:org.accada.reader.rprm.core.Source.java

/**
 * Remove a list of read triggers.//w  w w.jav a 2s .  c  o  m
 * @param triggerList
 *           The list of read triggers
 */
public void removeReadTriggers(final Trigger[] triggerList) {

    Vector triggers = readerDevice.getVector(triggerList);

    Enumeration iterator = triggers.elements();
    Trigger cur;

    while (iterator.hasMoreElements()) {
        cur = (Trigger) iterator.nextElement();

        if (readTriggers.containsKey(cur.getName())) {
            if (cur.getType().equals(TriggerType.CONTINUOUS)) {
                // continuous trigger
                continuousThread.stop();
                continuousThread = null;
            } else if (cur.getType().equals(TriggerType.TIMER)) {
                // timer trigger
                if (timerThreads.containsKey(cur.getName())) {
                    Timer t = (Timer) timerThreads.get(cur.getName());
                    t.cancel();
                    timerThreads.remove(cur.getName());
                }
            } else if (cur.getType().equals(TriggerType.IO_EDGE)) {
                // io edge trigger
                // get port
                final int num = 6;
                String port = cur.getValue().substring(cur.getValue().indexOf(';') + num,
                        cur.getValue().lastIndexOf(';'));
                if (readerDevice.getEdgeTriggers().containsKey(port)) {
                    IOEdgeTriggerPortManager manager = (IOEdgeTriggerPortManager) readerDevice.getEdgeTriggers()
                            .get(port);
                    manager.removeListener(cur, this.getName());
                    if (manager.getNumberOfTriggers() <= 0) {
                        manager.stop();
                    }
                }
            } else if (cur.getType().equals(TriggerType.IO_VALUE)) {
                // io value trigger
                // get port
                final int num = 5;
                String port = cur.getValue().substring(num, cur.getValue().indexOf(';'));
                if (readerDevice.getValueTriggers().containsKey(port)) {
                    IOValueTriggerPortManager manager = (IOValueTriggerPortManager) readerDevice
                            .getValueTriggers().get(port);
                    manager.removeListener(cur, this.getName());
                    if (manager.getNumberOfTriggers() <= 0) {
                        manager.stop();
                    }
                }
            }

            this.readTriggers.remove(cur.getName());
        }
    }

}

From source file:org.kurento.test.functional.recorder.BaseRecorder.java

protected void launchBrowser(MediaPipeline mp, WebRtcEndpoint webRtcEp, PlayerEndpoint playerEp,
        RecorderEndpoint recorderEp, String expectedVideoCodec, String expectedAudioCodec, String recordingFile,
        Color expectedColor, int xColor, int yColor, int playTime) throws InterruptedException {

    Timer gettingStats = new Timer();
    final CountDownLatch errorContinuityAudiolatch = new CountDownLatch(1);

    getPage().subscribeEvents("playing");
    getPage().initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
    playerEp.play();/*  w  ww .j a v  a  2s .c  o m*/
    final CountDownLatch eosLatch = new CountDownLatch(1);
    playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
        @Override
        public void onEvent(EndOfStreamEvent event) {
            eosLatch.countDown();
        }
    });

    if (recorderEp != null) {
        recorderEp.record();
    }

    // Assertions
    String inRecording = recorderEp == null ? " in the recording" : "";

    Assert.assertTrue("Not received media (timeout waiting playing event)" + inRecording,
            getPage().waitForEvent("playing"));

    if (recorderEp == null) {
        // Checking continuity of the audio
        getPage().activatePeerConnectionInboundStats("webRtcPeer.peerConnection");

        gettingStats.schedule(new CheckAudioTimerTask(errorContinuityAudiolatch, getPage()), 100, 200);
    }

    Assert.assertTrue(
            "Color at coordinates " + xColor + "," + yColor + " must be " + expectedColor + inRecording,
            getPage().similarColorAt(expectedColor, xColor, yColor));
    Assert.assertTrue("Not received EOS event in player" + inRecording,
            eosLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

    final CountDownLatch recorderLatch = new CountDownLatch(1);
    if (recorderEp != null) {

        saveGstreamerDot(mp);

        recorderEp.stopAndWait(new Continuation<Void>() {

            @Override
            public void onSuccess(Void result) throws Exception {
                recorderLatch.countDown();
            }

            @Override
            public void onError(Throwable cause) throws Exception {
                recorderLatch.countDown();
            }
        });

        Assert.assertTrue("Not stop properly", recorderLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

        // Wait until file exists
        waitForFileExists(recordingFile);

        AssertMedia.assertCodecs(recordingFile, expectedVideoCodec, expectedAudioCodec);
        AssertMedia.assertDuration(recordingFile, TimeUnit.SECONDS.toMillis(playTime),
                TimeUnit.SECONDS.toMillis(getPage().getThresholdTime()));

    } else {
        gettingStats.cancel();
        getPage().stopPeerConnectionInboundStats("webRtcPeer.peerConnection");
        double currentTime = getPage().getCurrentTime();
        Assert.assertTrue("Error in play time in the recorded video (expected: " + playTime + " sec, real: "
                + currentTime + " sec) " + inRecording, getPage().compare(playTime, currentTime));

        if (recorderEp == null) {
            Assert.assertTrue("Check audio. There were more than 2 seconds without receiving packets",
                    errorContinuityAudiolatch.getCount() == 1);
        }

    }
}

From source file:at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider.java

private HTTPMetadataProvider createNewHTTPMetaDataProvider(String metadataURL, byte[] certificate,
        String oaName, MetadataFilterChain filter) {
    HTTPMetadataProvider httpProvider = null;
    Timer timer = null;
    MOAHttpClient httpClient = null;//from   www .ja  v  a2s  .c o  m
    try {
        httpClient = new MOAHttpClient();

        if (metadataURL.startsWith("https:")) {
            try {
                MOAHttpProtocolSocketFactory protoSocketFactory = new MOAHttpProtocolSocketFactory(
                        PVPConstants.SSLSOCKETFACTORYNAME,
                        AuthConfigurationProvider.getInstance().getCertstoreDirectory(),
                        AuthConfigurationProvider.getInstance().getTrustedCACertificates(), null,
                        ChainingModeType
                                .fromValue(AuthConfigurationProvider.getInstance().getDefaultChainingMode()),
                        AuthConfigurationProvider.getInstance().isTrustmanagerrevoationchecking());

                httpClient.setCustomSSLTrustStore(metadataURL, protoSocketFactory);

            } catch (MOAHttpProtocolSocketFactoryException e) {
                Logger.warn("MOA SSL-TrustStore can not initialized. Use default Java TrustStore.");

            }
        }

        timer = new Timer();
        httpProvider = new HTTPMetadataProvider(timer, httpClient, metadataURL);
        httpProvider.setParserPool(new BasicParserPool());
        httpProvider.setRequireValidMetadata(true);
        httpProvider.setMinRefreshDelay(1000 * 60 * 15); //15 minutes
        httpProvider.setMaxRefreshDelay(1000 * 60 * 60 * 24); //24 hours
        //httpProvider.setRefreshDelayFactor(0.1F);

        if (filter == null) {
            filter = new MetadataFilterChain(metadataURL, certificate);
        }
        httpProvider.setMetadataFilter(filter);
        httpProvider.initialize();

        httpProvider.setRequireValidMetadata(true);

        return httpProvider;

    } catch (Throwable e) {
        if (e.getCause() != null && e.getCause().getCause() instanceof SSLHandshakeException) {
            Logger.warn("SSL-Server certificate for metadata " + metadataURL + " not trusted.", e);
        }

        Logger.error("Failed to add Metadata file for " + oaName + "[ " + e.getMessage() + " ]", e);

        if (httpProvider != null) {
            Logger.debug("Destroy failed Metadata provider");
            httpProvider.destroy();
        }

        if (timer != null) {
            Logger.debug("Destroy Timer.");
            timer.cancel();
        }

    }

    return null;
}