List of usage examples for java.util.concurrent ScheduledFuture cancel
boolean cancel(boolean mayInterruptIfRunning);
From source file:org.openhab.io.transport.modbus.internal.ModbusManagerImpl.java
@SuppressWarnings({ "null", "unused" }) @Override/*from ww w .j ava 2 s . com*/ public boolean unregisterRegularPoll(PollTask task) { synchronized (this) { ScheduledExecutorService executor = this.scheduledThreadPoolExecutor; ModbusSlaveConnectionFactoryImpl factory = this.connectionFactory; Objects.requireNonNull(executor, "Not activated!"); Objects.requireNonNull(factory, "Not activated!"); // cancel poller @Nullable ScheduledFuture<?> future = scheduledPollTasks.remove(task); if (future == null) { // No such poll task logger.warn("Caller tried to unregister nonexisting poll task {}", task); return false; } logger.info("Unregistering regular poll task {} (interrupting if necessary)", task); // Make sure connections to this endpoint are closed when they are returned to pool (which // is usually pretty soon as transactions should be relatively short-lived) factory.disconnectOnReturn(task.getEndpoint(), System.currentTimeMillis()); future.cancel(true); logger.info("Poll task {} canceled", task); try { // Close all idle connections as well (they will be reconnected if necessary on borrow) if (connectionPool != null) { connectionPool.clear(task.getEndpoint()); } } catch (Exception e) { logger.error("Could not clear poll task {} endpoint {}. Stack trace follows", task, task.getEndpoint(), e); return false; } return true; } }
From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Updates the task stopping it and rescheduling it * @param task the task to update//from w ww . j a va 2 s . c om */ public void updateScheduledTask(ScheduledTaskWrapper task) { if (task == null) { if (log.isTraceEnabled()) { log.trace("Trying to update a null task. Request rejected"); } return; } if (log.isInfoEnabled()) { log.info("Updating task '" + task + "'. The task will be cancelled and " + "then re-scheduled"); } // // Locking the lock for this task so no other thread can handle it avoiding // conflict (what happens if a thread is removing it an another threead is // updating it ?) // Lock handlingTaskLock = getHandlingTaskLock(task.getId()); handlingTaskLock.lock(); try { ScheduledFuture scheduledFuture = null; ScheduledTaskWrapper oldScheduledTask = null; synchronized (scheduledFutures) { scheduledFuture = (ScheduledFuture) scheduledFutures.get(task); oldScheduledTask = (ScheduledTaskWrapper) scheduledFutures.getKey(scheduledFuture); } boolean cancelled = false; if (scheduledFuture != null) { cancelled = scheduledFuture.isCancelled(); if (!cancelled) { cancelled = scheduledFuture.cancel(true); // if we can, we stop its // execution. Remember that // cancel means cancel its // scheduled execution and // not just the running one if (cancelled) { if (log.isTraceEnabled()) { log.trace("Task '" + task.getId() + "' cancelled successfully"); } } else { if (log.isTraceEnabled()) { log.trace("Task '" + task.getId() + "' not cancelled for unknown reasons." + "Is it already cancelled ? " + ((scheduledFuture.isCancelled() ? "YES" : "NO"))); } } } else { if (log.isTraceEnabled()) { log.trace("Task '" + task.getId() + "' has been already cancelled"); } } if (!ScheduledTaskWrapper.State.SHUTDOWN.equals(oldScheduledTask.getState())) { if (log.isTraceEnabled()) { log.trace("Shutting down task '" + task.getId() + "'"); } try { oldScheduledTask.shutdown(); } catch (TaskException ex) { log.error("Error shutting down scheduled task '" + oldScheduledTask + "'", ex); } oldScheduledTask.setState(ScheduledTaskWrapper.State.SHUTDOWN); } synchronized (scheduledFutures) { // // Any time we remove the scheduledTask from scheduledFutures, // we try to remove the scheduledFuture from the queue. This // is not really needed because after a while this is performed // automatically but in this way we keep scheduledFutures and // the queue in sync // if (scheduledFuture instanceof Runnable) { super.remove((Runnable) scheduledFuture); } scheduledFutures.remove(oldScheduledTask); } } else { if (log.isTraceEnabled()) { log.trace("Task '" + task + "' seems not scheduled"); } } scheduleTask(task, 0); } finally { handlingTaskLock.unlock(); } }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java
/** * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle. * * @param script the script to evaluate/* w w w . ja v a2s.c o m*/ * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process */ public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars, final LifeCycle lifeCycle) { final String lang = Optional.ofNullable(language).orElse("gremlin-groovy"); logger.debug("Preparing to evaluate script - {} - in thread [{}]", script, Thread.currentThread().getName()); final Bindings bindings = new SimpleBindings(); bindings.putAll(globalBindings); bindings.putAll(boundVars); final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>(); final FutureTask<Void> f = new FutureTask<>(() -> { try { lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings); logger.debug("Evaluating script - {} - in thread [{}]", script, Thread.currentThread().getName()); final Object o = scriptEngines.eval(script, bindings, lang); // apply a transformation before sending back the result - useful when trying to force serialization // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some // transactional constraints final Object result = lifeCycle.getTransformResult().isPresent() ? lifeCycle.getTransformResult().get().apply(o) : o; // a mechanism for taking the final result and doing something with it in the same thread, but // AFTER the eval and transform are done and that future completed. this provides a final means // for working with the result in the same thread as it was eval'd if (lifeCycle.getWithResult().isPresent()) lifeCycle.getWithResult().get().accept(result); lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings); // the evaluationFuture must be completed after all processing as an exception in lifecycle events // that must raise as an exception to the caller who has the returned evaluationFuture. in other words, // if it occurs before this point, then the handle() method won't be called again if there is an // exception that ends up below trying to completeExceptionally() evaluationFuture.complete(result); } catch (Throwable ex) { final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex); // thread interruptions will typically come as the result of a timeout, so in those cases, // check for that situation and convert to TimeoutException if (root instanceof InterruptedException) evaluationFuture.completeExceptionally(new TimeoutException(String.format( "Script evaluation exceeded the configured 'scriptEvaluationTimeout' threshold of %s ms for request [%s]: %s", scriptEvaluationTimeout, script, root.getMessage()))); else { lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root); evaluationFuture.completeExceptionally(root); } } return null; }); executorService.execute(f); if (scriptEvaluationTimeout > 0) { // Schedule a timeout in the thread pool for future execution final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> { logger.warn("Timing out script - {} - in thread [{}]", script, Thread.currentThread().getName()); if (!f.isDone()) { lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings); f.cancel(true); } }, scriptEvaluationTimeout, TimeUnit.MILLISECONDS); // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed // with exception evaluationFuture.handleAsync((v, t) -> { logger.debug( "Killing scheduled timeout on script evaluation as the eval completed (possibly with exception)."); return sf.cancel(true); }); } return evaluationFuture; }
From source file:org.apache.hadoop.hbase.test.IntegrationTestTimeBoundedRequestsWithRegionReplicas.java
@Override protected void runIngestTest(long defaultRunTime, long keysPerServerPerIter, int colsPerKey, int recordSize, int writeThreads, int readThreads) throws Exception { LOG.info("Cluster size:" + util.getHBaseClusterInterface().getClusterStatus().getServersSize()); long start = System.currentTimeMillis(); String runtimeKey = String.format(RUN_TIME_KEY, this.getClass().getSimpleName()); long runtime = util.getConfiguration().getLong(runtimeKey, defaultRunTime); long startKey = 0; long numKeys = getNumKeys(keysPerServerPerIter); // write data once LOG.info("Writing some data to the table"); writeData(colsPerKey, recordSize, writeThreads, startKey, numKeys); // flush the table LOG.info("Flushing the table"); Admin admin = util.getHBaseAdmin();//from w w w . jav a 2s.com admin.flush(getTablename()); // re-open the regions to make sure that the replicas are up to date long refreshTime = conf.getLong(StorefileRefresherChore.REGIONSERVER_STOREFILE_REFRESH_PERIOD, 0); if (refreshTime > 0 && refreshTime <= 10000) { LOG.info("Sleeping " + refreshTime + "ms to ensure that the data is replicated"); Threads.sleep(refreshTime * 3); } else { LOG.info("Reopening the table"); admin.disableTable(getTablename()); admin.enableTable(getTablename()); } // We should only start the ChaosMonkey after the readers are started and have cached // all of the region locations. Because the meta is not replicated, the timebounded reads // will timeout if meta server is killed. // We will start the chaos monkey after 1 minute, and since the readers are reading random // keys, it should be enough to cache every region entry. long chaosMonkeyDelay = conf.getLong(String.format("%s.%s", TEST_NAME, CHAOS_MONKEY_DELAY_KEY), DEFAUL_CHAOS_MONKEY_DELAY); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); LOG.info(String.format("ChaosMonkey delay is : %d seconds. Will start %s " + "ChaosMonkey after delay", chaosMonkeyDelay / 1000, monkeyToUse)); ScheduledFuture<?> result = executorService.schedule(new Runnable() { @Override public void run() { try { LOG.info("Starting ChaosMonkey"); monkey.start(); monkey.waitForStop(); } catch (Exception e) { LOG.warn(StringUtils.stringifyException(e)); } } }, chaosMonkeyDelay, TimeUnit.MILLISECONDS); // set the intended run time for the reader. The reader will do read requests // to random keys for this amount of time. long remainingTime = runtime - (System.currentTimeMillis() - start); LOG.info("Reading random keys from the table for " + remainingTime / 60000 + " min"); this.conf.setLong(String.format(RUN_TIME_KEY, TimeBoundedMultiThreadedReader.class.getSimpleName()), remainingTime); // load tool shares the same conf // now start the readers which will run for configured run time try { int ret = loadTool .run(getArgsForLoadTestTool("-read", String.format("100:%d", readThreads), startKey, numKeys)); if (0 != ret) { String errorMsg = "Verification failed with error code " + ret; LOG.error(errorMsg); Assert.fail(errorMsg); } } finally { if (result != null) result.cancel(false); monkey.stop("Stopping the test"); monkey.waitForStop(); executorService.shutdown(); } }
From source file:org.openhab.binding.amazonechocontrol.internal.handler.EchoHandler.java
@Override public void handleCommand(ChannelUID channelUID, Command command) { try {/* w w w .j av a 2 s. com*/ int waitForUpdate = 1000; boolean needBluetoothRefresh = false; String lastKnownBluetoothMAC = this.lastKnownBluetoothMAC; ScheduledFuture<?> updateStateJob = this.updateStateJob; this.updateStateJob = null; if (updateStateJob != null) { this.disableUpdate = false; updateStateJob.cancel(false); } AccountHandler account = this.account; if (account == null) { return; } Connection connection = account.findConnection(); if (connection == null) { return; } Device device = this.device; if (device == null) { return; } // Player commands String channelId = channelUID.getId(); if (channelId.equals(CHANNEL_PLAYER)) { if (command == PlayPauseType.PAUSE || command == OnOffType.OFF) { connection.command(device, "{\"type\":\"PauseCommand\"}"); } else if (command == PlayPauseType.PLAY || command == OnOffType.ON) { if (isPaused) { connection.command(device, "{\"type\":\"PlayCommand\"}"); } else { connection.playMusicVoiceCommand(device, this.musicProviderId, "!"); waitForUpdate = 3000; } } else if (command == NextPreviousType.NEXT) { connection.command(device, "{\"type\":\"NextCommand\"}"); } else if (command == NextPreviousType.PREVIOUS) { connection.command(device, "{\"type\":\"PreviousCommand\"}"); } else if (command == RewindFastforwardType.FASTFORWARD) { connection.command(device, "{\"type\":\"ForwardCommand\"}"); } else if (command == RewindFastforwardType.REWIND) { connection.command(device, "{\"type\":\"RewindCommand\"}"); } } // Notification commands if (channelId.equals(CHANNEL_NOTIFICATION_VOLUME)) { if (command instanceof PercentType) { int volume = ((PercentType) command).intValue(); connection.notificationVolume(device, volume); this.noticationVolumeLevel = volume; waitForUpdate = -1; account.forceCheckData(); } } if (channelId.equals(CHANNEL_ASCENDING_ALARM)) { if (command == OnOffType.OFF) { connection.ascendingAlarm(device, false); this.ascendingAlarm = false; waitForUpdate = -1; account.forceCheckData(); } if (command == OnOffType.ON) { connection.ascendingAlarm(device, true); this.ascendingAlarm = true; waitForUpdate = -1; account.forceCheckData(); } } // Media progress commands Long mediaPosition = null; if (channelId.equals(CHANNEL_MEDIA_PROGRESS)) { if (command instanceof PercentType) { PercentType value = (PercentType) command; int percent = value.intValue(); mediaPosition = Math.round((mediaLengthMs / 1000d) * (percent / 100d)); } } if (channelId.equals(CHANNEL_MEDIA_PROGRESS_TIME)) { if (command instanceof DecimalType) { DecimalType value = (DecimalType) command; mediaPosition = value.longValue(); } if (command instanceof QuantityType<?>) { QuantityType<?> value = (QuantityType<?>) command; @Nullable QuantityType<?> seconds = value.toUnit(SmartHomeUnits.SECOND); if (seconds != null) { mediaPosition = seconds.longValue(); } } } if (mediaPosition != null) { waitForUpdate = -1; synchronized (progressLock) { String seekCommand = "{\"type\":\"SeekCommand\",\"mediaPosition\":" + mediaPosition + ",\"contentFocusClientId\":null}"; connection.command(device, seekCommand); connection.command(device, seekCommand); // Must be sent twice, the first one is ignored sometimes this.mediaProgressMs = mediaPosition * 1000; mediaStartMs = System.currentTimeMillis() - this.mediaProgressMs; updateMediaProgress(false); } } // Volume commands if (channelId.equals(CHANNEL_VOLUME)) { Integer volume = null; if (command instanceof PercentType) { PercentType value = (PercentType) command; volume = value.intValue(); } else if (command == OnOffType.OFF) { volume = 0; } else if (command == OnOffType.ON) { volume = lastKnownVolume; } else if (command == IncreaseDecreaseType.INCREASE) { if (lastKnownVolume < 100) { lastKnownVolume++; volume = lastKnownVolume; } } else if (command == IncreaseDecreaseType.DECREASE) { if (lastKnownVolume > 0) { lastKnownVolume--; volume = lastKnownVolume; } } if (volume != null) { if (StringUtils.equals(device.deviceFamily, "WHA")) { connection.command(device, "{\"type\":\"VolumeLevelCommand\",\"volumeLevel\":" + volume + ",\"contentFocusClientId\":\"Default\"}"); } else { Map<String, Object> parameters = new Hashtable<String, Object>(); parameters.put("value", volume); connection.executeSequenceCommand(device, "Alexa.DeviceControls.Volume", parameters); } lastKnownVolume = volume; updateState(CHANNEL_VOLUME, new PercentType(lastKnownVolume)); waitForUpdate = -1; } } // equalizer commands if (channelId.equals(CHANNEL_EQUALIZER_BASS) || channelId.equals(CHANNEL_EQUALIZER_MIDRANGE) || channelId.equals(CHANNEL_EQUALIZER_TREBLE)) { if (handleEqualizerCommands(channelId, command, connection, device)) { waitForUpdate = -1; } } // shuffle command if (channelId.equals(CHANNEL_SHUFFLE)) { if (command instanceof OnOffType) { OnOffType value = (OnOffType) command; connection.command(device, "{\"type\":\"ShuffleCommand\",\"shuffle\":\"" + (value == OnOffType.ON ? "true" : "false") + "\"}"); } } // play music command if (channelId.equals(CHANNEL_MUSIC_PROVIDER_ID)) { if (command instanceof StringType) { waitForUpdate = 0; String musicProviderId = ((StringType) command).toFullString(); if (!StringUtils.equals(musicProviderId, this.musicProviderId)) { this.musicProviderId = musicProviderId; if (this.isPlaying) { connection.playMusicVoiceCommand(device, this.musicProviderId, "!"); waitForUpdate = 3000; } } } } if (channelId.equals(CHANNEL_PLAY_MUSIC_VOICE_COMMAND)) { if (command instanceof StringType) { String voiceCommand = ((StringType) command).toFullString(); if (!this.musicProviderId.isEmpty()) { connection.playMusicVoiceCommand(device, this.musicProviderId, voiceCommand); waitForUpdate = 3000; updatePlayMusicVoiceCommand = true; } } } // bluetooth commands if (channelId.equals(CHANNEL_BLUETOOTH_MAC)) { needBluetoothRefresh = true; if (command instanceof StringType) { String address = ((StringType) command).toFullString(); if (!address.isEmpty()) { waitForUpdate = 4000; } connection.bluetooth(device, address); } } if (channelId.equals(CHANNEL_BLUETOOTH)) { needBluetoothRefresh = true; if (command == OnOffType.ON) { waitForUpdate = 4000; String bluetoothId = lastKnownBluetoothMAC; BluetoothState state = bluetoothState; if (state != null && (StringUtils.isEmpty(bluetoothId))) { PairedDevice[] pairedDeviceList = state.pairedDeviceList; if (pairedDeviceList != null) { for (PairedDevice paired : pairedDeviceList) { if (paired == null) { continue; } if (StringUtils.isNotEmpty(paired.address)) { lastKnownBluetoothMAC = paired.address; break; } } } } if (StringUtils.isNotEmpty(lastKnownBluetoothMAC)) { connection.bluetooth(device, lastKnownBluetoothMAC); } } else if (command == OnOffType.OFF) { connection.bluetooth(device, null); } } if (channelId.equals(CHANNEL_BLUETOOTH_DEVICE_NAME)) { needBluetoothRefresh = true; } // amazon music commands if (channelId.equals(CHANNEL_AMAZON_MUSIC_TRACK_ID)) { if (command instanceof StringType) { String trackId = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(trackId)) { waitForUpdate = 3000; } connection.playAmazonMusicTrack(device, trackId); } } if (channelId.equals(CHANNEL_AMAZON_MUSIC_PLAY_LIST_ID)) { if (command instanceof StringType) { String playListId = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(playListId)) { waitForUpdate = 3000; } connection.playAmazonMusicPlayList(device, playListId); } } if (channelId.equals(CHANNEL_AMAZON_MUSIC)) { if (command == OnOffType.ON) { String lastKnownAmazonMusicId = this.lastKnownAmazonMusicId; if (StringUtils.isNotEmpty(lastKnownAmazonMusicId)) { waitForUpdate = 3000; } connection.playAmazonMusicTrack(device, lastKnownAmazonMusicId); } else if (command == OnOffType.OFF) { connection.playAmazonMusicTrack(device, ""); } } // radio commands if (channelId.equals(CHANNEL_RADIO_STATION_ID)) { if (command instanceof StringType) { String stationId = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(stationId)) { waitForUpdate = 3000; } connection.playRadio(device, stationId); } } if (channelId.equals(CHANNEL_RADIO)) { if (command == OnOffType.ON) { String lastKnownRadioStationId = this.lastKnownRadioStationId; if (StringUtils.isNotEmpty(lastKnownRadioStationId)) { waitForUpdate = 3000; } connection.playRadio(device, lastKnownRadioStationId); } else if (command == OnOffType.OFF) { connection.playRadio(device, ""); } } // notification if (channelId.equals(CHANNEL_REMIND)) { if (command instanceof StringType) { stopCurrentNotification(); String reminder = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(reminder)) { waitForUpdate = 3000; updateRemind = true; currentNotification = connection.notification(device, "Reminder", reminder, null); currentNotifcationUpdateTimer = scheduler.scheduleWithFixedDelay(() -> { updateNotificationTimerState(); }, 1, 1, TimeUnit.SECONDS); } } } if (channelId.equals(CHANNEL_PLAY_ALARM_SOUND)) { if (command instanceof StringType) { stopCurrentNotification(); String alarmSound = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(alarmSound)) { waitForUpdate = 3000; updateAlarm = true; String[] parts = alarmSound.split(":", 2); JsonNotificationSound sound = new JsonNotificationSound(); if (parts.length == 2) { sound.providerId = parts[0]; sound.id = parts[1]; } else { sound.providerId = "ECHO"; sound.id = alarmSound; } currentNotification = connection.notification(device, "Alarm", null, sound); currentNotifcationUpdateTimer = scheduler.scheduleWithFixedDelay(() -> { updateNotificationTimerState(); }, 1, 1, TimeUnit.SECONDS); } } } // routine commands if (channelId.equals(CHANNEL_TEXT_TO_SPEECH)) { if (command instanceof StringType) { String text = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(text)) { waitForUpdate = 1000; updateTextToSpeech = true; startTextToSpeech(connection, device, text); } } } if (channelId.equals(CHANNEL_TEXT_TO_SPEECH_VOLUME)) { if (command instanceof PercentType) { PercentType value = (PercentType) command; textToSpeechVolume = value.intValue(); } else if (command == OnOffType.OFF) { textToSpeechVolume = 0; } else if (command == OnOffType.ON) { textToSpeechVolume = lastKnownVolume; } else if (command == IncreaseDecreaseType.INCREASE) { if (textToSpeechVolume < 100) { textToSpeechVolume++; } } else if (command == IncreaseDecreaseType.DECREASE) { if (textToSpeechVolume > 0) { textToSpeechVolume--; } } this.updateState(channelId, new PercentType(textToSpeechVolume)); } if (channelId.equals(CHANNEL_LAST_VOICE_COMMAND)) { if (command instanceof StringType) { String text = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(text)) { waitForUpdate = -1; startTextToSpeech(connection, device, text); } } } if (channelId.equals(CHANNEL_START_COMMAND)) { if (command instanceof StringType) { String commandText = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(commandText)) { updateStartCommand = true; if (commandText.startsWith(FLASH_BRIEFING_COMMAND_PREFIX)) { // Handle custom flashbriefings commands String flashbriefing = commandText.substring(FLASH_BRIEFING_COMMAND_PREFIX.length()); for (FlashBriefingProfileHandler flashBriefing : account .getFlashBriefingProfileHandlers()) { ThingUID flashBriefingId = flashBriefing.getThing().getUID(); if (StringUtils.equals(flashBriefing.getThing().getUID().getId(), flashbriefing)) { flashBriefing.handleCommand( new ChannelUID(flashBriefingId, CHANNEL_PLAY_ON_DEVICE), new StringType(device.serialNumber)); break; } } } else { // Handle standard commands if (!commandText.startsWith("Alexa.")) { commandText = "Alexa." + commandText + ".Play"; } waitForUpdate = 1000; connection.executeSequenceCommand(device, commandText, null); } } } } if (channelId.equals(CHANNEL_START_ROUTINE)) { if (command instanceof StringType) { String utterance = ((StringType) command).toFullString(); if (StringUtils.isNotEmpty(utterance)) { waitForUpdate = 1000; updateRoutine = true; connection.startRoutine(device, utterance); } } } if (waitForUpdate < 0) { return; } // force update of the state this.disableUpdate = true; final boolean bluetoothRefresh = needBluetoothRefresh; Runnable doRefresh = () -> { this.disableUpdate = false; BluetoothState state = null; if (bluetoothRefresh) { JsonBluetoothStates states; states = connection.getBluetoothConnectionStates(); state = states.findStateByDevice(device); } updateState(account, device, state, null, null, null, null, null); }; if (command instanceof RefreshType) { waitForUpdate = 0; account.forceCheckData(); } if (waitForUpdate == 0) { doRefresh.run(); } else { this.updateStateJob = scheduler.schedule(doRefresh, waitForUpdate, TimeUnit.MILLISECONDS); } } catch (IOException | URISyntaxException e) { logger.info("handleCommand fails: {}", e); } }
From source file:fr.bmartel.fadecandy.FadecandySingleton.java
private void createWebsocketClient() { Log.v(TAG, "connecting to websocket server"); final ScheduledFuture cancelTask = mExecutorService.schedule(new Runnable() { @Override//from w ww . jav a 2 s . c o m public void run() { if (mWebsocketFuture != null) { mWebsocketFuture.cancel(true); } for (int i = 0; i < mListeners.size(); i++) { mListeners.get(i).onServerConnectionFailure(); } } }, AppConstants.WEBSOCKET_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS); AsyncHttpClient.WebSocketConnectCallback mWebSocketConnectCallback = new AsyncHttpClient.WebSocketConnectCallback() { @Override public void onCompleted(Exception ex, WebSocket webSocket) { Log.v(TAG, "onCompleted"); if (cancelTask != null) { cancelTask.cancel(true); } mWebsocket = webSocket; if (ex != null) { for (int i = 0; i < mListeners.size(); i++) { mListeners.get(i).onServerConnectionFailure(); } return; } webSocket.setStringCallback(new WebSocket.StringCallback() { @Override public void onStringAvailable(String message) { Log.v(TAG, "messageJson : " + message); try { JSONObject messageJson = new JSONObject(message); if (messageJson.has("type")) { String type = messageJson.getString("type"); if (type.equals("connected_devices_changed")) { JSONArray devices = (JSONArray) messageJson.get("devices"); for (int i = 0; i < mListeners.size(); i++) { mListeners.get(i).onConnectedDeviceChanged(devices.length()); } } else if (type.equals("list_connected_devices")) { JSONArray devices = (JSONArray) messageJson.get("devices"); for (int i = 0; i < mListeners.size(); i++) { mListeners.get(i).onConnectedDeviceChanged(devices.length()); } } } } catch (JSONException e) { e.printStackTrace(); } } }); webSocket.setClosedCallback(new CompletedCallback() { @Override public void onCompleted(Exception ex) { if (!mWebsocketClose) { for (int i = 0; i < mListeners.size(); i++) { mListeners.get(i).onServerConnectionClosed(); } } eventManager.set(); } }); for (int i = 0; i < mListeners.size(); i++) { mListeners.get(i).onServerConnectionSuccess(); } sendListConnectedDevices(); initOpcClient(); } }; AsyncHttpClient asyncHttpClient = AsyncHttpClient.getDefaultInstance(); mWebsocketFuture = asyncHttpClient.websocket( "ws://" + getRemoteServerIp() + ":" + getRemoteServerPort() + "/", null, mWebSocketConnectCallback); }
From source file:com.cloud.utils.script.Script.java
public String execute(OutputInterpreter interpreter) { String[] command = _command.toArray(new String[_command.size()]); if (_logger.isDebugEnabled()) { _logger.debug("Executing: " + buildCommandLine(command)); }/*w w w .j a v a 2 s . c om*/ try { ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); if (_workDir != null) pb.directory(new File(_workDir)); _process = pb.start(); if (_process == null) { _logger.warn("Unable to execute: " + buildCommandLine(command)); return "Unable to execute the command: " + command[0]; } BufferedReader ir = new BufferedReader(new InputStreamReader(_process.getInputStream())); _thread = Thread.currentThread(); ScheduledFuture<String> future = null; if (_timeout > 0) { future = s_executors.schedule(this, _timeout, TimeUnit.MILLISECONDS); } Task task = null; if (interpreter != null && interpreter.drain()) { task = new Task(interpreter, ir); s_executors.execute(task); } while (true) { try { if (_process.waitFor() == 0) { _logger.debug("Execution is successful."); if (interpreter != null) { return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); } else { // null return exitValue apparently return String.valueOf(_process.exitValue()); } } else { break; } } catch (InterruptedException e) { if (!_isTimeOut) { /* * This is not timeout, we are interrupted by others, * continue */ _logger.debug("We are interrupted but it's not a timeout, just continue"); continue; } TimedOutLogger log = new TimedOutLogger(_process); Task timedoutTask = new Task(log, ir); timedoutTask.run(); if (!_passwordCommand) { _logger.warn("Timed out: " + buildCommandLine(command) + ". Output is: " + timedoutTask.getResult()); } else { _logger.warn("Timed out: " + buildCommandLine(command)); } return ERR_TIMEOUT; } finally { if (future != null) { future.cancel(false); } Thread.interrupted(); } } _logger.debug("Exit value is " + _process.exitValue()); BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128); String error; if (interpreter != null) { error = interpreter.processError(reader); } else { error = String.valueOf(_process.exitValue()); } if (_logger.isDebugEnabled()) { _logger.debug(error); } return error; } catch (SecurityException ex) { _logger.warn("Security Exception....not running as root?", ex); return stackTraceAsString(ex); } catch (Exception ex) { _logger.warn("Exception: " + buildCommandLine(command), ex); return stackTraceAsString(ex); } finally { if (_process != null) { IOUtils.closeQuietly(_process.getErrorStream()); IOUtils.closeQuietly(_process.getOutputStream()); IOUtils.closeQuietly(_process.getInputStream()); _process.destroy(); } } }
From source file:org.apache.flink.runtime.executiongraph.ExecutionGraph.java
/** * /*w ww . ja v a 2 s . c o m*/ * * @param slotProvider The resource provider from which the slots are allocated * @param timeout The maximum time that the deployment may take, before a * TimeoutException is thrown. */ private void scheduleEager(SlotProvider slotProvider, final Time timeout) { checkState(state == JobStatus.RUNNING, "job is not running currently"); // Important: reserve all the space we need up front. // that way we do not have any operation that can fail between allocating the slots // and adding them to the list. If we had a failure in between there, that would // cause the slots to get lost final ArrayList<ExecutionAndSlot[]> resources = new ArrayList<>(getNumberOfExecutionJobVertices()); final boolean queued = allowQueuedScheduling; // we use this flag to handle failures in a 'finally' clause // that allows us to not go through clumsy cast-and-rethrow logic boolean successful = false; try { // collecting all the slots may resize and fail in that operation without slots getting lost final ArrayList<Future<SimpleSlot>> slotFutures = new ArrayList<>(getNumberOfExecutionJobVertices()); // allocate the slots (obtain all their futures for (ExecutionJobVertex ejv : getVerticesTopologically()) { // these calls are not blocking, they only return futures ExecutionAndSlot[] slots = ejv.allocateResourcesForAll(slotProvider, queued); // we need to first add the slots to this list, to be safe on release resources.add(slots); for (ExecutionAndSlot ens : slots) { slotFutures.add(ens.slotFuture); } } // this future is complete once all slot futures are complete. // the future fails once one slot future fails. final ConjunctFuture allAllocationsComplete = FutureUtils.combineAll(slotFutures); // make sure that we fail if the allocation timeout was exceeded final ScheduledFuture<?> timeoutCancelHandle = futureExecutor.schedule(new Runnable() { @Override public void run() { // When the timeout triggers, we try to complete the conjunct future with an exception. // Note that this is a no-op if the future is already completed int numTotal = allAllocationsComplete.getNumFuturesTotal(); int numComplete = allAllocationsComplete.getNumFuturesCompleted(); String message = "Could not allocate all requires slots within timeout of " + timeout + ". Slots required: " + numTotal + ", slots allocated: " + numComplete; allAllocationsComplete.completeExceptionally(new NoResourceAvailableException(message)); } }, timeout.getSize(), timeout.getUnit()); allAllocationsComplete.handleAsync(new BiFunction<Void, Throwable, Void>() { @Override public Void apply(Void ignored, Throwable throwable) { try { // we do not need the cancellation timeout any more timeoutCancelHandle.cancel(false); if (throwable == null) { // successfully obtained all slots, now deploy for (ExecutionAndSlot[] jobVertexTasks : resources) { for (ExecutionAndSlot execAndSlot : jobVertexTasks) { // the futures must all be ready - this is simply a sanity check final SimpleSlot slot; try { slot = execAndSlot.slotFuture.getNow(null); checkNotNull(slot); } catch (ExecutionException | NullPointerException e) { throw new IllegalStateException("SlotFuture is incomplete " + "or erroneous even though all futures completed"); } // actual deployment execAndSlot.executionAttempt.deployToSlot(slot); } } } else { // let the exception handler deal with this throw throwable; } } catch (Throwable t) { // we catch everything here to make sure cleanup happens and the // ExecutionGraph notices // we need to go into recovery and make sure to release all slots try { fail(t); } finally { ExecutionGraphUtils.releaseAllSlotsSilently(resources); } } // Wouldn't it be nice if we could return an actual Void object? // return (Void) Unsafe.getUnsafe().allocateInstance(Void.class); return null; } }, futureExecutor); // from now on, slots will be rescued by the the futures and their completion, or by the timeout successful = true; } finally { if (!successful) { // we come here only if the 'try' block finished with an exception // we release the slots (possibly failing some executions on the way) and // let the exception bubble up ExecutionGraphUtils.releaseAllSlotsSilently(resources); } } }
From source file:org.apache.ambari.server.bootstrap.BSRunner.java
@Override public void run() { if (sshHostInfo.getSshKey() == null || sshHostInfo.getSshKey().equals("")) { beforeBootStrap(sshHostInfo);/* ww w . j a va 2 s. c o m*/ } String hostString = createHostString(sshHostInfo.getHosts()); String user = sshHostInfo.getUser(); String userRunAs = sshHostInfo.getUserRunAs(); if (user == null || user.isEmpty()) { user = DEFAULT_USER; } String command[] = new String[12]; BSStat stat = BSStat.RUNNING; String scriptlog = ""; try { createRunDir(); if (LOG.isDebugEnabled()) { // FIXME needs to be removed later // security hole LOG.debug("Using ssh key=\"" + sshHostInfo.getSshKey() + "\""); } String password = sshHostInfo.getPassword(); if (password != null && !password.isEmpty()) { this.passwordFile = new File(this.requestIdDir, "host_pass"); // TODO : line separator should be changed // if we are going to support multi platform server-agent solution String lineSeparator = System.getProperty("line.separator"); password = password + lineSeparator; writePasswordFile(password); } writeSshKeyFile(sshHostInfo.getSshKey()); /* Running command: * script hostlist bsdir user sshkeyfile */ command[0] = this.bsScript; command[1] = hostString; command[2] = this.requestIdDir.toString(); command[3] = user; command[4] = this.sshKeyFile.toString(); command[5] = this.agentSetupScript.toString(); command[6] = this.ambariHostname; command[7] = this.clusterOsFamily; command[8] = this.projectVersion; command[9] = this.serverPort + ""; command[10] = userRunAs; command[11] = (this.passwordFile == null) ? "null" : this.passwordFile.toString(); LOG.info("Host= " + hostString + " bs=" + this.bsScript + " requestDir=" + requestIdDir + " user=" + user + " keyfile=" + this.sshKeyFile + " passwordFile " + this.passwordFile + " server=" + this.ambariHostname + " version=" + projectVersion + " serverPort=" + this.serverPort + " userRunAs=" + userRunAs); String[] env = new String[] { "AMBARI_PASSPHRASE=" + agentSetupPassword }; if (this.verbose) env = new String[] { env[0], " BS_VERBOSE=\"-vvv\" " }; if (LOG.isDebugEnabled()) { LOG.debug(Arrays.toString(command)); } String bootStrapOutputFilePath = requestIdDir + File.separator + "bootstrap.out"; String bootStrapErrorFilePath = requestIdDir + File.separator + "bootstrap.err"; Process process = Runtime.getRuntime().exec(command, env); PrintWriter stdOutWriter = null; PrintWriter stdErrWriter = null; try { stdOutWriter = new PrintWriter(bootStrapOutputFilePath); stdErrWriter = new PrintWriter(bootStrapErrorFilePath); IOUtils.copy(process.getInputStream(), stdOutWriter); IOUtils.copy(process.getErrorStream(), stdErrWriter); } finally { if (stdOutWriter != null) stdOutWriter.close(); if (stdErrWriter != null) stdErrWriter.close(); } // Startup a scheduled executor service to look through the logs ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); BSStatusCollector statusCollector = new BSStatusCollector(); ScheduledFuture<?> handle = scheduler.scheduleWithFixedDelay(statusCollector, 0, 10, TimeUnit.SECONDS); LOG.info("Kicking off the scheduler for polling on logs in " + this.requestIdDir); try { LOG.info("Bootstrap output, log=" + bootStrapErrorFilePath + " " + bootStrapOutputFilePath); int exitCode = process.waitFor(); String outMesg = ""; String errMesg = ""; try { outMesg = FileUtils.readFileToString(new File(bootStrapOutputFilePath)); errMesg = FileUtils.readFileToString(new File(bootStrapErrorFilePath)); } catch (IOException io) { LOG.info("Error in reading files ", io); } scriptlog = outMesg + "\n\n" + errMesg; LOG.info("Script log Mesg " + scriptlog); if (exitCode != 0) { stat = BSStat.ERROR; } else { stat = BSStat.SUCCESS; } scheduler.schedule(new BSStatusCollector(), 0, TimeUnit.SECONDS); long startTime = System.currentTimeMillis(); while (true) { if (LOG.isDebugEnabled()) { LOG.debug("Waiting for hosts status to be updated"); } boolean pendingHosts = false; BootStrapStatus tmpStatus = bsImpl.getStatus(requestId); List<BSHostStatus> hostStatusList = tmpStatus.getHostsStatus(); if (hostStatusList != null) { for (BSHostStatus status : hostStatusList) { if (status.getStatus().equals("RUNNING")) { pendingHosts = true; } } } else { //Failed to get host status, waiting for hosts status to be updated pendingHosts = true; } if (LOG.isDebugEnabled()) { LOG.debug("Whether hosts status yet to be updated, pending=" + pendingHosts); } if (!pendingHosts) { break; } try { Thread.sleep(1000); } catch (InterruptedException e) { // continue } long now = System.currentTimeMillis(); if (now >= (startTime + 15000)) { LOG.warn("Gave up waiting for hosts status to be updated"); break; } } } catch (InterruptedException e) { throw new IOException(e); } finally { handle.cancel(true); /* schedule a last update */ scheduler.schedule(new BSStatusCollector(), 0, TimeUnit.SECONDS); scheduler.shutdownNow(); try { scheduler.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.info("Interruped while waiting for scheduler"); } process.destroy(); } } catch (IOException io) { LOG.info("Error executing bootstrap " + io.getMessage()); stat = BSStat.ERROR; } finally { /* get the bstatus */ BootStrapStatus tmpStatus = bsImpl.getStatus(requestId); List<BSHostStatus> hostStatusList = tmpStatus.getHostsStatus(); if (hostStatusList != null) { for (BSHostStatus hostStatus : hostStatusList) { if ("FAILED".equals(hostStatus.getStatus())) { stat = BSStat.ERROR; break; } } } else { stat = BSStat.ERROR; } tmpStatus.setLog(scriptlog); tmpStatus.setStatus(stat); bsImpl.updateStatus(requestId, tmpStatus); bsImpl.reset(); // Remove private ssh key after bootstrap is complete try { FileUtils.forceDelete(sshKeyFile); } catch (IOException io) { LOG.warn(io.getMessage()); } if (passwordFile != null) { // Remove password file after bootstrap is complete try { FileUtils.forceDelete(passwordFile); } catch (IOException io) { LOG.warn(io.getMessage()); } } finished(); } }
From source file:com.l2jfree.gameserver.gameobjects.L2Creature.java
/** * Enable a skill (remove it from _disabledSkills of the L2Creature).<BR> * <BR>/*from www .j av a2 s. c o m*/ * <B><U> Concept</U> :</B><BR> * <BR> * All skills disabled are identified by their skillId in <B>_disabledSkills</B> of the L2Creature <BR> * <BR> * * @param skillId The identifier of the L2Skill to enable */ public void enableSkill(int skillId) { if (_disabledSkills == null) return; final ScheduledFuture<?> task = _disabledSkills.remove(skillId); if (task != null) task.cancel(false); }