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.gizwits.smartlight.activity.MainListActivity.java

@Override
public void onResume() {
    super.onResume();
    refreshMenu();//from w ww .j av  a2s.  com
    //?
    Log.d(TAG, "centralControlsetListener");
    centralControlDevice = (XPGWifiCentralControlDevice) mXpgWifiDevice;
    centralControlDevice.setListener(xpgWifiCentralControlDeviceListener);
    mCenter.cSetXPGWifiCentralControlDevice(centralControlDevice);
    mCenter.cSetDid(centralControlDevice.getDid());
    // bottomClose();
    ledList.clear();
    ControllerList.clear();
    showItemDevices.clear();
    //First get group information then subdeviceList
    mCenter.cGetGroups(setmanager.getUid(), setmanager.getToken(), Configs.PRODUCT_KEY_Sub);//?
    mCenter.cGetSubDevicesList(centralControlDevice);//??
    mCenter.cGetAllScenes(setmanager.getUid(), setmanager.getToken(), Configs.PRODUCT_KEY_Sub);//?

    //        // bottomClose();
    //        ledList.clear();
    //        ControllerList.clear();
    //        showItemDevices.clear();

    //3??Loadding
    getStatusProgress.show();
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            getStatusProgress.cancel();
            timer.cancel();
        }
    }, 3000);
}

From source file:net.ustyugov.jtalk.service.JTalkService.java

public void disconnect(String account) {
    if (!started)
        return;//from  w w w  .  j  a va  2s .  c  o  m
    Log.e("Disconnect", account);
    if (connections.containsKey(account)) {
        if (connectionTasks.containsKey(account)) {
            connectionTasks.remove(account).cancel(true);
        }

        if (pingTimers.containsKey(account)) {
            Timer timer = pingTimers.remove(account);
            timer.cancel();
            timer.purge();
        }

        try {
            removeConnectionListener(account);
            Presence presence = new Presence(Presence.Type.unavailable, "", 0, null);
            XMPPConnection connection = connections.remove(account);
            connection.disconnect(presence);
        } catch (Exception ignored) {
        }

        try {
            if (sipManagers.containsKey(account)) {
                SipManager manager = sipManagers.get(account);
                manager.close("sip:" + account);
            }
        } catch (Exception ignored) {
        }
        setState(account, getString(R.string.Disconnect));
    }
    sendBroadcast(new Intent(Constants.UPDATE));
}

From source file:net.ustyugov.jtalk.service.JTalkService.java

public void disconnect() {
    if (!started)
        return;/*w w  w .  j a  va 2  s . co m*/
    if (wifiLock != null && wifiLock.isHeld())
        wifiLock.release();
    if (wakeLock != null && wakeLock.isHeld())
        wakeLock.release();
    Collection<XMPPConnection> con = getAllConnections();
    for (XMPPConnection connection : con) {
        String account = StringUtils.parseBareAddress(connection.getUser());
        if (isAuthenticated(account)) {
            if (connectionTasks.containsKey(account)) {
                connectionTasks.remove(account).cancel(true);
            }
            if (pingTimers.containsKey(account)) {
                Timer timer = pingTimers.remove(account);
                timer.cancel();
                timer.purge();
            }
            removeConnectionListener(account);
            Presence presence = new Presence(Presence.Type.unavailable, "", 0, null);
            connection.disconnect(presence);

            try {
                if (sipManagers.containsKey(account)) {
                    SipManager manager = sipManagers.get(account);
                    manager.close("sip:" + account);
                }
            } catch (Exception ignored) {
            }
        } else if (connection.isConnected())
            connection.disconnect();
        setState(account, getString(R.string.Disconnect));
        connections.remove(account);
    }
}

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

protected void checkRecordingFile(String recordingFile, String browserName, Color[] expectedColors,
        long playTime, String expectedVideoCodec, String expectedAudioCodec) throws InterruptedException {

    // Checking continuity of the audio
    Timer gettingStats = new Timer();
    final CountDownLatch errorContinuityAudiolatch = new CountDownLatch(1);

    waitForFileExists(recordingFile);/*from  w  ww.j  a va  2  s . com*/

    MediaPipeline mp = kurentoClient.createMediaPipeline();
    PlayerEndpoint playerEp = new PlayerEndpoint.Builder(mp, recordingFile).build();
    WebRtcEndpoint webRtcEp = new WebRtcEndpoint.Builder(mp).build();
    playerEp.connect(webRtcEp);

    // Playing the recording
    WebRtcTestPage checkPage = getPage(browserName);
    checkPage.setThresholdTime(checkPage.getThresholdTime() * 2);
    checkPage.subscribeEvents("playing");
    checkPage.initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
    final CountDownLatch eosLatch = new CountDownLatch(1);
    playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
        @Override
        public void onEvent(EndOfStreamEvent event) {
            eosLatch.countDown();
        }
    });
    playerEp.play();

    // Assertions in recording
    final String messageAppend = "[played file with media pipeline]";
    Assert.assertTrue("Not received media in the recording (timeout waiting playing event) " + messageAppend,
            checkPage.waitForEvent("playing"));

    checkPage.activatePeerConnectionInboundStats("webRtcPeer.peerConnection");

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

    for (Color color : expectedColors) {
        Assert.assertTrue("The color of the recorded video should be " + color + " " + messageAppend,
                checkPage.similarColorAt(color, 50, 50));
    }
    Assert.assertTrue("Not received EOS event in player",
            eosLatch.await(checkPage.getTimeout(), TimeUnit.SECONDS));

    gettingStats.cancel();

    double currentTime = checkPage.getCurrentTime();
    Assert.assertTrue("Error in play time in the recorded video (expected: " + playTime + " sec, real: "
            + currentTime + " sec) " + messageAppend, checkPage.compare(playTime, currentTime));

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

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

    mp.release();
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.IdentityProviderConfiguratorTests.java

@Test
public void testGetEntityID() throws Exception {
    Timer t = new Timer();
    conf.setIdentityProviders(sampleData);
    conf.afterPropertiesSet();//  ww  w. j a  va  2s. c  o m
    for (SamlIdentityProviderDefinition def : conf.getIdentityProviderDefinitions()) {
        switch (def.getIdpEntityAlias()) {
        case "okta-local": {
            ComparableProvider provider = (ComparableProvider) conf.getExtendedMetadataDelegateFromCache(def)
                    .getDelegate();
            assertEquals("http://www.okta.com/k2lvtem0VAJDMINKEYJW", provider.getEntityID());
            break;
        }
        case "okta-local-3": {
            ComparableProvider provider = (ComparableProvider) conf.getExtendedMetadataDelegateFromCache(def)
                    .getDelegate();
            assertEquals("http://www.okta.com/k2lvtem0VAJDMINKEYJX", provider.getEntityID());
            break;
        }
        case "okta-local-2": {
            ComparableProvider provider = (ComparableProvider) conf.getExtendedMetadataDelegateFromCache(def)
                    .getDelegate();
            assertEquals("http://www.okta.com/k2lw4l5bPODCMIIDBRYZ", provider.getEntityID());
            break;
        }
        case "simplesamlphp-url": {
            ComparableProvider provider = (ComparableProvider) conf.getExtendedMetadataDelegateFromCache(def)
                    .getDelegate();
            assertEquals("http://simplesamlphp.identity.cf-app.com/saml2/idp/metadata.php",
                    provider.getEntityID());
            break;
        }
        default:
            fail(String.format("Unknown provider %s", def.getIdpEntityAlias()));
        }

    }
    t.cancel();
}

From source file:hydrograph.server.execution.tracking.client.main.HydrographMain.java

/**
 *    //from  www .  j  av a2 s.c  o  m
 * @param latch
 * @param session
 * @param jobId
 * @param timer
 * @param execution
 * @param socket
 * @throws IOException
 */
private void sendExecutionTrackingStatus(final CountDownLatch latch, Session session, final String jobId,
        final Timer timer, final HydrographService execution, final HydrographEngineCommunicatorSocket socket)
        throws IOException {
    try {
        TimerTask task = new TimerTask() {
            ExecutionStatus previousExecutionStatus = null;

            @Override
            public void run() {
                List<ComponentInfo> componentInfos = execution.getStatus();
                if (!componentInfos.isEmpty()) {
                    List<ComponentStatus> componentStatusList = new ArrayList<ComponentStatus>();
                    for (ComponentInfo componentInfo : componentInfos) {
                        ComponentStatus componentStatus = new ComponentStatus(componentInfo.getComponentId(),
                                componentInfo.getComponentName(), componentInfo.getCurrentStatus(),
                                componentInfo.getBatch(), componentInfo.getProcessedRecords());
                        componentStatusList.add(componentStatus);
                    }
                    ExecutionStatus executionStatus = new ExecutionStatus(componentStatusList);
                    executionStatus.setJobId(jobId);
                    executionStatus.setClientId(Constants.ENGINE_CLIENT + jobId);
                    executionStatus.setType(Constants.POST);
                    Gson gson = new Gson();
                    try {
                        if (previousExecutionStatus == null
                                || !executionStatus.equals(previousExecutionStatus)) {
                            socket.sendMessage(gson.toJson(executionStatus));
                            previousExecutionStatus = executionStatus;
                        }
                    } catch (IOException e) {
                        logger.error("Fail to send status for job - " + jobId, e);
                        timer.cancel();
                    }

                    if (StringUtils.isNotBlank(jobId)) {
                        //moved this after sendMessage in order to log even if the service is not running 
                        ExecutionTrackingFileLogger.INSTANCE.log(jobId, executionStatus);
                    }

                }
                if (!execution.getJobRunningStatus()) {
                    timer.cancel();
                    latch.countDown();
                }
            }
        };

        timer.schedule(task, 0l, ExecutionTrackingUtils.INSTANCE.getStatusFrequency());
        latch.await();

    } catch (Throwable t) {
        logger.error("Failure in job - " + jobId, t);
        timer.cancel();
        throw new RuntimeException(t);
    } finally {

        if (session != null && session.isOpen()) {
            logger.debug("Closing Websocket engine client");
            CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Session Closed");
            session.close(closeReason);
        }
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.GerritServer.java

/**
 * Server to sleep. This method returns actual connection status is changed or timeout.
 * Used by jelly./*from ww w . j av  a  2  s  . c o m*/
 *
 * @return connection status.
 */
public JSONObject doSleep() {
    Timer timer = new Timer();
    try {
        stopConnection();

        final CountDownLatch responseLatch = new CountDownLatch(RESPONSE_COUNT);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (gerritConnectionListener == null || !gerritConnectionListener.isConnected()) {
                    responseLatch.countDown();
                }
            }
        }, RESPONSE_INTERVAL_MS, RESPONSE_INTERVAL_MS);

        if (responseLatch.await(RESPONSE_TIMEOUT_S, TimeUnit.SECONDS)) {
            setConnectionResponse(STOP_SUCCESS);
        } else {
            throw new InterruptedException("time out.");
        }
    } catch (Exception ex) {
        setConnectionResponse(STOP_FAILURE);
        logger.error("Could not stop connection. ", ex);
    }
    timer.cancel();

    JSONObject obj = new JSONObject();
    String status = "down";
    if (gerritConnectionListener != null) {
        if (gerritConnectionListener.isConnected()) {
            status = "up";
        }
    }
    obj.put("status", status);
    return obj;
}

From source file:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command//from   w w w .  j  a v a  2 s .c o  m
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}

From source file:gate.util.reporting.PRTimeReporter.java

/**
 * Calls store, calculate and printReport for generating the actual report.
 *//*from  ww  w  . j  ava  2 s.c o  m*/
@SuppressWarnings("unchecked")
private void generateReport() throws BenchmarkReportInputFileFormatException {
    Timer timer = null;
    try {
        TimerTask task = new FileWatcher(getBenchmarkFile()) {
            @Override
            protected void onChange(File file) throws BenchmarkReportExecutionException {
                throw new BenchmarkReportExecutionException(
                        getBenchmarkFile() + " file has been modified while generating the report.");
            }
        };
        timer = new Timer();
        // repeat the check every second
        timer.schedule(task, new Date(), 1000);

        Object report1Container1 = store(getBenchmarkFile());
        Object report1Container2 = calculate(report1Container1);
        if (getSortOrder().equalsIgnoreCase("time_taken")) {
            report1Container2 = sortReport((LinkedHashMap<String, Object>) report1Container2);
        }
        if (reportFile == null) {
            reportFile = new File(System.getProperty("java.io.tmpdir"),
                    "report." + ((printMedia.equals(MEDIA_HTML)) ? "html" : "txt"));
        }
        printReport(report1Container2, reportFile);
    } finally {
        if (timer != null) {
            timer.cancel();
        }
    }
}

From source file:com.xiaoyu.DoctorHelp.chat.chatuidemo.adapter.MessageAdapter.java

/**
 * ?/*from  w  ww.j  a v  a 2s.  co  m*/
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleFileMessage(final EMMessage message, final ViewHolder holder, int position,
        View convertView) {
    final NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody();
    final String filePath = fileMessageBody.getLocalUrl();
    holder.tv_file_name.setText(fileMessageBody.getFileName());
    holder.tv_file_size.setText(TextFormater.getDataSize(fileMessageBody.getFileSize()));
    holder.ll_container.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
            File file = new File(filePath);
            if (file != null && file.exists()) {
                // 
                FileUtils.openFile(file, (Activity) context);
            } else {
                // 
                context.startActivity(
                        new Intent(context, ShowNormalFileActivity.class).putExtra("msgbody", fileMessageBody));
            }
            if (message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
                    && message.getChatType() != ChatType.GroupChat
                    && message.getChatType() != ChatType.ChatRoom) {
                try {
                    EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                    message.isAcked = true;
                } catch (EaseMobException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    });
    String st1 = context.getResources().getString(R.string.Have_downloaded);
    String st2 = context.getResources().getString(R.string.Did_not_download);
    if (message.direct == EMMessage.Direct.RECEIVE) { // ?
        EMLog.d(TAG, "it is receive msg");
        File file = new File(filePath);
        if (file != null && file.exists()) {
            holder.tv_file_download_state.setText(st1);
        } else {
            holder.tv_file_download_state.setText(st2);
        }
        return;
    }

    // until here, deal with send voice msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.INVISIBLE);
        holder.tv.setVisibility(View.INVISIBLE);
        holder.staus_iv.setVisibility(View.INVISIBLE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.INVISIBLE);
        holder.tv.setVisibility(View.INVISIBLE);
        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.INVISIBLE);
                            holder.tv.setVisibility(View.INVISIBLE);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.INVISIBLE);
                            holder.tv.setVisibility(View.INVISIBLE);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(R.string.send_fail)
                                            + activity.getString(R.string.connect_failuer_toast),
                                    Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }

                    }
                });

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

}