Search in sources :

Example 56 with CancellationException

use of java.util.concurrent.CancellationException in project android_packages_apps_Dialer by LineageOS.

the class StatusCheckTask method onExecuteInBackgroundThread.

@Override
public void onExecuteInBackgroundThread() {
    TelephonyManager telephonyManager = getContext().getSystemService(TelephonyManager.class).createForPhoneAccountHandle(getPhoneAccountHandle());
    if (telephonyManager == null) {
        VvmLog.w("StatusCheckTask.onExecuteInBackgroundThread", getPhoneAccountHandle() + " no longer valid");
        return;
    }
    if (telephonyManager.getServiceState().getState() != ServiceState.STATE_IN_SERVICE) {
        VvmLog.i("StatusCheckTask.onExecuteInBackgroundThread", getPhoneAccountHandle() + " not in service");
        return;
    }
    OmtpVvmCarrierConfigHelper config = new OmtpVvmCarrierConfigHelper(getContext(), getPhoneAccountHandle());
    if (!config.isValid()) {
        VvmLog.e("StatusCheckTask.onExecuteInBackgroundThread", "config no longer valid for " + getPhoneAccountHandle());
        VvmAccountManager.removeAccount(getContext(), getPhoneAccountHandle());
        return;
    }
    Bundle data;
    try (StatusSmsFetcher fetcher = new StatusSmsFetcher(getContext(), getPhoneAccountHandle())) {
        config.getProtocol().requestStatus(config, fetcher.getSentIntent());
        // Both the fetcher and OmtpMessageReceiver will be triggered, but
        // OmtpMessageReceiver will just route the SMS back to ActivationTask, which will be
        // rejected because the task is still running.
        data = fetcher.get();
    } catch (TimeoutException e) {
        VvmLog.e("StatusCheckTask.onExecuteInBackgroundThread", "timeout requesting status");
        return;
    } catch (CancellationException e) {
        VvmLog.e("StatusCheckTask.onExecuteInBackgroundThread", "Unable to send status request SMS");
        return;
    } catch (InterruptedException | ExecutionException | IOException e) {
        VvmLog.e("StatusCheckTask.onExecuteInBackgroundThread", "can't get future STATUS SMS", e);
        return;
    }
    StatusMessage message = new StatusMessage(data);
    VvmLog.i("StatusCheckTask.onExecuteInBackgroundThread", "STATUS SMS received: st=" + message.getProvisioningStatus() + ", rc=" + message.getReturnCode());
    if (message.getProvisioningStatus().equals(OmtpConstants.SUBSCRIBER_READY)) {
        VvmLog.i("StatusCheckTask.onExecuteInBackgroundThread", "subscriber ready, no activation required");
        LoggerUtils.logImpressionOnMainThread(getContext(), DialerImpression.Type.VVM_STATUS_CHECK_READY);
        VvmAccountManager.addAccount(getContext(), getPhoneAccountHandle(), message);
    } else {
        VvmLog.i("StatusCheckTask.onExecuteInBackgroundThread", "subscriber not ready, attempting reactivation");
        VvmAccountManager.removeAccount(getContext(), getPhoneAccountHandle());
        LoggerUtils.logImpressionOnMainThread(getContext(), DialerImpression.Type.VVM_STATUS_CHECK_REACTIVATION);
        ActivationTask.start(getContext(), getPhoneAccountHandle(), data);
    }
}
Also used : TelephonyManager(android.telephony.TelephonyManager) StatusSmsFetcher(com.android.voicemail.impl.sms.StatusSmsFetcher) CancellationException(java.util.concurrent.CancellationException) Bundle(android.os.Bundle) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) StatusMessage(com.android.voicemail.impl.sms.StatusMessage)

Example 57 with CancellationException

use of java.util.concurrent.CancellationException in project ksql by confluentinc.

the class Cli method handlePrintedTopic.

private void handlePrintedTopic(String printTopic) throws InterruptedException, ExecutionException, IOException {
    RestResponse<InputStream> topicResponse = restClient.makePrintTopicRequest(printTopic);
    if (topicResponse.isSuccessful()) {
        try (Scanner topicStreamScanner = new Scanner(topicResponse.getResponse(), StandardCharsets.UTF_8.name())) {
            Future<?> topicPrintFuture = queryStreamExecutorService.submit(() -> {
                while (topicStreamScanner.hasNextLine()) {
                    String line = topicStreamScanner.nextLine();
                    if (!line.isEmpty()) {
                        terminal.writer().println(line);
                        terminal.flush();
                    }
                }
            });
            terminal.handle(Terminal.Signal.INT, signal -> {
                terminal.handle(Terminal.Signal.INT, Terminal.SignalHandler.SIG_IGN);
                topicPrintFuture.cancel(true);
            });
            try {
                topicPrintFuture.get();
            } catch (CancellationException exception) {
                topicResponse.getResponse().close();
                terminal.writer().println("Topic printing ceased");
                terminal.flush();
            }
        }
    } else {
        terminal.writer().println(topicResponse.getErrorMessage().getMessage());
        terminal.flush();
    }
}
Also used : Scanner(java.util.Scanner) CancellationException(java.util.concurrent.CancellationException) InputStream(java.io.InputStream)

Example 58 with CancellationException

use of java.util.concurrent.CancellationException in project spf4j by zolyfarkas.

the class JdbcHeartBeat method scheduleHeartbeat.

public void scheduleHeartbeat() {
    synchronized (jdbc) {
        if (isClosed) {
            throw new IllegalStateException("Heartbeater is closed " + this);
        }
        if (scheduledHearbeat == null) {
            long lrn = lastRunNanos;
            long nanosSincelLastHB = TimeSource.nanoTime() - lrn;
            long delayNanos = intervalNanos - nanosSincelLastHB;
            if (delayNanos < (-intervalNanos) * missedHBRatio) {
                throw new HeartBeatError("Missed heartbeat since last one was " + nanosSincelLastHB + " ns ago");
            }
            if (delayNanos < 0) {
                delayNanos = 0;
            }
            ListenableScheduledFuture<?> scheduleFut = DefaultScheduler.LISTENABLE_INSTANCE.schedule(getHeartBeatRunnable(), delayNanos, TimeUnit.NANOSECONDS);
            scheduledHearbeat = scheduleFut;
            Futures.addCallback(scheduleFut, new FutureCallback() {

                @Override
                public void onSuccess(final Object result) {
                    synchronized (jdbc) {
                        if (!isClosed) {
                            scheduledHearbeat = null;
                            scheduleHeartbeat();
                        }
                    }
                }

                @Override
                @SuppressFBWarnings("ITC_INHERITANCE_TYPE_CHECKING")
                public void onFailure(final Throwable t) {
                    if (t instanceof Error) {
                        throw (Error) t;
                    } else if (!(t instanceof CancellationException)) {
                        throw new HeartBeatError(t);
                    }
                }
            }, DefaultExecutor.INSTANCE);
        }
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 59 with CancellationException

use of java.util.concurrent.CancellationException in project apache-kafka-on-k8s by banzaicloud.

the class SourceTaskOffsetCommitterTest method testRemove.

@Test
public void testRemove() throws Exception {
    // Try to remove a non-existing task
    EasyMock.expect(committers.remove(taskId)).andReturn(null);
    PowerMock.replayAll();
    committer.remove(taskId);
    PowerMock.verifyAll();
    PowerMock.resetAll();
    // Try to remove an existing task
    EasyMock.expect(committers.remove(taskId)).andReturn(taskFuture);
    EasyMock.expect(taskFuture.cancel(eq(false))).andReturn(false);
    EasyMock.expect(taskFuture.isDone()).andReturn(false);
    EasyMock.expect(taskFuture.get()).andReturn(null);
    PowerMock.replayAll();
    committer.remove(taskId);
    PowerMock.verifyAll();
    PowerMock.resetAll();
    // Try to remove a cancelled task
    EasyMock.expect(committers.remove(taskId)).andReturn(taskFuture);
    EasyMock.expect(taskFuture.cancel(eq(false))).andReturn(false);
    EasyMock.expect(taskFuture.isDone()).andReturn(false);
    EasyMock.expect(taskFuture.get()).andThrow(new CancellationException());
    mockLog.trace(EasyMock.anyString(), EasyMock.<Object>anyObject());
    PowerMock.expectLastCall();
    PowerMock.replayAll();
    committer.remove(taskId);
    PowerMock.verifyAll();
    PowerMock.resetAll();
    // Try to remove an interrupted task
    EasyMock.expect(committers.remove(taskId)).andReturn(taskFuture);
    EasyMock.expect(taskFuture.cancel(eq(false))).andReturn(false);
    EasyMock.expect(taskFuture.isDone()).andReturn(false);
    EasyMock.expect(taskFuture.get()).andThrow(new InterruptedException());
    PowerMock.replayAll();
    try {
        committer.remove(taskId);
        fail("Expected ConnectException to be raised");
    } catch (ConnectException e) {
    // ignore
    }
    PowerMock.verifyAll();
}
Also used : CancellationException(java.util.concurrent.CancellationException) ConnectException(org.apache.kafka.connect.errors.ConnectException) ThreadedTest(org.apache.kafka.connect.util.ThreadedTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 60 with CancellationException

use of java.util.concurrent.CancellationException in project etcd-java by IBM.

the class RangeCache method fullRefreshCache.

// internal method - should not be called while watch is active
protected ListenableFuture<Boolean> fullRefreshCache() {
    ListenableFuture<List<RangeResponse>> rrfut;
    long seenUpTo = seenUpToRev;
    boolean firstTime = (seenUpTo == 0L);
    if (firstTime || entries.size() <= 20) {
        // TODO *maybe* chunking (for large caches)
        ListenableFuture<RangeResponse> rrf = kvClient.get(fromKey).rangeEnd(toKey).backoffRetry(() -> !closed).timeout(300_000L).async();
        rrfut = Futures.transform(rrf, (Function<RangeResponse, List<RangeResponse>>) rr -> Collections.singletonList(rr));
    } else {
        // in case the local cache is large, reduce data transfer by requesting
        // just keys, and full key+value only for those modified since seenUpToRev
        RangeRequest.Builder rangeReqBld = RangeRequest.newBuilder().setKey(fromKey).setRangeEnd(toKey);
        RangeRequest newModsReq = rangeReqBld.setMinModRevision(seenUpTo + 1).build();
        RangeRequest otherKeysReq = rangeReqBld.clearMinModRevision().setMaxModRevision(seenUpTo).setKeysOnly(true).build();
        ListenableFuture<TxnResponse> trf = kvClient.batch().get(newModsReq).get(otherKeysReq).backoffRetry(() -> !closed).timeout(300_000L).async();
        rrfut = Futures.transform(trf, (Function<TxnResponse, List<RangeResponse>>) tr -> tr.getResponsesList().stream().map(r -> r.getResponseRange()).collect(Collectors.toList()));
    }
    return Futures.transformAsync(rrfut, rrs -> {
        if (closed)
            throw new CancellationException();
        Set<ByteString> snapshot = firstTime ? null : new HashSet<>();
        RangeResponse toUpdate = rrs.get(0);
        if (toUpdate.getKvsCount() > 0)
            for (KeyValue kv : toUpdate.getKvsList()) {
                if (!firstTime)
                    snapshot.add(kv.getKey());
                offerUpdate(kv, true);
            }
        long snapshotRev = toUpdate.getHeader().getRevision();
        if (firstTime)
            notifyListeners(EventType.INITIALIZED, null, true);
        else {
            if (rrs.size() > 1)
                for (KeyValue kv : rrs.get(1).getKvsList()) {
                    snapshot.add(kv.getKey());
                }
            // prune deleted entries
            KeyValue.Builder kvBld = null;
            for (ByteString key : entries.keySet()) if (!snapshot.contains(key)) {
                if (kvBld == null)
                    kvBld = KeyValue.newBuilder().setVersion(0L).setModRevision(snapshotRev);
                offerUpdate(kvBld.setKey(key).build(), true);
            }
        }
        revisionUpdate(snapshotRev);
        Watch newWatch = // .prevKv() //TODO TBD
        kvClient.watch(fromKey).rangeEnd(toKey).progressNotify().startRevision(snapshotRev + 1).executor(listenerExecutor).start(new StreamObserver<WatchUpdate>() {

            @Override
            public void onNext(WatchUpdate update) {
                List<Event> events = update.getEvents();
                int eventCount = events != null ? events.size() : 0;
                if (eventCount > 0)
                    for (Event event : events) {
                        KeyValue kv = event.getKv();
                        // event.getPrevKv(); //TBD
                        switch(event.getType()) {
                            case DELETE:
                                if (kv.getVersion() != 0L)
                                    kv = KeyValue.newBuilder(kv).setVersion(0L).clearValue().build();
                            // fall-thru
                            case PUT:
                                offerUpdate(kv, true);
                                break;
                            case UNRECOGNIZED:
                            default:
                                logger.warn("Unrecognized event for key " + kv.getKey().toStringUtf8());
                                break;
                        }
                    }
                revisionUpdate(eventCount == 0 ? update.getHeader().getRevision() - 1L : events.get(eventCount - 1).getKv().getModRevision());
            }

            @Override
            public void onCompleted() {
                // should only happen after external close()
                if (!closed) {
                    if (!client.isClosed()) {
                        logger.error("Watch completed unexpectedly (not closed)");
                    }
                    close();
                }
            }

            @Override
            public void onError(Throwable t) {
                logger.error("Watch failed with exception ", t);
                if (t instanceof RevisionCompactedException)
                    synchronized (RangeCache.this) {
                        // fail if happens during start, otherwise refresh
                        if (!closed && startFuture != null && startFuture.isDone()) {
                            // will renew watch
                            startFuture = fullRefreshCache();
                        }
                    }
            }
        });
        synchronized (this) {
            if (closed)
                throw new CancellationException();
            return watch = newWatch;
        }
    }, listenerExecutor);
}
Also used : KeyValue(com.ibm.etcd.api.KeyValue) ByteString(com.google.protobuf.ByteString) WatchUpdate(com.ibm.etcd.client.kv.WatchUpdate) Function(com.google.common.base.Function) RangeResponse(com.ibm.etcd.api.RangeResponse) DeleteRangeResponse(com.ibm.etcd.api.DeleteRangeResponse) RevisionCompactedException(com.ibm.etcd.client.watch.RevisionCompactedException) CancellationException(java.util.concurrent.CancellationException) RangeRequest(com.ibm.etcd.api.RangeRequest) DeleteRangeRequest(com.ibm.etcd.api.DeleteRangeRequest) Watch(com.ibm.etcd.client.kv.KvClient.Watch) Event(com.ibm.etcd.api.Event) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) TxnResponse(com.ibm.etcd.api.TxnResponse)

Aggregations

CancellationException (java.util.concurrent.CancellationException)505 ExecutionException (java.util.concurrent.ExecutionException)150 Test (org.junit.Test)91 TimeoutException (java.util.concurrent.TimeoutException)76 ArrayList (java.util.ArrayList)47 CountDownLatch (java.util.concurrent.CountDownLatch)46 Future (java.util.concurrent.Future)46 IOException (java.io.IOException)42 ExecutorService (java.util.concurrent.ExecutorService)30 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)29 CompletableFuture (java.util.concurrent.CompletableFuture)28 Callable (java.util.concurrent.Callable)27 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)27 List (java.util.List)24 Map (java.util.Map)23 HashMap (java.util.HashMap)22 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)22 TimeUnit (java.util.concurrent.TimeUnit)20 CharStream (org.antlr.v4.runtime.CharStream)20 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)20