id
int64 0
10.2k
| text_id
stringlengths 17
67
| repo_owner
stringclasses 232
values | repo_name
stringclasses 295
values | issue_url
stringlengths 39
89
| pull_url
stringlengths 37
87
| comment_url
stringlengths 37
94
| links_count
int64 1
2
| link_keyword
stringclasses 12
values | issue_title
stringlengths 7
197
| issue_body
stringlengths 45
21.3k
| base_sha
stringlengths 40
40
| head_sha
stringlengths 40
40
| diff_url
stringlengths 120
170
| diff
stringlengths 478
132k
| changed_files
stringlengths 47
2.6k
| changed_files_exts
stringclasses 22
values | changed_files_count
int64 1
22
| java_changed_files_count
int64 1
22
| kt_changed_files_count
int64 0
0
| py_changed_files_count
int64 0
0
| code_changed_files_count
int64 1
22
| repo_symbols_count
int64 32.6k
242M
| repo_tokens_count
int64 6.59k
49.2M
| repo_lines_count
int64 992
6.2M
| repo_files_without_tests_count
int64 12
28.1k
| changed_symbols_count
int64 0
36.1k
| changed_tokens_count
int64 0
6.5k
| changed_lines_count
int64 0
561
| changed_files_without_tests_count
int64 1
17
| issue_symbols_count
int64 45
21.3k
| issue_words_count
int64 2
1.39k
| issue_tokens_count
int64 13
4.47k
| issue_lines_count
int64 1
325
| issue_links_count
int64 0
19
| issue_code_blocks_count
int64 0
31
| pull_create_at
timestamp[s] | stars
int64 10
44.3k
| language
stringclasses 8
values | languages
stringclasses 296
values | license
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,401 | grpc/grpc-java/1404/875 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/875 | https://github.com/grpc/grpc-java/pull/1404 | https://github.com/grpc/grpc-java/pull/1404 | 1 | fixes | InProcessTransport doesn't call onReady | The in-process transport supports flow control and supports `isReady()`, but it never calls `onReady()`. It seems to be just an oversight/bug. Since the in-process transport connects immediately, `onReady()` should probably be called on the client immediately in `newStream()`.
Locking will be a little interesting since for a single `request()` both client and server listeners may need to be called (because numMessages can be > 1). It looks like `{client,server}Requested()` could maybe return a boolean for whether `{client,server}Requested > 0 && {client,server}Requested <= numMessages`, which would imply `onReady()` should be called.
| 5b9726ea7dade0952d64796178dc0bdfd134d16d | 86f2c9f2243a8aa34e5d9de78dcae11da80edff6 | https://github.com/grpc/grpc-java/compare/5b9726ea7dade0952d64796178dc0bdfd134d16d...86f2c9f2243a8aa34e5d9de78dcae11da80edff6 | diff --git a/core/src/main/java/io/grpc/inprocess/InProcessTransport.java b/core/src/main/java/io/grpc/inprocess/InProcessTransport.java
index 3498173d6..f9ecf01ac 100644
--- a/core/src/main/java/io/grpc/inprocess/InProcessTransport.java
+++ b/core/src/main/java/io/grpc/inprocess/InProcessTransport.java
@@ -231,14 +231,27 @@ class InProcessTransport implements ServerTransport, ClientTransport {
@Override
public void request(int numMessages) {
- clientStream.serverRequested(numMessages);
+ boolean onReady = clientStream.serverRequested(numMessages);
+ if (onReady) {
+ synchronized (this) {
+ if (!closed) {
+ clientStreamListener.onReady();
+ }
+ }
+ }
}
// This method is the only reason we have to synchronize field accesses.
- private synchronized void clientRequested(int numMessages) {
+ /**
+ * Client requested more messages.
+ *
+ * @return whether onReady should be called on the server
+ */
+ private synchronized boolean clientRequested(int numMessages) {
if (closed) {
- return;
+ return false;
}
+ boolean previouslyReady = clientRequested > 0;
clientRequested += numMessages;
while (clientRequested > 0 && !clientReceiveQueue.isEmpty()) {
clientRequested--;
@@ -246,12 +259,14 @@ class InProcessTransport implements ServerTransport, ClientTransport {
}
// Attempt being reentrant-safe
if (closed) {
- return;
+ return false;
}
if (clientReceiveQueue.isEmpty() && clientNotifyStatus != null) {
closed = true;
clientStreamListener.closed(clientNotifyStatus, clientNotifyTrailers);
}
+ boolean nowReady = clientRequested > 0;
+ return !previouslyReady && nowReady;
}
private void clientCancelled(Status status) {
@@ -366,14 +381,27 @@ class InProcessTransport implements ServerTransport, ClientTransport {
@Override
public void request(int numMessages) {
- serverStream.clientRequested(numMessages);
+ boolean onReady = serverStream.clientRequested(numMessages);
+ if (onReady) {
+ synchronized (this) {
+ if (!closed) {
+ serverStreamListener.onReady();
+ }
+ }
+ }
}
// This method is the only reason we have to synchronize field accesses.
- private synchronized void serverRequested(int numMessages) {
+ /**
+ * Client requested more messages.
+ *
+ * @return whether onReady should be called on the server
+ */
+ private synchronized boolean serverRequested(int numMessages) {
if (closed) {
- return;
+ return false;
}
+ boolean previouslyReady = serverRequested > 0;
serverRequested += numMessages;
while (serverRequested > 0 && !serverReceiveQueue.isEmpty()) {
serverRequested--;
@@ -383,6 +411,8 @@ class InProcessTransport implements ServerTransport, ClientTransport {
serverNotifyHalfClose = false;
serverStreamListener.halfClosed();
}
+ boolean nowReady = serverRequested > 0;
+ return !previouslyReady && nowReady;
}
private void serverClosed(Status status) { | ['core/src/main/java/io/grpc/inprocess/InProcessTransport.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,433,670 | 526,713 | 68,915 | 299 | 1,575 | 289 | 44 | 1 | 643 | 90 | 141 | 4 | 0 | 0 | 2016-02-10T17:52:17 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,400 | grpc/grpc-java/1490/1476 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1476 | https://github.com/grpc/grpc-java/pull/1490 | https://github.com/grpc/grpc-java/pull/1490 | 1 | resolves | TransportSet should reset current index on transportReady | If we successfully make a connection to an address, then that should mean the address is good. If it later is disconnected due to GOAWAY or transient failure we should start at the top of the list instead of trying less-desirable IPs.
This can cause errors, but any errors can already be gotten other ways, so it shouldn't be considered a major bug.
| 86bad4ffea5faf4d65cb943456bdf3d0d51d0766 | 643bb2c6b53d5a4516f13af856d98a85b334f0dc | https://github.com/grpc/grpc-java/compare/86bad4ffea5faf4d65cb943456bdf3d0d51d0766...643bb2c6b53d5a4516f13af856d98a85b334f0dc | diff --git a/core/src/main/java/io/grpc/internal/TransportSet.java b/core/src/main/java/io/grpc/internal/TransportSet.java
index 0fa578476..d3f884e38 100644
--- a/core/src/main/java/io/grpc/internal/TransportSet.java
+++ b/core/src/main/java/io/grpc/internal/TransportSet.java
@@ -77,12 +77,11 @@ final class TransportSet {
@GuardedBy("lock")
private BackoffPolicy reconnectPolicy;
- // The address index from which the current series of consecutive failing connection attempts
- // started. -1 means the current series have not started.
- // In the case of consecutive failures, the time between two attempts for this address is
- // controlled by connectPolicy.
+ // True if the next connect attempt is the first attempt ever, or the one right after a successful
+ // connection (i.e., transportReady() was called). If true, the next connect attempt will start
+ // from the first address and will reset back-off.
@GuardedBy("lock")
- private int headIndex = -1;
+ private boolean firstAttempt = true;
@GuardedBy("lock")
private final Stopwatch backoffWatch;
@@ -176,6 +175,9 @@ final class TransportSet {
Preconditions.checkState(reconnectTask == null || reconnectTask.isDone(),
"previous reconnectTask is not done");
+ if (firstAttempt) {
+ nextAddressIndex = 0;
+ }
final int currentAddressIndex = nextAddressIndex;
List<SocketAddress> addrs = addressGroup.getAddresses();
final SocketAddress address = addrs.get(currentAddressIndex);
@@ -192,7 +194,7 @@ final class TransportSet {
boolean savedShutdown;
synchronized (lock) {
savedShutdown = shutdown;
- if (currentAddressIndex == headIndex) {
+ if (currentAddressIndex == 0) {
backoffWatch.reset().start();
}
newActiveTransport = transportFactory.newClientTransport(address, authority);
@@ -224,19 +226,18 @@ final class TransportSet {
}
};
- long delayMillis;
- if (currentAddressIndex == headIndex) {
- // Back to the first attempted address. Calculate back-off delay.
- delayMillis =
- reconnectPolicy.nextBackoffMillis() - backoffWatch.elapsed(TimeUnit.MILLISECONDS);
- } else {
- delayMillis = 0;
- if (headIndex == -1) {
+ long delayMillis = 0;
+ if (currentAddressIndex == 0) {
+ if (firstAttempt) {
// First connect attempt, or the first attempt since last successful connection.
- headIndex = currentAddressIndex;
reconnectPolicy = backoffPolicyProvider.get();
+ } else {
+ // Back to the first address. Calculate back-off delay.
+ delayMillis =
+ reconnectPolicy.nextBackoffMillis() - backoffWatch.elapsed(TimeUnit.MILLISECONDS);
}
}
+ firstAttempt = false;
if (delayMillis <= 0) {
reconnectTask = null;
// No back-off this time.
@@ -333,7 +334,7 @@ final class TransportSet {
super.transportReady();
synchronized (lock) {
if (isAttachedToActiveTransport()) {
- headIndex = -1;
+ firstAttempt = true;
}
}
loadBalancer.handleTransportReady(addressGroup);
diff --git a/core/src/test/java/io/grpc/internal/ManagedChannelImplTransportManagerTest.java b/core/src/test/java/io/grpc/internal/ManagedChannelImplTransportManagerTest.java
index 27605559e..45f1a391b 100644
--- a/core/src/test/java/io/grpc/internal/ManagedChannelImplTransportManagerTest.java
+++ b/core/src/test/java/io/grpc/internal/ManagedChannelImplTransportManagerTest.java
@@ -248,7 +248,7 @@ public class ManagedChannelImplTransportManagerTest {
// Second pick fails. This is the beginning of a series of failures.
ClientTransport t2 = tm.getTransport(addressGroup);
assertNotNull(t2);
- verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
+ verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
// Back-off policy was reset.
verify(mockBackoffPolicyProvider, times(++backoffReset)).get();
transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
@@ -256,15 +256,15 @@ public class ManagedChannelImplTransportManagerTest {
// Third pick fails too
ClientTransport t3 = tm.getTransport(addressGroup);
assertNotNull(t3);
- verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
+ verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
// Back-off policy was not reset.
verify(mockBackoffPolicyProvider, times(backoffReset)).get();
transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
- // Forth pick is on addr2, back-off policy kicks in.
+ // Forth pick is on the first address, back-off policy kicks in.
ClientTransport t4 = tm.getTransport(addressGroup);
assertNotNull(t4);
- verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
+ verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
// Back-off policy was not reset, but was consulted.
verify(mockBackoffPolicyProvider, times(backoffReset)).get();
verify(mockBackoffPolicy, times(++backoffConsulted)).nextBackoffMillis();
diff --git a/core/src/test/java/io/grpc/internal/TransportSetTest.java b/core/src/test/java/io/grpc/internal/TransportSetTest.java
index a7ed5f9c5..702a84b45 100644
--- a/core/src/test/java/io/grpc/internal/TransportSetTest.java
+++ b/core/src/test/java/io/grpc/internal/TransportSetTest.java
@@ -176,82 +176,52 @@ public class TransportSetTest {
transportSet.obtainActiveTransport();
verify(mockBackoffPolicyProvider, times(++backoffReset)).get();
verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
- // Let this one through
- transports.peek().listener.transportReady();
- // Then shut it down
- transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
-
-
- ////// Now start a series of failing attempts, where addr2 is the head.
- // First attempt after a connection closed. Reset back-off policy.
- transportSet.obtainActiveTransport();
- verify(mockBackoffPolicyProvider, times(++backoffReset)).get();
- verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
- // Fail this one
+ // Let this one fail without success
transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
// Second attempt will start immediately. Keep back-off policy.
transportSet.obtainActiveTransport();
verify(mockBackoffPolicyProvider, times(backoffReset)).get();
- verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
+ verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
// Fail this one too
transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
- // Third attempt is on head, thus controlled by the first back-off interval.
+ // Third attempt is the first address, thus controlled by the first back-off interval.
transportSet.obtainActiveTransport();
- verify(mockBackoffPolicy2, times(++backoff2Consulted)).nextBackoffMillis();
+ verify(mockBackoffPolicy1, times(++backoff1Consulted)).nextBackoffMillis();
verify(mockBackoffPolicyProvider, times(backoffReset)).get();
fakeClock.forwardMillis(9);
- verify(mockTransportFactory, times(transportsAddr2)).newClientTransport(addr2, authority);
+ verify(mockTransportFactory, times(transportsAddr1)).newClientTransport(addr1, authority);
fakeClock.forwardMillis(1);
- verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
+ verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
// Fail this one too
transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
// Forth attempt will start immediately. Keep back-off policy.
transportSet.obtainActiveTransport();
verify(mockBackoffPolicyProvider, times(backoffReset)).get();
- verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
+ verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
// Fail this one too
transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
- // Fifth attempt is on head, thus controlled by the second back-off interval.
+ // Fifth attempt for the first address, thus controlled by the second back-off interval.
transportSet.obtainActiveTransport();
- verify(mockBackoffPolicy2, times(++backoff2Consulted)).nextBackoffMillis();
+ verify(mockBackoffPolicy1, times(++backoff1Consulted)).nextBackoffMillis();
verify(mockBackoffPolicyProvider, times(backoffReset)).get();
fakeClock.forwardMillis(99);
- verify(mockTransportFactory, times(transportsAddr2)).newClientTransport(addr2, authority);
+ verify(mockTransportFactory, times(transportsAddr1)).newClientTransport(addr1, authority);
fakeClock.forwardMillis(1);
- verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
+ verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
// Let it through
transports.peek().listener.transportReady();
// Then close it.
transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
-
- ////// Now start a series of failing attempts, where addr1 is the head.
- // First attempt after a connection closed. Reset back-off policy.
+ // First attempt after a successful connection. Reset back-off policy, and start from the first
+ // address.
transportSet.obtainActiveTransport();
verify(mockBackoffPolicyProvider, times(++backoffReset)).get();
verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
- // Fail this one
- transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
-
- // Second attempt will start immediately. Keep back-off policy.
- transportSet.obtainActiveTransport();
- verify(mockBackoffPolicyProvider, times(backoffReset)).get();
- verify(mockTransportFactory, times(++transportsAddr2)).newClientTransport(addr2, authority);
- // Fail this one too
- transports.poll().listener.transportShutdown(Status.UNAVAILABLE);
-
- // Third attempt is on head, thus controlled by the first back-off interval.
- transportSet.obtainActiveTransport();
- verify(mockBackoffPolicy3, times(++backoff3Consulted)).nextBackoffMillis();
- verify(mockBackoffPolicyProvider, times(backoffReset)).get();
- fakeClock.forwardMillis(9);
- verify(mockTransportFactory, times(transportsAddr1)).newClientTransport(addr1, authority);
- fakeClock.forwardMillis(1);
- verify(mockTransportFactory, times(++transportsAddr1)).newClientTransport(addr1, authority);
// Final checks on invocations on back-off policies
verify(mockBackoffPolicy1, times(backoff1Consulted)).nextBackoffMillis(); | ['core/src/test/java/io/grpc/internal/TransportSetTest.java', 'core/src/test/java/io/grpc/internal/ManagedChannelImplTransportManagerTest.java', 'core/src/main/java/io/grpc/internal/TransportSet.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 2,484,255 | 536,922 | 70,259 | 303 | 1,510 | 333 | 33 | 1 | 351 | 63 | 74 | 4 | 0 | 0 | 2016-02-26T23:05:29 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,399 | grpc/grpc-java/1602/1546 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1546 | https://github.com/grpc/grpc-java/pull/1602 | https://github.com/grpc/grpc-java/pull/1602 | 1 | resolves | If DNS resolution fails, the Channel is permanently failed | We should probably update DnsNameResolver to continue retrying the DNS query until shutdown, at maybe a fixed rate of 1 minute or such. Overall, it's not a superb solution, but it fixes a lot of the problem and is expedient to implement.
| 575df76a8fa9a5c15213e49c3abb3de021239ace | 2d15af53c7a9129b53c6ac6ac510d38f23276117 | https://github.com/grpc/grpc-java/compare/575df76a8fa9a5c15213e49c3abb3de021239ace...2d15af53c7a9129b53c6ac6ac510d38f23276117 | diff --git a/core/src/main/java/io/grpc/DnsNameResolver.java b/core/src/main/java/io/grpc/DnsNameResolver.java
index ce787ebbe..ae5fa0457 100644
--- a/core/src/main/java/io/grpc/DnsNameResolver.java
+++ b/core/src/main/java/io/grpc/DnsNameResolver.java
@@ -31,16 +31,21 @@
package io.grpc;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
-import io.grpc.internal.GrpcUtil;
import io.grpc.internal.SharedResourceHolder;
+import io.grpc.internal.SharedResourceHolder.Resource;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
+import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
@@ -50,21 +55,33 @@ import javax.annotation.concurrent.GuardedBy;
*
* @see DnsNameResolverFactory
*/
-final class DnsNameResolver extends NameResolver {
+class DnsNameResolver extends NameResolver {
private final String authority;
private final String host;
private final int port;
+ private final Resource<ScheduledExecutorService> timerServiceResource;
+ private final Resource<ExecutorService> executorResource;
+ @GuardedBy("this")
+ private boolean shutdown;
+ @GuardedBy("this")
+ private ScheduledExecutorService timerService;
@GuardedBy("this")
private ExecutorService executor;
@GuardedBy("this")
+ private ScheduledFuture<?> resolutionTask;
+ @GuardedBy("this")
private boolean resolving;
@GuardedBy("this")
private Listener listener;
- DnsNameResolver(@Nullable String nsAuthority, String name, Attributes params) {
+ DnsNameResolver(@Nullable String nsAuthority, String name, Attributes params,
+ Resource<ScheduledExecutorService> timerServiceResource,
+ Resource<ExecutorService> executorResource) {
// TODO: if a DNS server is provided as nsAuthority, use it.
// https://www.captechconsulting.com/blogs/accessing-the-dusty-corners-of-dns-with-java
+ this.timerServiceResource = timerServiceResource;
+ this.executorResource = executorResource;
// Must prepend a "//" to the name when constructing a URI, otherwise it will be treated as an
// opaque URI, thus the authority and host of the resulted URI would be null.
URI nameUri = URI.create("//" + name);
@@ -85,39 +102,55 @@ final class DnsNameResolver extends NameResolver {
}
@Override
- public String getServiceAuthority() {
+ public final String getServiceAuthority() {
return authority;
}
@Override
- public synchronized void start(Listener listener) {
- Preconditions.checkState(executor == null, "already started");
- executor = SharedResourceHolder.get(GrpcUtil.SHARED_CHANNEL_EXECUTOR);
- this.listener = listener;
+ public final synchronized void start(Listener listener) {
+ Preconditions.checkState(this.listener == null, "already started");
+ timerService = SharedResourceHolder.get(timerServiceResource);
+ executor = SharedResourceHolder.get(executorResource);
+ this.listener = Preconditions.checkNotNull(listener, "listener");
resolve();
}
@Override
- public synchronized void refresh() {
- Preconditions.checkState(executor != null, "not started");
+ public final synchronized void refresh() {
+ Preconditions.checkState(listener != null, "not started");
resolve();
}
- @GuardedBy("this")
- private void resolve() {
- if (resolving) {
- return;
- }
- resolving = true;
- final Listener savedListener = Preconditions.checkNotNull(listener);
- executor.execute(new Runnable() {
+ private final Runnable resolutionRunnable = new Runnable() {
@Override
public void run() {
InetAddress[] inetAddrs;
+ Listener savedListener;
+ synchronized (DnsNameResolver.this) {
+ // If this task is started by refresh(), there might already be a scheduled task.
+ if (resolutionTask != null) {
+ resolutionTask.cancel(false);
+ resolutionTask = null;
+ }
+ if (shutdown) {
+ return;
+ }
+ savedListener = listener;
+ resolving = true;
+ }
try {
try {
- inetAddrs = InetAddress.getAllByName(host);
- } catch (Exception e) {
+ inetAddrs = getAllByName(host);
+ } catch (UnknownHostException e) {
+ synchronized (DnsNameResolver.this) {
+ if (shutdown) {
+ return;
+ }
+ // Because timerService is the single-threaded GrpcUtil.TIMER_SERVICE in production,
+ // we need to delegate the blocking work to the executor
+ resolutionTask = timerService.schedule(resolutionRunnableOnExecutor,
+ 1, TimeUnit.MINUTES);
+ }
savedListener.onError(Status.UNAVAILABLE.withCause(e));
return;
}
@@ -135,17 +168,51 @@ final class DnsNameResolver extends NameResolver {
}
}
}
- });
+ };
+
+ private final Runnable resolutionRunnableOnExecutor = new Runnable() {
+ @Override
+ public void run() {
+ synchronized (DnsNameResolver.this) {
+ if (!shutdown) {
+ executor.execute(resolutionRunnable);
+ }
+ }
+ }
+ };
+
+ // To be mocked out in tests
+ @VisibleForTesting
+ InetAddress[] getAllByName(String host) throws UnknownHostException {
+ return InetAddress.getAllByName(host);
+ }
+
+ @GuardedBy("this")
+ private void resolve() {
+ if (resolving || shutdown) {
+ return;
+ }
+ executor.execute(resolutionRunnable);
}
@Override
- public synchronized void shutdown() {
+ public final synchronized void shutdown() {
+ if (shutdown) {
+ return;
+ }
+ shutdown = true;
+ if (resolutionTask != null) {
+ resolutionTask.cancel(false);
+ }
+ if (timerService != null) {
+ timerService = SharedResourceHolder.release(timerServiceResource, timerService);
+ }
if (executor != null) {
- executor = SharedResourceHolder.release(GrpcUtil.SHARED_CHANNEL_EXECUTOR, executor);
+ executor = SharedResourceHolder.release(executorResource, executor);
}
}
- int getPort() {
+ final int getPort() {
return port;
}
}
diff --git a/core/src/main/java/io/grpc/DnsNameResolverFactory.java b/core/src/main/java/io/grpc/DnsNameResolverFactory.java
index 39c2238fc..6ee236d09 100644
--- a/core/src/main/java/io/grpc/DnsNameResolverFactory.java
+++ b/core/src/main/java/io/grpc/DnsNameResolverFactory.java
@@ -33,6 +33,8 @@ package io.grpc;
import com.google.common.base.Preconditions;
+import io.grpc.internal.GrpcUtil;
+
import java.net.URI;
/**
@@ -63,7 +65,8 @@ public final class DnsNameResolverFactory extends NameResolver.Factory {
Preconditions.checkArgument(targetPath.startsWith("/"),
"the path component (%s) of the target (%s) must start with '/'", targetPath, targetUri);
String name = targetPath.substring(1);
- return new DnsNameResolver(targetUri.getAuthority(), name, params);
+ return new DnsNameResolver(targetUri.getAuthority(), name, params, GrpcUtil.TIMER_SERVICE,
+ GrpcUtil.SHARED_CHANNEL_EXECUTOR);
} else {
return null;
}
diff --git a/core/src/main/java/io/grpc/internal/GrpcUtil.java b/core/src/main/java/io/grpc/internal/GrpcUtil.java
index f604a87e4..0ed5d4e11 100644
--- a/core/src/main/java/io/grpc/internal/GrpcUtil.java
+++ b/core/src/main/java/io/grpc/internal/GrpcUtil.java
@@ -385,7 +385,7 @@ public final class GrpcUtil {
};
/**
- * Shared executor for managing channel timers.
+ * Shared single-threaded executor for managing channel timers.
*/
public static final Resource<ScheduledExecutorService> TIMER_SERVICE =
new Resource<ScheduledExecutorService>() {
diff --git a/core/src/test/java/io/grpc/DnsNameResolverTest.java b/core/src/test/java/io/grpc/DnsNameResolverTest.java
index e034a6d01..92fad2b14 100644
--- a/core/src/test/java/io/grpc/DnsNameResolverTest.java
+++ b/core/src/test/java/io/grpc/DnsNameResolverTest.java
@@ -33,24 +33,82 @@ package io.grpc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import io.grpc.internal.FakeClock;
+import io.grpc.internal.SharedResourceHolder.Resource;
+
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
import java.net.URI;
+import java.net.UnknownHostException;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
/** Unit tests for {@link DnsNameResolver}. */
@RunWith(JUnit4.class)
public class DnsNameResolverTest {
-
- private DnsNameResolverFactory factory = DnsNameResolverFactory.getInstance();
-
private static final int DEFAULT_PORT = 887;
private static final Attributes NAME_RESOLVER_PARAMS =
Attributes.newBuilder().set(NameResolver.Factory.PARAMS_DEFAULT_PORT, DEFAULT_PORT).build();
+ private final DnsNameResolverFactory factory = DnsNameResolverFactory.getInstance();
+ private final FakeClock fakeClock = new FakeClock();
+ private final Resource<ScheduledExecutorService> fakeTimerService =
+ new Resource<ScheduledExecutorService>() {
+ @Override
+ public ScheduledExecutorService create() {
+ return fakeClock.scheduledExecutorService;
+ }
+
+ @Override
+ public void close(ScheduledExecutorService instance) {
+ assertSame(fakeClock, instance);
+ }
+ };
+
+ private final Resource<ExecutorService> fakeExecutor =
+ new Resource<ExecutorService>() {
+ @Override
+ public ExecutorService create() {
+ return fakeClock.scheduledExecutorService;
+ }
+
+ @Override
+ public void close(ExecutorService instance) {
+ assertSame(fakeClock, instance);
+ }
+ };
+
+ @Mock
+ private NameResolver.Listener mockListener;
+ @Captor
+ private ArgumentCaptor<List<ResolvedServerInfo>> resultCaptor;
+ @Captor
+ private ArgumentCaptor<Status> statusCaptor;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ }
+
@Test
public void invalidDnsName() throws Exception {
testInvalidUri(new URI("dns", null, "/[invalid]", null));
@@ -73,6 +131,116 @@ public class DnsNameResolverTest {
"foo.googleapis.com:456", 456);
}
+ @Test
+ public void resolve() throws Exception {
+ InetAddress[] answer1 = createAddressList(2);
+ InetAddress[] answer2 = createAddressList(1);
+ String name = "foo.googleapis.com";
+ MockResolver resolver = new MockResolver(name, 81, answer1, answer2);
+ resolver.start(mockListener);
+ verify(mockListener).onUpdate(resultCaptor.capture(), any(Attributes.class));
+ assertEquals(name, resolver.invocations.poll());
+ assertAnswerMatches(answer1, 81, resultCaptor.getValue());
+ assertEquals(0, fakeClock.numPendingTasks());
+
+ resolver.refresh();
+ verify(mockListener, times(2)).onUpdate(resultCaptor.capture(), any(Attributes.class));
+ assertEquals(name, resolver.invocations.poll());
+ assertAnswerMatches(answer2, 81, resultCaptor.getValue());
+ assertEquals(0, fakeClock.numPendingTasks());
+
+ resolver.shutdown();
+ }
+
+ @Test
+ public void retry() throws Exception {
+ String name = "foo.googleapis.com";
+ UnknownHostException error = new UnknownHostException(name);
+ InetAddress[] answer = createAddressList(2);
+ MockResolver resolver = new MockResolver(name, 81, error, error, answer);
+ resolver.start(mockListener);
+ verify(mockListener).onError(statusCaptor.capture());
+ assertEquals(name, resolver.invocations.poll());
+ Status status = statusCaptor.getValue();
+ assertEquals(Status.Code.UNAVAILABLE, status.getCode());
+ assertSame(error, status.getCause());
+
+ // First retry scheduled
+ assertEquals(1, fakeClock.numPendingTasks());
+ fakeClock.forwardMillis(TimeUnit.MINUTES.toMillis(1) - 1);
+ assertEquals(1, fakeClock.numPendingTasks());
+
+ // First retry
+ fakeClock.forwardMillis(1);
+ verify(mockListener, times(2)).onError(statusCaptor.capture());
+ assertEquals(name, resolver.invocations.poll());
+ status = statusCaptor.getValue();
+ assertEquals(Status.Code.UNAVAILABLE, status.getCode());
+ assertSame(error, status.getCause());
+
+ // Second retry scheduled
+ assertEquals(1, fakeClock.numPendingTasks());
+ fakeClock.forwardMillis(TimeUnit.MINUTES.toMillis(1) - 1);
+ assertEquals(1, fakeClock.numPendingTasks());
+
+ // Second retry
+ fakeClock.forwardMillis(1);
+ assertEquals(0, fakeClock.numPendingTasks());
+ verify(mockListener).onUpdate(resultCaptor.capture(), any(Attributes.class));
+ assertEquals(name, resolver.invocations.poll());
+ assertAnswerMatches(answer, 81, resultCaptor.getValue());
+
+ verifyNoMoreInteractions(mockListener);
+ }
+
+ @Test
+ public void refreshCancelsScheduledRetry() throws Exception {
+ String name = "foo.googleapis.com";
+ UnknownHostException error = new UnknownHostException(name);
+ InetAddress[] answer = createAddressList(2);
+ MockResolver resolver = new MockResolver(name, 81, error, answer);
+ resolver.start(mockListener);
+ verify(mockListener).onError(statusCaptor.capture());
+ assertEquals(name, resolver.invocations.poll());
+ Status status = statusCaptor.getValue();
+ assertEquals(Status.Code.UNAVAILABLE, status.getCode());
+ assertSame(error, status.getCause());
+
+ // First retry scheduled
+ assertEquals(1, fakeClock.numPendingTasks());
+
+ resolver.refresh();
+ // Refresh cancelled the retry
+ assertEquals(0, fakeClock.numPendingTasks());
+ verify(mockListener).onUpdate(resultCaptor.capture(), any(Attributes.class));
+ assertEquals(name, resolver.invocations.poll());
+ assertAnswerMatches(answer, 81, resultCaptor.getValue());
+
+ verifyNoMoreInteractions(mockListener);
+ }
+
+ @Test
+ public void shutdownCancelsScheduledRetry() throws Exception {
+ String name = "foo.googleapis.com";
+ UnknownHostException error = new UnknownHostException(name);
+ MockResolver resolver = new MockResolver(name, 81, error);
+ resolver.start(mockListener);
+ verify(mockListener).onError(statusCaptor.capture());
+ assertEquals(name, resolver.invocations.poll());
+ Status status = statusCaptor.getValue();
+ assertEquals(Status.Code.UNAVAILABLE, status.getCode());
+ assertSame(error, status.getCause());
+
+ // Retry scheduled
+ assertEquals(1, fakeClock.numPendingTasks());
+
+ // Shutdown cancelled the retry
+ resolver.shutdown();
+ assertEquals(0, fakeClock.numPendingTasks());
+
+ verifyNoMoreInteractions(mockListener);
+ }
+
private void testInvalidUri(URI uri) {
try {
factory.newNameResolver(uri, NAME_RESOLVER_PARAMS);
@@ -88,4 +256,48 @@ public class DnsNameResolverTest {
assertEquals(expectedPort, resolver.getPort());
assertEquals(exportedAuthority, resolver.getServiceAuthority());
}
+
+ private byte lastByte = 0;
+
+ private InetAddress[] createAddressList(int n) throws UnknownHostException {
+ InetAddress[] list = new InetAddress[n];
+ for (int i = 0; i < n; i++) {
+ list[i] = InetAddress.getByAddress(new byte[] {127, 0, 0, ++lastByte});
+ }
+ return list;
+ }
+
+ private static void assertAnswerMatches(InetAddress[] addrs, int port,
+ List<ResolvedServerInfo> result) {
+ assertEquals(addrs.length, result.size());
+ for (int i = 0; i < addrs.length; i++) {
+ InetSocketAddress socketAddr = (InetSocketAddress) result.get(i).getAddress();
+ assertEquals("Addr " + i, port, socketAddr.getPort());
+ assertEquals("Addr " + i, addrs[i], socketAddr.getAddress());
+ }
+ }
+
+ private class MockResolver extends DnsNameResolver {
+ final LinkedList<Object> answers = new LinkedList<Object>();
+ final LinkedList<String> invocations = new LinkedList<String>();
+
+ MockResolver(String name, int defaultPort, Object ... answers) {
+ super(null, name, Attributes.newBuilder().set(
+ NameResolver.Factory.PARAMS_DEFAULT_PORT, defaultPort).build(), fakeTimerService,
+ fakeExecutor);
+ for (Object answer : answers) {
+ this.answers.add(answer);
+ }
+ }
+
+ @Override
+ InetAddress[] getAllByName(String host) throws UnknownHostException {
+ invocations.add(host);
+ Object answer = answers.poll();
+ if (answer instanceof UnknownHostException) {
+ throw (UnknownHostException) answer;
+ }
+ return (InetAddress[]) answer;
+ }
+ }
}
diff --git a/core/src/test/java/io/grpc/internal/FakeClock.java b/core/src/test/java/io/grpc/internal/FakeClock.java
index 9f5f8cc40..d0db8f29e 100644
--- a/core/src/test/java/io/grpc/internal/FakeClock.java
+++ b/core/src/test/java/io/grpc/internal/FakeClock.java
@@ -47,9 +47,9 @@ import java.util.concurrent.TimeUnit;
/**
* A manipulated clock that exports a {@link Ticker} and a {@link ScheduledExecutorService}.
*/
-final class FakeClock {
+public final class FakeClock {
- final ScheduledExecutorService scheduledExecutorService = new ScheduledExecutorImpl();
+ public final ScheduledExecutorService scheduledExecutorService = new ScheduledExecutorImpl();
final Ticker ticker = new Ticker() {
@Override public long read() {
return TimeUnit.MILLISECONDS.toNanos(currentTimeNanos);
@@ -183,12 +183,16 @@ final class FakeClock {
}
}
- void forwardTime(long value, TimeUnit unit) {
+ public void forwardTime(long value, TimeUnit unit) {
currentTimeNanos += unit.toNanos(value);
runDueTasks();
}
- void forwardMillis(long millis) {
+ public void forwardMillis(long millis) {
forwardTime(millis, TimeUnit.MILLISECONDS);
}
+
+ public int numPendingTasks() {
+ return tasks.size();
+ }
} | ['core/src/main/java/io/grpc/DnsNameResolverFactory.java', 'core/src/main/java/io/grpc/internal/GrpcUtil.java', 'core/src/main/java/io/grpc/DnsNameResolver.java', 'core/src/test/java/io/grpc/DnsNameResolverTest.java', 'core/src/test/java/io/grpc/internal/FakeClock.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 3,146,686 | 672,419 | 87,585 | 284 | 4,932 | 950 | 122 | 3 | 238 | 42 | 54 | 2 | 0 | 0 | 2016-03-28T01:31:45 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,392 | grpc/grpc-java/2258/2246 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/2246 | https://github.com/grpc/grpc-java/pull/2258 | https://github.com/grpc/grpc-java/pull/2258 | 1 | resolves | Deadlock with TransportSet | Hello,
I was testing Grpc with RoundRobinLB and a custom NameResolver when this deadlock happened:
> Found one Java-level deadlock:
>
> "grpc-timer-0":
> waiting to lock monitor 0x00007fa1b00062c8 (object 0x00000007397d7f88, a java.lang.Object),
> which is held by "main"
> "main":
> waiting to lock monitor 0x00007fa1800087f8 (object 0x00000007397d7e00, a java.lang.Object),
> which is held by "grpc-timer-0"
>
> "grpc-timer-0":
> at io.grpc.internal.DelayedClientTransport.hasPendingStreams(DelayedClientTransport.java:284)
> - waiting to lock <0x00000007397d7f88> (a java.lang.Object)
> at io.grpc.internal.TransportSet$1EndOfCurrentBackoff.run(TransportSet.java:246)
> - locked <0x00000007397d7e00> (a java.lang.Object)
> at io.grpc.internal.LogExceptionRunnable.run(LogExceptionRunnable.java:56)
> at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
> at java.util.concurrent.FutureTask.run(FutureTask.java:266)
> at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
> at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
> at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
> at java.lang.Thread.run(Thread.java:745)
>
> "main":
> at io.grpc.internal.InUseStateAggregator.updateObjectInUse(InUseStateAggregator.java:50)
> - waiting to lock <0x00000007397d7e00> (a java.lang.Object)
> at io.grpc.internal.TransportSet$BaseTransportListener.transportInUse(TransportSet.java:357)
> at io.grpc.internal.DelayedClientTransport.newStream(DelayedClientTransport.java:128)
> - locked <0x00000007397d7f88> (a java.lang.Object)
> at io.grpc.internal.ClientCallImpl.start(ClientCallImpl.java:214)
> at io.grpc.stub.ClientCalls.startCall(ClientCalls.java:273)
> at io.grpc.stub.ClientCalls.asyncUnaryRequestCall(ClientCalls.java:252)
> at io.grpc.stub.ClientCalls.futureUnaryCall(ClientCalls.java:189)
> at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:135)
> at [...]remote.TestGrpc$TestBlockingStub.sayHello(TestGrpc.java:156)
I don't know if it may relate to my own code or if the issue is on grpc side.
| 8b745d9114fe11b0b9c65b67006a8ad0b7a11325 | 3d4ae360746c7f95b42a685d1254e69d0f0061f4 | https://github.com/grpc/grpc-java/compare/8b745d9114fe11b0b9c65b67006a8ad0b7a11325...3d4ae360746c7f95b42a685d1254e69d0f0061f4 | diff --git a/core/src/main/java/io/grpc/internal/TransportSet.java b/core/src/main/java/io/grpc/internal/TransportSet.java
index 025b83276..d89a8ac49 100644
--- a/core/src/main/java/io/grpc/internal/TransportSet.java
+++ b/core/src/main/java/io/grpc/internal/TransportSet.java
@@ -249,9 +249,14 @@ final class TransportSet implements WithLogId {
delayedTransport.endBackoff();
boolean shutdownDelayedTransport = false;
Runnable runnable = null;
+ // TransportSet as a channel layer class should not call into transport methods while
+ // holding the lock, thus we call hasPendingStreams() outside of the lock. It will cause
+ // a _benign_ race where the TransportSet may transition to CONNECTING when there is not
+ // pending stream.
+ boolean hasPendingStreams = delayedTransport.hasPendingStreams();
synchronized (lock) {
reconnectTask = null;
- if (delayedTransport.hasPendingStreams()) {
+ if (hasPendingStreams) {
// Transition directly to CONNECTING
runnable = startNewTransport(delayedTransport);
} else { | ['core/src/main/java/io/grpc/internal/TransportSet.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,796,050 | 808,722 | 105,188 | 333 | 499 | 98 | 7 | 1 | 2,336 | 167 | 631 | 42 | 0 | 0 | 2016-09-12T17:01:13 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,397 | grpc/grpc-java/1896/1883 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1883 | https://github.com/grpc/grpc-java/pull/1896 | https://github.com/grpc/grpc-java/pull/1896 | 1 | resolves | java.lang.IllegalArgumentException when try to use ipv6 | I guess this is caused by the scopeId:
```
java.lang.IllegalArgumentException: cannot find a NameResolver for directaddress:////0:0:0:0:0:0:0:0%0:10005 (Malformed escape pair at index 33: directaddress:////0:0:0:0:0:0:0:0%0:10005)
at io.grpc.internal.ManagedChannelImpl.getNameResolver(ManagedChannelImpl.java:238)
at io.grpc.internal.ManagedChannelImpl.(ManagedChannelImpl.java:159)
at io.grpc.internal.AbstractManagedChannelImplBuilder.build(AbstractManagedChannelImplBuilder.java:205)
```
| d25b65bb53258fc033e58cbaab4013a329ff45ce | 631a9d5fac0257416d3f74e53c9729989b8cd8b2 | https://github.com/grpc/grpc-java/compare/d25b65bb53258fc033e58cbaab4013a329ff45ce...631a9d5fac0257416d3f74e53c9729989b8cd8b2 | diff --git a/core/src/main/java/io/grpc/internal/AbstractManagedChannelImplBuilder.java b/core/src/main/java/io/grpc/internal/AbstractManagedChannelImplBuilder.java
index d14b09f1c..4cb74e9b9 100644
--- a/core/src/main/java/io/grpc/internal/AbstractManagedChannelImplBuilder.java
+++ b/core/src/main/java/io/grpc/internal/AbstractManagedChannelImplBuilder.java
@@ -33,6 +33,7 @@ package io.grpc.internal;
import static com.google.common.base.MoreObjects.firstNonNull;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.MoreExecutors;
@@ -49,6 +50,7 @@ import io.grpc.SimpleLoadBalancerFactory;
import java.net.SocketAddress;
import java.net.URI;
+import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -98,8 +100,23 @@ public abstract class AbstractManagedChannelImplBuilder
this.directServerAddress = null;
}
+ /**
+ * Returns a target string for the SocketAddress. It is only used as a placeholder, because
+ * DirectAddressNameResolverFactory will not actually try to use it. However, it must be a valid
+ * URI.
+ */
+ @VisibleForTesting
+ static String makeTargetStringForDirectAddress(SocketAddress address) {
+ try {
+ return new URI(DIRECT_ADDRESS_SCHEME, "", "/" + address, null).toString();
+ } catch (URISyntaxException e) {
+ // It should not happen.
+ throw new RuntimeException(e);
+ }
+ }
+
protected AbstractManagedChannelImplBuilder(SocketAddress directServerAddress, String authority) {
- this.target = DIRECT_ADDRESS_SCHEME + ":///" + directServerAddress;
+ this.target = makeTargetStringForDirectAddress(directServerAddress);
this.directServerAddress = directServerAddress;
this.nameResolverFactory = new DirectAddressNameResolverFactory(directServerAddress, authority);
}
diff --git a/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java b/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
index d0c70192f..ff448d638 100644
--- a/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
+++ b/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
@@ -229,7 +229,7 @@ public final class ManagedChannelImpl extends ManagedChannel implements WithLogI
// It doesn't look like a URI target. Maybe it's an authority string. Try with the default
// scheme from the factory.
try {
- targetUri = new URI(nameResolverFactory.getDefaultScheme(), null, "/" + target, null);
+ targetUri = new URI(nameResolverFactory.getDefaultScheme(), "", "/" + target, null);
} catch (URISyntaxException e) {
// Should not be possible.
throw new IllegalArgumentException(e);
diff --git a/core/src/test/java/io/grpc/internal/ManagedChannelImplGetNameResolverTest.java b/core/src/test/java/io/grpc/internal/ManagedChannelImplGetNameResolverTest.java
index dbbf078f6..13342593f 100644
--- a/core/src/test/java/io/grpc/internal/ManagedChannelImplGetNameResolverTest.java
+++ b/core/src/test/java/io/grpc/internal/ManagedChannelImplGetNameResolverTest.java
@@ -58,34 +58,38 @@ public class ManagedChannelImplGetNameResolverTest {
@Test
public void validTargetWithInvalidDnsName() throws Exception {
- testValidTarget("[valid]", new URI("defaultscheme", null, "/[valid]", null));
+ testValidTarget("[valid]", "defaultscheme:///%5Bvalid%5D",
+ new URI("defaultscheme", "", "/[valid]", null));
}
@Test
public void validAuthorityTarget() throws Exception {
- testValidTarget("foo.googleapis.com:8080",
- new URI("defaultscheme", null, "/foo.googleapis.com:8080", null));
+ testValidTarget("foo.googleapis.com:8080", "defaultscheme:///foo.googleapis.com:8080",
+ new URI("defaultscheme", "", "/foo.googleapis.com:8080", null));
}
@Test
public void validUriTarget() throws Exception {
- testValidTarget("scheme:///foo.googleapis.com:8080",
- new URI("scheme", null, "/foo.googleapis.com:8080", null));
+ testValidTarget("scheme:///foo.googleapis.com:8080", "scheme:///foo.googleapis.com:8080",
+ new URI("scheme", "", "/foo.googleapis.com:8080", null));
}
@Test
public void validIpv4AuthorityTarget() throws Exception {
- testValidTarget("127.0.0.1:1234", new URI("defaultscheme", null, "/127.0.0.1:1234", null));
+ testValidTarget("127.0.0.1:1234", "defaultscheme:///127.0.0.1:1234",
+ new URI("defaultscheme", "", "/127.0.0.1:1234", null));
}
@Test
public void validIpv4UriTarget() throws Exception {
- testValidTarget("dns:///127.0.0.1:1234", new URI("dns", null, "/127.0.0.1:1234", null));
+ testValidTarget("dns:///127.0.0.1:1234", "dns:///127.0.0.1:1234",
+ new URI("dns", "", "/127.0.0.1:1234", null));
}
@Test
public void validIpv6AuthorityTarget() throws Exception {
- testValidTarget("[::1]:1234", new URI("defaultscheme", null, "/[::1]:1234", null));
+ testValidTarget("[::1]:1234", "defaultscheme:///%5B::1%5D:1234",
+ new URI("defaultscheme", "", "/[::1]:1234", null));
}
@Test
@@ -95,7 +99,14 @@ public class ManagedChannelImplGetNameResolverTest {
@Test
public void validIpv6UriTarget() throws Exception {
- testValidTarget("dns:///%5B::1%5D:1234", new URI("dns", null, "/[::1]:1234", null));
+ testValidTarget("dns:///%5B::1%5D:1234", "dns:///%5B::1%5D:1234",
+ new URI("dns", "", "/[::1]:1234", null));
+ }
+
+ @Test
+ public void validTargetStartingWithSlash() throws Exception {
+ testValidTarget("/target", "defaultscheme:////target",
+ new URI("defaultscheme", "", "//target", null));
}
@Test
@@ -120,12 +131,13 @@ public class ManagedChannelImplGetNameResolverTest {
}
}
- private void testValidTarget(String target, URI expectedUri) {
+ private void testValidTarget(String target, String expectedUriString, URI expectedUri) {
Factory nameResolverFactory = new FakeNameResolverFactory(expectedUri.getScheme());
FakeNameResolver nameResolver = (FakeNameResolver) ManagedChannelImpl.getNameResolver(
target, nameResolverFactory, NAME_RESOLVER_PARAMS);
assertNotNull(nameResolver);
assertEquals(expectedUri, nameResolver.uri);
+ assertEquals(expectedUriString, nameResolver.uri.toString());
}
private void testInvalidTarget(String target) { | ['core/src/main/java/io/grpc/internal/ManagedChannelImpl.java', 'core/src/main/java/io/grpc/internal/AbstractManagedChannelImplBuilder.java', 'core/src/test/java/io/grpc/internal/ManagedChannelImplGetNameResolverTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,501,533 | 745,601 | 97,876 | 311 | 961 | 207 | 21 | 2 | 493 | 30 | 137 | 9 | 0 | 1 | 2016-06-03T00:12:12 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,396 | grpc/grpc-java/1979/1652 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1652 | https://github.com/grpc/grpc-java/pull/1979 | https://github.com/grpc/grpc-java/pull/1979 | 1 | fixes | Exceptions thrown in StreamObserver.onNext() may be swallowed | For unary calls it appears the exception is basically guaranteed to be swallowed.
See #1638 for some discussion. Basically we try to fail the call with a Status, but if the call already completed successfully (which is especially likely for unary calls) the exception is thrown away.
| 6c59770a5bd54857290dfb0496fe0b81fc79bd57 | 46f418da9408bc6e9d5172ea3a7c467b30c6b358 | https://github.com/grpc/grpc-java/compare/6c59770a5bd54857290dfb0496fe0b81fc79bd57...46f418da9408bc6e9d5172ea3a7c467b30c6b358 | diff --git a/core/src/main/java/io/grpc/internal/ClientCallImpl.java b/core/src/main/java/io/grpc/internal/ClientCallImpl.java
index 366d0f7b3..baa117507 100644
--- a/core/src/main/java/io/grpc/internal/ClientCallImpl.java
+++ b/core/src/main/java/io/grpc/internal/ClientCallImpl.java
@@ -414,8 +414,10 @@ final class ClientCallImpl<ReqT, RespT> extends ClientCall<ReqT, RespT>
observer.onHeaders(headers);
} catch (Throwable t) {
- stream.cancel(Status.CANCELLED.withCause(t).withDescription("Failed to read headers"));
- return;
+ Status status =
+ Status.CANCELLED.withCause(t).withDescription("Failed to read headers");
+ stream.cancel(status);
+ close(status, new Metadata());
}
}
});
@@ -437,13 +439,28 @@ final class ClientCallImpl<ReqT, RespT> extends ClientCall<ReqT, RespT>
message.close();
}
} catch (Throwable t) {
- stream.cancel(Status.CANCELLED.withCause(t).withDescription("Failed to read message."));
- return;
+ Status status =
+ Status.CANCELLED.withCause(t).withDescription("Failed to read message.");
+ stream.cancel(status);
+ close(status, new Metadata());
}
}
});
}
+ /**
+ * Must be called from application thread.
+ */
+ private void close(Status status, Metadata trailers) {
+ closed = true;
+ cancelListenersShouldBeRemoved = true;
+ try {
+ observer.onClose(status, trailers);
+ } finally {
+ removeContextListenerAndCancelDeadlineFuture();
+ }
+ }
+
@Override
public void closed(Status status, Metadata trailers) {
Deadline deadline = effectiveDeadline();
@@ -462,13 +479,11 @@ final class ClientCallImpl<ReqT, RespT> extends ClientCall<ReqT, RespT>
callExecutor.execute(new ContextRunnable(context) {
@Override
public final void runInContext() {
- try {
- closed = true;
- cancelListenersShouldBeRemoved = true;
- observer.onClose(savedStatus, savedTrailers);
- } finally {
- removeContextListenerAndCancelDeadlineFuture();
+ if (closed) {
+ // We intentionally don't keep the status or metadata from the server.
+ return;
}
+ close(savedStatus, savedTrailers);
}
});
}
@@ -478,7 +493,14 @@ final class ClientCallImpl<ReqT, RespT> extends ClientCall<ReqT, RespT>
callExecutor.execute(new ContextRunnable(context) {
@Override
public final void runInContext() {
- observer.onReady();
+ try {
+ observer.onReady();
+ } catch (Throwable t) {
+ Status status =
+ Status.CANCELLED.withCause(t).withDescription("Failed to call onReady.");
+ stream.cancel(status);
+ close(status, new Metadata());
+ }
}
});
}
diff --git a/core/src/test/java/io/grpc/internal/ClientCallImplTest.java b/core/src/test/java/io/grpc/internal/ClientCallImplTest.java
index 8a73fb0b7..ed0773082 100644
--- a/core/src/test/java/io/grpc/internal/ClientCallImplTest.java
+++ b/core/src/test/java/io/grpc/internal/ClientCallImplTest.java
@@ -43,6 +43,7 @@ import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
@@ -75,6 +76,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
+import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -82,8 +84,11 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
+import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -146,6 +151,103 @@ public class ClientCallImplTest {
Context.ROOT.attach();
}
+ @Test
+ public void exceptionInOnMessageTakesPrecedenceOverServer() {
+ DelayedExecutor executor = new DelayedExecutor();
+ ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
+ method,
+ executor,
+ CallOptions.DEFAULT,
+ provider,
+ deadlineCancellationExecutor);
+ call.start(callListener, new Metadata());
+ verify(stream).start(listenerArgumentCaptor.capture());
+ final ClientStreamListener streamListener = listenerArgumentCaptor.getValue();
+ streamListener.headersRead(new Metadata());
+
+ RuntimeException failure = new RuntimeException("bad");
+ doThrow(failure).when(callListener).onMessage(any(Void.class));
+
+ /*
+ * In unary calls, the server closes the call right after responding, so the onClose call is
+ * queued to run. When messageRead is called, an exception will occur and attempt to cancel the
+ * stream. However, since the server closed it "first" the second exception is lost leading to
+ * the call being counted as successful.
+ */
+ streamListener.messageRead(new ByteArrayInputStream(new byte[]{}));
+ streamListener.closed(Status.OK, new Metadata());
+ executor.release();
+
+ verify(callListener).onClose(statusArgumentCaptor.capture(), Matchers.isA(Metadata.class));
+ assertThat(statusArgumentCaptor.getValue().getCode()).isEqualTo(Status.Code.CANCELLED);
+ assertThat(statusArgumentCaptor.getValue().getCause()).isSameAs(failure);
+ verify(stream).cancel(statusArgumentCaptor.getValue());
+ }
+
+ @Test
+ public void exceptionInOnHeadersTakesPrecedenceOverServer() {
+ DelayedExecutor executor = new DelayedExecutor();
+ ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
+ method,
+ executor,
+ CallOptions.DEFAULT,
+ provider,
+ deadlineCancellationExecutor);
+ call.start(callListener, new Metadata());
+ verify(stream).start(listenerArgumentCaptor.capture());
+ final ClientStreamListener streamListener = listenerArgumentCaptor.getValue();
+
+ RuntimeException failure = new RuntimeException("bad");
+ doThrow(failure).when(callListener).onHeaders(any(Metadata.class));
+
+ /*
+ * In unary calls, the server closes the call right after responding, so the onClose call is
+ * queued to run. When headersRead is called, an exception will occur and attempt to cancel the
+ * stream. However, since the server closed it "first" the second exception is lost leading to
+ * the call being counted as successful.
+ */
+ streamListener.headersRead(new Metadata());
+ streamListener.closed(Status.OK, new Metadata());
+ executor.release();
+
+ verify(callListener).onClose(statusArgumentCaptor.capture(), Matchers.isA(Metadata.class));
+ assertThat(statusArgumentCaptor.getValue().getCode()).isEqualTo(Status.Code.CANCELLED);
+ assertThat(statusArgumentCaptor.getValue().getCause()).isSameAs(failure);
+ verify(stream).cancel(statusArgumentCaptor.getValue());
+ }
+
+ @Test
+ public void exceptionInOnReadyTakesPrecedenceOverServer() {
+ DelayedExecutor executor = new DelayedExecutor();
+ ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
+ method,
+ executor,
+ CallOptions.DEFAULT,
+ provider,
+ deadlineCancellationExecutor);
+ call.start(callListener, new Metadata());
+ verify(stream).start(listenerArgumentCaptor.capture());
+ final ClientStreamListener streamListener = listenerArgumentCaptor.getValue();
+
+ RuntimeException failure = new RuntimeException("bad");
+ doThrow(failure).when(callListener).onReady();
+
+ /*
+ * In unary calls, the server closes the call right after responding, so the onClose call is
+ * queued to run. When onReady is called, an exception will occur and attempt to cancel the
+ * stream. However, since the server closed it "first" the second exception is lost leading to
+ * the call being counted as successful.
+ */
+ streamListener.onReady();
+ streamListener.closed(Status.OK, new Metadata());
+ executor.release();
+
+ verify(callListener).onClose(statusArgumentCaptor.capture(), Matchers.isA(Metadata.class));
+ assertThat(statusArgumentCaptor.getValue().getCode()).isEqualTo(Status.Code.CANCELLED);
+ assertThat(statusArgumentCaptor.getValue().getCause()).isSameAs(failure);
+ verify(stream).cancel(statusArgumentCaptor.getValue());
+ }
+
@Test
public void advertisedEncodingsAreSent() {
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
@@ -668,5 +770,19 @@ public class ClientCallImplTest {
assertTrue("timeout: " + timeout + " ns", timeout >= from);
}
+ private static final class DelayedExecutor implements Executor {
+ private final BlockingQueue<Runnable> commands = new LinkedBlockingQueue<Runnable>();
+
+ @Override
+ public void execute(Runnable command) {
+ commands.add(command);
+ }
+
+ void release() {
+ while (!commands.isEmpty()) {
+ commands.poll().run();
+ }
+ }
+ }
}
| ['core/src/main/java/io/grpc/internal/ClientCallImpl.java', 'core/src/test/java/io/grpc/internal/ClientCallImplTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,591,771 | 764,473 | 100,173 | 326 | 1,734 | 309 | 44 | 1 | 284 | 47 | 55 | 3 | 0 | 0 | 2016-06-24T22:58:40 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,395 | grpc/grpc-java/2025/1947 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1947 | https://github.com/grpc/grpc-java/pull/2025 | https://github.com/grpc/grpc-java/pull/2025 | 1 | fixes | ServerCallImpl's use of metadata in sendHeaders is thread-unsafe | `ServerCallImpl` uses metadata to determine compression settings in [sendHeaders](https://github.com/grpc/grpc-java/blob/a2076f4/core/src/main/java/io/grpc/internal/ServerCallImpl.java#L111). However, that `Metadata` has already been passed to the application which is free to modify it. The `acceptEncodings` should just be saved as a field during the constructor instead.
| 0d6a9de54c3ef7800b76405ecd9ff581c90f6c7a | 0e47be12878fe1dfb0504ed43ec8f363fe9eb1ce | https://github.com/grpc/grpc-java/compare/0d6a9de54c3ef7800b76405ecd9ff581c90f6c7a...0e47be12878fe1dfb0504ed43ec8f363fe9eb1ce | diff --git a/core/src/main/java/io/grpc/internal/ServerCallImpl.java b/core/src/main/java/io/grpc/internal/ServerCallImpl.java
index 6e0707b32..d2a4e9029 100644
--- a/core/src/main/java/io/grpc/internal/ServerCallImpl.java
+++ b/core/src/main/java/io/grpc/internal/ServerCallImpl.java
@@ -62,7 +62,7 @@ final class ServerCallImpl<ReqT, RespT> extends ServerCall<ReqT, RespT> {
private final ServerStream stream;
private final MethodDescriptor<ReqT, RespT> method;
private final Context.CancellableContext context;
- private Metadata inboundHeaders;
+ private final String messageAcceptEncoding;
private final DecompressorRegistry decompressorRegistry;
private final CompressorRegistry compressorRegistry;
@@ -78,7 +78,7 @@ final class ServerCallImpl<ReqT, RespT> extends ServerCall<ReqT, RespT> {
this.stream = stream;
this.method = method;
this.context = context;
- this.inboundHeaders = inboundHeaders;
+ this.messageAcceptEncoding = inboundHeaders.get(MESSAGE_ACCEPT_ENCODING_KEY);
this.decompressorRegistry = decompressorRegistry;
this.compressorRegistry = compressorRegistry;
@@ -108,9 +108,9 @@ final class ServerCallImpl<ReqT, RespT> extends ServerCall<ReqT, RespT> {
if (compressor == null) {
compressor = Codec.Identity.NONE;
} else {
- if (inboundHeaders.containsKey(MESSAGE_ACCEPT_ENCODING_KEY)) {
- String acceptEncodings = inboundHeaders.get(MESSAGE_ACCEPT_ENCODING_KEY);
- List<String> acceptedEncodingsList = ACCEPT_ENCODING_SPLITER.splitToList(acceptEncodings);
+ if (messageAcceptEncoding != null) {
+ List<String> acceptedEncodingsList =
+ ACCEPT_ENCODING_SPLITER.splitToList(messageAcceptEncoding);
if (!acceptedEncodingsList.contains(compressor.getMessageEncoding())) {
// resort to using no compression.
compressor = Codec.Identity.NONE;
@@ -119,7 +119,6 @@ final class ServerCallImpl<ReqT, RespT> extends ServerCall<ReqT, RespT> {
compressor = Codec.Identity.NONE;
}
}
- inboundHeaders = null;
// Always put compressor, even if it's identity.
headers.put(MESSAGE_ENCODING_KEY, compressor.getMessageEncoding());
@@ -178,7 +177,6 @@ final class ServerCallImpl<ReqT, RespT> extends ServerCall<ReqT, RespT> {
public void close(Status status, Metadata trailers) {
checkState(!closeCalled, "call already closed");
closeCalled = true;
- inboundHeaders = null;
stream.close(status, trailers);
}
| ['core/src/main/java/io/grpc/internal/ServerCallImpl.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,656,371 | 777,801 | 101,644 | 330 | 680 | 131 | 12 | 1 | 374 | 38 | 83 | 2 | 1 | 0 | 2016-07-08T22:18:46 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,394 | grpc/grpc-java/2064/2036 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/2036 | https://github.com/grpc/grpc-java/pull/2064 | https://github.com/grpc/grpc-java/pull/2064 | 1 | fixes | Metadata trailers are not passed to Status*Exception when using ClientCalls.blockingUnaryCall. | Trying to write a sample for #1295, but when calling unary rpc method on blocking stub, the trailers are not passed during `ClientCalls.getUnchecked` which is called from [ClientCalls.blockingUnaryCall](https://github.com/grpc/grpc-java/blob/master/stub/src/main/java/io/grpc/stub/ClientCalls.java#L141).
Is this by design or bug ?
Sample code is [here](https://github.com/chikei/grpc-java/commit/ea1ec3f5503a40d39c0ad10360c8a6ecbad46eca), the [blockingCall()](https://github.com/chikei/grpc-java/blob/ea1ec3f5503a40d39c0ad10360c8a6ecbad46eca/examples/src/main/java/io/grpc/examples/errorhandling/ErrorHandlingClient.java#L94) fails but others are good.
| 30c2b0eda023e05e431d7bc2cb977c958dab958e | 26065c742d21bc10361aacce3c4e38e83bab579f | https://github.com/grpc/grpc-java/compare/30c2b0eda023e05e431d7bc2cb977c958dab958e...26065c742d21bc10361aacce3c4e38e83bab579f | diff --git a/stub/src/main/java/io/grpc/stub/ClientCalls.java b/stub/src/main/java/io/grpc/stub/ClientCalls.java
index 529649763..b3cb880ac 100644
--- a/stub/src/main/java/io/grpc/stub/ClientCalls.java
+++ b/stub/src/main/java/io/grpc/stub/ClientCalls.java
@@ -31,6 +31,8 @@
package io.grpc.stub;
+import static com.google.common.base.Preconditions.checkNotNull;
+
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.ListenableFuture;
@@ -38,9 +40,11 @@ import com.google.common.util.concurrent.ListenableFuture;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
+import io.grpc.ExperimentalApi;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
+import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import java.util.Iterator;
@@ -205,8 +209,30 @@ public class ClientCalls {
Thread.currentThread().interrupt();
throw Status.CANCELLED.withCause(e).asRuntimeException();
} catch (ExecutionException e) {
- throw Status.fromThrowable(e).asRuntimeException();
+ throw toStatusRuntimeException(e);
+ }
+ }
+
+ /**
+ * Wraps the given {@link Throwable} in a {@link StatusRuntimeException}. If it contains an
+ * embedded {@link StatusException} or {@link StatusRuntimeException}, the returned exception will
+ * contain the embedded trailers and status, with the given exception as the cause. Otherwise, an
+ * exception will be generated from an {@link Status#UNKNOWN} status.
+ */
+ private static StatusRuntimeException toStatusRuntimeException(Throwable t) {
+ Throwable cause = checkNotNull(t);
+ while (cause != null) {
+ // If we have an embedded status, use it and replace the cause
+ if (cause instanceof StatusException) {
+ StatusException se = (StatusException) cause;
+ return new StatusRuntimeException(se.getStatus().withCause(t), se.getTrailers());
+ } else if (cause instanceof StatusRuntimeException) {
+ StatusRuntimeException se = (StatusRuntimeException) cause;
+ return new StatusRuntimeException(se.getStatus().withCause(t), se.getTrailers());
+ }
+ cause = cause.getCause();
}
+ return Status.UNKNOWN.withCause(t).asRuntimeException();
}
private static <ReqT, RespT> void asyncUnaryRequestCall(
diff --git a/stub/src/test/java/io/grpc/stub/ClientCallsTest.java b/stub/src/test/java/io/grpc/stub/ClientCallsTest.java
index 4547e9468..079a1d49a 100644
--- a/stub/src/test/java/io/grpc/stub/ClientCallsTest.java
+++ b/stub/src/test/java/io/grpc/stub/ClientCallsTest.java
@@ -36,6 +36,7 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -44,6 +45,7 @@ import com.google.common.util.concurrent.SettableFuture;
import io.grpc.CallOptions;
import io.grpc.ClientCall;
+import io.grpc.ClientCall.Listener;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
@@ -51,6 +53,7 @@ import io.grpc.Server;
import io.grpc.ServerServiceDefinition;
import io.grpc.ServiceDescriptor;
import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.ServerCalls.NoopStreamObserver;
@@ -63,7 +66,10 @@ import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
+import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
import java.util.ArrayList;
import java.util.Arrays;
@@ -81,10 +87,11 @@ import java.util.concurrent.TimeUnit;
@RunWith(JUnit4.class)
public class ClientCallsTest {
- static final MethodDescriptor<Integer, Integer> STREAMING_METHOD = MethodDescriptor.create(
- MethodDescriptor.MethodType.BIDI_STREAMING,
- "some/method",
- new IntegerMarshaller(), new IntegerMarshaller());
+ private static final MethodDescriptor<Integer, Integer> STREAMING_METHOD = MethodDescriptor
+ .create(
+ MethodDescriptor.MethodType.BIDI_STREAMING,
+ "some/method",
+ new IntegerMarshaller(), new IntegerMarshaller());
private Server server;
private ManagedChannel channel;
@@ -107,6 +114,53 @@ public class ClientCallsTest {
}
}
+ @Test
+ public void unaryBlockingCallSuccess() throws Exception {
+ Integer req = 2;
+ final String resp = "bar";
+ final Status status = Status.OK;
+ final Metadata trailers = new Metadata();
+
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock in) throws Throwable {
+ @SuppressWarnings("unchecked")
+ Listener<String> listener = (Listener<String>) in.getArguments()[0];
+ listener.onMessage(resp);
+ listener.onClose(status, trailers);
+ return null;
+ }
+ }).when(call).start(Mockito.<Listener<String>>any(), any(Metadata.class));
+
+ String actualResponse = ClientCalls.blockingUnaryCall(call, req);
+ assertEquals(resp, actualResponse);
+ }
+
+ @Test
+ public void unaryBlockingCallFailed() throws Exception {
+ Integer req = 2;
+ final Status status = Status.INTERNAL;
+ final Metadata trailers = new Metadata();
+
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock in) throws Throwable {
+ @SuppressWarnings("unchecked")
+ Listener<String> listener = (Listener<String>) in.getArguments()[0];
+ listener.onClose(status, trailers);
+ return null;
+ }
+ }).when(call).start(Mockito.<Listener<String>>any(), any(Metadata.class));
+
+ try {
+ ClientCalls.blockingUnaryCall(call, req);
+ fail("Should fail");
+ } catch (StatusRuntimeException e) {
+ assertSame(status.getCode(), e.getStatus().getCode());
+ assertSame(trailers, e.getTrailers());
+ }
+ }
+
@Test
public void unaryFutureCallSuccess() throws Exception {
Integer req = 2;
@@ -246,24 +300,24 @@ public class ClientCallsTest {
ArgumentCaptor<ClientCall.Listener<String>> listenerCaptor = ArgumentCaptor.forClass(null);
ClientResponseObserver<Integer, String> responseObserver =
new ClientResponseObserver<Integer, String>() {
- @Override
- public void beforeStart(ClientCallStreamObserver<Integer> requestStream) {
- requestStream.disableAutoInboundFlowControl();
- requestStream.request(5);
- }
+ @Override
+ public void beforeStart(ClientCallStreamObserver<Integer> requestStream) {
+ requestStream.disableAutoInboundFlowControl();
+ requestStream.request(5);
+ }
- @Override
- public void onNext(String value) {
- }
+ @Override
+ public void onNext(String value) {
+ }
- @Override
- public void onError(Throwable t) {
- }
+ @Override
+ public void onError(Throwable t) {
+ }
- @Override
- public void onCompleted() {
- }
- };
+ @Override
+ public void onCompleted() {
+ }
+ };
ClientCalls.asyncServerStreamingCall(call, 1, responseObserver);
verify(call).start(listenerCaptor.capture(), any(Metadata.class));
listenerCaptor.getValue().onMessage("message");
@@ -398,6 +452,7 @@ public class ClientCallsTest {
public void beforeStart(final ClientCallStreamObserver<Integer> requestStream) {
requestStream.setOnReadyHandler(new Runnable() {
int iteration;
+
@Override
public void run() {
while (requestStream.isReady()) { | ['stub/src/main/java/io/grpc/stub/ClientCalls.java', 'stub/src/test/java/io/grpc/stub/ClientCallsTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,465,530 | 735,797 | 95,719 | 310 | 1,371 | 266 | 28 | 1 | 656 | 46 | 184 | 6 | 3 | 0 | 2016-07-18T22:52:18 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,393 | grpc/grpc-java/2154/2152 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/2152 | https://github.com/grpc/grpc-java/pull/2154 | https://github.com/grpc/grpc-java/pull/2154 | 1 | resolves | Deadlock found in TransportSet | When running benchmarks where the client started up faster than the server, The first few calls failed as unavailable. Our internal deadlock detector seems to think there is a deadlock around here:
```
Deadlock(s) found:
"grpc-client-net-1-32" daemon prio=5 Id=175 BLOCKED on java.lang.Object@7eeb2e6b owned by "grpc-client-app-5" Id=119
io.grpc.internal.DelayedClientTransport.startBackoff(DelayedClientTransport.java:323)
io.grpc.internal.TransportSet.scheduleBackoff(TransportSet.java:235)
io.grpc.internal.TransportSet.access$1500(TransportSet.java:61)
io.grpc.internal.TransportSet$TransportListener.transportShutdown(TransportSet.java:440)
io.grpc.netty.ClientTransportLifecycleManager.notifyShutdown(ClientTransportLifecycleManager.java:68)
io.grpc.netty.ClientTransportLifecycleManager.notifyTerminated(ClientTransportLifecycleManager.java:84)
io.grpc.netty.NettyClientTransport$4.operationComplete(NettyClientTransport.java:181)
io.grpc.netty.NettyClientTransport$4.operationComplete(NettyClientTransport.java:175)
io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:514)
io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:488)
io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:427)
io.netty.util.concurrent.DefaultPromise.setFailure(DefaultPromise.java:120)
io.netty.channel.DefaultChannelPromise.setFailure(DefaultChannelPromise.java:87)
io.grpc.netty.ProtocolNegotiators$AbstractBufferingHandler.fail(ProtocolNegotiators.java:436)
io.grpc.netty.ProtocolNegotiators$AbstractBufferingHandler.exceptionCaught(ProtocolNegotiators.java:376)
io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:295)
io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:274)
io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:266)
io.grpc.netty.NettyClientTransport$3.operationComplete(NettyClientTransport.java:165)
io.grpc.netty.NettyClientTransport$3.operationComplete(NettyClientTransport.java:156)
io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:514)
io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:507)
io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:486)
io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:427)
io.netty.util.concurrent.DefaultPromise.tryFailure(DefaultPromise.java:129)
io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.fulfillConnectPromise(AbstractNioChannel.java:321)
io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:337)
io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:588)
io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:512)
io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:426)
io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:398)
io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:877)
io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
java.lang.Thread.run(Thread.java:745)
"grpc-client-app-5" daemon prio=5 Id=119 BLOCKED on java.lang.Object@17902cf5 owned by "grpc-client-net-1-32" Id=175
io.grpc.internal.InUseStateAggregator.updateObjectInUse(InUseStateAggregator.java:51)
io.grpc.internal.TransportSet$BaseTransportListener.transportInUse(TransportSet.java:345)
io.grpc.internal.DelayedClientTransport.newStream(DelayedClientTransport.java:128)
io.grpc.internal.DelayedClientTransport$PendingStream.createRealStream(DelayedClientTransport.java:382)
io.grpc.internal.DelayedClientTransport$PendingStream.access$100(DelayedClientTransport.java:369)
io.grpc.internal.DelayedClientTransport$2.run(DelayedClientTransport.java:261)
java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1402)
java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
```
| 3879c6a8fa4b0ec25f211019ec26b0acee8976cb | 7a33fae8e8cd4d36c4986b0644f13c8d8d2f2d6f | https://github.com/grpc/grpc-java/compare/3879c6a8fa4b0ec25f211019ec26b0acee8976cb...7a33fae8e8cd4d36c4986b0644f13c8d8d2f2d6f | diff --git a/core/src/main/java/io/grpc/internal/TransportSet.java b/core/src/main/java/io/grpc/internal/TransportSet.java
index dc04c9497..025b83276 100644
--- a/core/src/main/java/io/grpc/internal/TransportSet.java
+++ b/core/src/main/java/io/grpc/internal/TransportSet.java
@@ -227,8 +227,10 @@ final class TransportSet implements WithLogId {
* @param status the causal status when the channel begins transition to
* TRANSIENT_FAILURE.
*/
+ @CheckReturnValue
@GuardedBy("lock")
- private void scheduleBackoff(final DelayedClientTransport delayedTransport, Status status) {
+ private Runnable scheduleBackoff(
+ final DelayedClientTransport delayedTransport, final Status status) {
Preconditions.checkState(reconnectTask == null, "previous reconnectTask is not done");
if (reconnectPolicy == null) {
@@ -240,7 +242,6 @@ final class TransportSet implements WithLogId {
log.log(Level.FINE, "[{0}] Scheduling backoff for {1} ms",
new Object[]{getLogId(), delayMillis});
}
- delayedTransport.startBackoff(status);
class EndOfCurrentBackoff implements Runnable {
@Override
public void run() {
@@ -281,6 +282,16 @@ final class TransportSet implements WithLogId {
reconnectTask = scheduledExecutor.schedule(
new LogExceptionRunnable(new EndOfCurrentBackoff()), delayMillis, TimeUnit.MILLISECONDS);
+ return new Runnable() {
+ @Override
+ public void run() {
+ // This must be run outside of lock. The TransportSet lock is a channel level lock.
+ // startBackoff() will acquire the delayed transport lock, which is a transport level
+ // lock. Our lock ordering mandates transport lock > channel lock. Otherwise a deadlock
+ // could happen (https://github.com/grpc/grpc-java/issues/2152).
+ delayedTransport.startBackoff(status);
+ }
+ };
}
/**
@@ -450,7 +461,7 @@ final class TransportSet implements WithLogId {
allAddressesFailed = true;
// Initiate backoff
// Transition to TRANSIENT_FAILURE
- scheduleBackoff(delayedTransport, s);
+ runnable = scheduleBackoff(delayedTransport, s);
} else {
// Still CONNECTING
runnable = startNewTransport(delayedTransport); | ['core/src/main/java/io/grpc/internal/TransportSet.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,723,185 | 792,487 | 103,198 | 322 | 885 | 177 | 17 | 1 | 4,355 | 103 | 938 | 56 | 0 | 1 | 2016-08-10T16:48:54 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,406 | grpc/grpc-java/1260/1251 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1251 | https://github.com/grpc/grpc-java/pull/1260 | https://github.com/grpc/grpc-java/pull/1260 | 1 | fixes | Netty Server does not observe channelInactive | If the TCP connection goes down, gRPC isn't noticing because nothing is observing the `channelInactive()` notification on the channel pipeline. I confirmed that `channelInactive()` is called, but saw that an outstanding streaming RPC was not cancelled.
This likely applies to both client-side and server-side; I only verified it broken on server-side.
| 8d0b5b0c4d40c5ee4dba7e74851c9eecc3bb400e | 96f9cefda41bbbf1462bfe607864d451bc716219 | https://github.com/grpc/grpc-java/compare/8d0b5b0c4d40c5ee4dba7e74851c9eecc3bb400e...96f9cefda41bbbf1462bfe607864d451bc716219 | diff --git a/netty/src/main/java/io/grpc/netty/NettyServerHandler.java b/netty/src/main/java/io/grpc/netty/NettyServerHandler.java
index e7d6ea2dd..06b5a3fb9 100644
--- a/netty/src/main/java/io/grpc/netty/NettyServerHandler.java
+++ b/netty/src/main/java/io/grpc/netty/NettyServerHandler.java
@@ -261,18 +261,21 @@ class NettyServerHandler extends AbstractNettyHandler {
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- super.channelInactive(ctx);
- // Any streams that are still active must be closed
- connection().forEachActiveStream(new Http2StreamVisitor() {
- @Override
- public boolean visit(Http2Stream stream) throws Http2Exception {
- NettyServerStream serverStream = serverStream(stream);
- if (serverStream != null) {
- serverStream.abortStream(GOAWAY_STATUS, false);
+ try {
+ // Any streams that are still active must be closed
+ connection().forEachActiveStream(new Http2StreamVisitor() {
+ @Override
+ public boolean visit(Http2Stream stream) throws Http2Exception {
+ NettyServerStream serverStream = serverStream(stream);
+ if (serverStream != null) {
+ serverStream.abortStream(GOAWAY_STATUS, false);
+ }
+ return true;
}
- return true;
- }
- });
+ });
+ } finally {
+ super.channelInactive(ctx);
+ }
}
WriteQueue getWriteQueue() {
diff --git a/netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java b/netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java
index 87078c2a4..52ec3fd40 100644
--- a/netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java
+++ b/netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java
@@ -237,6 +237,15 @@ public class NettyServerHandlerTest extends NettyHandlerTestBase<NettyServerHand
assertFalse(channel().isOpen());
}
+ @Test
+ public void channelInactiveShouldCloseStreams() throws Exception {
+ createStream();
+ handler().channelInactive(ctx());
+ ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
+ verify(streamListener).closed(captor.capture());
+ assertFalse(captor.getValue().isOk());
+ }
+
@Test
public void shouldAdvertiseMaxConcurrentStreams() throws Exception {
maxConcurrentStreams = 314; | ['netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java', 'netty/src/main/java/io/grpc/netty/NettyServerHandler.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,139,256 | 461,888 | 60,556 | 276 | 946 | 191 | 25 | 1 | 353 | 51 | 68 | 4 | 0 | 0 | 2015-12-05T00:19:02 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,405 | grpc/grpc-java/1262/1251 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1251 | https://github.com/grpc/grpc-java/pull/1262 | https://github.com/grpc/grpc-java/pull/1262 | 1 | fixes | Netty Server does not observe channelInactive | If the TCP connection goes down, gRPC isn't noticing because nothing is observing the `channelInactive()` notification on the channel pipeline. I confirmed that `channelInactive()` is called, but saw that an outstanding streaming RPC was not cancelled.
This likely applies to both client-side and server-side; I only verified it broken on server-side.
| 999f408ff29b61d2bdd5cd723f614c70320adf16 | 3e0f44fb8c73e51927eb5e077fd69c8571f693ad | https://github.com/grpc/grpc-java/compare/999f408ff29b61d2bdd5cd723f614c70320adf16...3e0f44fb8c73e51927eb5e077fd69c8571f693ad | diff --git a/netty/src/main/java/io/grpc/netty/NettyServerHandler.java b/netty/src/main/java/io/grpc/netty/NettyServerHandler.java
index 94f287629..7e53e731a 100644
--- a/netty/src/main/java/io/grpc/netty/NettyServerHandler.java
+++ b/netty/src/main/java/io/grpc/netty/NettyServerHandler.java
@@ -224,15 +224,18 @@ class NettyServerHandler extends Http2ConnectionHandler {
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- super.channelInactive(ctx);
- // Any streams that are still active must be closed
- connection().forEachActiveStream(new Http2StreamVisitor() {
- @Override
- public boolean visit(Http2Stream stream) throws Http2Exception {
- serverStream(stream).abortStream(GOAWAY_STATUS, false);
- return true;
- }
- });
+ try {
+ // Any streams that are still active must be closed
+ connection().forEachActiveStream(new Http2StreamVisitor() {
+ @Override
+ public boolean visit(Http2Stream stream) throws Http2Exception {
+ serverStream(stream).abortStream(GOAWAY_STATUS, false);
+ return true;
+ }
+ });
+ } finally {
+ super.channelInactive(ctx);
+ }
}
WriteQueue getWriteQueue() {
diff --git a/netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java b/netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java
index 7293907ea..b3a99f228 100644
--- a/netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java
+++ b/netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java
@@ -249,6 +249,15 @@ public class NettyServerHandlerTest extends NettyHandlerTestBase<NettyServerHand
assertFalse(channel().isOpen());
}
+ @Test
+ public void channelInactiveShouldCloseStreams() throws Exception {
+ createStream();
+ handler().channelInactive(ctx());
+ ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
+ verify(streamListener).closed(captor.capture());
+ assertFalse(captor.getValue().isOk());
+ }
+
@Test
public void shouldAdvertiseMaxConcurrentStreams() throws Exception {
maxConcurrentStreams = 314; | ['netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java', 'netty/src/main/java/io/grpc/netty/NettyServerHandler.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,856,798 | 390,397 | 53,465 | 239 | 750 | 153 | 21 | 1 | 353 | 51 | 68 | 4 | 0 | 0 | 2015-12-07T16:58:31 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,416 | grpc/grpc-java/364/359 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/359 | https://github.com/grpc/grpc-java/pull/364 | https://github.com/grpc/grpc-java/pull/364 | 1 | resolves | Http2ClientStream overwrites error message | [Http2ClientStream.transportHeadersReceived()](https://github.com/grpc/grpc-java/blob/d0aad72441f2f110910003599bb923db6f671f02/core/src/main/java/io/grpc/transport/Http2ClientStream.java#L102) is calling withDescription instead of augmentDescription. This hinders debugging what went wrong.
@yang-g, since he is interested in when this is resolved.
| 41940f7ff7025ba703bf7d77f90fd376f825f75b | 2b33598ec4b377a7cae8d55e8c020c1171d119a2 | https://github.com/grpc/grpc-java/compare/41940f7ff7025ba703bf7d77f90fd376f825f75b...2b33598ec4b377a7cae8d55e8c020c1171d119a2 | diff --git a/core/src/main/java/io/grpc/transport/Http2ClientStream.java b/core/src/main/java/io/grpc/transport/Http2ClientStream.java
index badc7c0f2..85577cc8f 100644
--- a/core/src/main/java/io/grpc/transport/Http2ClientStream.java
+++ b/core/src/main/java/io/grpc/transport/Http2ClientStream.java
@@ -99,7 +99,7 @@ public abstract class Http2ClientStream extends AbstractClientStream<Integer> {
if (transportError != null) {
// Note we don't immediately report the transport error, instead we wait for more data on the
// stream so we can accumulate more detail into the error before reporting it.
- transportError = transportError.withDescription("\\n" + headers.toString());
+ transportError = transportError.augmentDescription("\\n" + headers.toString());
errorCharset = extractCharset(headers);
} else {
stripTransportDetails(headers); | ['core/src/main/java/io/grpc/transport/Http2ClientStream.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 748,500 | 156,719 | 20,878 | 125 | 168 | 32 | 2 | 1 | 350 | 23 | 87 | 4 | 1 | 0 | 2015-04-30T17:01:21 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,407 | grpc/grpc-java/1112/1111 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1111 | https://github.com/grpc/grpc-java/pull/1112 | https://github.com/grpc/grpc-java/pull/1112 | 1 | fixes | transportShutdown() should be called before calling transportTerminated(). | With the changes of TransportSet, transportShutdown() must be called before calling transportTerminated().
```
10-06 15:32:45.917 5126 5126 E AndroidRuntime: FATAL EXCEPTION: OkHttpClientTransport
10-06 15:32:45.917 5126 5126 E AndroidRuntime: Process: com.google.android.apps.fireball, PID: 5126
10-06 15:32:45.917 5126 5126 E AndroidRuntime: java.lang.IllegalStateException: Listener is still attached to activeTransportFuture. Seems transportTerminated was not called.
10-06 15:32:45.917 5126 5126 E AndroidRuntime: at com.google.common.base.Preconditions.checkState(Preconditions.java:173)
10-06 15:32:45.917 5126 5126 E AndroidRuntime: at io.grpc.internal.TransportSet$TransportListener.transportTerminated(TransportSet.java:249)
10-06 15:32:45.917 5126 5126 E AndroidRuntime: at io.grpc.okhttp.OkHttpClientTransport$ClientFrameHandler.run(OkHttpClientTransport.java:606)
10-06 15:32:45.917 5126 5126 E AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-06 15:32:45.917 5126 5126 E AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-06 15:32:45.917 5126 5126 E AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
10-06 15:32:45.918 745 1319 W ActivityManager: Force finishing activity com.google.android.apps.fireball/.ui.photoviewer.FireballPhotoViewActivity
```
| 6474938fe7e9c9355a5fa1004f4cae39ad069797 | 72a0a38182bc7b1f32868cfc8c1fc3e2667a5f04 | https://github.com/grpc/grpc-java/compare/6474938fe7e9c9355a5fa1004f4cae39ad069797...72a0a38182bc7b1f32868cfc8c1fc3e2667a5f04 | diff --git a/core/src/main/java/io/grpc/internal/ClientTransport.java b/core/src/main/java/io/grpc/internal/ClientTransport.java
index 8f287973c..c2c88e47b 100644
--- a/core/src/main/java/io/grpc/internal/ClientTransport.java
+++ b/core/src/main/java/io/grpc/internal/ClientTransport.java
@@ -114,6 +114,8 @@ public interface ClientTransport {
/**
* The transport completed shutting down. All resources have been released.
+ *
+ * <p> {@link #transportShutdown(Status)} must be called before calling this method.
*/
void transportTerminated();
diff --git a/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java b/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java
index 1001f3eba..7779fb13b 100644
--- a/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java
+++ b/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java
@@ -144,9 +144,14 @@ class OkHttpClientTransport implements ClientTransport {
private final int maxMessageSize;
private int connectionUnacknowledgedBytesRead;
private ClientFrameHandler clientFrameHandler;
- // The status used to finish all active streams when the transport is closed.
+ // Indicates the transport is in go-away state: no new streams will be processed,
+ // but existing streams may continue.
@GuardedBy("lock")
private boolean goAway;
+ // Used to indicate the special phase while we are going to enter go-away state but before
+ // goAway is turned to true, see the comment at where this is set about why it is needed.
+ @GuardedBy("lock")
+ private boolean startedGoAway;
@GuardedBy("lock")
private Status goAwayStatus;
@GuardedBy("lock")
@@ -284,7 +289,7 @@ class OkHttpClientTransport implements ClientTransport {
// Make sure nextStreamId greater than all used id, so that mayHaveCreatedStream() performs
// correctly.
nextStreamId = Integer.MAX_VALUE;
- onGoAway(Integer.MAX_VALUE, Status.INTERNAL.withDescription("Stream ids exhausted"));
+ startGoAway(Integer.MAX_VALUE, Status.INTERNAL.withDescription("Stream ids exhausted"));
} else {
nextStreamId += 2;
}
@@ -449,7 +454,7 @@ class OkHttpClientTransport implements ClientTransport {
// The GOAWAY is part of graceful shutdown.
frameWriter.goAway(0, ErrorCode.NO_ERROR, new byte[0]);
- onGoAway(Integer.MAX_VALUE, Status.UNAVAILABLE.withDescription("Transport stopped"));
+ startGoAway(Integer.MAX_VALUE, Status.UNAVAILABLE.withDescription("Transport stopped"));
}
/**
@@ -477,8 +482,8 @@ class OkHttpClientTransport implements ClientTransport {
* Finish all active streams due to an IOException, then close the transport.
*/
void onException(Throwable failureCause) {
- log.log(Level.SEVERE, "Transport failed", failureCause);
- onGoAway(0, Status.UNAVAILABLE.withCause(failureCause));
+ log.log(Level.WARNING, "Transport failed", failureCause);
+ startGoAway(0, Status.UNAVAILABLE.withCause(failureCause));
}
/**
@@ -486,13 +491,24 @@ class OkHttpClientTransport implements ClientTransport {
*/
private void onError(ErrorCode errorCode, String moreDetail) {
frameWriter.goAway(0, errorCode, new byte[0]);
- onGoAway(0, toGrpcStatus(errorCode).augmentDescription(moreDetail));
+ startGoAway(0, toGrpcStatus(errorCode).augmentDescription(moreDetail));
}
- private void onGoAway(int lastKnownStreamId, Status status) {
- boolean notifyShutdown;
+ private void startGoAway(int lastKnownStreamId, Status status) {
+ synchronized (lock) {
+ if (startedGoAway) {
+ // Another go-away is in progress, ignore this one.
+ return;
+ }
+ // We use startedGoAway here instead of goAway, because once the goAway becomes true, other
+ // thread in stopIfNecessary() may stop the transport and cause the
+ // listener.transportTerminated() be called before listener.transportShutdown().
+ startedGoAway = true;
+ }
+
+ listener.transportShutdown(status);
+
synchronized (lock) {
- notifyShutdown = !goAway;
goAway = true;
goAwayStatus = status;
Iterator<Map.Entry<Integer, OkHttpClientStream>> it = streams.entrySet().iterator();
@@ -510,12 +526,6 @@ class OkHttpClientTransport implements ClientTransport {
pendingStreams.clear();
}
- if (notifyShutdown) {
- // TODO(madongfly): Another thread may called stopIfNecessary() and closed the socket, so that
- // the reading thread calls listener.transportTerminated() and race with this call.
- listener.transportShutdown(status);
- }
-
stopIfNecessary();
}
@@ -552,7 +562,7 @@ class OkHttpClientTransport implements ClientTransport {
}
/**
- * When the transport is in goAway states, we should stop it once all active streams finish.
+ * When the transport is in goAway state, we should stop it once all active streams finish.
*/
void stopIfNecessary() {
synchronized (lock) {
@@ -624,6 +634,12 @@ class OkHttpClientTransport implements ClientTransport {
// Read until the underlying socket closes.
while (frameReader.nextFrame(this)) {
}
+ // frameReader.nextFrame() returns false when the underlying read encounters an IOException,
+ // it may be triggered by the socket closing, in such case, the startGoAway() will do
+ // nothing, otherwise, we finish all streams since it's a real IO issue.
+ // We don't call onException() here since we don't want to log the warning in case this is
+ // triggered by socket closing.
+ startGoAway(0, Status.UNAVAILABLE);
} catch (Exception t) {
// TODO(madongfly): Send the exception message to the server.
frameWriter.goAway(0, ErrorCode.PROTOCOL_ERROR, new byte[0]);
@@ -770,7 +786,7 @@ class OkHttpClientTransport implements ClientTransport {
// If a debug message was provided, use it.
status.augmentDescription(debugData.utf8());
}
- onGoAway(lastGoodStreamId, status);
+ startGoAway(lastGoodStreamId, status);
}
@Override
diff --git a/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java b/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
index fbb19c684..ada890f68 100644
--- a/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
+++ b/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
@@ -234,6 +234,19 @@ public class OkHttpClientTransportTest {
shutdownAndVerify();
}
+ @Test
+ public void nextFrameReturnFalse() throws Exception {
+ initTransport();
+ MockStreamListener listener = new MockStreamListener();
+ clientTransport.newStream(method, new Metadata(), listener).request(1);
+ frameReader.nextFrameAtEndOfStream();
+ listener.waitUntilStreamClosed();
+ assertEquals(Status.UNAVAILABLE.getCode(), listener.status.getCode());
+ verify(transportListener, timeout(TIME_OUT_MS)).transportShutdown(isA(Status.class));
+ verify(transportListener, timeout(TIME_OUT_MS)).transportTerminated();
+ shutdownAndVerify();
+ }
+
@Test
public void readMessages() throws Exception {
initTransport(); | ['core/src/main/java/io/grpc/internal/ClientTransport.java', 'okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java', 'okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 1,873,238 | 393,629 | 53,916 | 241 | 3,020 | 657 | 52 | 2 | 1,418 | 109 | 427 | 15 | 0 | 1 | 2015-10-09T06:22:51 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,414 | grpc/grpc-java/692/687 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/687 | https://github.com/grpc/grpc-java/pull/692 | https://github.com/grpc/grpc-java/pull/692 | 1 | fixes | Fix UNKNOWN status without description | https://github.com/grpc/grpc-java/blob/d2b1b37ed7ba0087fd8a2920549118191ce22f95/core/src/main/java/io/grpc/ChannelImpl.java#L311
https://github.com/grpc/grpc-java/blob/3e26b993ce90901b32faa1b8b855abfdc2153bc6/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java#L212
We should basically always provide a description, so that users have a hope of distinguishing whether an error is local or remote. The NettyClientHandler should be converting the HTTP/2 error code to a status.
| 384a80593d42cf3a4045e21b6a61fa601a81bbb1 | 248f575a59ec39be9e30f0b21984bea07dc8e775 | https://github.com/grpc/grpc-java/compare/384a80593d42cf3a4045e21b6a61fa601a81bbb1...248f575a59ec39be9e30f0b21984bea07dc8e775 | diff --git a/core/src/main/java/io/grpc/ChannelImpl.java b/core/src/main/java/io/grpc/ChannelImpl.java
index 4e4acebb7..c50950d1a 100644
--- a/core/src/main/java/io/grpc/ChannelImpl.java
+++ b/core/src/main/java/io/grpc/ChannelImpl.java
@@ -308,7 +308,7 @@ public final class ChannelImpl extends Channel {
activeTransport = null;
}
// TODO(notcarl): replace this with something more meaningful
- transportShutdown(Status.UNKNOWN);
+ transportShutdown(Status.UNKNOWN.withDescription("transport shutdown for unknown reason"));
transports.remove(transport);
if (shutdown && transports.isEmpty()) {
if (terminated) {
diff --git a/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java b/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java
index 7e73a392d..1f169179d 100644
--- a/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java
+++ b/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java
@@ -205,11 +205,10 @@ class NettyClientHandler extends Http2ConnectionHandler {
/**
* Handler for an inbound HTTP/2 RST_STREAM frame, terminating a stream.
*/
- private void onRstStreamRead(int streamId)
- throws Http2Exception {
- // TODO(nmittler): do something with errorCode?
+ private void onRstStreamRead(int streamId, long errorCode) throws Http2Exception {
NettyClientStream stream = clientStream(requireHttp2Stream(streamId));
- stream.transportReportStatus(Status.UNKNOWN, false, new Metadata.Trailers());
+ Status status = HttpUtil.Http2Error.statusForCode((int) errorCode);
+ stream.transportReportStatus(status, false, new Metadata.Trailers());
}
@Override
@@ -524,7 +523,7 @@ class NettyClientHandler extends Http2ConnectionHandler {
@Override
public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode)
throws Http2Exception {
- handler.onRstStreamRead(streamId);
+ handler.onRstStreamRead(streamId, errorCode);
}
@Override public void onPingAckRead(ChannelHandlerContext ctx, ByteBuf data) | ['core/src/main/java/io/grpc/ChannelImpl.java', 'netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,690,743 | 355,500 | 49,039 | 211 | 685 | 140 | 11 | 2 | 493 | 36 | 140 | 5 | 2 | 0 | 2015-08-03T18:23:21 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,408 | grpc/grpc-java/1027/694 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/694 | https://github.com/grpc/grpc-java/pull/1027 | https://github.com/grpc/grpc-java/pull/1027 | 1 | fixes | Double-closure of call during interop tests | I find it in the stderr of the test report of Netty, Netty local channel, and OkHttp. I see it printed out to my console once, so I think that may be from the InProcess test.
This exception very likely means we have a bug and are double-closing.
```
java.lang.IllegalStateException: call already closed
at com.google.common.base.Preconditions.checkState(Preconditions.java:173)
at io.grpc.ServerImpl$ServerCallImpl.close(ServerImpl.java:507)
at io.grpc.ForwardingServerCall.close(ForwardingServerCall.java:65)
at io.grpc.testing.TestUtils$1$1.close(TestUtils.java:109)
at io.grpc.stub.ServerCalls$ResponseObserver.onError(ServerCalls.java:237)
at io.grpc.testing.integration.TestServiceImpl$ResponseDispatcher.dispatchChunk(TestServiceImpl.java:277)
at io.grpc.testing.integration.TestServiceImpl$ResponseDispatcher.access$000(TestServiceImpl.java:207)
at io.grpc.testing.integration.TestServiceImpl$ResponseDispatcher$1.run(TestServiceImpl.java:219)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
```
| efa774b846ac493886509cd51f71db4554e92993 | 47ad6f81bfee08aefec15f6b42bef9e0d2c66863 | https://github.com/grpc/grpc-java/compare/efa774b846ac493886509cd51f71db4554e92993...47ad6f81bfee08aefec15f6b42bef9e0d2c66863 | diff --git a/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceImpl.java b/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceImpl.java
index b3de8b624..d73aee095 100644
--- a/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceImpl.java
+++ b/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceImpl.java
@@ -35,6 +35,7 @@ import com.google.common.collect.Queues;
import com.google.protobuf.ByteString;
import com.google.protobuf.EmptyProtos;
+import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.integration.Messages.PayloadType;
import io.grpc.testing.integration.Messages.ResponseParameters;
@@ -205,10 +206,11 @@ public class TestServiceImpl implements TestServiceGrpc.TestService {
* available, the stream is half-closed.
*/
private class ResponseDispatcher {
+ private final Chunk completionChunk = new Chunk(0, 0, 0, false);
private final Queue<Chunk> chunks;
private final StreamObserver<StreamingOutputCallResponse> responseStream;
- private volatile boolean isInputComplete;
private boolean scheduled;
+ private Throwable failure;
private Runnable dispatchTask = new Runnable() {
@Override
public void run() {
@@ -247,6 +249,7 @@ public class TestServiceImpl implements TestServiceGrpc.TestService {
* needed.
*/
public synchronized ResponseDispatcher enqueue(Queue<Chunk> moreChunks) {
+ assertNotFailed();
chunks.addAll(moreChunks);
scheduleNextChunk();
return this;
@@ -257,7 +260,8 @@ public class TestServiceImpl implements TestServiceGrpc.TestService {
* remain to be scheduled for dispatch to the client.
*/
public ResponseDispatcher completeInput() {
- isInputComplete = true;
+ assertNotFailed();
+ chunks.add(completionChunk);
scheduleNextChunk();
return this;
}
@@ -266,15 +270,24 @@ public class TestServiceImpl implements TestServiceGrpc.TestService {
* Dispatches the current response chunk to the client. This is only called by the executor. At
* any time, a given dispatch task should only be registered with the executor once.
*/
- private void dispatchChunk() {
+ private synchronized void dispatchChunk() {
try {
-
// Pop off the next chunk and send it to the client.
Chunk chunk = chunks.remove();
- responseStream.onNext(chunk.toResponse());
-
+ if (chunk == completionChunk) {
+ responseStream.onCompleted();
+ } else {
+ responseStream.onNext(chunk.toResponse());
+ }
} catch (Throwable e) {
- responseStream.onError(e);
+ failure = e;
+ if (Status.fromThrowable(e).getCode() == Status.CANCELLED.getCode()) {
+ // Stream was cancelled by client, responseStream.onError() might be called already or
+ // will be called soon by inbounding StreamObserver.
+ chunks.clear();
+ } else {
+ responseStream.onError(e);
+ }
}
}
@@ -297,14 +310,12 @@ public class TestServiceImpl implements TestServiceGrpc.TestService {
return;
}
}
+ }
- if (isInputComplete) {
- // All of the response chunks have been enqueued but there is no chunks left. Close the
- // stream.
- responseStream.onCompleted();
+ private void assertNotFailed() {
+ if (failure != null) {
+ throw new IllegalStateException("Stream already failed", failure);
}
-
- // Otherwise, the input is not yet complete - wait for more chunks to arrive.
}
}
diff --git a/stub/src/main/java/io/grpc/stub/ServerCalls.java b/stub/src/main/java/io/grpc/stub/ServerCalls.java
index 9cf44508a..dc2a46044 100644
--- a/stub/src/main/java/io/grpc/stub/ServerCalls.java
+++ b/stub/src/main/java/io/grpc/stub/ServerCalls.java
@@ -202,10 +202,10 @@ public class ServerCalls {
@Override
public void onCancel() {
+ responseObserver.cancelled = true;
if (!halfClosed) {
requestObserver.onError(Status.CANCELLED.asException());
}
- responseObserver.cancelled = true;
}
};
} | ['interop-testing/src/main/java/io/grpc/testing/integration/TestServiceImpl.java', 'stub/src/main/java/io/grpc/stub/ServerCalls.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,869,737 | 392,608 | 53,814 | 241 | 1,510 | 291 | 39 | 2 | 1,594 | 84 | 347 | 23 | 0 | 1 | 2015-09-15T23:42:04 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,420 | grpc/grpc-java/247/246 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/246 | https://github.com/grpc/grpc-java/pull/247 | https://github.com/grpc/grpc-java/pull/247 | 1 | resolves | ClientAuthInterceptor synchronizes on wrong object | The "this" in synchronized (this), is not the correct object to synchronize on:
https://github.com/grpc/grpc-java/blob/master/auth/src/main/java/io/grpc/auth/ClientAuthInterceptor.java#L77
It should be ClientAuthInterceptor.this instead. As the code stands, there is no synchronization between threads so you can see NullPointerExceptions as lastMetadata is set but not cached.
| e515c772cd81cc4ee1b6f24c1c36afbaac1c2ebb | b48b4db3fb3577ed21da8f05e3c0428a991e3eed | https://github.com/grpc/grpc-java/compare/e515c772cd81cc4ee1b6f24c1c36afbaac1c2ebb...b48b4db3fb3577ed21da8f05e3c0428a991e3eed | diff --git a/auth/src/main/java/io/grpc/auth/ClientAuthInterceptor.java b/auth/src/main/java/io/grpc/auth/ClientAuthInterceptor.java
index 17c3aaec5..3351aa715 100644
--- a/auth/src/main/java/io/grpc/auth/ClientAuthInterceptor.java
+++ b/auth/src/main/java/io/grpc/auth/ClientAuthInterceptor.java
@@ -74,7 +74,8 @@ public class ClientAuthInterceptor implements ClientInterceptor {
@Override
public void start(Listener<RespT> responseListener, Metadata.Headers headers) {
try {
- synchronized (this) {
+ Metadata.Headers cachedSaved;
+ synchronized (ClientAuthInterceptor.this) {
// TODO(lryan): This is icky but the current auth library stores the same
// metadata map until the next refresh cycle. This will be fixed once
// https://github.com/google/google-auth-library-java/issues/3
@@ -83,8 +84,9 @@ public class ClientAuthInterceptor implements ClientInterceptor {
lastMetadata = credentials.getRequestMetadata();
cached = toHeaders(lastMetadata);
}
+ cachedSaved = cached;
}
- headers.merge(cached);
+ headers.merge(cachedSaved);
super.start(responseListener, headers);
} catch (IOException ioe) {
responseListener.onClose(Status.fromThrowable(ioe), new Metadata.Trailers());
@@ -105,4 +107,4 @@ public class ClientAuthInterceptor implements ClientInterceptor {
}
return headers;
}
-}
\\ No newline at end of file
+} | ['auth/src/main/java/io/grpc/auth/ClientAuthInterceptor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 681,110 | 142,103 | 18,955 | 109 | 241 | 42 | 8 | 1 | 379 | 41 | 78 | 5 | 1 | 0 | 2015-03-26T14:38:55 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,419 | grpc/grpc-java/249/239 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/239 | https://github.com/grpc/grpc-java/pull/249 | https://github.com/grpc/grpc-java/pull/249 | 1 | resolves | Lacking preconditions for start() in ChannelImpl.CallImpl | For instance, calling request() before start() has been called results in a NullPointerException.
| 191dcd38ac8a5bb3e6ce4238d673200d6ff6f097 | 966e1200986c007666a7a4a74bbcb9c0a28742e9 | https://github.com/grpc/grpc-java/compare/191dcd38ac8a5bb3e6ce4238d673200d6ff6f097...966e1200986c007666a7a4a74bbcb9c0a28742e9 | diff --git a/core/src/main/java/io/grpc/ChannelImpl.java b/core/src/main/java/io/grpc/ChannelImpl.java
index 033de038a..8baf9824f 100644
--- a/core/src/main/java/io/grpc/ChannelImpl.java
+++ b/core/src/main/java/io/grpc/ChannelImpl.java
@@ -265,6 +265,7 @@ public final class ChannelImpl implements Channel {
@Override
public void request(int numMessages) {
+ Preconditions.checkState(stream != null, "Not started");
stream.request(numMessages);
}
| ['core/src/main/java/io/grpc/ChannelImpl.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 681,132 | 142,129 | 18,944 | 109 | 63 | 12 | 1 | 1 | 98 | 13 | 17 | 2 | 0 | 0 | 2015-03-26T18:09:44 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,418 | grpc/grpc-java/250/238 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/238 | https://github.com/grpc/grpc-java/pull/250 | https://github.com/grpc/grpc-java/pull/250 | 1 | resolves | Race in Server handler initialization | When initializing an incoming client connection, [we call startAsync()](https://github.com/grpc/grpc-java/blob/master/netty/src/main/java/io/grpc/transport/netty/NettyServer.java#L84) on the transport, which [registers the handler](https://github.com/grpc/grpc-java/blob/master/netty/src/main/java/io/grpc/transport/netty/NettyServerTransport.java#L108) on a separate thread. This is obviously a race, and it would have probably been fixed if I had finished Service removal in #35.
Symptom:
```
DEBUG i.n.channel.DefaultChannelPipeline - Discarded inbound message SimpleLeakAwareByteBuf(PooledUnsafeDirectByteBuf(ridx: 0, widx: 259, cap: 1024)) that reached at the tail of the pipeline. Please check your pipeline configuration.
```
The quickest fix would be to call awaitRunning() from initChannel(). That reduces the rate new connections can connect, but is probably the most expedient solution, until #35 is finished.
@nmittler, thoughts?
| 966e1200986c007666a7a4a74bbcb9c0a28742e9 | 9bd31daee673adfd3877bb2a6e1635e665231e9e | https://github.com/grpc/grpc-java/compare/966e1200986c007666a7a4a74bbcb9c0a28742e9...9bd31daee673adfd3877bb2a6e1635e665231e9e | diff --git a/netty/src/main/java/io/grpc/transport/netty/NettyServer.java b/netty/src/main/java/io/grpc/transport/netty/NettyServer.java
index a96dce64b..c2c252789 100644
--- a/netty/src/main/java/io/grpc/transport/netty/NettyServer.java
+++ b/netty/src/main/java/io/grpc/transport/netty/NettyServer.java
@@ -81,7 +81,10 @@ public class NettyServer extends AbstractService {
@Override
public void initChannel(Channel ch) throws Exception {
NettyServerTransport transport = new NettyServerTransport(ch, serverListener, sslContext);
- transport.startAsync();
+ // TODO(ejona86): Ideally we wouldn't handle handler registration asyncly and then be forced
+ // to block for completion on another thread. This should be resolved as part of removing
+ // Service from server transport.
+ transport.startAsync().awaitRunning();
// TODO(nmittler): Should we wait for transport shutdown before shutting down server?
}
}; | ['netty/src/main/java/io/grpc/transport/netty/NettyServer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 681,195 | 142,141 | 18,945 | 109 | 324 | 61 | 5 | 1 | 946 | 99 | 221 | 12 | 2 | 1 | 2015-03-26T18:54:14 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,417 | grpc/grpc-java/345/330 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/330 | https://github.com/grpc/grpc-java/pull/345 | https://github.com/grpc/grpc-java/pull/345 | 1 | fixes | OkHttpClientTransport.onGoAway() races with startPendingStreams() | onGoAway has two phases: do things necessary under lock and final cleanup. In the first phase it collects the streams to terminate in the second and sets goAway.
startPendingStreams() does not observe goAway and also creates new streams that should be failed due to the goAway. From an initial look, it seems it would be best to remove failPendingStreams() and simply integrate its two phases into onGoAway()'s two phases; that is, when holding the lock in onGoAway, replace pendingStreams with an empty list, and then when not holding the lock call transportReportStatus
| 986d221eaa70139206e035821e9951f822e01893 | 8a5d927a9a8d61431f7ed7fab97abaff03d23d2c | https://github.com/grpc/grpc-java/compare/986d221eaa70139206e035821e9951f822e01893...8a5d927a9a8d61431f7ed7fab97abaff03d23d2c | diff --git a/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java b/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java
index 0e37a3884..04fd3612e 100644
--- a/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java
+++ b/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java
@@ -279,19 +279,6 @@ public class OkHttpClientTransport implements ClientTransport {
return hasStreamStarted;
}
- private void failPendingStreams(Status status) {
- LinkedList<PendingStream> streams;
- synchronized (lock) {
- streams = pendingStreams;
- pendingStreams = new LinkedList<PendingStream>();
- }
- for (PendingStream stream : streams) {
- stream.clientStream.transportReportStatus(
- status, true, new Metadata.Trailers());
- stream.createdFuture.set(null);
- }
- }
-
@Override
public void start(Listener listener) {
this.listener = Preconditions.checkNotNull(listener, "listener");
@@ -368,6 +355,7 @@ public class OkHttpClientTransport implements ClientTransport {
private void onGoAway(int lastKnownStreamId, Status status) {
boolean notifyShutdown;
ArrayList<OkHttpClientStream> goAwayStreams = new ArrayList<OkHttpClientStream>();
+ List<PendingStream> pendingStreamsCopy;
synchronized (lock) {
notifyShutdown = !goAway;
goAway = true;
@@ -382,6 +370,9 @@ public class OkHttpClientTransport implements ClientTransport {
}
}
}
+
+ pendingStreamsCopy = pendingStreams;
+ pendingStreams = new LinkedList<PendingStream>();
}
if (notifyShutdown) {
@@ -390,7 +381,12 @@ public class OkHttpClientTransport implements ClientTransport {
for (OkHttpClientStream stream : goAwayStreams) {
stream.transportReportStatus(status, false, new Metadata.Trailers());
}
- failPendingStreams(status);
+
+ for (PendingStream stream : pendingStreamsCopy) {
+ stream.clientStream.transportReportStatus(
+ status, true, new Metadata.Trailers());
+ stream.createdFuture.set(null);
+ }
stopIfNecessary();
}
| ['okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 732,947 | 153,475 | 20,388 | 123 | 798 | 156 | 24 | 1 | 573 | 92 | 122 | 4 | 0 | 0 | 2015-04-28T00:02:12 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,415 | grpc/grpc-java/667/583 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/583 | https://github.com/grpc/grpc-java/pull/667 | https://github.com/grpc/grpc-java/pull/667 | 1 | fixes | OkHttp's cancellation is not properly synchronized | [`OkHttpClientStream.sendCancel()` calls `finishStream()`](https://github.com/grpc/grpc-java/blob/master/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientStream.java#L213) from an application thread. But `finishStream()` [calls transportReportStatus() without any lock held](https://github.com/grpc/grpc-java/blob/master/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java#L463). That is not synchronized correctly, as `transportReportStatus()` may only be called from the transport thread (i.e., while `lock` is held).
It seems that all usages of `streams` is done while `lock` is held except for within `finishStream()` and [data()](https://github.com/grpc/grpc-java/blob/master/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java#L570). `data()` can actually race with `finishStream()` and end up sending DATA frames after the RST_STREAM. It seems it would be best to just have `stream` protected by `lock`, because it having its own synchronization isn't providing much benefit and isn't leading to correct code.
| 1ac64bd09ddcec60829d5291c4db4147aeb2328a | 750f6265e21ffb83a0ee46d2120af92b30785b30 | https://github.com/grpc/grpc-java/compare/1ac64bd09ddcec60829d5291c4db4147aeb2328a...750f6265e21ffb83a0ee46d2120af92b30785b30 | diff --git a/okhttp/src/main/java/io/grpc/transport/okhttp/AsyncFrameWriter.java b/okhttp/src/main/java/io/grpc/transport/okhttp/AsyncFrameWriter.java
index bbc6e79ca..8615e489b 100644
--- a/okhttp/src/main/java/io/grpc/transport/okhttp/AsyncFrameWriter.java
+++ b/okhttp/src/main/java/io/grpc/transport/okhttp/AsyncFrameWriter.java
@@ -32,7 +32,6 @@
package io.grpc.transport.okhttp;
import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.SettableFuture;
import com.squareup.okhttp.internal.spdy.ErrorCode;
import com.squareup.okhttp.internal.spdy.FrameWriter;
@@ -44,11 +43,15 @@ import io.grpc.SerializingExecutor;
import okio.Buffer;
import java.io.IOException;
+import java.net.Socket;
import java.util.List;
-import java.util.concurrent.ExecutionException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
class AsyncFrameWriter implements FrameWriter {
+ private static final Logger log = Logger.getLogger(OkHttpClientTransport.class.getName());
private FrameWriter frameWriter;
+ private Socket socket;
// Although writes are thread-safe, we serialize them to prevent consuming many Threads that are
// just waiting on each other.
private final SerializingExecutor executor;
@@ -60,12 +63,16 @@ class AsyncFrameWriter implements FrameWriter {
}
/**
- * Set the real frameWriter, should only be called by thread of executor.
+ * Set the real frameWriter and the corresponding underlying socket, the socket is needed for
+ * closing.
+ *
+ * <p>should only be called by thread of executor.
*/
- void setFrameWriter(FrameWriter frameWriter) {
+ void becomeConnected(FrameWriter frameWriter, Socket socket) {
Preconditions.checkState(this.frameWriter == null,
"AsyncFrameWriter's setFrameWriter() should only be called once.");
- this.frameWriter = frameWriter;
+ this.frameWriter = Preconditions.checkNotNull(frameWriter);
+ this.socket = Preconditions.checkNotNull(socket);
}
@Override
@@ -207,30 +214,19 @@ class AsyncFrameWriter implements FrameWriter {
@Override
public void close() {
- // Wait for the frameWriter to close.
- final SettableFuture<?> closeFuture = SettableFuture.create();
executor.execute(new Runnable() {
@Override
public void run() {
- try {
- if (frameWriter != null) {
+ if (frameWriter != null) {
+ try {
frameWriter.close();
+ socket.close();
+ } catch (IOException e) {
+ log.log(Level.WARNING, "Failed closing connection", e);
}
- } catch (IOException e) {
- closeFuture.setException(e);
- } finally {
- closeFuture.set(null);
}
}
});
- try {
- closeFuture.get();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new RuntimeException(e);
- } catch (ExecutionException e) {
- throw new RuntimeException(e);
- }
}
private abstract class WriteRunnable implements Runnable {
diff --git a/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientStream.java b/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientStream.java
index 0f92bad3c..fa042944d 100644
--- a/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientStream.java
+++ b/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientStream.java
@@ -37,7 +37,6 @@ import static com.google.common.base.Preconditions.checkState;
import com.squareup.okhttp.internal.spdy.ErrorCode;
import com.squareup.okhttp.internal.spdy.Header;
-import io.grpc.Metadata;
import io.grpc.MethodDescriptor.MethodType;
import io.grpc.Status;
import io.grpc.transport.ClientStreamListener;
@@ -69,8 +68,8 @@ class OkHttpClientStream extends Http2ClientStream {
AsyncFrameWriter frameWriter,
OkHttpClientTransport transport,
OutboundFlowController outboundFlow,
- MethodType type) {
- return new OkHttpClientStream(listener, frameWriter, transport, outboundFlow, type);
+ MethodType type, Object lock) {
+ return new OkHttpClientStream(listener, frameWriter, transport, outboundFlow, type, lock);
}
@GuardedBy("lock")
@@ -80,7 +79,7 @@ class OkHttpClientStream extends Http2ClientStream {
private final AsyncFrameWriter frameWriter;
private final OutboundFlowController outboundFlow;
private final OkHttpClientTransport transport;
- private final Object lock = new Object();
+ private final Object lock;
private Object outboundFlowState;
private volatile Integer id;
@@ -88,12 +87,14 @@ class OkHttpClientStream extends Http2ClientStream {
AsyncFrameWriter frameWriter,
OkHttpClientTransport transport,
OutboundFlowController outboundFlow,
- MethodType type) {
+ MethodType type,
+ Object lock) {
super(new OkHttpWritableBufferAllocator(), listener);
this.frameWriter = frameWriter;
this.transport = transport;
this.outboundFlow = outboundFlow;
this.type = type;
+ this.lock = lock;
}
/**
@@ -139,33 +140,30 @@ class OkHttpClientStream extends Http2ClientStream {
onSentBytes(numBytes);
}
+ /**
+ * Must be called with holding the transport lock.
+ */
public void transportHeadersReceived(List<Header> headers, boolean endOfStream) {
- synchronized (lock) {
- if (endOfStream) {
- transportTrailersReceived(Utils.convertTrailers(headers));
- } else {
- transportHeadersReceived(Utils.convertHeaders(headers));
- }
+ if (endOfStream) {
+ transportTrailersReceived(Utils.convertTrailers(headers));
+ } else {
+ transportHeadersReceived(Utils.convertHeaders(headers));
}
}
/**
- * We synchronized on "lock" for delivering frames and updating window size, because
- * the {@link #request(int)} call can be called in other thread for delivering frames.
+ * Must be called with holding the transport lock.
*/
public void transportDataReceived(okio.Buffer frame, boolean endOfStream) {
- synchronized (lock) {
- long length = frame.size();
- window -= length;
- if (window < 0) {
- frameWriter.rstStream(id(), ErrorCode.FLOW_CONTROL_ERROR);
- Status status = Status.INTERNAL.withDescription(
- "Received data size exceeded our receiving window size");
- transport.finishStream(id(), status, null);
- return;
- }
- super.transportDataReceived(new OkHttpReadableBuffer(frame), endOfStream);
+ long length = frame.size();
+ window -= length;
+ if (window < 0) {
+ frameWriter.rstStream(id(), ErrorCode.FLOW_CONTROL_ERROR);
+ transport.finishStream(id(), Status.INTERNAL.withDescription(
+ "Received data size exceeded our receiving window size"), null);
+ return;
}
+ super.transportDataReceived(new OkHttpReadableBuffer(frame), endOfStream);
}
@Override
@@ -199,14 +197,6 @@ class OkHttpClientStream extends Http2ClientStream {
}
}
- @Override
- public void transportReportStatus(Status newStatus, boolean stopDelivery,
- Metadata.Trailers trailers) {
- synchronized (lock) {
- super.transportReportStatus(newStatus, stopDelivery, trailers);
- }
- }
-
@Override
protected void sendCancel(Status reason) {
transport.finishStream(id(), reason, ErrorCode.CANCEL);
diff --git a/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java b/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java
index c62927156..c4ed67932 100644
--- a/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java
+++ b/okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java
@@ -70,7 +70,6 @@ import okio.Okio;
import java.io.IOException;
import java.net.Socket;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
@@ -93,6 +92,7 @@ import javax.net.ssl.SSLSocketFactory;
class OkHttpClientTransport implements ClientTransport {
private static final Map<ErrorCode, Status> ERROR_CODE_TO_STATUS;
private static final Logger log = Logger.getLogger(OkHttpClientTransport.class.getName());
+ private static final OkHttpClientStream[] EMPTY_STREAM_ARRAY = new OkHttpClientStream[0];
static {
Map<ErrorCode, Status> errorToStatus = new HashMap<ErrorCode, Status>();
@@ -138,8 +138,9 @@ class OkHttpClientTransport implements ClientTransport {
private final Object lock = new Object();
@GuardedBy("lock")
private int nextStreamId;
+ @GuardedBy("lock")
private final Map<Integer, OkHttpClientStream> streams =
- Collections.synchronizedMap(new HashMap<Integer, OkHttpClientStream>());
+ new HashMap<Integer, OkHttpClientStream>();
private final Executor executor;
// Wrap on executor, to guarantee some operations be executed serially.
private final SerializingExecutor serializingExecutor;
@@ -245,8 +246,8 @@ class OkHttpClientTransport implements ClientTransport {
Preconditions.checkNotNull(headers, "headers");
Preconditions.checkNotNull(listener, "listener");
- OkHttpClientStream clientStream =
- OkHttpClientStream.newStream(listener, frameWriter, this, outboundFlow, method.getType());
+ OkHttpClientStream clientStream = OkHttpClientStream.newStream(
+ listener, frameWriter, this, outboundFlow, method.getType(), lock);
String defaultPath = "/" + method.getFullMethodName();
List<Header> requestHeaders =
@@ -332,7 +333,7 @@ class OkHttpClientTransport implements ClientTransport {
clientFrameHandler = new ClientFrameHandler(testFrameReader);
executor.execute(clientFrameHandler);
connectedCallback.run();
- frameWriter.setFrameWriter(testFrameWriter);
+ frameWriter.becomeConnected(testFrameWriter, socket);
return;
}
BufferedSource source;
@@ -369,7 +370,7 @@ class OkHttpClientTransport implements ClientTransport {
Variant variant = new Http2();
rawFrameWriter = variant.newWriter(sink, true);
- frameWriter.setFrameWriter(rawFrameWriter);
+ frameWriter.becomeConnected(rawFrameWriter, socket);
try {
// Do these with the raw FrameWriter, so that they will be done in this thread,
@@ -390,25 +391,35 @@ class OkHttpClientTransport implements ClientTransport {
@Override
public void shutdown() {
- boolean normalClose;
synchronized (lock) {
- normalClose = !goAway;
+ if (goAway) {
+ return;
+ }
}
- if (normalClose) {
- // Send GOAWAY with lastGoodStreamId of 0, since we don't expect any server-initiated streams.
- // The GOAWAY is part of graceful shutdown.
- frameWriter.goAway(0, ErrorCode.NO_ERROR, new byte[0]);
- onGoAway(Integer.MAX_VALUE, Status.UNAVAILABLE.withDescription("Transport stopped"));
+ // Send GOAWAY with lastGoodStreamId of 0, since we don't expect any server-initiated streams.
+ // The GOAWAY is part of graceful shutdown.
+ frameWriter.goAway(0, ErrorCode.NO_ERROR, new byte[0]);
+
+ onGoAway(Integer.MAX_VALUE, Status.UNAVAILABLE.withDescription("Transport stopped"));
+ }
+
+ /**
+ * Gets all active streams as an array.
+ */
+ OkHttpClientStream[] getActiveStreams() {
+ synchronized (lock) {
+ return streams.values().toArray(EMPTY_STREAM_ARRAY);
}
- stopIfNecessary();
}
+
@VisibleForTesting
ClientFrameHandler getHandler() {
return clientFrameHandler;
}
+ @VisibleForTesting
Map<Integer, OkHttpClientStream> getStreams() {
return streams;
}
@@ -438,37 +449,32 @@ class OkHttpClientTransport implements ClientTransport {
private void onGoAway(int lastKnownStreamId, Status status) {
boolean notifyShutdown;
- ArrayList<OkHttpClientStream> goAwayStreams = new ArrayList<OkHttpClientStream>();
- List<PendingStream> pendingStreamsCopy;
synchronized (lock) {
notifyShutdown = !goAway;
goAway = true;
goAwayStatus = status;
- synchronized (streams) {
- Iterator<Map.Entry<Integer, OkHttpClientStream>> it = streams.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<Integer, OkHttpClientStream> entry = it.next();
- if (entry.getKey() > lastKnownStreamId) {
- goAwayStreams.add(entry.getValue());
- it.remove();
- }
+ Iterator<Map.Entry<Integer, OkHttpClientStream>> it = streams.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry<Integer, OkHttpClientStream> entry = it.next();
+ if (entry.getKey() > lastKnownStreamId) {
+ it.remove();
+ entry.getValue().transportReportStatus(status, false, new Metadata.Trailers());
}
}
- pendingStreamsCopy = pendingStreams;
- pendingStreams = new LinkedList<PendingStream>();
+
+ for (PendingStream stream : pendingStreams) {
+ stream.clientStream.transportReportStatus(status, true, new Metadata.Trailers());
+ stream.createdFuture.set(null);
+ }
+ pendingStreams.clear();
}
if (notifyShutdown) {
+ // TODO(madongfly): Another thread may called stopIfNecessary() and closed the socket, so that
+ // the reading thread calls listener.transportTerminated() and race with this call.
listener.transportShutdown();
}
- for (OkHttpClientStream stream : goAwayStreams) {
- stream.transportReportStatus(status, false, new Metadata.Trailers());
- }
- for (PendingStream stream : pendingStreamsCopy) {
- stream.clientStream.transportReportStatus(
- status, true, new Metadata.Trailers());
- stream.createdFuture.set(null);
- }
+
stopIfNecessary();
}
@@ -486,19 +492,20 @@ class OkHttpClientTransport implements ClientTransport {
* @param errorCode reset the stream with this ErrorCode if not null.
*/
void finishStream(int streamId, @Nullable Status status, @Nullable ErrorCode errorCode) {
- OkHttpClientStream stream;
- stream = streams.remove(streamId);
- if (stream != null) {
- if (errorCode != null) {
- frameWriter.rstStream(streamId, ErrorCode.CANCEL);
- }
- if (status != null) {
- boolean isCancelled = (status.getCode() == Code.CANCELLED
- || status.getCode() == Code.DEADLINE_EXCEEDED);
- stream.transportReportStatus(status, isCancelled, new Metadata.Trailers());
- }
- if (!startPendingStreams()) {
- stopIfNecessary();
+ synchronized (lock) {
+ OkHttpClientStream stream = streams.remove(streamId);
+ if (stream != null) {
+ if (errorCode != null) {
+ frameWriter.rstStream(streamId, ErrorCode.CANCEL);
+ }
+ if (status != null) {
+ boolean isCancelled = (status.getCode() == Code.CANCELLED
+ || status.getCode() == Code.DEADLINE_EXCEEDED);
+ stream.transportReportStatus(status, isCancelled, new Metadata.Trailers());
+ }
+ if (!startPendingStreams()) {
+ stopIfNecessary();
+ }
}
}
}
@@ -507,39 +514,21 @@ class OkHttpClientTransport implements ClientTransport {
* When the transport is in goAway states, we should stop it once all active streams finish.
*/
void stopIfNecessary() {
- boolean shouldStop;
- Http2Ping outstandingPing = null;
- boolean socketConnected;
synchronized (lock) {
- shouldStop = (goAway && streams.size() == 0);
- if (shouldStop) {
- if (stopped) {
- // We've already stopped, don't stop again.
- shouldStop = false;
- } else {
+ if (goAway && streams.size() == 0) {
+ if (!stopped) {
stopped = true;
- outstandingPing = ping;
- ping = null;
- }
- }
- socketConnected = socket != null;
- }
- if (shouldStop) {
- // Wait for the frame writer to close.
- frameWriter.close();
- if (socketConnected) {
- // Close the socket to break out the reader thread, which will close the
- // frameReader and notify the listener.
- try {
- socket.close();
- } catch (IOException e) {
- log.log(Level.WARNING, "Failed closing socket", e);
+ // We will close the underlying socket in the writing thread to break out the reader
+ // thread, which will close the frameReader and notify the listener.
+ frameWriter.close();
+
+ if (ping != null) {
+ ping.failed(getPingFailure());
+ ping = null;
+ }
}
}
}
- if (outstandingPing != null) {
- outstandingPing.failed(getPingFailure());
- }
}
private Throwable getPingFailure() {
@@ -558,6 +547,12 @@ class OkHttpClientTransport implements ClientTransport {
}
}
+ OkHttpClientStream getStream(int streamId) {
+ synchronized (lock) {
+ return streams.get(streamId);
+ }
+ }
+
/**
* Returns a Grpc status corresponding to the given ErrorCode.
*/
@@ -607,8 +602,7 @@ class OkHttpClientTransport implements ClientTransport {
@Override
public void data(boolean inFinished, int streamId, BufferedSource in, int length)
throws IOException {
- final OkHttpClientStream stream;
- stream = streams.get(streamId);
+ OkHttpClientStream stream = getStream(streamId);
if (stream == null) {
if (mayHaveCreatedStream(streamId)) {
frameWriter.rstStream(streamId, ErrorCode.INVALID_STREAM);
@@ -622,7 +616,9 @@ class OkHttpClientTransport implements ClientTransport {
Buffer buf = new Buffer();
buf.write(in.buffer(), length);
- stream.transportDataReceived(buf, inFinished);
+ synchronized (lock) {
+ stream.transportDataReceived(buf, inFinished);
+ }
}
// connection window update
@@ -643,18 +639,23 @@ class OkHttpClientTransport implements ClientTransport {
int associatedStreamId,
List<Header> headerBlock,
HeadersMode headersMode) {
- OkHttpClientStream stream;
- stream = streams.get(streamId);
- if (stream == null) {
- if (mayHaveCreatedStream(streamId)) {
- frameWriter.rstStream(streamId, ErrorCode.INVALID_STREAM);
+ boolean unknownStream = false;
+ synchronized (lock) {
+ OkHttpClientStream stream = streams.get(streamId);
+ if (stream == null) {
+ if (mayHaveCreatedStream(streamId)) {
+ frameWriter.rstStream(streamId, ErrorCode.INVALID_STREAM);
+ } else {
+ unknownStream = true;
+ }
} else {
- // We don't expect any server-initiated streams.
- onError(ErrorCode.PROTOCOL_ERROR, "Received header for unknown stream: " + streamId);
+ stream.transportHeadersReceived(headerBlock, inFinished);
}
- return;
}
- stream.transportHeadersReceived(headerBlock, inFinished);
+ if (unknownStream) {
+ // We don't expect any server-initiated streams.
+ onError(ErrorCode.PROTOCOL_ERROR, "Received header for unknown stream: " + streamId);
+ }
}
@Override
@@ -748,7 +749,7 @@ class OkHttpClientTransport implements ClientTransport {
return;
}
- OkHttpClientStream stream = streams.get(streamId);
+ OkHttpClientStream stream = getStream(streamId);
if (stream != null) {
outboundFlow.windowUpdate(stream, (int) delta);
} else if (!mayHaveCreatedStream(streamId)) {
diff --git a/okhttp/src/main/java/io/grpc/transport/okhttp/OutboundFlowController.java b/okhttp/src/main/java/io/grpc/transport/okhttp/OutboundFlowController.java
index ebe062be0..3112c5635 100644
--- a/okhttp/src/main/java/io/grpc/transport/okhttp/OutboundFlowController.java
+++ b/okhttp/src/main/java/io/grpc/transport/okhttp/OutboundFlowController.java
@@ -54,7 +54,6 @@ import javax.annotation.Nullable;
* streams.
*/
class OutboundFlowController {
- private static final OkHttpClientStream[] EMPTY_STREAM_ARRAY = new OkHttpClientStream[0];
private final OkHttpClientTransport transport;
private final FrameWriter frameWriter;
private int initialWindowSize = DEFAULT_WINDOW_SIZE;
@@ -72,7 +71,7 @@ class OutboundFlowController {
int delta = newWindowSize - initialWindowSize;
initialWindowSize = newWindowSize;
- for (OkHttpClientStream stream : getActiveStreams()) {
+ for (OkHttpClientStream stream : transport.getActiveStreams()) {
OutboundFlowState state = (OutboundFlowState) stream.getOutboundFlowState();
if (state == null) {
// Create the OutboundFlowState with the new window size.
@@ -116,7 +115,7 @@ class OutboundFlowController {
throw new IllegalArgumentException("Invalid streamId: " + streamId);
}
- OkHttpClientStream stream = transport.getStreams().get(streamId);
+ OkHttpClientStream stream = transport.getStream(streamId);
if (stream == null) {
// This is possible for a stream that has received end-of-stream from server (but hasn't sent
// end-of-stream), and was removed from the transport stream map.
@@ -173,18 +172,11 @@ class OutboundFlowController {
return state;
}
- /**
- * Gets all active streams as an array.
- */
- private OkHttpClientStream[] getActiveStreams() {
- return transport.getStreams().values().toArray(EMPTY_STREAM_ARRAY);
- }
-
/**
* Writes as much data for all the streams as possible given the current flow control windows.
*/
private void writeStreams() {
- OkHttpClientStream[] streams = getActiveStreams();
+ OkHttpClientStream[] streams = transport.getActiveStreams();
int connectionWindow = connectionState.window();
for (int numStreams = streams.length; numStreams > 0 && connectionWindow > 0;) {
int nextNumStreams = 0;
@@ -210,7 +202,7 @@ class OutboundFlowController {
// Now take one last pass through all of the streams and write any allocated bytes.
WriteStatus writeStatus = new WriteStatus();
- for (OkHttpClientStream stream : getActiveStreams()) {
+ for (OkHttpClientStream stream : transport.getActiveStreams()) {
OutboundFlowState state = state(stream);
state.writeBytes(state.allocatedBytes(), writeStatus);
state.clearAllocatedBytes();
diff --git a/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java b/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java
index cec61987d..58a8b41d3 100644
--- a/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java
+++ b/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java
@@ -195,7 +195,7 @@ public class OkHttpClientTransportTest {
assertEquals("Protocol error\\n" + NETWORK_ISSUE_MESSAGE, listener1.status.getDescription());
assertEquals(Status.INTERNAL.getCode(), listener2.status.getCode());
assertEquals("Protocol error\\n" + NETWORK_ISSUE_MESSAGE, listener2.status.getDescription());
- verify(transportListener).transportShutdown();
+ verify(transportListener, timeout(TIME_OUT_MS)).transportShutdown();
verify(transportListener, timeout(TIME_OUT_MS)).transportTerminated();
}
| ['okhttp/src/main/java/io/grpc/transport/okhttp/OutboundFlowController.java', 'okhttp/src/main/java/io/grpc/transport/okhttp/AsyncFrameWriter.java', 'okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientStream.java', 'okhttp/src/main/java/io/grpc/transport/okhttp/OkHttpClientTransport.java', 'okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 1,687,079 | 354,616 | 48,934 | 211 | 12,204 | 2,434 | 285 | 4 | 1,069 | 98 | 247 | 4 | 3 | 0 | 2015-07-24T18:17:02 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,413 | grpc/grpc-java/787/786 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/786 | https://github.com/grpc/grpc-java/pull/787 | https://github.com/grpc/grpc-java/pull/787 | 1 | fixes | okhttp: pending stream is broken due to stream id check. | `OkHttpClientTransport.mayHaveCreatedStream()` checks the stream id less than the `nextStreamId`, but the `nextStreamId` is not increased yet when the pending stream is being started.
And `OkHttpClientTransport.mayHaveCreatedStream()` is wrong when the stream id greater than Integer.MAX_VALUE - 2.
| b42122b035da900d10f4b9e41017ef98ef62880a | ddea7435c9952e4ee8ecaf8f52bda6733a7bc824 | https://github.com/grpc/grpc-java/compare/b42122b035da900d10f4b9e41017ef98ef62880a...ddea7435c9952e4ee8ecaf8f52bda6733a7bc824 | diff --git a/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java b/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java
index f121f6a30..8c8ef855b 100644
--- a/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java
+++ b/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java
@@ -272,6 +272,9 @@ class OkHttpClientTransport implements ClientTransport {
frameWriter.flush();
}
if (nextStreamId >= Integer.MAX_VALUE - 2) {
+ // Make sure nextStreamId greater than all used id, so that mayHaveCreatedStream() performs
+ // correctly.
+ nextStreamId = Integer.MAX_VALUE;
onGoAway(Integer.MAX_VALUE, Status.INTERNAL.withDescription("Stream ids exhausted"));
} else {
nextStreamId += 2;
diff --git a/okhttp/src/main/java/io/grpc/okhttp/OutboundFlowController.java b/okhttp/src/main/java/io/grpc/okhttp/OutboundFlowController.java
index b686667e0..259a5d75e 100644
--- a/okhttp/src/main/java/io/grpc/okhttp/OutboundFlowController.java
+++ b/okhttp/src/main/java/io/grpc/okhttp/OutboundFlowController.java
@@ -119,9 +119,6 @@ class OutboundFlowController {
*/
void data(boolean outFinished, int streamId, Buffer source, boolean flush) {
Preconditions.checkNotNull(source, "source");
- if (streamId <= 0 || !transport.mayHaveCreatedStream(streamId)) {
- throw new IllegalArgumentException("Invalid streamId: " + streamId);
- }
OkHttpClientStream stream = transport.getStream(streamId);
if (stream == null) {
diff --git a/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java b/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
index 6c8159a71..2a86c28ed 100644
--- a/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
+++ b/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
@@ -603,13 +603,28 @@ public class OkHttpClientTransportTest {
int startId = Integer.MAX_VALUE - 2;
initTransport(startId, new ConnectedCallback(false));
- MockStreamListener listener1 = new MockStreamListener();
- clientTransport.newStream(method, new Metadata.Headers(), listener1);
+ MockStreamListener listener = new MockStreamListener();
+ clientTransport.newStream(method, new Metadata.Headers(), listener).request(1);
+ // New stream should be failed.
assertNewStreamFail();
+ // The alive stream should be functional, receives a message.
+ frameHandler().headers(
+ false, false, startId, 0, grpcResponseHeaders(), HeadersMode.HTTP_20_HEADERS);
+ assertNotNull(listener.headers);
+ String message = "hello";
+ Buffer buffer = createMessageFrame(message);
+ frameHandler().data(false, startId, buffer, (int) buffer.size());
+
getStream(startId).cancel(Status.CANCELLED);
- listener1.waitUntilStreamClosed();
+ // Receives the second message after be cancelled.
+ buffer = createMessageFrame(message);
+ frameHandler().data(false, startId, buffer, (int) buffer.size());
+
+ listener.waitUntilStreamClosed();
+ // Should only have the first message delivered.
+ assertEquals(message, listener.messages.get(0));
verify(frameWriter, timeout(TIME_OUT_MS)).rstStream(eq(startId), eq(ErrorCode.CANCEL));
verify(transportListener).transportShutdown(isA(Status.class));
verify(transportListener, timeout(TIME_OUT_MS)).transportTerminated();
@@ -627,6 +642,12 @@ public class OkHttpClientTransportTest {
// The second stream should be pending.
OkHttpClientStream stream2 =
clientTransport.newStream(method, new Metadata.Headers(), listener2);
+ String sentMessage = "hello";
+ InputStream input = new ByteArrayInputStream(sentMessage.getBytes(UTF_8));
+ assertEquals(5, input.available());
+ stream2.writeMessage(input);
+ stream2.flush();
+ stream2.halfClose();
waitForStreamPending(1);
assertEquals(1, activeStreamCount());
@@ -635,10 +656,16 @@ public class OkHttpClientTransportTest {
stream1.cancel(Status.CANCELLED);
listener1.waitUntilStreamClosed();
- // The second stream should be active now.
+ // The second stream should be active now, and the pending data should be sent out.
assertEquals(1, activeStreamCount());
assertEquals(0, clientTransport.getPendingStreamSize());
- stream2.cancel(Status.CANCELLED);
+ ArgumentCaptor<Buffer> captor = ArgumentCaptor.forClass(Buffer.class);
+ verify(frameWriter, timeout(TIME_OUT_MS))
+ .data(eq(false), eq(5), captor.capture(), eq(5 + HEADER_LENGTH));
+ Buffer sentFrame = captor.getValue();
+ assertEquals(createMessageFrame(sentMessage), sentFrame);
+ verify(frameWriter, timeout(TIME_OUT_MS)).data(eq(true), eq(5), any(Buffer.class), eq(0));
+ stream2.sendCancel(Status.CANCELLED);
}
@Test | ['okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java', 'okhttp/src/main/java/io/grpc/okhttp/OutboundFlowController.java', 'okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 1,706,074 | 358,903 | 49,497 | 218 | 313 | 71 | 6 | 2 | 300 | 36 | 67 | 4 | 0 | 0 | 2015-08-11T00:01:24 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,412 | grpc/grpc-java/889/887 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/887 | https://github.com/grpc/grpc-java/pull/889 | https://github.com/grpc/grpc-java/pull/889 | 1 | fixes | OkHttp: race between sendCancel and sendFrame. | If sendCancel is called (by timeout for example) before the stream is started, a following sendFrame will cause a NPE:
```
java.lang.NullPointerException
at io.grpc.okhttp.OkHttpClientStream.sendFrame(OkHttpClientStream.java:197)
at io.grpc.internal.AbstractClientStream.internalSendFrame(AbstractClientStream.java:199)
at io.grpc.internal.AbstractStream$2.deliverFrame(AbstractStream.java:128)
at io.grpc.internal.MessageFramer.commitToSink(MessageFramer.java:297)
at io.grpc.internal.MessageFramer.flush(MessageFramer.java:255)
at io.grpc.internal.AbstractStream.flush(AbstractStream.java:178)
at io.grpc.ClientCallImpl.sendMessage(ClientCallImpl.java:213)
at io.grpc.stub.ClientCalls$CallToStreamObserverAdapter.onNext(ClientCalls.java:210)
at io.grpc.testing.integration.AbstractTransportTest.timeoutOnSleepingServer(AbstractTransportTest.java:843)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.FailOnTimeout$StatementThread.run(FailOnTimeout.java:74)
```
| 080190c753a484559b5aace35561626c73d5fe8b | a3f2f6249e5fd7d809b780f8e160796c469dc045 | https://github.com/grpc/grpc-java/compare/080190c753a484559b5aace35561626c73d5fe8b...a3f2f6249e5fd7d809b780f8e160796c469dc045 | diff --git a/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientStream.java b/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientStream.java
index ffa4b316b..9a299b595 100644
--- a/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientStream.java
+++ b/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientStream.java
@@ -190,11 +190,14 @@ class OkHttpClientStream extends Http2ClientStream {
}
synchronized (lock) {
+ if (cancelSent) {
+ return;
+ }
if (pendingData != null) {
// Stream is pending start, queue the data.
pendingData.add(new PendingData(buffer, endOfStream, flush));
} else {
- checkState(id() != 0, "streamId should be set");
+ checkState(id() != null, "streamId should be set");
// If buffer > frameWriter.maxDataLength() the flow-controller will ensure that it is
// properly chunked.
outboundFlow.data(endOfStream, id(), buffer, flush);
diff --git a/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java b/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
index cf81e9cce..997d4adf6 100644
--- a/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
+++ b/okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java
@@ -197,7 +197,7 @@ public class OkHttpClientTransportTest {
startTransport(3, null, true, 1);
MockStreamListener listener = new MockStreamListener();
- clientTransport.newStream(method, new Metadata.Headers(), listener).request(1);
+ clientTransport.newStream(method, new Metadata(), listener).request(1);
assertContainStream(3);
frameHandler().headers(false, false, 3, 0, grpcResponseHeaders(), HeadersMode.HTTP_20_HEADERS);
assertNotNull(listener.headers); | ['okhttp/src/main/java/io/grpc/okhttp/OkHttpClientStream.java', 'okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,783,012 | 374,873 | 51,546 | 226 | 169 | 43 | 5 | 1 | 1,659 | 60 | 362 | 24 | 0 | 1 | 2015-08-27T21:36:22 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,411 | grpc/grpc-java/948/926 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/926 | https://github.com/grpc/grpc-java/pull/948 | https://github.com/grpc/grpc-java/pull/948 | 1 | resolves | NettyServer prematurely releases worker event loop | 777e928 causes flaky server shutdown, as the individual transports out-live the server.
| d42559c6afa666ed7d96a1c324fe09f0d0f8f7ed | 2a3ae36bd3730058d00564bca7e7502f84d099df | https://github.com/grpc/grpc-java/compare/d42559c6afa666ed7d96a1c324fe09f0d0f8f7ed...2a3ae36bd3730058d00564bca7e7502f84d099df | diff --git a/netty/src/main/java/io/grpc/netty/NettyServer.java b/netty/src/main/java/io/grpc/netty/NettyServer.java
index bd083e49e..f1ba4df27 100644
--- a/netty/src/main/java/io/grpc/netty/NettyServer.java
+++ b/netty/src/main/java/io/grpc/netty/NettyServer.java
@@ -48,6 +48,8 @@ import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
+import io.netty.util.AbstractReferenceCounted;
+import io.netty.util.ReferenceCounted;
import java.io.IOException;
import java.net.SocketAddress;
@@ -74,6 +76,7 @@ public class NettyServer implements Server {
private Channel channel;
private final int flowControlWindow;
private final int maxMessageSize;
+ private final ReferenceCounted eventLoopReferenceCounter = new EventLoopReferenceCounter();
NettyServer(SocketAddress address, Class<? extends ServerChannel> channelType,
@Nullable EventLoopGroup bossGroup, @Nullable EventLoopGroup workerGroup,
@@ -108,6 +111,12 @@ public class NettyServer implements Server {
b.childHandler(new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel ch) throws Exception {
+ eventLoopReferenceCounter.retain();
+ ch.closeFuture().addListener(new ChannelFutureListener() {
+ public void operationComplete(ChannelFuture future) {
+ eventLoopReferenceCounter.release();
+ }
+ });
NettyServerTransport transport
= new NettyServerTransport(ch, sslContext, maxStreamsPerConnection, flowControlWindow,
maxMessageSize);
@@ -142,7 +151,7 @@ public class NettyServer implements Server {
log.log(Level.WARNING, "Error shutting down server", future.cause());
}
listener.serverShutdown();
- releaseSharedGroups();
+ eventLoopReferenceCounter.release();
}
});
}
@@ -156,20 +165,28 @@ public class NettyServer implements Server {
}
}
- private void releaseSharedGroups() {
- try {
- if (usingSharedBossGroup && bossGroup != null) {
- SharedResourceHolder.release(Utils.DEFAULT_BOSS_EVENT_LOOP_GROUP, bossGroup);
- }
- } finally {
- bossGroup = null;
+ class EventLoopReferenceCounter extends AbstractReferenceCounted {
+ @Override
+ protected void deallocate() {
try {
- if (usingSharedWorkerGroup && workerGroup != null) {
- SharedResourceHolder.release(Utils.DEFAULT_WORKER_EVENT_LOOP_GROUP, workerGroup);
+ if (usingSharedBossGroup && bossGroup != null) {
+ SharedResourceHolder.release(Utils.DEFAULT_BOSS_EVENT_LOOP_GROUP, bossGroup);
}
} finally {
- workerGroup = null;
+ bossGroup = null;
+ try {
+ if (usingSharedWorkerGroup && workerGroup != null) {
+ SharedResourceHolder.release(Utils.DEFAULT_WORKER_EVENT_LOOP_GROUP, workerGroup);
+ }
+ } finally {
+ workerGroup = null;
+ }
}
}
+
+ @Override
+ public ReferenceCounted touch(Object hint) {
+ return this;
+ }
}
} | ['netty/src/main/java/io/grpc/netty/NettyServer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,823,182 | 382,647 | 52,583 | 233 | 1,581 | 302 | 39 | 1 | 88 | 12 | 18 | 2 | 0 | 0 | 2015-09-03T22:55:24 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,410 | grpc/grpc-java/1018/1017 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1017 | https://github.com/grpc/grpc-java/pull/1018 | https://github.com/grpc/grpc-java/pull/1018 | 1 | fixes | The run-test-server.sh exits immediately | After changing to using daemon threads by default, this script stopped working. We need to update the server to keep alive until cancelled (e.g. ctrl+c).
| abe5b8e5516042d8a5265f8502bfc10a13ac5639 | 49bb24c25f0225af92ab55086f3004d5838118da | https://github.com/grpc/grpc-java/compare/abe5b8e5516042d8a5265f8502bfc10a13ac5639...49bb24c25f0225af92ab55086f3004d5838118da | diff --git a/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceServer.java b/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceServer.java
index 07ebefec6..f994c2cd5 100644
--- a/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceServer.java
+++ b/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceServer.java
@@ -74,6 +74,7 @@ public class TestServiceServer {
});
server.start();
System.out.println("Server started on port " + server.port);
+ server.blockUntilShutdown();
}
private int port = 8080;
@@ -152,4 +153,13 @@ public class TestServiceServer {
}
MoreExecutors.shutdownAndAwaitTermination(executor, 5, TimeUnit.SECONDS);
}
+
+ /**
+ * Await termination on the main thread since the grpc library uses daemon threads.
+ */
+ private void blockUntilShutdown() throws InterruptedException {
+ if (server != null) {
+ server.awaitTermination();
+ }
+ }
} | ['interop-testing/src/main/java/io/grpc/testing/integration/TestServiceServer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,869,166 | 392,451 | 53,808 | 241 | 276 | 55 | 10 | 1 | 155 | 25 | 33 | 2 | 0 | 0 | 2015-09-11T23:01:53 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,409 | grpc/grpc-java/1023/999 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/999 | https://github.com/grpc/grpc-java/pull/1023 | https://github.com/grpc/grpc-java/pull/1023 | 1 | fixes | Possible race condition ServerImpl between start() and shutdown() | I believe it may be possible if start and stop are called concurrently that the shared executor may not get released. I'm not sure if this is an actual problem, but it does go against the @ ThreadSafe annotation.
| 45c75f2c96456cb7c1cd675c85a1c36ffdc51a9a | 4b27e542e08abe5bccd48ebdc5c4d242fd12f662 | https://github.com/grpc/grpc-java/compare/45c75f2c96456cb7c1cd675c85a1c36ffdc51a9a...4b27e542e08abe5bccd48ebdc5c4d242fd12f662 | diff --git a/core/src/main/java/io/grpc/internal/ServerImpl.java b/core/src/main/java/io/grpc/internal/ServerImpl.java
index 80523832f..e45a6cecb 100644
--- a/core/src/main/java/io/grpc/internal/ServerImpl.java
+++ b/core/src/main/java/io/grpc/internal/ServerImpl.java
@@ -31,6 +31,7 @@
package io.grpc.internal;
+import static com.google.common.base.Preconditions.checkState;
import static io.grpc.internal.GrpcUtil.TIMEOUT_KEY;
import static io.grpc.internal.GrpcUtil.TIMER_SERVICE;
@@ -114,9 +115,8 @@ public final class ServerImpl extends io.grpc.Server {
@Override
public ServerImpl start() throws IOException {
synchronized (lock) {
- if (started) {
- throw new IllegalStateException("Already started");
- }
+ checkState(!started, "Already started");
+ checkState(!shutdown, "Shutting down");
usingSharedExecutor = executor == null;
if (usingSharedExecutor) {
executor = SharedResourceHolder.get(GrpcUtil.SHARED_CHANNEL_EXECUTOR); | ['core/src/main/java/io/grpc/internal/ServerImpl.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,869,290 | 392,501 | 53,802 | 241 | 250 | 48 | 6 | 1 | 214 | 39 | 45 | 2 | 0 | 0 | 2015-09-14T18:39:54 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
36 | jhy/jsoup/292/290 | jhy | jsoup | https://github.com/jhy/jsoup/issues/290 | https://github.com/jhy/jsoup/pull/292 | https://github.com/jhy/jsoup/pull/292 | 1 | fixes | Element.clone() causes StackOverflowError when the element has excessively stacked children | This is similar to the issue I previously opened and was subsequently fixed in 1.7.2.
Excessively stacked elements contained in a parent element, such as a couple hundred `<i>` tags wrapped around some text, cause `Element.clone()` to throw a `StackOverflowError` in `Node.doClone()`
Consider this page: http://m.gamefaqs.com/boards/577800-one-man-and-his-droid/64768563
In that page's source, you can see this:
```
<blockquote><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i><i>censor f***ing bypass</i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></i></blockquote>
```
Now clearly, something like this isn't normal. And it isn't going to happen often. But, while this page is a recreation of the issue, it did occur naturally on a different board (I don't have access to this separate board, hence why it was recreated)
This is on an Android device, where per-app stack allocation might be smaller than on a desktop or laptop.
| 834d3142304e0927dc659791da6a4521f271d7fd | 586c85420990eab5e0f07c324fc26fcdae3af05c | https://github.com/jhy/jsoup/compare/834d3142304e0927dc659791da6a4521f271d7fd...586c85420990eab5e0f07c324fc26fcdae3af05c | diff --git a/src/main/java/org/jsoup/nodes/Node.java b/src/main/java/org/jsoup/nodes/Node.java
index f3411a75..41a13fbf 100644
--- a/src/main/java/org/jsoup/nodes/Node.java
+++ b/src/main/java/org/jsoup/nodes/Node.java
@@ -10,6 +10,7 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.LinkedList;
import java.util.List;
/**
@@ -593,11 +594,32 @@ public abstract class Node implements Cloneable {
*/
@Override
public Node clone() {
- return doClone(null); // splits for orphan
+ Node thisClone = doClone(null); // splits for orphan
+
+ // Queue up nodes that need their children cloned (BFS).
+ LinkedList<Node> nodesToProcess = new LinkedList<Node>();
+ nodesToProcess.add(thisClone);
+
+ while (!nodesToProcess.isEmpty()) {
+ Node currParent = nodesToProcess.remove();
+
+ for (int i = 0; i < currParent.childNodes.size(); i++) {
+ Node childClone = currParent.childNodes.get(i).doClone(currParent);
+ currParent.childNodes.set(i, childClone);
+ nodesToProcess.add(childClone);
+ }
+ }
+
+ return thisClone;
}
+ /*
+ * Return a clone of the node using the given parent (which can be null).
+ * Not a deep copy of children.
+ */
protected Node doClone(Node parent) {
Node clone;
+
try {
clone = (Node) super.clone();
} catch (CloneNotSupportedException e) {
@@ -609,8 +631,9 @@ public abstract class Node implements Cloneable {
clone.attributes = attributes != null ? attributes.clone() : null;
clone.baseUri = baseUri;
clone.childNodes = new ArrayList<Node>(childNodes.size());
+
for (Node child: childNodes)
- clone.childNodes.add(child.doClone(clone)); // clone() creates orphans, doClone() keeps parent
+ clone.childNodes.add(child);
return clone;
}
diff --git a/src/test/java/org/jsoup/nodes/DocumentTest.java b/src/test/java/org/jsoup/nodes/DocumentTest.java
index e5b50d12..fc58b894 100644
--- a/src/test/java/org/jsoup/nodes/DocumentTest.java
+++ b/src/test/java/org/jsoup/nodes/DocumentTest.java
@@ -3,6 +3,7 @@ package org.jsoup.nodes;
import org.jsoup.Jsoup;
import org.jsoup.TextUtil;
import org.junit.Test;
+import org.junit.Ignore;
import static org.junit.Assert.*;
@@ -82,4 +83,16 @@ public class DocumentTest {
TextUtil.stripNewlines(clone.html()));
}
+ // Ignored since this test can take awhile to run.
+ @Ignore
+ @Test public void testOverflowClone() {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < 100000; i++) {
+ builder.insert(0, "<i>");
+ builder.append("</i>");
+ }
+
+ Document doc = Jsoup.parse(builder.toString());
+ doc.clone();
+ }
} | ['src/main/java/org/jsoup/nodes/Node.java', 'src/test/java/org/jsoup/nodes/DocumentTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 489,133 | 100,159 | 14,028 | 53 | 1,028 | 206 | 27 | 1 | 2,932 | 123 | 1,398 | 16 | 1 | 1 | 2013-02-09T03:06:46 | 10,266 | Java | {'Java': 1474668, 'HTML': 316865} | MIT License |
1,437 | netflix/conductor/1973/1960 | netflix | conductor | https://github.com/Netflix/conductor/issues/1960 | https://github.com/Netflix/conductor/pull/1973 | https://github.com/Netflix/conductor/pull/1973 | 1 | fixes | Mismatched parameter naming for IsolationGroup | In IsolatedTaskQueueProducer
```
@VisibleForTesting
void addTaskQueues() {
Set<TaskDef> isolationTaskDefs = getIsolationExecutionNameSpaces();
logger.debug("Retrieved queues {}", isolationTaskDefs);
Set<String> taskTypes = SystemTaskWorkerCoordinator.taskNameWorkflowTaskMapping.keySet();
for (TaskDef isolatedTaskDef : isolationTaskDefs) {
for (String taskType : taskTypes) {
String taskQueue = QueueUtils.getQueueName(taskType, null,
isolatedTaskDef.getExecutionNameSpace(), isolatedTaskDef.getIsolationGroupId());
logger.debug("Adding taskQueue:'{}' to system task worker coordinator", taskQueue);
SystemTaskWorkerCoordinator.queue.add(taskQueue);
}
}
}
```
It gets the name for the isolated task by calling QueueUtils.getQueueName(with the following order
- taskType
- null (domain)
- isolatedTaskDef.getExecutionNameSpace()
- isolatedTaskDef.getIsolationGroupId()
But the signature of QueueUtils.getQueueName is like
```
public static String getQueueName(String taskType, String domain, String isolationGroup, String executionNameSpace) {
...
}
```
The order of `isolationGroup` and `executionNameSpace` is swapped.
I think this might cause bug for IsolatedTask. Since other places are using it like
```
public static String getQueueName(Task task) {
return getQueueName(task.getTaskType(), task.getDomain(), task.getIsolationGroupId(), task.getExecutionNameSpace());
}
```
Since I haven't experimented with IsolatedTasks, sorry I can't provide ways to observe the bug. | 69d996d58657229712ecffaaca780831efda0a54 | 7a19487a7a0f778e116f29fe5a93170d26ba9a0c | https://github.com/netflix/conductor/compare/69d996d58657229712ecffaaca780831efda0a54...7a19487a7a0f778e116f29fe5a93170d26ba9a0c | diff --git a/core/src/main/java/com/netflix/conductor/core/execution/tasks/IsolatedTaskQueueProducer.java b/core/src/main/java/com/netflix/conductor/core/execution/tasks/IsolatedTaskQueueProducer.java
index ce4477c5c..46dab7916 100644
--- a/core/src/main/java/com/netflix/conductor/core/execution/tasks/IsolatedTaskQueueProducer.java
+++ b/core/src/main/java/com/netflix/conductor/core/execution/tasks/IsolatedTaskQueueProducer.java
@@ -79,7 +79,7 @@ public class IsolatedTaskQueueProducer {
for (TaskDef isolatedTaskDef : isolationTaskDefs) {
for (String taskType : taskTypes) {
String taskQueue = QueueUtils.getQueueName(taskType, null,
- isolatedTaskDef.getExecutionNameSpace(), isolatedTaskDef.getIsolationGroupId());
+ isolatedTaskDef.getIsolationGroupId(), isolatedTaskDef.getExecutionNameSpace());
logger.debug("Adding taskQueue:'{}' to system task worker coordinator", taskQueue);
SystemTaskWorkerCoordinator.queue.add(taskQueue);
} | ['core/src/main/java/com/netflix/conductor/core/execution/tasks/IsolatedTaskQueueProducer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,194,648 | 452,740 | 58,618 | 376 | 173 | 36 | 2 | 1 | 1,579 | 149 | 356 | 44 | 0 | 3 | 2020-11-17T00:15:18 | 9,943 | Java | {'Java': 3462518, 'Groovy': 850012, 'JavaScript': 390784, 'Go': 45821, 'Python': 27631, 'TypeScript': 8934, 'Dockerfile': 4469, 'SCSS': 4366, 'HTML': 2524, 'Shell': 2374, 'PLpgSQL': 1962, 'CSS': 1347, 'Makefile': 253} | Apache License 2.0 |
1,438 | netflix/conductor/943/856 | netflix | conductor | https://github.com/Netflix/conductor/issues/856 | https://github.com/Netflix/conductor/pull/943 | https://github.com/Netflix/conductor/pull/943 | 1 | fix | NullPointerException when starting up (using dynomite) | Using conductor version 2.1.0 (downloaded from https://bintray.com/netflixoss/maven/conductor/2.1.0)
Configuration is as follows (all IPs replaced with 1.2.3.4, they are unique in actual config)
I have validated the dynomite cluster is functioning properly using redis-cli
```
db=dynomite
workflow.dynomite.cluster=my-dyno
workflow.dynomite.cluster.name=my-dyno
workflow.dynomite.cluster.hosts=1.2.3.4:8102:us-west-2a:us-west-2;1.2.3.4:8102:us-west-2a:us-west-2;1.2.3.4:8102:us-east-1a:us-east-1;1.2.3.4:8102:us-east-1a:us-east-1;1.2.3.4:8102:eu-west-1a:eu-west-1;1.2.3.4:8102:eu-west-1a:eu-west-1
queues.dynomite.nonQuorum.port=8102
queues.dynomite.threads=10
workflow.namespace.prefix=my-conductor
wworkflow.namespace.queue.prefix=my-conductor-queue
# Elasticsearch
workflow.elasticsearch.instanceType=memory
# workflow.elasticsearch.url=my-elasticsearch.my.dom:9300
# workflow.elasticsearch.version=5
# workflow.elasticsearch.index.name=my-conductor-index
# I tried running with and without this property
EC2_AVAILABILITY_ZONE=us-east-1a
```
Stack Trace
```
1) Error in custom provider, java.lang.RuntimeException: java.lang.NullPointerException
while locating com.netflix.conductor.jedis.DynomiteJedisProvider
at com.netflix.conductor.server.DynomiteClusterModule.configure(DynomiteClusterModule.java:25)
while locating redis.clients.jedis.JedisCommands
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at com.netflix.dyno.jedis.DynoJedisClient$Builder.startConnectionPool(DynoJedisClient.java:4309)
at com.netflix.dyno.jedis.DynoJedisClient$Builder.createConnectionPool(DynoJedisClient.java:4281)
at com.netflix.dyno.jedis.DynoJedisClient$Builder.buildDynoJedisClient(DynoJedisClient.java:4257)
at com.netflix.dyno.jedis.DynoJedisClient$Builder.build(DynoJedisClient.java:4186)
at com.netflix.conductor.jedis.DynomiteJedisProvider.get(DynomiteJedisProvider.java:49)
at com.netflix.conductor.jedis.DynomiteJedisProvider.get(DynomiteJedisProvider.java:14)
at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
at com.google.inject.internal.BoundProviderFactory.provision(BoundProviderFactory.java:72)
at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:65)
at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
at com.netflix.governator.event.ApplicationEventModule$ApplicationEventSubscribingProvisionListener.onProvision(ApplicationEventModule.java:89)
at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:126)
at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:63)
at com.google.inject.internal.BoundProviderFactory.get(BoundProviderFactory.java:62)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:194)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:205)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:199)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1085)
at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:199)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:180)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110)
at com.google.inject.Guice.createInjector(Guice.java:99)
at com.google.inject.Guice.createInjector(Guice.java:73)
at com.netflix.conductor.bootstrap.Main.main(Main.java:53)
Caused by: java.lang.NullPointerException
at com.netflix.dyno.connectionpool.impl.HostsUpdater.refreshHosts(HostsUpdater.java:111)
at com.netflix.dyno.connectionpool.impl.ConnectionPoolImpl.start(ConnectionPoolImpl.java:486)
at com.netflix.dyno.jedis.DynoJedisClient$Builder.startConnectionPool(DynoJedisClient.java:4292)
... 29 more
```
Full log (there are 51 "Error in custom provider" stack traces, mostly very similar)
[server.log](https://github.com/Netflix/conductor/files/2558912/server.log)
| aa036d49bb225e4bdc4c951a6cd0cb71d0753123 | 6669e5265fb5c29a574d1e0f18941a2521f1f49c | https://github.com/netflix/conductor/compare/aa036d49bb225e4bdc4c951a6cd0cb71d0753123...6669e5265fb5c29a574d1e0f18941a2521f1f49c | diff --git a/redis-persistence/src/main/java/com/netflix/conductor/jedis/TokenMapSupplierProvider.java b/redis-persistence/src/main/java/com/netflix/conductor/jedis/TokenMapSupplierProvider.java
index 627fed072..92a7ef207 100644
--- a/redis-persistence/src/main/java/com/netflix/conductor/jedis/TokenMapSupplierProvider.java
+++ b/redis-persistence/src/main/java/com/netflix/conductor/jedis/TokenMapSupplierProvider.java
@@ -1,43 +1,53 @@
+/*
+ * Copyright 2016 Netflix, Inc.
+ * <p>
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
package com.netflix.conductor.jedis;
-import com.google.common.collect.Lists;
-
import com.netflix.dyno.connectionpool.Host;
-import com.netflix.dyno.connectionpool.HostSupplier;
import com.netflix.dyno.connectionpool.TokenMapSupplier;
import com.netflix.dyno.connectionpool.impl.lb.HostToken;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
+import com.netflix.dyno.connectionpool.impl.utils.CollectionUtils;
import javax.inject.Inject;
import javax.inject.Provider;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
public class TokenMapSupplierProvider implements Provider<TokenMapSupplier> {
- private final HostSupplier hostSupplier;
+ private final List<HostToken> hostTokens;
@Inject
- public TokenMapSupplierProvider(HostSupplier hostSupplier) {
- this.hostSupplier = hostSupplier;
+ public TokenMapSupplierProvider() {
+ this.hostTokens = new ArrayList<>();
}
@Override
public TokenMapSupplier get() {
return new TokenMapSupplier() {
-
- // FIXME This isn't particularly safe, but it is equivalent to the existing code.
- // FIXME It seems like we should be supply tokens for more than one host?
- HostToken token = new HostToken(1L, Lists.newArrayList(hostSupplier.getHosts()).get(0));
-
@Override
public List<HostToken> getTokens(Set<Host> activeHosts) {
- return Arrays.asList(token);
+ long i = activeHosts.size();
+ for (Host host : activeHosts) {
+ HostToken hostToken = new HostToken(i, host);
+ hostTokens.add(hostToken);
+ i--;
+ }
+ return hostTokens;
}
@Override
public HostToken getTokenForHost(Host host, Set<Host> activeHosts) {
- return token;
+ return CollectionUtils.find(hostTokens, token -> token.getHost().compareTo(host) == 0);
}
};
} | ['redis-persistence/src/main/java/com/netflix/conductor/jedis/TokenMapSupplierProvider.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,457,915 | 304,798 | 41,258 | 265 | 1,973 | 395 | 44 | 1 | 5,181 | 172 | 1,241 | 82 | 2 | 2 | 2019-01-15T23:03:37 | 9,943 | Java | {'Java': 3462518, 'Groovy': 850012, 'JavaScript': 390784, 'Go': 45821, 'Python': 27631, 'TypeScript': 8934, 'Dockerfile': 4469, 'SCSS': 4366, 'HTML': 2524, 'Shell': 2374, 'PLpgSQL': 1962, 'CSS': 1347, 'Makefile': 253} | Apache License 2.0 |
1,436 | netflix/conductor/3495/3494 | netflix | conductor | https://github.com/Netflix/conductor/issues/3494 | https://github.com/Netflix/conductor/pull/3495 | https://github.com/Netflix/conductor/pull/3495 | 1 | fixes | Complete WAIT task inside for loop by TaskRef | See discussion https://github.com/Netflix/conductor/discussions/2873
Seems like it was partially fixed https://github.com/Netflix/conductor/pull/2883 for eventhandler actions, but did not get fixed for default WAIT task handlers.
| 719677de34ff323fc30578ad13436865e18ccbac | a72599fbd673408d62701fa376373f5154c7d948 | https://github.com/netflix/conductor/compare/719677de34ff323fc30578ad13436865e18ccbac...a72599fbd673408d62701fa376373f5154c7d948 | diff --git a/core/src/main/java/com/netflix/conductor/core/events/queue/DefaultEventQueueProcessor.java b/core/src/main/java/com/netflix/conductor/core/events/queue/DefaultEventQueueProcessor.java
index 78abf836b..f1c508803 100644
--- a/core/src/main/java/com/netflix/conductor/core/events/queue/DefaultEventQueueProcessor.java
+++ b/core/src/main/java/com/netflix/conductor/core/events/queue/DefaultEventQueueProcessor.java
@@ -22,6 +22,7 @@ import org.springframework.stereotype.Component;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskResult;
+import com.netflix.conductor.common.utils.TaskUtils;
import com.netflix.conductor.core.exception.NotFoundException;
import com.netflix.conductor.core.execution.WorkflowExecutor;
import com.netflix.conductor.model.TaskModel;
@@ -124,7 +125,10 @@ public class DefaultEventQueueProcessor {
.filter(
task ->
!task.getStatus().isTerminal()
- && task.getReferenceTaskName()
+ && TaskUtils
+ .removeIterationFromTaskRefName(
+ task
+ .getReferenceTaskName())
.equals(
taskRefName))
.findFirst(); | ['core/src/main/java/com/netflix/conductor/core/events/queue/DefaultEventQueueProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,261,284 | 443,640 | 60,343 | 356 | 593 | 42 | 6 | 1 | 233 | 23 | 52 | 3 | 2 | 0 | 2023-02-16T13:36:48 | 9,943 | Java | {'Java': 3462518, 'Groovy': 850012, 'JavaScript': 390784, 'Go': 45821, 'Python': 27631, 'TypeScript': 8934, 'Dockerfile': 4469, 'SCSS': 4366, 'HTML': 2524, 'Shell': 2374, 'PLpgSQL': 1962, 'CSS': 1347, 'Makefile': 253} | Apache License 2.0 |
44 | tootallnate/java-websocket/570/564 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/564 | https://github.com/TooTallNate/Java-WebSocket/pull/570 | https://github.com/TooTallNate/Java-WebSocket/pull/570 | 2 | fix | Continuous binary getting swallowed? | My WS JS hosted in Chrome seems to be sending the following frames:
BINARY, isFin = false
CONTINUOUS, isFin = true
Java-WebSocket seems to drop the CONTINUOUS frame on the floor and the application never gets it:
```java
// org/java_websocket/drafts/Draft_6455.java:542
} else if( frame.isFin() ) {
if( current_continuous_frame == null )
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." );
//Check if the whole payload is valid utf8, when the opcode indicates a text
if( current_continuous_frame.getOpcode() == Framedata.Opcode.TEXT ) {
//Checking a bit more from the frame before this one just to make sure all the code points are correct
int off = Math.max( current_continuous_frame.getPayloadData().limit() - 64, 0 );
current_continuous_frame.append( frame );
if( !Charsetfunctions.isValidUTF8( current_continuous_frame.getPayloadData(), off ) ) {
throw new InvalidDataException( CloseFrame.NO_UTF8 );
}
}
// **** What about if the current_continuous_frame.getOpcode() == Framedata.Opcode.BINARY ****//
current_continuous_frame = null;
```
Is this expected? Is Chrome breaking the spec? Is this something Java-WebSocket should handle differently? | f33422e9951369ffd948d473c026ef0e6da6b8e4 | 32c1ce01c9064d68c8adcfa3b1b577d30bed8cb2 | https://github.com/tootallnate/java-websocket/compare/f33422e9951369ffd948d473c026ef0e6da6b8e4...32c1ce01c9064d68c8adcfa3b1b577d30bed8cb2 | diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java
index 74aca19..f794591 100644
--- a/src/main/java/org/java_websocket/WebSocketImpl.java
+++ b/src/main/java/org/java_websocket/WebSocketImpl.java
@@ -605,7 +605,7 @@ public class WebSocketImpl implements WebSocket {
if( !isOpen() ) {
throw new WebsocketNotConnectedException();
}
- if( frames == null || frames.isEmpty() ) {
+ if( frames == null) {
throw new IllegalArgumentException();
}
ArrayList<ByteBuffer> outgoingFrames = new ArrayList<ByteBuffer>();
diff --git a/src/main/java/org/java_websocket/WebSocketListener.java b/src/main/java/org/java_websocket/WebSocketListener.java
index d865504..fd19883 100644
--- a/src/main/java/org/java_websocket/WebSocketListener.java
+++ b/src/main/java/org/java_websocket/WebSocketListener.java
@@ -59,7 +59,7 @@ public interface WebSocketListener {
* @throws InvalidDataException
* Throwing this exception will cause this handshake to be rejected
*/
- public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException;
+ ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException;
/**
* Called on the client side when the socket connection is first established, and the WebSocketImpl
@@ -74,7 +74,7 @@ public interface WebSocketListener {
* @throws InvalidDataException
* Allows the client to reject the connection with the server in respect of its handshake response.
*/
- public void onWebsocketHandshakeReceivedAsClient( WebSocket conn, ClientHandshake request, ServerHandshake response ) throws InvalidDataException;
+ void onWebsocketHandshakeReceivedAsClient( WebSocket conn, ClientHandshake request, ServerHandshake response ) throws InvalidDataException;
/**
* Called on the client side when the socket connection is first established, and the WebSocketImpl
@@ -87,7 +87,7 @@ public interface WebSocketListener {
* @throws InvalidDataException
* Allows the client to stop the connection from progressing
*/
- public void onWebsocketHandshakeSentAsClient( WebSocket conn, ClientHandshake request ) throws InvalidDataException;
+ void onWebsocketHandshakeSentAsClient( WebSocket conn, ClientHandshake request ) throws InvalidDataException;
/**
* Called when an entire text frame has been received. Do whatever you want
@@ -98,7 +98,7 @@ public interface WebSocketListener {
* @param message
* The UTF-8 decoded message that was received.
*/
- public void onWebsocketMessage( WebSocket conn, String message );
+ void onWebsocketMessage( WebSocket conn, String message );
/**
* Called when an entire binary frame has been received. Do whatever you want
@@ -109,16 +109,18 @@ public interface WebSocketListener {
* @param blob
* The binary message that was received.
*/
- public void onWebsocketMessage( WebSocket conn, ByteBuffer blob );
+ void onWebsocketMessage( WebSocket conn, ByteBuffer blob );
/**
* Called when a frame fragment has been recieved
*
+ * This method will be removed in a future version since the lib will also call the respective onWebsocketMessage method
* @param conn
* The <tt>WebSocket</tt> instance this event is occurring on.
* @param frame The fragmented frame
*/
- public void onWebsocketMessageFragment( WebSocket conn, Framedata frame );
+ @Deprecated
+ void onWebsocketMessageFragment( WebSocket conn, Framedata frame );
/**
* Called after <var>onHandshakeReceived</var> returns <var>true</var>.
@@ -128,7 +130,7 @@ public interface WebSocketListener {
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param d The handshake of the websocket instance
*/
- public void onWebsocketOpen( WebSocket conn, Handshakedata d );
+ void onWebsocketOpen( WebSocket conn, Handshakedata d );
/**
* Called after <tt>WebSocket#close</tt> is explicity called, or when the
@@ -139,7 +141,7 @@ public interface WebSocketListener {
* @param reason Additional information string
* @param remote Returns whether or not the closing of the connection was initiated by the remote host.
*/
- public void onWebsocketClose( WebSocket ws, int code, String reason, boolean remote );
+ void onWebsocketClose( WebSocket ws, int code, String reason, boolean remote );
/** Called as soon as no further frames are accepted
*
@@ -148,7 +150,7 @@ public interface WebSocketListener {
* @param reason Additional information string
* @param remote Returns whether or not the closing of the connection was initiated by the remote host.
*/
- public void onWebsocketClosing( WebSocket ws, int code, String reason, boolean remote );
+ void onWebsocketClosing( WebSocket ws, int code, String reason, boolean remote );
/** send when this peer sends a close handshake
*
@@ -156,7 +158,7 @@ public interface WebSocketListener {
* @param code The codes can be looked up here: {@link CloseFrame}
* @param reason Additional information string
*/
- public void onWebsocketCloseInitiated( WebSocket ws, int code, String reason );
+ void onWebsocketCloseInitiated( WebSocket ws, int code, String reason );
/**
* Called if an exception worth noting occurred.
@@ -167,7 +169,7 @@ public interface WebSocketListener {
* The exception that occurred. <br>
* Might be null if the exception is not related to any specific connection. For example if the server port could not be bound.
*/
- public void onWebsocketError( WebSocket conn, Exception ex );
+ void onWebsocketError( WebSocket conn, Exception ex );
/**
* Called a ping frame has been received.
@@ -176,7 +178,7 @@ public interface WebSocketListener {
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param f The ping frame. Control frames may contain payload.
*/
- public void onWebsocketPing( WebSocket conn, Framedata f );
+ void onWebsocketPing( WebSocket conn, Framedata f );
/**
* Called when a pong frame is received.
@@ -184,7 +186,7 @@ public interface WebSocketListener {
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param f The pong frame. Control frames may contain payload.
**/
- public void onWebsocketPong( WebSocket conn, Framedata f );
+ void onWebsocketPong( WebSocket conn, Framedata f );
/**
* @see WebSocketAdapter#getFlashPolicy(WebSocket)
@@ -192,12 +194,13 @@ public interface WebSocketListener {
* @throws InvalidDataException thrown when some data that is required to generate the flash-policy like the websocket local port could not be obtained.
* @return An XML String that comforts to Flash's security policy. You MUST not include the null char at the end, it is appended automatically.
*/
- public String getFlashPolicy( WebSocket conn ) throws InvalidDataException;
+ @Deprecated
+ String getFlashPolicy( WebSocket conn ) throws InvalidDataException;
/** This method is used to inform the selector thread that there is data queued to be written to the socket.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
*/
- public void onWriteDemand( WebSocket conn );
+ void onWriteDemand( WebSocket conn );
/**
* @see WebSocket#getLocalSocketAddress()
@@ -205,7 +208,7 @@ public interface WebSocketListener {
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @return Returns the address of the endpoint this socket is bound to.
*/
- public InetSocketAddress getLocalSocketAddress( WebSocket conn );
+ InetSocketAddress getLocalSocketAddress( WebSocket conn );
/**
* @see WebSocket#getRemoteSocketAddress()
@@ -213,5 +216,5 @@ public interface WebSocketListener {
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @return Returns the address of the endpoint this socket is connected to, or{@code null} if it is unconnected.
*/
- public InetSocketAddress getRemoteSocketAddress( WebSocket conn );
+ InetSocketAddress getRemoteSocketAddress( WebSocket conn );
}
diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java
index e44e72f..03bb639 100644
--- a/src/main/java/org/java_websocket/drafts/Draft_6455.java
+++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java
@@ -62,6 +62,11 @@ public class Draft_6455 extends Draft {
*/
private Framedata current_continuous_frame;
+ /**
+ * Attribute for the payload of the current continuous frame
+ */
+ private List<ByteBuffer> byteBufferList;
+
/**
* Attribute for the current incomplete frame
*/
@@ -96,6 +101,7 @@ public class Draft_6455 extends Draft {
public Draft_6455( List<IExtension> inputExtensions ) {
knownExtensions = new ArrayList<IExtension>();
boolean hasDefault = false;
+ byteBufferList = new ArrayList<ByteBuffer>();
for( IExtension inputExtension : inputExtensions ) {
if( inputExtension.getClass().equals( DefaultExtension.class ) ) {
hasDefault = true;
@@ -548,19 +554,30 @@ public class Draft_6455 extends Draft {
if( current_continuous_frame != null )
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Previous continuous frame sequence not completed." );
current_continuous_frame = frame;
+ byteBufferList.add( frame.getPayloadData() );
} else if( frame.isFin() ) {
if( current_continuous_frame == null )
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." );
- //Check if the whole payload is valid utf8, when the opcode indicates a text
+ byteBufferList.add( frame.getPayloadData() );
if( current_continuous_frame.getOpcode() == Framedata.Opcode.TEXT ) {
- //Checking a bit more from the frame before this one just to make sure all the code points are correct
- int off = Math.max( current_continuous_frame.getPayloadData().limit() - 64, 0 );
- current_continuous_frame.append( frame );
- if( !Charsetfunctions.isValidUTF8( current_continuous_frame.getPayloadData(), off ) ) {
- throw new InvalidDataException( CloseFrame.NO_UTF8 );
+ ((FramedataImpl1) current_continuous_frame).setPayload( getPayloadFromByteBufferList() );
+ ((FramedataImpl1) current_continuous_frame ).isValid();
+ try {
+ webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( current_continuous_frame.getPayloadData() ) );
+ } catch ( RuntimeException e ) {
+ webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e );
+ }
+ } else if( current_continuous_frame.getOpcode() == Framedata.Opcode.BINARY ) {
+ ((FramedataImpl1) current_continuous_frame).setPayload( getPayloadFromByteBufferList() );
+ ((FramedataImpl1) current_continuous_frame ).isValid();
+ try {
+ webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, current_continuous_frame.getPayloadData() );
+ } catch ( RuntimeException e ) {
+ webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e );
}
}
current_continuous_frame = null;
+ byteBufferList.clear();
} else if( current_continuous_frame == null ) {
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." );
}
@@ -571,18 +588,8 @@ public class Draft_6455 extends Draft {
}
}
//Checking if the current continous frame contains a correct payload with the other frames combined
- if( curop == Framedata.Opcode.CONTINUOUS && current_continuous_frame != null && current_continuous_frame.getOpcode() == Framedata.Opcode.TEXT ) {
- //Checking a bit more from the frame before this one just to make sure all the code points are correct
- int off = Math.max( current_continuous_frame.getPayloadData().limit() - 64, 0 );
- current_continuous_frame.append( frame );
- if( !Charsetfunctions.isValidUTF8( current_continuous_frame.getPayloadData(), off ) ) {
- throw new InvalidDataException( CloseFrame.NO_UTF8 );
- }
- }
- try {
- webSocketImpl.getWebSocketListener().onWebsocketMessageFragment( webSocketImpl, frame );
- } catch ( RuntimeException e ) {
- webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e );
+ if( curop == Framedata.Opcode.CONTINUOUS && current_continuous_frame != null ) {
+ byteBufferList.add( frame.getPayloadData() );
}
return;
} else if( current_continuous_frame != null ) {
@@ -632,4 +639,25 @@ public class Draft_6455 extends Draft {
public int hashCode() {
return extension != null ? extension.hashCode() : 0;
}
+
+ /**
+ * Method to generate a full bytebuffer out of all the fragmented frame payload
+ * @return a bytebuffer containing all the data
+ * @throws LimitExedeedException will be thrown when the totalSize is bigger then Integer.MAX_VALUE due to not being able to allocate more
+ */
+ private ByteBuffer getPayloadFromByteBufferList() throws LimitExedeedException {
+ long totalSize = 0;
+ for (ByteBuffer buffer : byteBufferList) {
+ totalSize +=buffer.limit();
+ }
+ if (totalSize > Integer.MAX_VALUE) {
+ throw new LimitExedeedException( "Payloadsize is to big..." );
+ }
+ ByteBuffer resultingByteBuffer = ByteBuffer.allocate( (int) totalSize );
+ for (ByteBuffer buffer : byteBufferList) {
+ resultingByteBuffer.put( buffer );
+ }
+ resultingByteBuffer.flip();
+ return resultingByteBuffer;
+ }
}
diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java
index 872db60..38c2a6e 100644
--- a/src/main/java/org/java_websocket/server/WebSocketServer.java
+++ b/src/main/java/org/java_websocket/server/WebSocketServer.java
@@ -767,6 +767,7 @@ public abstract class WebSocketServer extends AbstractWebSocket implements Runna
* The <tt>WebSocket</tt> instance this event is occurring on.
* @param fragment The fragmented frame
*/
+ @Deprecated
public void onFragment( WebSocket conn, Framedata fragment ) {
}
diff --git a/src/test/java/org/java_websocket/example/AutobahnServerTest.java b/src/test/java/org/java_websocket/example/AutobahnServerTest.java
index 1cc752d..e8749a4 100644
--- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java
+++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java
@@ -48,7 +48,6 @@ import java.util.Collections;
public class AutobahnServerTest extends WebSocketServer {
private static int counter = 0;
-
public AutobahnServerTest( int port, Draft d ) throws UnknownHostException {
super( new InetSocketAddress( port ), Collections.singletonList( d ) );
}
@@ -83,17 +82,14 @@ public class AutobahnServerTest extends WebSocketServer {
public void onMessage( WebSocket conn, String message ) {
conn.send( message );
}
-
@Override
- public void onMessage( WebSocket conn, ByteBuffer blob ) {
- conn.send( blob );
+ public void onFragment( WebSocket conn, Framedata fragment ) {
+ System.out.println( "received fragment: " + fragment );
}
@Override
- public void onWebsocketMessageFragment( WebSocket conn, Framedata frame ) {
- FramedataImpl1 builder = ( FramedataImpl1 ) frame;
- builder.setTransferemasked( false );
- conn.sendFrame( frame );
+ public void onMessage( WebSocket conn, ByteBuffer blob ) {
+ conn.send( blob );
}
public static void main( String[] args ) throws UnknownHostException { | ['src/main/java/org/java_websocket/WebSocketListener.java', 'src/main/java/org/java_websocket/WebSocketImpl.java', 'src/main/java/org/java_websocket/drafts/Draft_6455.java', 'src/main/java/org/java_websocket/server/WebSocketServer.java', 'src/test/java/org/java_websocket/example/AutobahnServerTest.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 404,340 | 97,292 | 11,329 | 64 | 6,409 | 1,398 | 104 | 4 | 1,252 | 157 | 291 | 25 | 0 | 1 | 2017-10-10T20:30:24 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
45 | tootallnate/java-websocket/470/465 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/465 | https://github.com/TooTallNate/Java-WebSocket/pull/470 | https://github.com/TooTallNate/Java-WebSocket/pull/470 | 1 | fix | Bad rsv 4 on android | Hello, our team using this library for connecting websocket server on Android platform,
sometimes, there are 'bad rsv 4' errors occurred. Seems same problem with #430.
```
04-27 14:26:09.960 I/System.out( 1564): D/WebsocketChannel: 000000 48 54 54 50 2f 31 2e 31 20 31 30 31 20 53 77 69 74 63 HTTP/1.1 101 Switc
04-27 14:26:09.960 D/WebSocketChannel( 1564): onError:org.java_websocket.exceptions.InvalidFrameException: bad rsv 4
```
The debug log above shows the **WebSocketImpl** treat the handshake response as normal websocket frame and decode it, then throw an InvalidFrameException.
Our client tries to reconnect to server endlessly when it is in condition of unstable network environment.
So is it possible that method **org.java_websocket.WebSocketImpl#decode** was invoked after **WebSocketClient** closed in some extreme cases? | b983c881b2dfb9f4c607f4b8b8201666e3491a12 | 2daee16dacbf1e0a9186f260310400a03c10803d | https://github.com/tootallnate/java-websocket/compare/b983c881b2dfb9f4c607f4b8b8201666e3491a12...2daee16dacbf1e0a9186f260310400a03c10803d | diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java
index f3c3142..560651d 100644
--- a/src/main/java/org/java_websocket/WebSocketImpl.java
+++ b/src/main/java/org/java_websocket/WebSocketImpl.java
@@ -151,7 +151,9 @@ public class WebSocketImpl implements WebSocket {
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( readystate != READYSTATE.NOT_YET_CONNECTED ) {
- decodeFrames( socketBuffer );
+ if ( readystate == READYSTATE.OPEN ) {
+ decodeFrames( socketBuffer );
+ }
} else {
if( decodeHandshake( socketBuffer ) ) {
assert ( tmpHandshakeBytes.hasRemaining() != socketBuffer.hasRemaining() || !socketBuffer.hasRemaining() ); // the buffers will never have remaining bytes at the same time | ['src/main/java/org/java_websocket/WebSocketImpl.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 286,679 | 70,843 | 8,405 | 50 | 117 | 30 | 4 | 1 | 854 | 118 | 234 | 12 | 0 | 1 | 2017-05-03T02:48:45 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
47 | tootallnate/java-websocket/276/171 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/171 | https://github.com/TooTallNate/Java-WebSocket/pull/276 | https://github.com/TooTallNate/Java-WebSocket/pull/276 | 2 | fix | Endless loop in client upon close() when using wss | First, thanks so much for creating the library, it's really useful. I am using this via gottox/socket-io (client) and have run into this nasty problem of an endless loop in SSLSocketChannel2.java when closing a connection (maybe after the other side closed first). A couple of these failures is all it takes to pin the CPU at 100% as the threads that execute these loops pile up.
I doubt this is the correct fix, but what I did was change the following in SSLSocketChannel2.readRemaining(), which seems to work.
``` java
if( inCrypt.hasRemaining() ) {
unwrap();
int amount = transfereTo( inData, dst );
>>> if (engineStatus == SSLEngineResult.Status.CLOSED) {
>>> return -1;
>>> }
if( amount > 0 )
return amount;
}
```
EDIT by @Davidisudadi: formatted code
| 05d2e2ed045d955947d944d7111ce3e6758843b6 | ea7e061369477bfdf5a0c32bad920c91f8af61fb | https://github.com/tootallnate/java-websocket/compare/05d2e2ed045d955947d944d7111ce3e6758843b6...ea7e061369477bfdf5a0c32bad920c91f8af61fb | diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java
index ba8d8f8..e540612 100644
--- a/src/main/java/org/java_websocket/SSLSocketChannel2.java
+++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java
@@ -5,6 +5,13 @@
*/
package org.java_websocket;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
+import javax.net.ssl.SSLEngineResult.Status;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLSession;
+import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
@@ -20,13 +27,6 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-import javax.net.ssl.SSLEngineResult.Status;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-
/**
* Implements the relevant portions of the SocketChannel interface with the SSLEngine wrapper.
*/
@@ -213,6 +213,9 @@ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel {
// createBuffers( sslEngine.getSession() );
//}
int num = socketChannel.write( wrap( src ) );
+ if (writeEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) {
+ throw new EOFException("Connection is closed");
+ }
return num;
}
@@ -286,6 +289,9 @@ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel {
if( inCrypt.hasRemaining() ) {
unwrap();
int amount = transfereTo( inData, dst );
+ if (readEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) {
+ return -1;
+ }
if( amount > 0 )
return amount;
} | ['src/main/java/org/java_websocket/SSLSocketChannel2.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 262,194 | 64,649 | 7,706 | 50 | 793 | 181 | 20 | 1 | 856 | 126 | 198 | 18 | 0 | 1 | 2014-09-08T17:21:33 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
37 | tootallnate/java-websocket/567/390 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/390 | https://github.com/TooTallNate/Java-WebSocket/pull/567 | https://github.com/TooTallNate/Java-WebSocket/issues/390#issuecomment-335473419 | 1 | fixes | Websocket server returning 401; can't handle on client side | I have a websocket server that returns 401 on the http handshake
I can't figure out how to get that information on the websocket client
Two things I can't figure out:
1. Where can I get the http status code returned form the server (401 in this case)
onClose is called but with irrelevant code (-1) which I saw in your code that it means "never connected"
2. onError is called but for totally different reason. I get onError ssl == null
why would the client library continue to try to decode the handshake, or something like that, when the socket wasn't upgraded (101)? why not just stop there? The ssl error is irrelevant here and is fired do to the fact that the server did not upgrade the socket
What I did to get the status code from the server was to subclass my own Draft, implement acceptHandshakeAsClient and copyInsance; this gave me access to the handshake response
When I see that the status code is 401 I return NOT_MATCHED
This is the only place I saw I can get the status code, but it makes me do ugly things like saving the status code in a variable to be used by onClose and onError which are then called (but with irrelevant data - code == -1 and error exception is ssl == null)
Thanks
| 37b4610cd6c5b5f717b8c4ca196947019a0ed8b1 | f1eeff4c3b677a503d04d260475b9725445a82d6 | https://github.com/tootallnate/java-websocket/compare/37b4610cd6c5b5f717b8c4ca196947019a0ed8b1...f1eeff4c3b677a503d04d260475b9725445a82d6 | diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java
index 74aca19..7cc3330 100644
--- a/src/main/java/org/java_websocket/WebSocketImpl.java
+++ b/src/main/java/org/java_websocket/WebSocketImpl.java
@@ -447,11 +447,11 @@ public class WebSocketImpl implements WebSocket {
} else if( code == CloseFrame.FLASHPOLICY ) {
assert ( remote );
flushAndClose( CloseFrame.FLASHPOLICY, message, true );
+ } else if( code == CloseFrame.PROTOCOL_ERROR ) { // this endpoint found a PROTOCOL_ERROR
+ flushAndClose( code, message, remote );
} else {
flushAndClose( CloseFrame.NEVER_CONNECTED, message, false );
}
- if( code == CloseFrame.PROTOCOL_ERROR )// this endpoint found a PROTOCOL_ERROR
- flushAndClose( code, message, remote );
readystate = READYSTATE.CLOSING;
tmpHandshakeBytes = null;
return; | ['src/main/java/org/java_websocket/WebSocketImpl.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 407,737 | 98,043 | 11,419 | 65 | 265 | 68 | 4 | 1 | 1,212 | 226 | 269 | 15 | 0 | 0 | 2017-10-05T22:10:36 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
38 | tootallnate/java-websocket/1232/1230 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/1230 | https://github.com/TooTallNate/Java-WebSocket/pull/1232 | https://github.com/TooTallNate/Java-WebSocket/pull/1232 | 1 | fixes | CONTINUOUS should be decoded depending on the first frame | **Describe the bug**
Due to changes with #1165 a return was introduced to handle not decode messages where no RSV1 is set.
This is however the case for a frame with opcode CONTINUOUS.
It is a valid framing and should therefore work
**To Reproduce**
Steps to reproduce the behavior:
1. Run autobahn testsuite
**Expected behavior**
autoban testsuite passes
| 2c9b09127fbbc6d73438097a961a1337dd0d8a65 | 8f1f8e4462b8939f4f1706681d934658c6794bc4 | https://github.com/tootallnate/java-websocket/compare/2c9b09127fbbc6d73438097a961a1337dd0d8a65...8f1f8e4462b8939f4f1706681d934658c6794bc4 | diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java
index 68feb61..eb48799 100644
--- a/src/main/java/org/java_websocket/drafts/Draft_6455.java
+++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java
@@ -115,13 +115,23 @@ public class Draft_6455 extends Draft {
/**
* Attribute for the used extension in this draft
*/
- private IExtension extension = new DefaultExtension();
+ private IExtension negotiatedExtension = new DefaultExtension();
+
+ /**
+ * Attribute for the default extension
+ */
+ private IExtension defaultExtension = new DefaultExtension();
/**
* Attribute for all available extension in this draft
*/
private List<IExtension> knownExtensions;
+ /**
+ * Current active extension used to decode messages
+ */
+ private IExtension currentDecodingExtension;
+
/**
* Attribute for the used protocol in this draft
*/
@@ -241,10 +251,11 @@ public class Draft_6455 extends Draft {
knownExtensions.addAll(inputExtensions);
//We always add the DefaultExtension to implement the normal RFC 6455 specification
if (!hasDefault) {
- knownExtensions.add(this.knownExtensions.size(), extension);
+ knownExtensions.add(this.knownExtensions.size(), negotiatedExtension);
}
knownProtocols.addAll(inputProtocols);
maxFrameSize = inputMaxFrameSize;
+ currentDecodingExtension = null;
}
@Override
@@ -259,9 +270,9 @@ public class Draft_6455 extends Draft {
String requestedExtension = handshakedata.getFieldValue(SEC_WEB_SOCKET_EXTENSIONS);
for (IExtension knownExtension : knownExtensions) {
if (knownExtension.acceptProvidedExtensionAsServer(requestedExtension)) {
- extension = knownExtension;
+ negotiatedExtension = knownExtension;
extensionState = HandshakeState.MATCHED;
- log.trace("acceptHandshakeAsServer - Matching extension found: {}", extension);
+ log.trace("acceptHandshakeAsServer - Matching extension found: {}", negotiatedExtension);
break;
}
}
@@ -316,9 +327,9 @@ public class Draft_6455 extends Draft {
String requestedExtension = response.getFieldValue(SEC_WEB_SOCKET_EXTENSIONS);
for (IExtension knownExtension : knownExtensions) {
if (knownExtension.acceptProvidedExtensionAsClient(requestedExtension)) {
- extension = knownExtension;
+ negotiatedExtension = knownExtension;
extensionState = HandshakeState.MATCHED;
- log.trace("acceptHandshakeAsClient - Matching extension found: {}", extension);
+ log.trace("acceptHandshakeAsClient - Matching extension found: {}", negotiatedExtension);
break;
}
}
@@ -337,7 +348,7 @@ public class Draft_6455 extends Draft {
* @return the extension which is used or null, if handshake is not yet done
*/
public IExtension getExtension() {
- return extension;
+ return negotiatedExtension;
}
/**
@@ -562,8 +573,20 @@ public class Draft_6455 extends Draft {
frame.setRSV3(rsv3);
payload.flip();
frame.setPayload(payload);
- getExtension().isFrameValid(frame);
- getExtension().decodeFrame(frame);
+ if (frame.getOpcode() != Opcode.CONTINUOUS) {
+ // Prioritize the negotiated extension
+ if (frame.isRSV1() || frame.isRSV2() || frame.isRSV3()) {
+ currentDecodingExtension = getExtension();
+ } else {
+ // No encoded message, so we can use the default one
+ currentDecodingExtension = defaultExtension;
+ }
+ }
+ if (currentDecodingExtension == null) {
+ currentDecodingExtension = defaultExtension;
+ }
+ currentDecodingExtension.isFrameValid(frame);
+ currentDecodingExtension.decodeFrame(frame);
if (log.isTraceEnabled()) {
log.trace("afterDecoding({}): {}", frame.getPayloadData().remaining(),
(frame.getPayloadData().remaining() > 1000 ? "too big to display"
@@ -780,10 +803,10 @@ public class Draft_6455 extends Draft {
@Override
public void reset() {
incompleteframe = null;
- if (extension != null) {
- extension.reset();
+ if (negotiatedExtension != null) {
+ negotiatedExtension.reset();
}
- extension = new DefaultExtension();
+ negotiatedExtension = new DefaultExtension();
protocol = null;
}
@@ -1116,7 +1139,7 @@ public class Draft_6455 extends Draft {
if (maxFrameSize != that.getMaxFrameSize()) {
return false;
}
- if (extension != null ? !extension.equals(that.getExtension()) : that.getExtension() != null) {
+ if (negotiatedExtension != null ? !negotiatedExtension.equals(that.getExtension()) : that.getExtension() != null) {
return false;
}
return protocol != null ? protocol.equals(that.getProtocol()) : that.getProtocol() == null;
@@ -1124,7 +1147,7 @@ public class Draft_6455 extends Draft {
@Override
public int hashCode() {
- int result = extension != null ? extension.hashCode() : 0;
+ int result = negotiatedExtension != null ? negotiatedExtension.hashCode() : 0;
result = 31 * result + (protocol != null ? protocol.hashCode() : 0);
result = 31 * result + (maxFrameSize ^ (maxFrameSize >>> 32));
return result;
diff --git a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java
index 824ceb6..f24f9b6 100644
--- a/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java
+++ b/src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java
@@ -142,15 +142,15 @@ public class PerMessageDeflateExtension extends CompressionExtension {
return;
}
+ if (!inputFrame.isRSV1() && inputFrame.getOpcode() != Opcode.CONTINUOUS) {
+ return;
+ }
+
// RSV1 bit must be set only for the first frame.
if (inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) {
throw new InvalidDataException(CloseFrame.POLICY_VALIDATION,
"RSV1 bit can only be set for the first frame.");
}
- // If rsv1 is not set, we dont have a compressed message
- if (!inputFrame.isRSV1()) {
- return;
- }
// Decompressed output buffer.
ByteArrayOutputStream output = new ByteArrayOutputStream();
@@ -181,11 +181,6 @@ public class PerMessageDeflateExtension extends CompressionExtension {
throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage());
}
- // RSV1 bit must be cleared after decoding, so that other extensions don't throw an exception.
- if (inputFrame.isRSV1()) {
- ((DataFrame) inputFrame).setRSV1(false);
- }
-
// Set frames payload to the new decompressed data.
((FramedataImpl1) inputFrame)
.setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); | ['src/main/java/org/java_websocket/drafts/Draft_6455.java', 'src/main/java/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 486,793 | 115,202 | 14,097 | 97 | 2,802 | 587 | 64 | 2 | 371 | 58 | 83 | 13 | 0 | 0 | 2022-04-03T10:29:24 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
39 | tootallnate/java-websocket/1133/1132 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/1132 | https://github.com/TooTallNate/Java-WebSocket/pull/1133 | https://github.com/TooTallNate/Java-WebSocket/pull/1133 | 2 | fixes | Draft_6455 flagged by Veracode CWE-331 replace Random with SecureRandom | Our veracode scan flagged usage of `Random` in Draft_6455.java as a vulnerability.
https://cwe.mitre.org/data/definitions/331.html
According to Websocket Protocol:
For example, each masking could be drawn from a cryptographically strong random number generator. If the same key is used or a decipherable pattern exists for how the next key is chosen, the attacker can send a message that, when masked, could appear to be an HTTP request (by taking the message the attacker wishes to see on the wire and masking it with the next masking key to be used, the masking key will effectively unmask the data when the client applies it).
According to this specification the library should be using SecureRandom to prevent brute force attacks.
**Environment(please complete the following information):**
- Version used: 1.5.1
- Java version: 1.8
- Operating System and version: Android
- Endpoint Name and version:
- Link to your project:
**Additional context**
Add any other context about the problem here.
| 32d5656ffd0aa4ba6caba830ac0205c7bf2609e3 | feec867c81d1a426815717b489147894a19826e5 | https://github.com/tootallnate/java-websocket/compare/32d5656ffd0aa4ba6caba830ac0205c7bf2609e3...feec867c81d1a426815717b489147894a19826e5 | diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java
index 06c964d..68feb61 100644
--- a/src/main/java/org/java_websocket/drafts/Draft_6455.java
+++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java
@@ -29,6 +29,7 @@ import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
@@ -36,7 +37,6 @@ import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
-import java.util.Random;
import java.util.TimeZone;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.enums.CloseHandshakeType;
@@ -150,7 +150,7 @@ public class Draft_6455 extends Draft {
/**
* Attribute for the reusable random instance
*/
- private final Random reuseableRandom = new Random();
+ private final SecureRandom reuseableRandom = new SecureRandom();
/**
* Attribute for the maximum allowed size of a frame | ['src/main/java/org/java_websocket/drafts/Draft_6455.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 484,669 | 114,730 | 14,035 | 97 | 185 | 36 | 4 | 1 | 1,029 | 155 | 217 | 20 | 1 | 0 | 2021-03-22T21:03:36 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
40 | tootallnate/java-websocket/1014/1011 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/1011 | https://github.com/TooTallNate/Java-WebSocket/pull/1014 | https://github.com/TooTallNate/Java-WebSocket/pull/1014 | 1 | fixes | Crash on Android due to missing method `setEndpointIdentificationAlgorithm` on 1.5.0. | Websocket library 1.5.0
The same code was not crashing on 1.4.1
This is the entire stack trace. I got it through Crashlytics so I cannot describe steps that led to it.
```
Fatal Exception: java.lang.NoSuchMethodError: No virtual method setEndpointIdentificationAlgorithm(Ljava/lang/String;)V in class Ljavax/net/ssl/SSLParameters; or its super classes (declaration of 'javax.net.ssl.SSLParameters' appears in /system/framework/core-libart.jar)
at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:476)
at java.lang.Thread.run(Thread.java:831)
```
Android 5.0.1 (API 21).
Brand: HUAWEI
Model: P8 Lite
| c207fb8a7c28e7c49bf42e8da7e7866e7db60043 | 877ad764e5d01166d754e611a4139e816cc04d0d | https://github.com/tootallnate/java-websocket/compare/c207fb8a7c28e7c49bf42e8da7e7866e7db60043...877ad764e5d01166d754e611a4139e816cc04d0d | diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java
index 0bbcfe5..4d735de 100644
--- a/src/main/java/org/java_websocket/client/WebSocketClient.java
+++ b/src/main/java/org/java_websocket/client/WebSocketClient.java
@@ -472,8 +472,6 @@ public abstract class WebSocketClient extends AbstractWebSocket implements Runna
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket)socket;
SSLParameters sslParameters = sslSocket.getSSLParameters();
- // Make sure we perform hostname validation
- sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
onSetSSLParameters(sslParameters);
sslSocket.setSSLParameters(sslParameters);
}
@@ -520,10 +518,14 @@ public abstract class WebSocketClient extends AbstractWebSocket implements Runna
/**
* Apply specific SSLParameters
+ * If you override this method make sure to always call super.onSetSSLParameters() to ensure the hostname validation is active
*
* @param sslParameters the SSLParameters which will be used for the SSLSocket
*/
protected void onSetSSLParameters(SSLParameters sslParameters) {
+ // If you run into problem on Android (NoSuchMethodException), check out the wiki https://github.com/TooTallNate/Java-WebSocket/wiki/No-such-method-error-setEndpointIdentificationAlgorithm
+ // Perform hostname validation
+ sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
}
/**
diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java
index 0fc81bc..493dd69 100644
--- a/src/test/java/org/java_websocket/issues/Issue997Test.java
+++ b/src/test/java/org/java_websocket/issues/Issue997Test.java
@@ -143,6 +143,8 @@ public class Issue997Test {
@Override
protected void onSetSSLParameters(SSLParameters sslParameters) {
+ // Always call super to ensure hostname validation is active by default
+ super.onSetSSLParameters(sslParameters);
if (endpointIdentificationAlgorithm != null) {
sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm);
} | ['src/test/java/org/java_websocket/issues/Issue997Test.java', 'src/main/java/org/java_websocket/client/WebSocketClient.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 469,383 | 112,447 | 13,300 | 96 | 529 | 110 | 6 | 1 | 648 | 66 | 164 | 15 | 0 | 1 | 2020-05-10T15:10:06 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
41 | tootallnate/java-websocket/901/905 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/905 | https://github.com/TooTallNate/Java-WebSocket/pull/901 | https://github.com/TooTallNate/Java-WebSocket/pull/901 | 1 | fixes | IOException wrapped in InternalError not handled properly | **Describe the bug**
The call to `socket.connect(...)` at `WebSocketClient:436` can throw a `java.lang.InternalError` that is currently not handled in the enclosing try/catch as it extends `java.lang.Error` and not `java.lang.Exception`
This `InternalError` wraps a `java.lang.IOException` that contains useful information to the websocket engine to hande this case.
**To Reproduce**
Steps to reproduce the behavior:
1. Install a proxy, i.e. squid
2. Make it deny connections
**Example application to reproduce the issue**
Use the previously installed proxy in the `ProxyClientExample`
**Expected behavior**
An IOException handled by the underlying websocket engine
**Debug log**
```
Exception in thread "WebSocketConnectReadThread-11" java.lang.InternalError: Should not reach here
at java.net.HttpConnectSocketImpl.doTunneling(HttpConnectSocketImpl.java:181)
at java.net.HttpConnectSocketImpl.doTunnel(HttpConnectSocketImpl.java:168)
at java.net.HttpConnectSocketImpl.access$200(HttpConnectSocketImpl.java:44)
at java.net.HttpConnectSocketImpl$2.run(HttpConnectSocketImpl.java:151)
at java.net.HttpConnectSocketImpl$2.run(HttpConnectSocketImpl.java:149)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.HttpConnectSocketImpl.privilegedDoTunnel(HttpConnectSocketImpl.java:148)
at java.net.HttpConnectSocketImpl.connect(HttpConnectSocketImpl.java:111)
at java.net.Socket.connect(Socket.java:589)
at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:436)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.net.HttpConnectSocketImpl.doTunneling(HttpConnectSocketImpl.java:179)
... 10 more
Caused by: java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 403 Forbidden"
at sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnection.java:2142)
... 15 more
```
**Environment(please complete the following information):**
- Version used: 1.4.0
- Java version: 1.8.0_181
- Operating System and version: Ubuntu 16.04 LTS
- Endpoint Name and version: "ws://echo.websocket.org"
- Link to your project: ProxyClientExample in the examples folder
**Additional context**
This is my first time reporting an issue on a open source project.
I'm open to feedback :)
| c9e75337940cd041e935191e3dbec0005a622c64 | f73cca0f3faf1bc5d72ba44d0ee42a1b6dabe28e | https://github.com/tootallnate/java-websocket/compare/c9e75337940cd041e935191e3dbec0005a622c64...f73cca0f3faf1bc5d72ba44d0ee42a1b6dabe28e | diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java
index f5cd9b1..7a93a0a 100644
--- a/src/main/java/org/java_websocket/client/WebSocketClient.java
+++ b/src/main/java/org/java_websocket/client/WebSocketClient.java
@@ -28,6 +28,7 @@ package org.java_websocket.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
@@ -480,6 +481,15 @@ public abstract class WebSocketClient extends AbstractWebSocket implements Runna
onWebsocketError( engine, e );
engine.closeConnection( CloseFrame.NEVER_CONNECTED, e.getMessage() );
return;
+ } catch (InternalError e) {
+ // https://bugs.openjdk.java.net/browse/JDK-8173620
+ if (e.getCause() instanceof InvocationTargetException && e.getCause().getCause() instanceof IOException) {
+ IOException cause = (IOException) e.getCause().getCause();
+ onWebsocketError(engine, cause);
+ engine.closeConnection(CloseFrame.NEVER_CONNECTED, cause.getMessage());
+ return;
+ }
+ throw e;
}
writeThread = new Thread( new WebsocketWriteThread(this) ); | ['src/main/java/org/java_websocket/client/WebSocketClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 443,103 | 106,639 | 12,595 | 90 | 461 | 106 | 10 | 1 | 2,649 | 216 | 598 | 53 | 0 | 1 | 2019-06-11T08:57:00 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
42 | tootallnate/java-websocket/683/685 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/685 | https://github.com/TooTallNate/Java-WebSocket/pull/683 | https://github.com/TooTallNate/Java-WebSocket/pull/683 | 1 | fixes | Exclude default port from wss host | <!--- Provide a general summary of the issue in the Title above -->
I'm working with a server balanced by a proxy that redirect my request to the targeted server depends on the URL I requested.
One of these servers has a secure Websocket (I mean wss) and it works on the default port (443).
In your client (class WebSocketClient.java) you avoid to include the port in the host by: `port != WebSocket.DEFAULT_PORT ? ":" + port : ""`, but this works only for ws default port and not for wss that now is including ":443" at the end of the host. In my app, for example I want to connect to "wss://app.example.com" and without this check it's trying to connect to "wss://app.example.com:443" and the proxy cannot resolve this host.
## Possible Solution
Adding a check for DEFAULT_WSS_PORT as well as the check for DEFAULT_PORT it solves the problem.
```java
String host = uri.getHost() + (
(port != WebSocket.DEFAULT_PORT && port != WbSocket.DEFAULT_WSS_PORT)
? ":" + port : "" );
``` | c08be4e43f2414d34ecd5b2fa9985f9e4ff48263 | 8a9df49a0e9fb7bedc0a08e10bed0862a28b9440 | https://github.com/tootallnate/java-websocket/compare/c08be4e43f2414d34ecd5b2fa9985f9e4ff48263...8a9df49a0e9fb7bedc0a08e10bed0862a28b9440 | diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java
index da30d5b..00e40fd 100644
--- a/src/main/java/org/java_websocket/client/WebSocketClient.java
+++ b/src/main/java/org/java_websocket/client/WebSocketClient.java
@@ -434,7 +434,10 @@ public abstract class WebSocketClient extends AbstractWebSocket implements Runna
if( part2 != null )
path += '?' + part2;
int port = getPort();
- String host = uri.getHost() + ( port != WebSocket.DEFAULT_PORT ? ":" + port : "" );
+ String host = uri.getHost() + (
+ (port != WebSocket.DEFAULT_PORT && port != WebSocket.DEFAULT_WSS_PORT)
+ ? ":" + port
+ : "" );
HandshakeImpl1Client handshake = new HandshakeImpl1Client();
handshake.setResourceDescriptor( path ); | ['src/main/java/org/java_websocket/client/WebSocketClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 432,537 | 104,289 | 12,202 | 80 | 227 | 59 | 5 | 1 | 1,002 | 171 | 237 | 14 | 0 | 1 | 2018-03-23T08:09:01 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
46 | tootallnate/java-websocket/329/259 | tootallnate | java-websocket | https://github.com/TooTallNate/Java-WebSocket/issues/259 | https://github.com/TooTallNate/Java-WebSocket/pull/329 | https://github.com/TooTallNate/Java-WebSocket/pull/329 | 2 | fixes | WebSocketServer freezes in stop() method | Hello,
first I would like to thank you for creating a great and useful library.
I'am using it in Android application to communicate with website.
When I try to stop the server, the application sometimes stops responding.
The main thread is indefinitely waiting in "WebSocketServer.stop()" method in "selectorThread.join()" line, because the "selectorThread" never ends. This happens because "selectorThread" is waiting in "run()" method in "selector.select()" line.
Do you know what could be the cause of this behavior?
Thank you all in advance for any help you can provide.
Regards,
Vito
| ac45d846806ad662de48c206896d1248acbb53ff | e4c248a69f0cb36f87e5b3d3100bd2b46e027289 | https://github.com/tootallnate/java-websocket/compare/ac45d846806ad662de48c206896d1248acbb53ff...e4c248a69f0cb36f87e5b3d3100bd2b46e027289 | diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java
index 5fc6a39..12cea2f 100644
--- a/src/main/java/org/java_websocket/server/WebSocketServer.java
+++ b/src/main/java/org/java_websocket/server/WebSocketServer.java
@@ -216,16 +216,10 @@ public abstract class WebSocketServer extends WebSocketAdapter implements Runnab
}
synchronized ( this ) {
- if( selectorthread != null ) {
- if( Thread.currentThread() != selectorthread ) {
-
- }
- if( selectorthread != Thread.currentThread() ) {
- if( socketsToClose.size() > 0 )
- selectorthread.join( timeout );// isclosed will tell the selectorthread to go down after the last connection was closed
- selectorthread.interrupt();// in case the selectorthread did not terminate in time we send the interrupt
- selectorthread.join();
- }
+ if( selectorthread != null && selectorthread != Thread.currentThread() ) {
+ selector.wakeup();
+ selectorthread.interrupt();
+ selectorthread.join( timeout );
}
}
} | ['src/main/java/org/java_websocket/server/WebSocketServer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 262,584 | 64,741 | 7,715 | 50 | 636 | 147 | 14 | 1 | 595 | 90 | 124 | 15 | 0 | 0 | 2015-08-06T21:13:00 | 9,888 | Java | {'Java': 920046, 'HTML': 673666, 'Gherkin': 1433} | MIT License |
544 | square/moshi/500/277 | square | moshi | https://github.com/square/moshi/issues/277 | https://github.com/square/moshi/pull/500 | https://github.com/square/moshi/pull/500 | 1 | closes | Error where map key doesn’t encode as a string is incoherent | When a map key doesn’t have a natural string encoding we crash with a difficult exception. [For example](https://bitbucket.org/robeden/moshi-test), when writing a `Map<Matcher,String> identifiers` we crash like so:
```
Exception in thread "main" java.lang.IllegalStateException: Nesting problem.
at com.squareup.moshi.JsonUtf8Writer.beforeValue(JsonUtf8Writer.java:367)
at com.squareup.moshi.JsonUtf8Writer.open(JsonUtf8Writer.java:102)
at com.squareup.moshi.JsonUtf8Writer.beginObject(JsonUtf8Writer.java:89)
at com.squareup.moshi.ClassJsonAdapter.toJson(ClassJsonAdapter.java:177)
at com.squareup.moshi.JsonAdapter$2.toJson(JsonAdapter.java:134)
at com.squareup.moshi.MapJsonAdapter.toJson(MapJsonAdapter.java:56)
```
Instead we should say “Matcher cannot be used as a map key in JSON.”
The fix for the above example is a JSON adapter, like so:
```
class MatcherJsonAdapter {
@ToJson String matcherToJson(Matcher m) {
return m.type + ":" + m.match;
}
@FromJson Matcher matcherFromJson(String s) {
String[] parts = s.split(":", 1);
return new Matcher(MatchType.valueOf(parts[0]), parts[1]);
}
}
``` | 1c68437f3c62a0092fab16afab84c19f5127a35c | 44e6fbd067404dc8b56fe75648aaf0f3d812670d | https://github.com/square/moshi/compare/1c68437f3c62a0092fab16afab84c19f5127a35c...44e6fbd067404dc8b56fe75648aaf0f3d812670d | diff --git a/moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java b/moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java
index 4fa074d..5cedfe1 100644
--- a/moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java
+++ b/moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java
@@ -77,6 +77,10 @@ final class JsonUtf8Writer extends JsonWriter {
}
@Override public JsonWriter beginArray() throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "Array cannot be used as a map key in JSON at path " + getPath());
+ }
writeDeferredName();
return open(EMPTY_ARRAY, "[");
}
@@ -86,6 +90,10 @@ final class JsonUtf8Writer extends JsonWriter {
}
@Override public JsonWriter beginObject() throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "Object cannot be used as a map key in JSON at path " + getPath());
+ }
writeDeferredName();
return open(EMPTY_OBJECT, "{");
}
@@ -171,6 +179,10 @@ final class JsonUtf8Writer extends JsonWriter {
}
@Override public JsonWriter nullValue() throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "null cannot be used as a map key in JSON at path " + getPath());
+ }
if (deferredName != null) {
if (serializeNulls) {
writeDeferredName();
@@ -186,6 +198,10 @@ final class JsonUtf8Writer extends JsonWriter {
}
@Override public JsonWriter value(boolean value) throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "Boolean cannot be used as a map key in JSON at path " + getPath());
+ }
writeDeferredName();
beforeValue();
sink.writeUtf8(value ? "true" : "false");
diff --git a/moshi/src/main/java/com/squareup/moshi/JsonValueWriter.java b/moshi/src/main/java/com/squareup/moshi/JsonValueWriter.java
index 9879739..9bc06b3 100644
--- a/moshi/src/main/java/com/squareup/moshi/JsonValueWriter.java
+++ b/moshi/src/main/java/com/squareup/moshi/JsonValueWriter.java
@@ -47,6 +47,10 @@ final class JsonValueWriter extends JsonWriter {
}
@Override public JsonWriter beginArray() throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "Array cannot be used as a map key in JSON at path " + getPath());
+ }
checkStack();
List<Object> list = new ArrayList<>();
add(list);
@@ -67,6 +71,10 @@ final class JsonValueWriter extends JsonWriter {
}
@Override public JsonWriter beginObject() throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "Object cannot be used as a map key in JSON at path " + getPath());
+ }
checkStack();
Map<String, Object> map = new LinkedHashTreeMap<>();
add(map);
@@ -116,18 +124,30 @@ final class JsonValueWriter extends JsonWriter {
}
@Override public JsonWriter nullValue() throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "null cannot be used as a map key in JSON at path " + getPath());
+ }
add(null);
pathIndices[stackSize - 1]++;
return this;
}
@Override public JsonWriter value(boolean value) throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "Boolean cannot be used as a map key in JSON at path " + getPath());
+ }
add(value);
pathIndices[stackSize - 1]++;
return this;
}
@Override public JsonWriter value(@Nullable Boolean value) throws IOException {
+ if (promoteValueToName) {
+ throw new IllegalStateException(
+ "Boolean cannot be used as a map key in JSON at path " + getPath());
+ }
add(value);
pathIndices[stackSize - 1]++;
return this;
diff --git a/moshi/src/test/java/com/squareup/moshi/MapJsonAdapterTest.java b/moshi/src/test/java/com/squareup/moshi/MapJsonAdapterTest.java
index dd3e796..c967047 100644
--- a/moshi/src/test/java/com/squareup/moshi/MapJsonAdapterTest.java
+++ b/moshi/src/test/java/com/squareup/moshi/MapJsonAdapterTest.java
@@ -141,6 +141,65 @@ public final class MapJsonAdapterTest {
assertThat(jsonAdapter.fromJsonValue(jsonObject)).isEqualTo(map);
}
+ @Test public void booleanKeyTypeHasCoherentErrorMessage() {
+ Map<Boolean, String> map = new LinkedHashMap<>();
+ map.put(true, "");
+ JsonAdapter<Map<Boolean, String>> adapter = mapAdapter(Boolean.class, String.class);
+ try {
+ adapter.toJson(map);
+ fail();
+ } catch (IllegalStateException expected) {
+ assertThat(expected).hasMessage("Boolean cannot be used as a map key in JSON at path $.");
+ }
+ try {
+ adapter.toJsonValue(map);
+ fail();
+ } catch (IllegalStateException expected) {
+ assertThat(expected).hasMessage("Boolean cannot be used as a map key in JSON at path $.");
+ }
+ }
+
+ static final class Key {
+ }
+
+ @Test public void objectKeyTypeHasCoherentErrorMessage() {
+ Map<Key, String> map = new LinkedHashMap<>();
+ map.put(new Key(), "");
+ JsonAdapter<Map<Key, String>> adapter = mapAdapter(Key.class, String.class);
+ try {
+ adapter.toJson(map);
+ fail();
+ } catch (IllegalStateException expected) {
+ assertThat(expected).hasMessage("Object cannot be used as a map key in JSON at path $.");
+ }
+ try {
+ adapter.toJsonValue(map);
+ fail();
+ } catch (IllegalStateException expected) {
+ assertThat(expected).hasMessage("Object cannot be "
+ + "used as a map key in JSON at path $.");
+ }
+ }
+
+ @Test public void arrayKeyTypeHasCoherentErrorMessage() {
+ Map<String[], String> map = new LinkedHashMap<>();
+ map.put(new String[0], "");
+ JsonAdapter<Map<String[], String>> adapter =
+ mapAdapter(Types.arrayOf(String.class), String.class);
+ try {
+ adapter.toJson(map);
+ fail();
+ } catch (IllegalStateException expected) {
+ assertThat(expected).hasMessage("Array cannot be used as a map key in JSON at path $.");
+ }
+ try {
+ adapter.toJsonValue(map);
+ fail();
+ } catch (IllegalStateException expected) {
+ assertThat(expected).hasMessage("Array cannot be used as a map key in JSON at path $.");
+ }
+ }
+
private <K, V> String toJson(Type keyType, Type valueType, Map<K, V> value) throws IOException {
JsonAdapter<Map<K, V>> jsonAdapter = mapAdapter(keyType, valueType);
Buffer buffer = new Buffer();
diff --git a/moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java b/moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java
index c50005d..335e9d0 100644
--- a/moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java
+++ b/moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java
@@ -252,7 +252,7 @@ public final class PromoteNameToValueTest {
writer.value(true);
fail();
} catch (IllegalStateException e) {
- assertThat(e).hasMessage("Nesting problem.");
+ assertThat(e).hasMessage("Boolean cannot be used as a map key in JSON at path $.");
}
writer.value("true");
assertThat(writer.getPath()).isEqualTo("$.true");
@@ -283,7 +283,7 @@ public final class PromoteNameToValueTest {
writer.nullValue();
fail();
} catch (IllegalStateException e) {
- assertThat(e).hasMessage("Nesting problem.");
+ assertThat(e).hasMessage("null cannot be used as a map key in JSON at path $.");
}
writer.value("null");
assertThat(writer.getPath()).isEqualTo("$.null"); | ['moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java', 'moshi/src/test/java/com/squareup/moshi/MapJsonAdapterTest.java', 'moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java', 'moshi/src/main/java/com/squareup/moshi/JsonValueWriter.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 291,888 | 67,004 | 8,571 | 53 | 1,408 | 315 | 36 | 2 | 1,199 | 107 | 286 | 28 | 1 | 2 | 2018-04-14T08:06:01 | 9,081 | Kotlin | {'Kotlin': 638860, 'Java': 422224, 'Shell': 785} | Apache License 2.0 |
545 | square/moshi/493/128 | square | moshi | https://github.com/square/moshi/issues/128 | https://github.com/square/moshi/pull/493 | https://github.com/square/moshi/pull/493 | 1 | closes | Android: failing to find adapter for a 'GenericArrayTypeImpl' type | We have an adapter in place to process `byte[]` as a base64 / base32 string. Everything works fine when a class has a `byte[]` field, but parsing json fails on Android when we have a field of type `Map<String, byte[]>`. The code below works in the standard JVM but fails on Android.
``` java
class Base32Adapter extends JsonAdapter<byte[]> {
@Override
public byte[] fromJson(JsonReader reader) throws IOException {
String string = reader.nextString();
return new BigInteger(string, 32).toByteArray();
}
@Override
public void toJson(JsonWriter writer, byte[] bytes) throws IOException {
String string = new BigInteger(bytes).toString(32);
writer.value(string);
}
}
static class FavoriteBytes {
@Json(name = "Bytes")
public Map<String, byte[]> keys;
}
@Test public void customAdapter() throws Exception {
String jsonString = "{\\"Bytes\\":{\\"jesse\\":\\"a\\",\\"jake\\":\\"1\\"}}";
Moshi binaryMoshi = new Moshi.Builder().add(byte[].class, new Base32Adapter()).build();
FavoriteBytes fav = binaryMoshi.adapter(FavoriteBytes.class).fromJson(jsonString);
assertThat(fav.keys).containsOnlyKeys("jesse", "jake");
assertThat(fav.keys.get("jesse")).isEqualTo(new byte[] { 0xa });
assertThat(fav.keys.get("jake")).isEqualTo(new byte[] { 0x1 });
}
```
On Android, this fails with exception:
```
E/MoshiTest(18268): com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was STRING at path $.Keys.jesse
E/MoshiTest(18268): at com.squareup.moshi.JsonReader.beginArray(JsonReader.java:346)
E/MoshiTest(18268): at com.squareup.moshi.ArrayJsonAdapter.fromJson(ArrayJsonAdapter.java:53)
E/MoshiTest(18268): at com.squareup.moshi.JsonAdapter$1.fromJson(JsonAdapter.java:68)
E/MoshiTest(18268): at com.squareup.moshi.MapJsonAdapter.fromJson(MapJsonAdapter.java:68)
E/MoshiTest(18268): at com.squareup.moshi.MapJsonAdapter.fromJson(MapJsonAdapter.java:29)
E/MoshiTest(18268): at com.squareup.moshi.JsonAdapter$1.fromJson(JsonAdapter.java:68)
E/MoshiTest(18268): at com.squareup.moshi.ClassJsonAdapter$FieldBinding.read(ClassJsonAdapter.java:183)
E/MoshiTest(18268): at com.squareup.moshi.ClassJsonAdapter.fromJson(ClassJsonAdapter.java:144)
E/MoshiTest(18268): at com.squareup.moshi.JsonAdapter$1.fromJson(JsonAdapter.java:68)
E/MoshiTest(18268): at com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.java:33)
E/MoshiTest(18268): at com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.java:37)
...
```
| 2cc878da8158741c31492240c172c36eb4824bb9 | fa1f10dc77b764022acdb6a1bcc54049a3f7214f | https://github.com/square/moshi/compare/2cc878da8158741c31492240c172c36eb4824bb9...fa1f10dc77b764022acdb6a1bcc54049a3f7214f | diff --git a/moshi/src/main/java/com/squareup/moshi/internal/Util.java b/moshi/src/main/java/com/squareup/moshi/internal/Util.java
index 0744728..e16980a 100644
--- a/moshi/src/main/java/com/squareup/moshi/internal/Util.java
+++ b/moshi/src/main/java/com/squareup/moshi/internal/Util.java
@@ -45,7 +45,7 @@ public final class Util {
public static boolean typesMatch(Type pattern, Type candidate) {
// TODO: permit raw types (like Set.class) to match non-raw candidates (like Set<Long>).
- return pattern.equals(candidate);
+ return Types.equals(pattern, candidate);
}
public static Set<? extends Annotation> jsonAnnotations(AnnotatedElement annotatedElement) { | ['moshi/src/main/java/com/squareup/moshi/internal/Util.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 287,403 | 65,997 | 8,453 | 52 | 84 | 14 | 2 | 1 | 2,527 | 194 | 634 | 51 | 0 | 2 | 2018-04-08T07:48:01 | 9,081 | Kotlin | {'Kotlin': 638860, 'Java': 422224, 'Shell': 785} | Apache License 2.0 |
546 | square/moshi/80/79 | square | moshi | https://github.com/square/moshi/issues/79 | https://github.com/square/moshi/pull/80 | https://github.com/square/moshi/pull/80 | 1 | fixes | Parsing fails on NULL field values | This JSON
{
"id":"2",
"name":"glpi",
"firstname":null
}
fails: Expected a value but was NULL at path $.firstname
class ObjectJsonAdapter in file StandardJsonAdapters.java
has switch (reader.peek()) {}
there are BEGIN_ARRAY, BEGIN_OBJECT, STRING, NUMBER, BOOLEAN
and noooooo NULL value among cases !!!
| 2a05fe4d692d4daf6621ffa6a5721c33b6d81619 | 80953219bda3eeac4da5a7ee7ac6ad9497ea8e38 | https://github.com/square/moshi/compare/2a05fe4d692d4daf6621ffa6a5721c33b6d81619...80953219bda3eeac4da5a7ee7ac6ad9497ea8e38 | diff --git a/moshi/src/main/java/com/squareup/moshi/StandardJsonAdapters.java b/moshi/src/main/java/com/squareup/moshi/StandardJsonAdapters.java
index 9283680..7e9c763 100644
--- a/moshi/src/main/java/com/squareup/moshi/StandardJsonAdapters.java
+++ b/moshi/src/main/java/com/squareup/moshi/StandardJsonAdapters.java
@@ -239,6 +239,9 @@ final class StandardJsonAdapters {
case BOOLEAN:
return reader.nextBoolean();
+ case NULL:
+ return reader.nextNull();
+
default:
throw new IllegalStateException("Expected a value but was " + reader.peek()
+ " at path " + reader.getPath());
diff --git a/moshi/src/test/java/com/squareup/moshi/ObjectAdapterTest.java b/moshi/src/test/java/com/squareup/moshi/ObjectAdapterTest.java
index eea2669..d85daad 100644
--- a/moshi/src/test/java/com/squareup/moshi/ObjectAdapterTest.java
+++ b/moshi/src/test/java/com/squareup/moshi/ObjectAdapterTest.java
@@ -84,6 +84,17 @@ public final class ObjectAdapterTest {
assertThat(adapter.fromJson("[0, 1]")).isEqualTo(Arrays.asList(0d, 1d));
}
+ @Test public void fromJsonDoesNotFailOnNullValues() throws Exception {
+ Map<Object, Object> emptyDelivery = new LinkedHashMap<>();
+ emptyDelivery.put("address", null);
+ emptyDelivery.put("items", null);
+
+ Moshi moshi = new Moshi.Builder().build();
+ JsonAdapter<Object> adapter = moshi.adapter(Object.class);
+ assertThat(adapter.fromJson("{\\"address\\":null, \\"items\\":null}"))
+ .isEqualTo(emptyDelivery);
+ }
+
@Test public void toJsonCoercesRuntimeTypeForCollections() throws Exception {
Collection<String> collection = new AbstractCollection<String>() {
@Override public Iterator<String> iterator() { | ['moshi/src/main/java/com/squareup/moshi/StandardJsonAdapters.java', 'moshi/src/test/java/com/squareup/moshi/ObjectAdapterTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 183,633 | 42,772 | 5,462 | 27 | 58 | 10 | 3 | 1 | 332 | 40 | 85 | 14 | 0 | 0 | 2015-09-16T20:03:22 | 9,081 | Kotlin | {'Kotlin': 638860, 'Java': 422224, 'Shell': 785} | Apache License 2.0 |
3,549 | square/okio/124/105 | square | okio | https://github.com/square/okio/issues/105 | https://github.com/square/okio/pull/124 | https://github.com/square/okio/pull/124 | 1 | closes | BufferedSink.write(Source, long) hides bugs | It calls `source.read(buffer, byteCount)` which might not read `byteCount` bytes and also might return -1 (which is ignored).
Our API should make it hard to write buggy code, and this one tripped me up forcing use of the inverse API which correctly reported read count.
| 9f2c6e38cd0ffc25d1df7337d71bafcd63504f3c | 828384545b72ddc005d35b33c2ebd674548c77df | https://github.com/square/okio/compare/9f2c6e38cd0ffc25d1df7337d71bafcd63504f3c...828384545b72ddc005d35b33c2ebd674548c77df | diff --git a/okio/src/main/java/okio/Buffer.java b/okio/src/main/java/okio/Buffer.java
index 92097b9e..44cfbf29 100644
--- a/okio/src/main/java/okio/Buffer.java
+++ b/okio/src/main/java/okio/Buffer.java
@@ -826,8 +826,10 @@ public final class Buffer implements BufferedSource, BufferedSink, Cloneable {
}
@Override public BufferedSink write(Source source, long byteCount) throws IOException {
- if (byteCount > 0) {
- source.read(this, byteCount);
+ while (byteCount > 0) {
+ long read = source.read(this, byteCount);
+ if (read == -1) throw new EOFException();
+ byteCount -= read;
}
return this;
}
diff --git a/okio/src/main/java/okio/RealBufferedSink.java b/okio/src/main/java/okio/RealBufferedSink.java
index d5d4799d..1902fd80 100644
--- a/okio/src/main/java/okio/RealBufferedSink.java
+++ b/okio/src/main/java/okio/RealBufferedSink.java
@@ -15,6 +15,7 @@
*/
package okio;
+import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
@@ -86,8 +87,11 @@ final class RealBufferedSink implements BufferedSink {
}
@Override public BufferedSink write(Source source, long byteCount) throws IOException {
- if (byteCount > 0) {
- source.read(buffer, byteCount);
+ while (byteCount > 0) {
+ long read = source.read(buffer, byteCount);
+ if (read == -1) throw new EOFException();
+ byteCount -= read;
+ emitCompleteSegments();
}
return this;
}
diff --git a/okio/src/test/java/okio/BufferedSinkTest.java b/okio/src/test/java/okio/BufferedSinkTest.java
index 879ecbdb..73a5cfbc 100644
--- a/okio/src/test/java/okio/BufferedSinkTest.java
+++ b/okio/src/test/java/okio/BufferedSinkTest.java
@@ -1,5 +1,6 @@
package okio;
+import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
@@ -170,6 +171,33 @@ public class BufferedSinkTest {
assertEquals("ef", source.readUtf8());
}
+ @Test public void writeSourceReadsFully() throws Exception {
+ Source source = new ForwardingSource(new Buffer()) {
+ @Override public long read(Buffer sink, long byteCount) throws IOException {
+ sink.writeUtf8("abcd");
+ return 4;
+ }
+ };
+
+ sink.write(source, 8);
+ sink.flush();
+ assertEquals("abcdabcd", data.readUtf8());
+ }
+
+ @Test public void writeSourcePropagatesEof() throws IOException {
+ Source source = new Buffer().writeUtf8("abcd");
+
+ try {
+ sink.write(source, 8);
+ fail();
+ } catch (EOFException expected) {
+ }
+
+ // Ensure that whatever was available was correctly written.
+ sink.flush();
+ assertEquals("abcd", data.readUtf8());
+ }
+
@Test public void writeSourceWithZeroIsNoOp() throws IOException {
// This test ensures that a zero byte count never calls through to read the source. It may be
// tied to something like a socket which will potentially block trying to read a segment when | ['okio/src/main/java/okio/RealBufferedSink.java', 'okio/src/main/java/okio/Buffer.java', 'okio/src/test/java/okio/BufferedSinkTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 157,834 | 38,438 | 4,856 | 23 | 495 | 127 | 14 | 2 | 271 | 45 | 60 | 4 | 0 | 0 | 2015-03-07T23:30:59 | 8,448 | Kotlin | {'Kotlin': 1473930, 'Java': 43685, 'Shell': 1180} | Apache License 2.0 |
3,548 | square/okio/130/129 | square | okio | https://github.com/square/okio/issues/129 | https://github.com/square/okio/pull/130 | https://github.com/square/okio/pull/130 | 1 | closes | DeflaterSink, InflaterSource may leave behind an empty tail | Both of these allocate a segment if necessary, but may end up not writing to that segment. We should write tests that exercise this situation and make sure we don't have a 0-byte segment still in a Buffer.
| d07412cc7cb917f852442d3d8ea056e374bad402 | 2526e7650dd965122e2a4a76d0f3c757d8e70353 | https://github.com/square/okio/compare/d07412cc7cb917f852442d3d8ea056e374bad402...2526e7650dd965122e2a4a76d0f3c757d8e70353 | diff --git a/okio/src/main/java/okio/DeflaterSink.java b/okio/src/main/java/okio/DeflaterSink.java
index 3b23655c..a5bca15d 100644
--- a/okio/src/main/java/okio/DeflaterSink.java
+++ b/okio/src/main/java/okio/DeflaterSink.java
@@ -99,7 +99,12 @@ public final class DeflaterSink implements Sink {
buffer.size += deflated;
sink.emitCompleteSegments();
} else if (deflater.needsInput()) {
- return; // TODO(jwilson): do we have a dangling empty tail segment here?
+ if (s.pos == s.limit) {
+ // We allocated a tail segment, but didn't end up needing it. Recycle!
+ buffer.head = s.pop();
+ SegmentPool.recycle(s);
+ }
+ return;
}
}
}
diff --git a/okio/src/main/java/okio/InflaterSource.java b/okio/src/main/java/okio/InflaterSource.java
index c38819dc..4011ca02 100644
--- a/okio/src/main/java/okio/InflaterSource.java
+++ b/okio/src/main/java/okio/InflaterSource.java
@@ -70,9 +70,13 @@ public final class InflaterSource implements Source {
sink.size += bytesInflated;
return bytesInflated;
}
- // TODO(jwilson): do we have an empty tail?
if (inflater.finished() || inflater.needsDictionary()) {
releaseInflatedBytes();
+ if (tail.pos == tail.limit) {
+ // We allocated a tail segment, but didn't end up needing it. Recycle!
+ sink.head = tail.pop();
+ SegmentPool.recycle(tail);
+ }
return -1;
}
if (sourceExhausted) throw new EOFException("source exhausted prematurely");
diff --git a/okio/src/main/java/okio/Okio.java b/okio/src/main/java/okio/Okio.java
index 8df1fde8..2b68d48b 100644
--- a/okio/src/main/java/okio/Okio.java
+++ b/okio/src/main/java/okio/Okio.java
@@ -130,6 +130,7 @@ public final class Okio {
return new Source() {
@Override public long read(Buffer sink, long byteCount) throws IOException {
if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount);
+ if (byteCount == 0) return 0;
timeout.throwIfReached();
Segment tail = sink.writableSegment(1);
int maxToCopy = (int) Math.min(byteCount, Segment.SIZE - tail.limit);
diff --git a/okio/src/test/java/okio/DeflaterSinkTest.java b/okio/src/test/java/okio/DeflaterSinkTest.java
index 87d6c598..b6cafb21 100644
--- a/okio/src/test/java/okio/DeflaterSinkTest.java
+++ b/okio/src/test/java/okio/DeflaterSinkTest.java
@@ -87,6 +87,24 @@ public final class DeflaterSinkTest {
assertEquals(repeat('a', byteCount), inflate(buffer).readUtf8(byteCount));
}
+ @Test public void deflateIntoNonemptySink() throws Exception {
+ String original = "They're moving in herds. They do move in herds.";
+
+ // Exercise all possible offsets for the outgoing segment.
+ for (int i = 0; i < Segment.SIZE; i++) {
+ Buffer data = new Buffer().writeUtf8(original);
+ Buffer sink = new Buffer().writeUtf8(repeat('a', i));
+
+ DeflaterSink deflaterSink = new DeflaterSink(sink, new Deflater());
+ deflaterSink.write(data, data.size());
+ deflaterSink.close();
+
+ sink.skip(i);
+ Buffer inflated = inflate(sink);
+ assertEquals(original, inflated.readUtf8());
+ }
+ }
+
/**
* This test deflates a single segment of without compression because that's
* the easiest way to force close() to emit a large amount of data to the
@@ -121,7 +139,9 @@ public final class DeflaterSinkTest {
byte[] buffer = new byte[8192];
while (!inflater.needsInput() || deflated.size() > 0 || deflatedIn.available() > 0) {
int count = inflatedIn.read(buffer, 0, buffer.length);
- result.write(buffer, 0, count);
+ if (count != -1) {
+ result.write(buffer, 0, count);
+ }
}
return result;
}
diff --git a/okio/src/test/java/okio/InflaterSourceTest.java b/okio/src/test/java/okio/InflaterSourceTest.java
index e32f18f2..d09d6d33 100644
--- a/okio/src/test/java/okio/InflaterSourceTest.java
+++ b/okio/src/test/java/okio/InflaterSourceTest.java
@@ -17,6 +17,7 @@ package okio;
import java.io.EOFException;
import java.io.IOException;
+import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import org.junit.Test;
@@ -74,6 +75,19 @@ public final class InflaterSourceTest {
assertEquals(original, inflated.readByteString());
}
+ @Test public void inflateIntoNonemptySink() throws Exception {
+ for (int i = 0; i < Segment.SIZE; i++) {
+ Buffer inflated = new Buffer().writeUtf8(repeat('a', i));
+ Buffer deflated = decodeBase64(
+ "eJxzz09RyEjNKVAoLdZRKE9VL0pVyMxTKMlIVchIzEspVshPU0jNS8/MS00tKtYDAF6CD5s=");
+ InflaterSource source = new InflaterSource(deflated, new Inflater());
+ while (source.read(inflated, Integer.MAX_VALUE) != -1) {
+ }
+ inflated.skip(i);
+ assertEquals("God help us, we're in the hands of engineers.", inflated.readUtf8());
+ }
+ }
+
private Buffer decodeBase64(String s) {
return new Buffer().write(ByteString.decodeBase64(s));
} | ['okio/src/main/java/okio/InflaterSource.java', 'okio/src/test/java/okio/InflaterSourceTest.java', 'okio/src/main/java/okio/DeflaterSink.java', 'okio/src/main/java/okio/Okio.java', 'okio/src/test/java/okio/DeflaterSinkTest.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 169,474 | 41,356 | 5,167 | 24 | 598 | 138 | 14 | 3 | 206 | 38 | 44 | 2 | 0 | 0 | 2015-03-16T03:10:50 | 8,448 | Kotlin | {'Kotlin': 1473930, 'Java': 43685, 'Shell': 1180} | Apache License 2.0 |
70 | dropwizard/dropwizard/2271/2268 | dropwizard | dropwizard | https://github.com/dropwizard/dropwizard/issues/2268 | https://github.com/dropwizard/dropwizard/pull/2271 | https://github.com/dropwizard/dropwizard/pull/2271 | 1 | resolves | ProxyServlet does not set Content-Length correctly for gzipped content | I have a Dropwizard application that uses a Jetty ProxyServlet to forward HTTP traffic. This works great when the HTTP traffic is not gzipped. When the HTTP traffic is gzipped, the proxy forwards a bad HTTP request.
The problem appears to be that when Dropwizard receives a gzipped HTTP request, the BiDiGzipHandler processes the request before the ProxyServlet. When the BiDiGzipHandler runs, it decompresses the payload and strips the `Content-Encoding: gzip` header. It does not modify the `Content-Length` header to reflect the length of the decompressed payload. When the ProxyServlet processes the request, it blindly copies the now incorrect `Content-Length` header (that reflects the length of the gzipped payload). It forwards the decompressed payload as the body though. When the request is received, you can see that the `Content-Length` does not reflect the length of the actual HTTP body.
I set up a simple test to demonstrate the problem.
I am running Dropwizard 1.0.0. I configured a ProxyServlet to forward all HTTP traffic matching the _/echo_ path.
```
// Register echo proxy
ServletRegistration echoServletRegistration =
environment.servlets().addServlet("EchoServlet", new ProxyServlet.Transparent());
echoServletRegistration.addMapping("/echo/*");
echoServletRegistration.setInitParameter("prefix", "/echo");
echoServletRegistration.setInitParameter(
"proxyTo", "http://localhost:47899");
```
I CURLed a normal HTTP POST to Dropwizard and used netcat to print what the proxy forwarded:
_test.sh_
```
#!/bin/bash
curl --data '@data.txt' \\
-H "Content-Type: application/json" \\
-X POST \\
http://localhost:8080/echo
```
_data.txt_ (length 19 bytes)
```
Hello, Dropwizard!
```
_netcat output_
```
$ nc -l 47899
POST / HTTP/1.1
User-Agent: curl/7.57.0
Accept: */*
Content-Type: application/json
Via: http/1.1 Jordans-MacBook-Pro.local
X-Forwarded-For: 127.0.0.1
X-Forwarded-Proto: http
X-Forwarded-Host: localhost:8080
X-Forwarded-Server: 127.0.0.1
Host: localhost:47899
Content-Length: 18
Hello, Dropwizard!
```
You can see the problem when I did the same thing gzipped.
_gzip-test.sh_
```
#!/bin/bash
curl --data-binary '@data.txt.gz' \\
-H "Content-Type: application/json" \\
-H "Content-Encoding: gzip" \\
-X POST \\
http://localhost:8080/echo
```
_data.txt.gz_ (length 48 bytes)
```
ã∫Ù}Z | b8f6c8f576ddfe1b4b62377da7beb3ec8be31f6c | 6d86f8afde0a0a2480a1d7744960dd2f26103c74 | https://github.com/dropwizard/dropwizard/compare/b8f6c8f576ddfe1b4b62377da7beb3ec8be31f6c...6d86f8afde0a0a2480a1d7744960dd2f26103c74 | diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java
index 375f42539..cdcca89c1 100644
--- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java
+++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java
@@ -1,5 +1,6 @@
package io.dropwizard.jetty;
+import com.google.common.collect.ImmutableSortedSet;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
@@ -59,12 +60,12 @@ public class BiDiGzipHandler extends GzipHandler {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
+ throws IOException, ServletException {
final String encoding = request.getHeader(HttpHeader.CONTENT_ENCODING.asString());
if (GZIP.equalsIgnoreCase(encoding)) {
- super.handle(target, baseRequest, wrapGzippedRequest(removeContentEncodingHeader(request)), response);
+ super.handle(target, baseRequest, wrapGzippedRequest(removeContentHeaders(request)), response);
} else if (DEFLATE.equalsIgnoreCase(encoding)) {
- super.handle(target, baseRequest, wrapDeflatedRequest(removeContentEncodingHeader(request)), response);
+ super.handle(target, baseRequest, wrapDeflatedRequest(removeContentHeaders(request)), response);
} else {
super.handle(target, baseRequest, request, response);
}
@@ -110,8 +111,13 @@ public class BiDiGzipHandler extends GzipHandler {
}
}
- private HttpServletRequest removeContentEncodingHeader(final HttpServletRequest request) {
- return new RemoveHttpHeaderWrapper(request, HttpHeader.CONTENT_ENCODING.asString());
+ private HttpServletRequest removeContentHeaders(final HttpServletRequest request) {
+ // The decoded content is plain and generated dynamically, therefore the "Content-Encoding" and "Content-Length"
+ // headers should be removed after after the processing.
+ return new RemoveHttpHeadersWrapper(request, ImmutableSortedSet.orderedBy(String::compareToIgnoreCase)
+ .add(HttpHeader.CONTENT_ENCODING.asString())
+ .add(HttpHeader.CONTENT_LENGTH.asString())
+ .build());
}
private static class WrappedServletRequest extends HttpServletRequestWrapper {
@@ -142,6 +148,17 @@ public class BiDiGzipHandler extends GzipHandler {
public BufferedReader getReader() throws IOException {
return reader;
}
+
+ @Override
+ public int getContentLength() {
+ // Because the we replace the original stream, the new content length is not known.
+ return -1;
+ }
+
+ @Override
+ public long getContentLengthLong() {
+ return -1L;
+ }
}
private static class WrappedServletInputStream extends ServletInputStream {
@@ -220,12 +237,12 @@ public class BiDiGzipHandler extends GzipHandler {
}
}
- private static class RemoveHttpHeaderWrapper extends HttpServletRequestWrapper {
- private final String headerName;
+ private static class RemoveHttpHeadersWrapper extends HttpServletRequestWrapper {
+ private final ImmutableSortedSet<String> headerNames;
- RemoveHttpHeaderWrapper(final HttpServletRequest request, final String headerName) {
+ RemoveHttpHeadersWrapper(final HttpServletRequest request, final ImmutableSortedSet<String> headerNames) {
super(request);
- this.headerName = headerName;
+ this.headerNames = headerNames;
}
/**
@@ -236,7 +253,7 @@ public class BiDiGzipHandler extends GzipHandler {
*/
@Override
public int getIntHeader(final String name) {
- if (headerName.equalsIgnoreCase(name)) {
+ if (headerNames.contains(name)) {
return -1;
} else {
return super.getIntHeader(name);
@@ -251,7 +268,7 @@ public class BiDiGzipHandler extends GzipHandler {
*/
@Override
public Enumeration<String> getHeaders(final String name) {
- if (headerName.equalsIgnoreCase(name)) {
+ if (headerNames.contains(name)) {
return Collections.emptyEnumeration();
} else {
return super.getHeaders(name);
@@ -267,7 +284,7 @@ public class BiDiGzipHandler extends GzipHandler {
@Override
@Nullable
public String getHeader(final String name) {
- if (headerName.equalsIgnoreCase(name)) {
+ if (headerNames.contains(name)) {
return null;
} else {
return super.getHeader(name);
@@ -282,7 +299,7 @@ public class BiDiGzipHandler extends GzipHandler {
*/
@Override
public long getDateHeader(final String name) {
- if (headerName.equalsIgnoreCase(name)) {
+ if (headerNames.contains(name)) {
return -1L;
} else {
return super.getDateHeader(name);
diff --git a/dropwizard-jetty/src/test/java/io/dropwizard/jetty/BiDiGzipHandlerTest.java b/dropwizard-jetty/src/test/java/io/dropwizard/jetty/BiDiGzipHandlerTest.java
index 711aebde4..fbf8c781b 100644
--- a/dropwizard-jetty/src/test/java/io/dropwizard/jetty/BiDiGzipHandlerTest.java
+++ b/dropwizard-jetty/src/test/java/io/dropwizard/jetty/BiDiGzipHandlerTest.java
@@ -162,6 +162,9 @@ public class BiDiGzipHandlerTest {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
assertThat(req.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualToIgnoringCase(PLAIN_TEXT_UTF_8);
assertThat(req.getHeader(HttpHeaders.CONTENT_ENCODING)).isNull();
+ assertThat(req.getHeader(HttpHeaders.CONTENT_LENGTH)).isNull();
+ assertThat(req.getContentLength()).isEqualTo(-1);
+ assertThat(req.getContentLengthLong()).isEqualTo(-1L);
assertThat(CharStreams.toString(req.getReader())).isEqualTo(
Resources.toString(Resources.getResource("assets/new-banner.txt"), StandardCharsets.UTF_8));
| ['dropwizard-jetty/src/test/java/io/dropwizard/jetty/BiDiGzipHandlerTest.java', 'dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipHandler.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,112,021 | 221,697 | 33,050 | 447 | 2,599 | 438 | 43 | 1 | 3,185 | 298 | 862 | 94 | 3 | 7 | 2018-02-10T11:51:38 | 8,421 | Java | {'Java': 2800516, 'Shell': 6214, 'FreeMarker': 992, 'Mustache': 569, 'HTML': 111} | Apache License 2.0 |
68 | dropwizard/dropwizard/5037/4943 | dropwizard | dropwizard | https://github.com/dropwizard/dropwizard/issues/4943 | https://github.com/dropwizard/dropwizard/pull/5037 | https://github.com/dropwizard/dropwizard/pull/5037 | 1 | closes | fix dropwizard-health log message | HealthCheckScheduler log message doesn't log the _value_ of the Counter object, but logs the object instead.
> DEBUG [2022-03-09 20:47:59,008] io.dropwizard.health.HealthCheckScheduler [thread=health-check-example-app-1]: Scheduled check: check=ScheduledHealthCheck{name='example-app-db', critical=true, healthCheck=io.dropwizard.jdbi3.JdbiHealthCheck@46a488c2, schedule=io.dropwizard.health.Schedule@626b286d, state=State{name='example-app-db', successAttempts=2, failureAttempts=3, healthStateListener=io.dropwizard.health.HealthCheckManager@43e1692f, counter=0, healthy=true}, healthyCheckCounter=com.codahale.metrics.Counter@6242ae3b, unhealthyCheckCounter=com.codahale.metrics.Counter@65ddee5a}
Dropwizard version: 2.1.0-beta.7 | d0a2fa78d630abca82f3c202700045a215cdec26 | 8100f17382a836f111d70bf6c5ba285f8989e755 | https://github.com/dropwizard/dropwizard/compare/d0a2fa78d630abca82f3c202700045a215cdec26...8100f17382a836f111d70bf6c5ba285f8989e755 | diff --git a/dropwizard-health/src/main/java/io/dropwizard/health/ScheduledHealthCheck.java b/dropwizard-health/src/main/java/io/dropwizard/health/ScheduledHealthCheck.java
index 349c6001d..ecec175c2 100644
--- a/dropwizard-health/src/main/java/io/dropwizard/health/ScheduledHealthCheck.java
+++ b/dropwizard-health/src/main/java/io/dropwizard/health/ScheduledHealthCheck.java
@@ -111,9 +111,13 @@ class ScheduledHealthCheck implements Runnable {
sb.append(", healthCheck=").append(healthCheck);
sb.append(", schedule=").append(schedule);
sb.append(", state=").append(state);
- sb.append(", healthyCheckCounter=").append(healthyCheckCounter);
- sb.append(", unhealthyCheckCounter=").append(unhealthyCheckCounter);
+ sb.append(", healthyCheckCounter=").append(getCounterString(healthyCheckCounter));
+ sb.append(", unhealthyCheckCounter=").append(getCounterString(unhealthyCheckCounter));
sb.append('}');
return sb.toString();
}
+
+ private String getCounterString(Counter counter) {
+ return Counter.class.equals(counter.getClass()) ? String.valueOf(counter.getCount()) : counter.toString();
+ }
} | ['dropwizard-health/src/main/java/io/dropwizard/health/ScheduledHealthCheck.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,282,196 | 258,084 | 38,033 | 472 | 520 | 94 | 8 | 1 | 740 | 39 | 200 | 6 | 0 | 0 | 2022-03-26T18:30:18 | 8,421 | Java | {'Java': 2800516, 'Shell': 6214, 'FreeMarker': 992, 'Mustache': 569, 'HTML': 111} | Apache License 2.0 |
69 | dropwizard/dropwizard/2643/2523 | dropwizard | dropwizard | https://github.com/dropwizard/dropwizard/issues/2523 | https://github.com/dropwizard/dropwizard/pull/2643 | https://github.com/dropwizard/dropwizard/pull/2643 | 1 | closes | DropwizardTestSupport should clean system properties (config overrides) on service startup failure | We had a few test classes using both `DropwizardAppRule` and `DropwizardClientRule` (`DropwizardClientRule` around `DropwizardAppRule`). The service started by the `DropwizardAppRule` would fail on startup because of some environment problem. The _config override_ properties would stick around for the following tests causing unexpected behavior.
The problem seems to be that in the `before` method, overrides are set as system properties but are not cleaned/reset in case the service fails to start.
```java
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.setup.Environment;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.DropwizardTestSupport;
import io.dropwizard.testing.ResourceHelpers;
import org.junit.Test;
import org.junit.runners.model.Statement;
import static junit.framework.TestCase.assertNull;
public class IntTestReproduce {
@Test
public void dropwizardTestSupportShouldCleanSystemPropertiesOnServiceStartupFailure() {
assertNull(System.getProperty("dw.dummyProperty"));
final DropwizardTestSupport<TestConfiguration> testSupport = new DropwizardTestSupport<>(TestService.class,
ResourceHelpers.resourceFilePath("config.yml"),
ConfigOverride.config("dummyProperty", "dummy"));
try {
testSupport.before();
} catch (Exception e) {
// expected since the service will throw on startup
}
// Since ExternalResource will not call `after()` on exception, maybe DropwizardTestSupport should
// clean system properties. Otherwise the properties stick around and might affect the following tests.
assertNull(String.format("System property is not null. The value is [%s]",
System.getProperty("dw.dummyProperty")),
System.getProperty("dw.dummyProperty"));
}
public static class TestService extends Application<TestConfiguration> {
@Override
public void run(TestConfiguration testConfiguration, Environment environment) throws Exception {
throw new RuntimeException("fail");
}
}
public static class TestConfiguration extends Configuration {
private String dummyProperty;
@JsonProperty("dummyProperty")
public String getDummyProperty() {
return dummyProperty;
}
public void setDummyProperty(String dummyProperty) {
this.dummyProperty = dummyProperty;
}
}
private static final Statement TEST_STATEMENT = new Statement() {
@Override
public void evaluate() {
}
};
}
```
| 1a34237e2e5119eced9c50f396fcd46644380a27 | 24650677e14264ae819c17e1f7a917684ce29446 | https://github.com/dropwizard/dropwizard/compare/1a34237e2e5119eced9c50f396fcd46644380a27...24650677e14264ae819c17e1f7a917684ce29446 | diff --git a/dropwizard-e2e/src/test/java/com/example/badlog/BadLogTest.java b/dropwizard-e2e/src/test/java/com/example/badlog/BadLogTest.java
index 03dd9abf9..147ce4337 100644
--- a/dropwizard-e2e/src/test/java/com/example/badlog/BadLogTest.java
+++ b/dropwizard-e2e/src/test/java/com/example/badlog/BadLogTest.java
@@ -66,11 +66,17 @@ public class BadLogTest {
// Clear out the log file
Files.write(logFile, new byte[]{});
+ final ConfigOverride logOverride = ConfigOverride.config("logging.appenders[0].currentLogFilename", logFile.toString());
final String configPath = ResourceHelpers.resourceFilePath("badlog/config.yaml");
- final DropwizardTestSupport<Configuration> app = new DropwizardTestSupport<>(BadLogApp.class, configPath,
- ConfigOverride.config("logging.appenders[0].currentLogFilename", logFile.toString()));
+ final DropwizardTestSupport<Configuration> app = new DropwizardTestSupport<>(BadLogApp.class, configPath, logOverride);
assertThatThrownBy(app::before).hasMessage("I'm a bad app");
+ // Dropwizard test support resets configuration overrides if `before` throws an exception
+ // which is fine, as that would normally signal the end of the test, but since we're
+ // testing logging behavior that is setup in the application `run` method, we need
+ // to ensure our log override is still present (it's removed again in `after`)
+ logOverride.addToSystemProperties();
+
// Explicitly run the command so that the fatal error function runs
app.getApplication().run("server", configPath);
app.after();
@@ -109,10 +115,12 @@ public class BadLogTest {
// Clear out the log file
Files.write(logFile, new byte[]{});
- final DropwizardTestSupport<Configuration> app3 = new DropwizardTestSupport<>(BadLogApp.class, configPath,
- ConfigOverride.config("logging.appenders[0].currentLogFilename", logFile.toString()));
+ final DropwizardTestSupport<Configuration> app3 = new DropwizardTestSupport<>(BadLogApp.class, configPath, logOverride);
assertThatThrownBy(app3::before).hasMessage("I'm a bad app");
+ // See comment above about manually adding config to system properties
+ logOverride.addToSystemProperties();
+
// Explicitly run the command so that the fatal error function runs
app3.getApplication().run("server", configPath);
app3.after();
diff --git a/dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java b/dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java
index c1942ead6..0d8cefa63 100644
--- a/dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java
+++ b/dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java
@@ -147,7 +147,16 @@ public class DropwizardTestSupport<C extends Configuration> {
public void before() {
applyConfigOverrides();
- startIfRequired();
+ try {
+ startIfRequired();
+ } catch (Exception e) {
+
+ // If there's an exception when setting up the server / application,
+ // manually call after as junit does not call the after method if
+ // the `before` method throws.
+ after();
+ throw e;
+ }
}
public void after() { | ['dropwizard-testing/src/main/java/io/dropwizard/testing/DropwizardTestSupport.java', 'dropwizard-e2e/src/test/java/com/example/badlog/BadLogTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,180,292 | 236,711 | 35,173 | 471 | 369 | 69 | 11 | 1 | 2,814 | 236 | 498 | 71 | 0 | 1 | 2019-02-12T13:05:01 | 8,421 | Java | {'Java': 2800516, 'Shell': 6214, 'FreeMarker': 992, 'Mustache': 569, 'HTML': 111} | Apache License 2.0 |
8,247 | trinodb/trino/17804/17803 | trinodb | trino | https://github.com/trinodb/trino/issues/17803 | https://github.com/trinodb/trino/pull/17804 | https://github.com/trinodb/trino/pull/17804 | 1 | fixes | Correctness issue with double slash location on Glue & S3 in Hive connector | The file is generated correctly under the table location, but it returns an empty result. Delta and Iceberg connectors are fine as far as I confirmed.
```sql
create table test_slash (c1 int) with (external_location = 's3://bucket/foo//bar');
insert into test_slash values (1);
table test_slash;
c1
----
(0 rows)
``` | eaf893a74737d877aeb4e6cd267a8018203a632d | 8cb4bd1b5e81541b96c5faeb725126a698789144 | https://github.com/trinodb/trino/compare/eaf893a74737d877aeb4e6cd267a8018203a632d...8cb4bd1b5e81541b96c5faeb725126a698789144 | diff --git a/plugin/trino-delta-lake/src/test/java/io/trino/plugin/deltalake/metastore/glue/TestDeltaLakeConcurrentModificationGlueMetastore.java b/plugin/trino-delta-lake/src/test/java/io/trino/plugin/deltalake/metastore/glue/TestDeltaLakeConcurrentModificationGlueMetastore.java
index f4aaad4880..de99991545 100644
--- a/plugin/trino-delta-lake/src/test/java/io/trino/plugin/deltalake/metastore/glue/TestDeltaLakeConcurrentModificationGlueMetastore.java
+++ b/plugin/trino-delta-lake/src/test/java/io/trino/plugin/deltalake/metastore/glue/TestDeltaLakeConcurrentModificationGlueMetastore.java
@@ -17,6 +17,8 @@ import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.glue.AWSGlueAsync;
import com.amazonaws.services.glue.model.ConcurrentModificationException;
import io.trino.Session;
+import io.trino.filesystem.hdfs.HdfsFileSystemFactory;
+import io.trino.hdfs.TrinoHdfsFileSystemStats;
import io.trino.plugin.deltalake.TestingDeltaLakePlugin;
import io.trino.plugin.deltalake.metastore.TestingDeltaLakeMetastoreModule;
import io.trino.plugin.hive.metastore.glue.DefaultGlueColumnStatisticsProviderFactory;
@@ -92,6 +94,7 @@ public class TestDeltaLakeConcurrentModificationGlueMetastore
});
metastore = new GlueHiveMetastore(
+ new HdfsFileSystemFactory(HDFS_ENVIRONMENT, new TrinoHdfsFileSystemStats()),
HDFS_ENVIRONMENT,
glueConfig,
directExecutor(),
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/BackgroundHiveSplitLoader.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/BackgroundHiveSplitLoader.java
index 1da5e9d99c..354fc61f27 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/BackgroundHiveSplitLoader.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/BackgroundHiveSplitLoader.java
@@ -106,6 +106,7 @@ import static com.google.common.util.concurrent.Futures.immediateVoidFuture;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static io.airlift.concurrent.MoreFutures.addExceptionCallback;
import static io.airlift.concurrent.MoreFutures.toListenableFuture;
+import static io.trino.filesystem.hdfs.HadoopPaths.hadoopPath;
import static io.trino.hdfs.ConfigurationUtils.toJobConf;
import static io.trino.plugin.hive.HiveErrorCode.HIVE_BAD_DATA;
import static io.trino.plugin.hive.HiveErrorCode.HIVE_EXCEEDED_PARTITION_LIMIT;
@@ -429,7 +430,8 @@ public class BackgroundHiveSplitLoader
return COMPLETED_FUTURE;
}
- Path path = new Path(getPartitionLocation(table, partition.getPartition()));
+ Location location = Location.of(getPartitionLocation(table, partition.getPartition()));
+ Path path = hadoopPath(location);
Configuration configuration = hdfsEnvironment.getConfiguration(hdfsContext, path);
InputFormat<?, ?> inputFormat = getInputFormat(configuration, schema, false);
FileSystem fs = hdfsEnvironment.getFileSystem(hdfsContext, path);
@@ -548,7 +550,6 @@ public class BackgroundHiveSplitLoader
}
TrinoFileSystem trinoFileSystem = fileSystemFactory.create(session);
- Location location = Location.of(path.toString());
// Bucketed partitions are fully loaded immediately since all files must be loaded to determine the file to bucket mapping
if (tableBucketInfo.isPresent()) {
List<TrinoFileStatus> files = listBucketFiles(trinoFileSystem, location, splitFactory.getPartitionName());
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveLocationService.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveLocationService.java
index 6da35e45ba..e91e99e58d 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveLocationService.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveLocationService.java
@@ -27,6 +27,7 @@ import org.apache.hadoop.fs.Path;
import java.util.Optional;
+import static io.trino.filesystem.hdfs.HadoopPaths.hadoopPath;
import static io.trino.plugin.hive.HiveErrorCode.HIVE_PATH_ALREADY_EXISTS;
import static io.trino.plugin.hive.LocationHandle.WriteMode.DIRECT_TO_TARGET_EXISTING_DIRECTORY;
import static io.trino.plugin.hive.LocationHandle.WriteMode.DIRECT_TO_TARGET_NEW_DIRECTORY;
@@ -63,7 +64,7 @@ public class HiveLocationService
Location targetPath = getTableDefaultLocation(context, metastore, hdfsEnvironment, schemaName, tableName);
// verify the target directory for table
- if (pathExists(context, hdfsEnvironment, new Path(targetPath.toString()))) {
+ if (pathExists(context, hdfsEnvironment, hadoopPath(targetPath))) {
throw new TrinoException(HIVE_PATH_ALREADY_EXISTS, format("Target directory for table '%s.%s' already exists: %s", schemaName, tableName, targetPath));
}
return targetPath;
@@ -76,13 +77,13 @@ public class HiveLocationService
Location targetPath = externalLocation.orElseGet(() -> getTableDefaultLocation(context, metastore, hdfsEnvironment, schemaName, tableName));
// verify the target directory for the table
- if (pathExists(context, hdfsEnvironment, new Path(targetPath.toString()))) {
+ if (pathExists(context, hdfsEnvironment, hadoopPath(targetPath))) {
throw new TrinoException(HIVE_PATH_ALREADY_EXISTS, format("Target directory for table '%s.%s' already exists: %s", schemaName, tableName, targetPath));
}
// TODO detect when existing table's location is a on a different file system than the temporary directory
- if (shouldUseTemporaryDirectory(context, new Path(targetPath.toString()), externalLocation.isPresent())) {
- Location writePath = createTemporaryPath(context, hdfsEnvironment, new Path(targetPath.toString()), temporaryStagingDirectoryPath);
+ if (shouldUseTemporaryDirectory(context, hadoopPath(targetPath), externalLocation.isPresent())) {
+ Location writePath = createTemporaryPath(context, hdfsEnvironment, hadoopPath(targetPath), temporaryStagingDirectoryPath);
return new LocationHandle(targetPath, writePath, STAGE_AND_MOVE_TO_TARGET_DIRECTORY);
}
return new LocationHandle(targetPath, targetPath, DIRECT_TO_TARGET_NEW_DIRECTORY);
@@ -94,8 +95,8 @@ public class HiveLocationService
HdfsContext context = new HdfsContext(session);
Location targetPath = Location.of(table.getStorage().getLocation());
- if (shouldUseTemporaryDirectory(context, new Path(targetPath.toString()), false) && !isTransactionalTable(table.getParameters())) {
- Location writePath = createTemporaryPath(context, hdfsEnvironment, new Path(targetPath.toString()), temporaryStagingDirectoryPath);
+ if (shouldUseTemporaryDirectory(context, hadoopPath(targetPath), false) && !isTransactionalTable(table.getParameters())) {
+ Location writePath = createTemporaryPath(context, hdfsEnvironment, hadoopPath(targetPath), temporaryStagingDirectoryPath);
return new LocationHandle(targetPath, writePath, STAGE_AND_MOVE_TO_TARGET_DIRECTORY);
}
return new LocationHandle(targetPath, targetPath, DIRECT_TO_TARGET_EXISTING_DIRECTORY);
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveMetadata.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveMetadata.java
index 564f128dd2..cd3d0dc742 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveMetadata.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveMetadata.java
@@ -165,6 +165,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.getOnlyElement;
+import static io.trino.filesystem.hdfs.HadoopPaths.hadoopPath;
import static io.trino.hdfs.ConfigurationUtils.toJobConf;
import static io.trino.plugin.hive.HiveAnalyzeProperties.getColumnNames;
import static io.trino.plugin.hive.HiveAnalyzeProperties.getPartitionList;
@@ -1734,7 +1735,7 @@ public class HiveMetadata
partitionUpdates = PartitionUpdate.mergePartitionUpdates(concat(partitionUpdates, partitionUpdatesForMissingBuckets));
for (PartitionUpdate partitionUpdate : partitionUpdatesForMissingBuckets) {
Optional<Partition> partition = table.getPartitionColumns().isEmpty() ? Optional.empty() : Optional.of(buildPartitionObject(session, table, partitionUpdate));
- createEmptyFiles(session, partitionUpdate.getWritePath(), table, partition, partitionUpdate.getFileNames());
+ createEmptyFiles(session, hadoopPath(partitionUpdate.getWritePath()), table, partition, partitionUpdate.getFileNames());
}
if (handle.isTransactional()) {
AcidTransaction transaction = handle.getTransaction();
@@ -1765,7 +1766,7 @@ public class HiveMetadata
tableStatistics = new PartitionStatistics(createEmptyStatistics(), ImmutableMap.of());
}
- Optional<Path> writePath = Optional.of(new Path(writeInfo.writePath().toString()));
+ Optional<Location> writePath = Optional.of(Location.of(writeInfo.writePath().toString()));
if (handle.getPartitionedBy().isEmpty()) {
List<String> fileNames;
if (partitionUpdates.isEmpty()) {
@@ -1845,7 +1846,7 @@ public class HiveMetadata
private List<String> computeFileNamesForMissingBuckets(
ConnectorSession session,
HiveStorageFormat storageFormat,
- Path targetPath,
+ Location targetPath,
int bucketCount,
boolean transactionalCreateTable,
PartitionUpdate partitionUpdate)
@@ -1855,7 +1856,7 @@ public class HiveMetadata
return ImmutableList.of();
}
HdfsContext hdfsContext = new HdfsContext(session);
- JobConf conf = toJobConf(hdfsEnvironment.getConfiguration(hdfsContext, targetPath));
+ JobConf conf = toJobConf(hdfsEnvironment.getConfiguration(hdfsContext, hadoopPath(targetPath)));
configureCompression(conf, selectCompressionCodec(session, storageFormat));
String fileExtension = HiveWriterFactory.getFileExtension(conf, fromHiveStorageFormat(storageFormat));
Set<String> fileNames = ImmutableSet.copyOf(partitionUpdate.getFileNames());
@@ -2141,7 +2142,7 @@ public class HiveMetadata
statistics,
handle.isRetriesEnabled());
}
- createEmptyFiles(session, partitionUpdate.getWritePath(), table, partition, partitionUpdate.getFileNames());
+ createEmptyFiles(session, hadoopPath(partitionUpdate.getWritePath()), table, partition, partitionUpdate.getFileNames());
}
}
@@ -2227,10 +2228,10 @@ public class HiveMetadata
getColumnStatistics(partitionComputedStatistics, partitionName, partitionValues, partitionTypes));
if (partitionUpdate.getUpdateMode() == OVERWRITE) {
if (handle.getLocationHandle().getWriteMode() == DIRECT_TO_TARGET_EXISTING_DIRECTORY) {
- removeNonCurrentQueryFiles(session, partitionUpdate.getTargetPath());
+ removeNonCurrentQueryFiles(session, hadoopPath(partitionUpdate.getTargetPath()));
if (handle.isRetriesEnabled()) {
HdfsContext hdfsContext = new HdfsContext(session);
- cleanExtraOutputFiles(hdfsEnvironment, hdfsContext, session.getQueryId(), partitionUpdate.getTargetPath(), ImmutableSet.copyOf(partitionUpdate.getFileNames()));
+ cleanExtraOutputFiles(hdfsEnvironment, hdfsContext, session.getQueryId(), hadoopPath(partitionUpdate.getTargetPath()), ImmutableSet.copyOf(partitionUpdate.getFileNames()));
}
}
else {
@@ -2555,22 +2556,22 @@ public class HiveMetadata
}
// path to be deleted
- Set<Path> scannedPaths = splitSourceInfo.stream()
- .map(file -> new Path((String) file))
+ Set<Location> scannedPaths = splitSourceInfo.stream()
+ .map(file -> Location.of((String) file))
.collect(toImmutableSet());
// track remaining files to be delted for error reporting
- Set<Path> remainingFilesToDelete = new HashSet<>(scannedPaths);
+ Set<Location> remainingFilesToDelete = new HashSet<>(scannedPaths);
// delete loop
boolean someDeleted = false;
- Optional<Path> firstScannedPath = Optional.empty();
+ Optional<Location> firstScannedPath = Optional.empty();
try {
- for (Path scannedPath : scannedPaths) {
+ for (Location scannedPath : scannedPaths) {
if (firstScannedPath.isEmpty()) {
firstScannedPath = Optional.of(scannedPath);
}
retry().run("delete " + scannedPath, () -> {
- checkedDelete(fs, scannedPath, false);
+ checkedDelete(fs, hadoopPath(scannedPath), false);
return null;
});
someDeleted = true;
@@ -2578,7 +2579,7 @@ public class HiveMetadata
}
}
catch (Exception e) {
- if (!someDeleted && (firstScannedPath.isEmpty() || exists(fs, firstScannedPath.get()))) {
+ if (!someDeleted && (firstScannedPath.isEmpty() || exists(fs, hadoopPath(firstScannedPath.get())))) {
// we are good - we did not delete any source files so we can just throw error and allow rollback to happend
// if someDeleted flag is false we do extra checkig if first file we tried to delete is still there. There is a chance that
// fs.delete above could throw exception but file was actually deleted.
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveWriter.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveWriter.java
index 7628b45362..4445ff3556 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveWriter.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveWriter.java
@@ -14,6 +14,7 @@
package io.trino.plugin.hive;
import com.google.common.collect.ImmutableList;
+import io.trino.filesystem.Location;
import io.trino.plugin.hive.PartitionUpdate.UpdateMode;
import io.trino.spi.Page;
@@ -114,8 +115,8 @@ public class HiveWriter
return new PartitionUpdate(
partitionName.orElse(""),
updateMode,
- writePath,
- targetPath,
+ Location.of(writePath),
+ Location.of(targetPath),
ImmutableList.of(fileName),
rowCount,
inputSizeInBytes,
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/PartitionUpdate.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/PartitionUpdate.java
index 926d02ae35..e6b26cf332 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/PartitionUpdate.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/PartitionUpdate.java
@@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimaps;
+import io.trino.filesystem.Location;
import io.trino.spi.TrinoException;
-import org.apache.hadoop.fs.Path;
import java.util.Collection;
import java.util.List;
@@ -33,8 +33,8 @@ public class PartitionUpdate
{
private final String name;
private final UpdateMode updateMode;
- private final Path writePath;
- private final Path targetPath;
+ private final Location writePath;
+ private final Location targetPath;
private final List<String> fileNames;
private final long rowCount;
private final long inMemoryDataSizeInBytes;
@@ -54,8 +54,8 @@ public class PartitionUpdate
this(
name,
updateMode,
- new Path(requireNonNull(writePath, "writePath is null")),
- new Path(requireNonNull(targetPath, "targetPath is null")),
+ Location.of(requireNonNull(writePath, "writePath is null")),
+ Location.of(requireNonNull(targetPath, "targetPath is null")),
fileNames,
rowCount,
inMemoryDataSizeInBytes,
@@ -65,8 +65,8 @@ public class PartitionUpdate
public PartitionUpdate(
String name,
UpdateMode updateMode,
- Path writePath,
- Path targetPath,
+ Location writePath,
+ Location targetPath,
List<String> fileNames,
long rowCount,
long inMemoryDataSizeInBytes,
@@ -101,12 +101,12 @@ public class PartitionUpdate
return updateMode;
}
- public Path getWritePath()
+ public Location getWritePath()
{
return writePath;
}
- public Path getTargetPath()
+ public Location getTargetPath()
{
return targetPath;
}
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/SemiTransactionalHiveMetastore.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/SemiTransactionalHiveMetastore.java
index 3e453c80d7..4aaf7410d6 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/SemiTransactionalHiveMetastore.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/SemiTransactionalHiveMetastore.java
@@ -98,6 +98,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static io.airlift.concurrent.MoreFutures.getFutureValue;
+import static io.trino.filesystem.hdfs.HadoopPaths.hadoopPath;
import static io.trino.plugin.hive.HiveErrorCode.HIVE_CORRUPTED_COLUMN_STATISTICS;
import static io.trino.plugin.hive.HiveErrorCode.HIVE_FILESYSTEM_ERROR;
import static io.trino.plugin.hive.HiveErrorCode.HIVE_METASTORE_ERROR;
@@ -562,7 +563,7 @@ public class SemiTransactionalHiveMetastore
ConnectorSession session,
Table table,
PrincipalPrivileges principalPrivileges,
- Optional<Path> currentPath,
+ Optional<Location> currentPath,
Optional<List<String>> files,
boolean ignoreExisting,
PartitionStatistics statistics,
@@ -680,7 +681,7 @@ public class SemiTransactionalHiveMetastore
ConnectorSession session,
String databaseName,
String tableName,
- Path currentLocation,
+ Location currentLocation,
List<String> fileNames,
PartitionStatistics statisticsUpdate,
boolean cleanExtraOutputFilesOnCommit)
@@ -792,7 +793,7 @@ public class SemiTransactionalHiveMetastore
new TableAndMergeResults(
table,
Optional.of(principalPrivileges),
- Optional.of(new Path(currentLocation.toString())),
+ Optional.of(currentLocation),
partitionUpdateAndMergeResults,
partitions),
hdfsContext,
@@ -968,7 +969,7 @@ public class SemiTransactionalHiveMetastore
String databaseName,
String tableName,
Partition partition,
- Path currentLocation,
+ Location currentLocation,
Optional<List<String>> files,
PartitionStatistics statistics,
boolean cleanExtraOutputFilesOnCommit)
@@ -1733,16 +1734,16 @@ public class SemiTransactionalHiveMetastore
}
}
- Path currentPath = tableAndMore.getCurrentLocation()
+ Location currentPath = tableAndMore.getCurrentLocation()
.orElseThrow(() -> new IllegalArgumentException("location should be present for alter table"));
- Path targetPath = new Path(targetLocation);
+ Location targetPath = Location.of(targetLocation);
if (!targetPath.equals(currentPath)) {
renameDirectory(
hdfsContext,
hdfsEnvironment,
- currentPath,
- targetPath,
- () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, targetPath, true)));
+ hadoopPath(currentPath),
+ hadoopPath(targetPath),
+ () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, hadoopPath(targetPath), true)));
}
// Partition alter must happen regardless of whether original and current location is the same
// because metadata might change: e.g. storage format, column types, etc
@@ -1766,8 +1767,8 @@ public class SemiTransactionalHiveMetastore
Optional<String> targetLocation = table.getStorage().getOptionalLocation();
if (targetLocation.isPresent()) {
checkArgument(!targetLocation.get().isEmpty(), "target location is empty");
- Optional<Path> currentPath = tableAndMore.getCurrentLocation();
- Path targetPath = new Path(targetLocation.get());
+ Optional<Location> currentPath = tableAndMore.getCurrentLocation();
+ Location targetPath = Location.of(targetLocation.get());
if (table.getPartitionColumns().isEmpty() && currentPath.isPresent()) {
// CREATE TABLE AS SELECT unpartitioned table
if (targetPath.equals(currentPath.get())) {
@@ -1777,15 +1778,15 @@ public class SemiTransactionalHiveMetastore
renameDirectory(
context,
hdfsEnvironment,
- currentPath.get(),
- targetPath,
- () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, targetPath, true)));
+ hadoopPath(currentPath.get()),
+ hadoopPath(targetPath),
+ () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, hadoopPath(targetPath), true)));
}
}
else {
// CREATE TABLE AS SELECT partitioned table, or
// CREATE TABLE partitioned/unpartitioned table (without data)
- if (pathExists(context, hdfsEnvironment, targetPath)) {
+ if (pathExists(context, hdfsEnvironment, hadoopPath(targetPath))) {
if (currentPath.isPresent() && currentPath.get().equals(targetPath)) {
// It is okay to skip directory creation when currentPath is equal to targetPath
// because the directory may have been created when creating partition directories.
@@ -1799,8 +1800,8 @@ public class SemiTransactionalHiveMetastore
}
}
else {
- cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, targetPath, true));
- createDirectory(context, hdfsEnvironment, targetPath);
+ cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, hadoopPath(targetPath), true));
+ createDirectory(context, hdfsEnvironment, hadoopPath(targetPath));
}
}
}
@@ -1813,10 +1814,10 @@ public class SemiTransactionalHiveMetastore
{
deleteOnly = false;
Table table = tableAndMore.getTable();
- Path targetPath = new Path(table.getStorage().getLocation());
+ Location targetPath = Location.of(table.getStorage().getLocation());
tablesToInvalidate.add(table);
- Path currentPath = tableAndMore.getCurrentLocation().orElseThrow();
- cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, targetPath, false));
+ Location currentPath = Location.of(tableAndMore.getCurrentLocation().orElseThrow().toString());
+ cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, hadoopPath(targetPath), false));
if (!targetPath.equals(currentPath)) {
// if staging directory is used we cherry-pick files to be moved
@@ -1846,9 +1847,9 @@ public class SemiTransactionalHiveMetastore
deleteOnly = false;
Table table = tableAndMore.getTable();
- Path targetPath = new Path(table.getStorage().getLocation());
- Path currentPath = tableAndMore.getCurrentLocation().get();
- cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, targetPath, false));
+ Location targetPath = Location.of(table.getStorage().getLocation());
+ Location currentPath = Location.of(tableAndMore.getCurrentLocation().get().toString());
+ cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, hadoopPath(targetPath), false));
if (!targetPath.equals(currentPath)) {
asyncRename(hdfsEnvironment, fileSystemExecutor, fileSystemOperationsCancelled, fileSystemOperationFutures, context, currentPath, targetPath, tableAndMore.getFileNames().get());
}
@@ -1920,15 +1921,15 @@ public class SemiTransactionalHiveMetastore
}
}
- Path currentPath = partitionAndMore.getCurrentLocation();
- Path targetPath = new Path(targetLocation);
+ Location currentPath = partitionAndMore.getCurrentLocation();
+ Location targetPath = Location.of(targetLocation);
if (!targetPath.equals(currentPath)) {
renameDirectory(
hdfsContext,
hdfsEnvironment,
- currentPath,
- targetPath,
- () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, targetPath, true)));
+ hadoopPath(currentPath),
+ hadoopPath(targetPath),
+ () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, hadoopPath(targetPath), true)));
}
// Partition alter must happen regardless of whether original and current location is the same
// because metadata might change: e.g. storage format, column types, etc
@@ -1944,7 +1945,7 @@ public class SemiTransactionalHiveMetastore
}
verify(partitionAndMore.hasFileNames(), "fileNames expected to be set if isCleanExtraOutputFilesOnCommit is true");
- SemiTransactionalHiveMetastore.cleanExtraOutputFiles(hdfsEnvironment, hdfsContext, queryId, partitionAndMore.getCurrentLocation(), ImmutableSet.copyOf(partitionAndMore.getFileNames()));
+ SemiTransactionalHiveMetastore.cleanExtraOutputFiles(hdfsEnvironment, hdfsContext, queryId, hadoopPath(partitionAndMore.getCurrentLocation()), ImmutableSet.copyOf(partitionAndMore.getFileNames()));
}
private void cleanExtraOutputFiles(HdfsContext hdfsContext, String queryId, TableAndMore tableAndMore)
@@ -1952,9 +1953,9 @@ public class SemiTransactionalHiveMetastore
if (!tableAndMore.isCleanExtraOutputFilesOnCommit()) {
return;
}
- Path tableLocation = tableAndMore.getCurrentLocation().orElseThrow(() -> new IllegalArgumentException("currentLocation expected to be set if isCleanExtraOutputFilesOnCommit is true"));
+ Location tableLocation = tableAndMore.getCurrentLocation().orElseThrow(() -> new IllegalArgumentException("currentLocation expected to be set if isCleanExtraOutputFilesOnCommit is true"));
List<String> files = tableAndMore.getFileNames().orElseThrow(() -> new IllegalArgumentException("fileNames expected to be set if isCleanExtraOutputFilesOnCommit is true"));
- SemiTransactionalHiveMetastore.cleanExtraOutputFiles(hdfsEnvironment, hdfsContext, queryId, tableLocation, ImmutableSet.copyOf(files));
+ SemiTransactionalHiveMetastore.cleanExtraOutputFiles(hdfsEnvironment, hdfsContext, queryId, hadoopPath(tableLocation), ImmutableSet.copyOf(files));
}
private PartitionStatistics getExistingPartitionStatistics(Partition partition, String partitionName)
@@ -1989,8 +1990,8 @@ public class SemiTransactionalHiveMetastore
Partition partition = partitionAndMore.getPartition();
String targetLocation = partition.getStorage().getLocation();
- Path currentPath = partitionAndMore.getCurrentLocation();
- Path targetPath = new Path(targetLocation);
+ Location currentPath = partitionAndMore.getCurrentLocation();
+ Location targetPath = Location.of(targetLocation);
cleanExtraOutputFiles(hdfsContext, queryId, partitionAndMore);
@@ -2002,19 +2003,19 @@ public class SemiTransactionalHiveMetastore
if (fileSystemOperationsCancelled.get()) {
return;
}
- if (pathExists(hdfsContext, hdfsEnvironment, currentPath)) {
+ if (pathExists(hdfsContext, hdfsEnvironment, hadoopPath(currentPath))) {
if (!targetPath.equals(currentPath)) {
renameDirectory(
hdfsContext,
hdfsEnvironment,
- currentPath,
- targetPath,
- () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, targetPath, true)));
+ hadoopPath(currentPath),
+ hadoopPath(targetPath),
+ () -> cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, hadoopPath(targetPath), true)));
}
}
else {
- cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, targetPath, true));
- createDirectory(hdfsContext, hdfsEnvironment, targetPath);
+ cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, hadoopPath(targetPath), true));
+ createDirectory(hdfsContext, hdfsEnvironment, hadoopPath(targetPath));
}
}, fileSystemExecutor));
@@ -2028,9 +2029,9 @@ public class SemiTransactionalHiveMetastore
Partition partition = partitionAndMore.getPartition();
partitionsToInvalidate.add(partition);
- Path targetPath = new Path(partition.getStorage().getLocation());
- Path currentPath = partitionAndMore.getCurrentLocation();
- cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, targetPath, false));
+ Location targetPath = Location.of(partition.getStorage().getLocation());
+ Location currentPath = partitionAndMore.getCurrentLocation();
+ cleanUpTasksForAbort.add(new DirectoryCleanUpTask(hdfsContext, hadoopPath(targetPath), false));
if (!targetPath.equals(currentPath)) {
// if staging directory is used we cherry-pick files to be moved
@@ -2499,21 +2500,21 @@ public class SemiTransactionalHiveMetastore
AtomicBoolean cancelled,
List<CompletableFuture<?>> fileRenameFutures,
HdfsContext context,
- Path currentPath,
- Path targetPath,
+ Location currentPath,
+ Location targetPath,
List<String> fileNames)
{
FileSystem fileSystem;
try {
- fileSystem = hdfsEnvironment.getFileSystem(context, currentPath);
+ fileSystem = hdfsEnvironment.getFileSystem(context, hadoopPath(currentPath));
}
catch (IOException e) {
throw new TrinoException(HIVE_FILESYSTEM_ERROR, format("Error moving data files to final location. Error listing directory %s", currentPath), e);
}
for (String fileName : fileNames) {
- Path source = new Path(currentPath, fileName);
- Path target = new Path(targetPath, fileName);
+ Path source = hadoopPath(currentPath.appendPath(fileName));
+ Path target = hadoopPath(targetPath.appendPath(fileName));
fileRenameFutures.add(CompletableFuture.runAsync(() -> {
if (cancelled.get()) {
return;
@@ -2830,7 +2831,7 @@ public class SemiTransactionalHiveMetastore
{
private final Table table;
private final Optional<PrincipalPrivileges> principalPrivileges;
- private final Optional<Path> currentLocation; // unpartitioned table only
+ private final Optional<Location> currentLocation; // unpartitioned table only
private final Optional<List<String>> fileNames;
private final boolean ignoreExisting;
private final PartitionStatistics statistics;
@@ -2840,7 +2841,7 @@ public class SemiTransactionalHiveMetastore
public TableAndMore(
Table table,
Optional<PrincipalPrivileges> principalPrivileges,
- Optional<Path> currentLocation,
+ Optional<Location> currentLocation,
Optional<List<String>> fileNames,
boolean ignoreExisting,
PartitionStatistics statistics,
@@ -2876,7 +2877,7 @@ public class SemiTransactionalHiveMetastore
return principalPrivileges.get();
}
- public Optional<Path> getCurrentLocation()
+ public Optional<Location> getCurrentLocation()
{
return currentLocation;
}
@@ -2923,7 +2924,7 @@ public class SemiTransactionalHiveMetastore
private final List<PartitionUpdateAndMergeResults> partitionMergeResults;
private final List<Partition> partitions;
- public TableAndMergeResults(Table table, Optional<PrincipalPrivileges> principalPrivileges, Optional<Path> currentLocation, List<PartitionUpdateAndMergeResults> partitionMergeResults, List<Partition> partitions)
+ public TableAndMergeResults(Table table, Optional<PrincipalPrivileges> principalPrivileges, Optional<Location> currentLocation, List<PartitionUpdateAndMergeResults> partitionMergeResults, List<Partition> partitions)
{
super(table, principalPrivileges, currentLocation, Optional.empty(), false, PartitionStatistics.empty(), PartitionStatistics.empty(), false); // retries are not supported for transactional tables
this.partitionMergeResults = requireNonNull(partitionMergeResults, "partitionMergeResults is null");
@@ -2951,13 +2952,13 @@ public class SemiTransactionalHiveMetastore
private static class PartitionAndMore
{
private final Partition partition;
- private final Path currentLocation;
+ private final Location currentLocation;
private final Optional<List<String>> fileNames;
private final PartitionStatistics statistics;
private final PartitionStatistics statisticsUpdate;
private final boolean cleanExtraOutputFilesOnCommit;
- public PartitionAndMore(Partition partition, Path currentLocation, Optional<List<String>> fileNames, PartitionStatistics statistics, PartitionStatistics statisticsUpdate, boolean cleanExtraOutputFilesOnCommit)
+ public PartitionAndMore(Partition partition, Location currentLocation, Optional<List<String>> fileNames, PartitionStatistics statistics, PartitionStatistics statisticsUpdate, boolean cleanExtraOutputFilesOnCommit)
{
this.partition = requireNonNull(partition, "partition is null");
this.currentLocation = requireNonNull(currentLocation, "currentLocation is null");
@@ -2972,7 +2973,7 @@ public class SemiTransactionalHiveMetastore
return partition;
}
- public Path getCurrentLocation()
+ public Location getCurrentLocation()
{
return currentLocation;
}
@@ -3704,9 +3705,9 @@ public class SemiTransactionalHiveMetastore
}
}
- public record PartitionUpdateInfo(List<String> partitionValues, Path currentLocation, List<String> fileNames, PartitionStatistics statisticsUpdate)
+ public record PartitionUpdateInfo(List<String> partitionValues, Location currentLocation, List<String> fileNames, PartitionStatistics statisticsUpdate)
{
- public PartitionUpdateInfo(List<String> partitionValues, Path currentLocation, List<String> fileNames, PartitionStatistics statisticsUpdate)
+ public PartitionUpdateInfo(List<String> partitionValues, Location currentLocation, List<String> fileNames, PartitionStatistics statisticsUpdate)
{
this.partitionValues = requireNonNull(partitionValues, "partitionValues is null");
this.currentLocation = requireNonNull(currentLocation, "currentLocation is null");
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/glue/GlueHiveMetastore.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/glue/GlueHiveMetastore.java
index 41b8cec11b..c6c06608cb 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/glue/GlueHiveMetastore.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/glue/GlueHiveMetastore.java
@@ -69,12 +69,16 @@ import dev.failsafe.Failsafe;
import dev.failsafe.RetryPolicy;
import io.airlift.concurrent.MoreFutures;
import io.airlift.log.Logger;
+import io.trino.filesystem.Location;
+import io.trino.filesystem.TrinoFileSystemFactory;
+import io.trino.filesystem.hdfs.HdfsFileSystemFactory;
import io.trino.hdfs.DynamicHdfsConfiguration;
import io.trino.hdfs.HdfsConfig;
import io.trino.hdfs.HdfsConfiguration;
import io.trino.hdfs.HdfsConfigurationInitializer;
import io.trino.hdfs.HdfsContext;
import io.trino.hdfs.HdfsEnvironment;
+import io.trino.hdfs.TrinoHdfsFileSystemStats;
import io.trino.hdfs.authentication.NoHdfsAuthentication;
import io.trino.plugin.hive.HiveColumnStatisticType;
import io.trino.plugin.hive.HiveType;
@@ -185,6 +189,7 @@ public class GlueHiveMetastore
.withMaxRetries(3)
.build();
+ private final TrinoFileSystemFactory fileSystemFactory;
private final HdfsEnvironment hdfsEnvironment;
private final HdfsContext hdfsContext;
private final AWSGlueAsync glueClient;
@@ -198,6 +203,7 @@ public class GlueHiveMetastore
@Inject
public GlueHiveMetastore(
+ TrinoFileSystemFactory fileSystemFactory,
HdfsEnvironment hdfsEnvironment,
GlueHiveMetastoreConfig glueConfig,
@ForGlueHiveMetastore Executor partitionsReadExecutor,
@@ -206,6 +212,7 @@ public class GlueHiveMetastore
@ForGlueHiveMetastore GlueMetastoreStats stats,
@ForGlueHiveMetastore Predicate<com.amazonaws.services.glue.model.Table> tableFilter)
{
+ this.fileSystemFactory = requireNonNull(fileSystemFactory, "fileSystemFactory is null");
this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null");
this.hdfsContext = new HdfsContext(ConnectorIdentity.ofUser(DEFAULT_METASTORE_USER));
this.glueClient = requireNonNull(glueClient, "glueClient is null");
@@ -227,7 +234,9 @@ public class GlueHiveMetastore
GlueMetastoreStats stats = new GlueMetastoreStats();
GlueHiveMetastoreConfig glueConfig = new GlueHiveMetastoreConfig()
.setDefaultWarehouseDir(defaultWarehouseDir.toUri().toString());
+ TrinoFileSystemFactory fileSystemFactory = new HdfsFileSystemFactory(hdfsEnvironment, new TrinoHdfsFileSystemStats());
return new GlueHiveMetastore(
+ fileSystemFactory,
hdfsEnvironment,
glueConfig,
directExecutor(),
@@ -555,7 +564,7 @@ public class GlueHiveMetastore
}
if (deleteData) {
- location.ifPresent(path -> deleteDir(hdfsContext, hdfsEnvironment, new Path(path), true));
+ location.ifPresent(path -> deleteDir(hdfsContext, path));
}
}
@@ -621,7 +630,7 @@ public class GlueHiveMetastore
Optional<String> location = table.getStorage().getOptionalLocation()
.filter(not(String::isEmpty));
if (deleteData && isManagedTable(table) && location.isPresent()) {
- deleteDir(hdfsContext, hdfsEnvironment, new Path(location.get()), true);
+ deleteDir(hdfsContext, location.get());
}
}
@@ -630,10 +639,10 @@ public class GlueHiveMetastore
return table.getTableType().equals(MANAGED_TABLE.name());
}
- private static void deleteDir(HdfsContext context, HdfsEnvironment hdfsEnvironment, Path path, boolean recursive)
+ private void deleteDir(HdfsContext context, String path)
{
try {
- hdfsEnvironment.getFileSystem(context, path).delete(path, recursive);
+ fileSystemFactory.create(context.getIdentity()).deleteDirectory(Location.of(path));
}
catch (Exception e) {
// don't fail if unable to delete path
@@ -1082,7 +1091,7 @@ public class GlueHiveMetastore
String partLocation = partition.getStorage().getLocation();
if (deleteData && isManagedTable(table) && !isNullOrEmpty(partLocation)) {
- deleteDir(hdfsContext, hdfsEnvironment, new Path(partLocation), true);
+ deleteDir(hdfsContext, partLocation);
}
}
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/RegisterPartitionProcedure.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/RegisterPartitionProcedure.java
index 7f7a737610..4a696a24e9 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/RegisterPartitionProcedure.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/RegisterPartitionProcedure.java
@@ -17,6 +17,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Provider;
+import io.trino.filesystem.Location;
import io.trino.hdfs.HdfsContext;
import io.trino.hdfs.HdfsEnvironment;
import io.trino.plugin.hive.HiveConfig;
@@ -34,12 +35,12 @@ import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.connector.TableNotFoundException;
import io.trino.spi.procedure.Procedure;
import io.trino.spi.type.ArrayType;
-import org.apache.hadoop.fs.Path;
import java.lang.invoke.MethodHandle;
import java.util.List;
import java.util.Optional;
+import static io.trino.filesystem.hdfs.HadoopPaths.hadoopPath;
import static io.trino.plugin.base.util.Procedures.checkProcedureArgument;
import static io.trino.plugin.hive.HiveMetadata.PRESTO_QUERY_ID_NAME;
import static io.trino.plugin.hive.procedure.Procedures.checkIsPartitionedTable;
@@ -131,16 +132,16 @@ public class RegisterPartitionProcedure
throw new TrinoException(ALREADY_EXISTS, format("Partition [%s] is already registered with location %s", partitionName, partition.get().getStorage().getLocation()));
}
- Path partitionLocation;
+ Location partitionLocation;
if (location == null) {
- partitionLocation = new Path(table.getStorage().getLocation(), makePartName(partitionColumns, partitionValues));
+ partitionLocation = Location.of(table.getStorage().getLocation()).appendPath(makePartName(partitionColumns, partitionValues));
}
else {
- partitionLocation = new Path(location);
+ partitionLocation = Location.of(location);
}
- if (!HiveWriteUtils.pathExists(hdfsContext, hdfsEnvironment, partitionLocation)) {
+ if (!HiveWriteUtils.pathExists(hdfsContext, hdfsEnvironment, hadoopPath(partitionLocation))) {
throw new TrinoException(INVALID_PROCEDURE_ARGUMENT, "Partition location does not exist: " + partitionLocation);
}
@@ -157,7 +158,7 @@ public class RegisterPartitionProcedure
metastore.commit();
}
- private static Partition buildPartitionObject(ConnectorSession session, Table table, List<String> partitionValues, Path location)
+ private static Partition buildPartitionObject(ConnectorSession session, Table table, List<String> partitionValues, Location location)
{
return Partition.builder()
.setDatabaseName(table.getDatabaseName())
diff --git a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/SyncPartitionMetadataProcedure.java b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/SyncPartitionMetadataProcedure.java
index dd0e0983b1..f25b56bd99 100644
--- a/plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/SyncPartitionMetadataProcedure.java
+++ b/plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/SyncPartitionMetadataProcedure.java
@@ -19,6 +19,7 @@ import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Provider;
+import io.trino.filesystem.Location;
import io.trino.hdfs.HdfsContext;
import io.trino.hdfs.HdfsEnvironment;
import io.trino.plugin.hive.PartitionStatistics;
@@ -240,7 +241,7 @@ public class SyncPartitionMetadataProcedure
table.getDatabaseName(),
table.getTableName(),
buildPartitionObject(session, table, name),
- new Path(table.getStorage().getLocation(), name),
+ Location.of(table.getStorage().getLocation()).appendPath(name),
Optional.empty(), // no need for failed attempts cleanup
PartitionStatistics.empty(),
false);
diff --git a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHive.java b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHive.java
index 06cb66a91c..78bd3c4dd9 100644
--- a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHive.java
+++ b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHive.java
@@ -203,6 +203,7 @@ import static io.airlift.testing.Assertions.assertGreaterThanOrEqual;
import static io.airlift.testing.Assertions.assertInstanceOf;
import static io.airlift.testing.Assertions.assertLessThanOrEqual;
import static io.airlift.units.DataSize.Unit.KILOBYTE;
+import static io.trino.filesystem.hdfs.HadoopPaths.hadoopPath;
import static io.trino.parquet.reader.ParquetReader.PARQUET_CODEC_METRIC_PREFIX;
import static io.trino.plugin.hive.AbstractTestHive.TransactionDeleteInsertTestTag.COMMIT;
import static io.trino.plugin.hive.AbstractTestHive.TransactionDeleteInsertTestTag.ROLLBACK_AFTER_APPEND_PAGE;
@@ -6304,8 +6305,8 @@ public abstract class AbstractTestHive
throws IOException
{
for (PartitionUpdate partitionUpdate : partitionUpdates) {
- if ("pk2=insert2".equals(partitionUpdate.getTargetPath().getName())) {
- path = new Path(partitionUpdate.getTargetPath(), partitionUpdate.getFileNames().get(0));
+ if ("pk2=insert2".equals(partitionUpdate.getTargetPath().fileName())) {
+ path = new Path(hadoopPath(partitionUpdate.getTargetPath()), partitionUpdate.getFileNames().get(0));
break;
}
}
diff --git a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHiveLocal.java b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHiveLocal.java
index f97a28461b..a3288f846e 100644
--- a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHiveLocal.java
+++ b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHiveLocal.java
@@ -18,6 +18,7 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.io.RecursiveDeleteOption;
import com.google.common.reflect.ClassPath;
import io.airlift.log.Logger;
+import io.trino.filesystem.Location;
import io.trino.plugin.hive.metastore.Column;
import io.trino.plugin.hive.metastore.Database;
import io.trino.plugin.hive.metastore.HiveMetastore;
@@ -33,7 +34,6 @@ import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.predicate.TupleDomain;
import io.trino.spi.security.PrincipalType;
import io.trino.testing.MaterializedResult;
-import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.metastore.TableType;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
@@ -44,7 +44,6 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
-import java.net.URI;
import java.nio.file.Files;
import java.util.List;
import java.util.Optional;
@@ -190,7 +189,7 @@ public abstract class AbstractTestHiveLocal
BUCKETING_V1,
3,
ImmutableList.of(new SortingColumn("name", SortingColumn.Order.ASCENDING)))),
- new Path(URI.create("file://" + externalLocation.toString())));
+ Location.of("file://" + externalLocation.toString()));
assertReadFailsWithMessageMatching(ORC, tableName, "Hive table is corrupt\\\\. File '.*/.*' is for bucket [0-2], but contains a row for bucket [0-2].");
markTableAsCreatedBySpark(tableName, "orc");
@@ -227,7 +226,7 @@ public abstract class AbstractTestHiveLocal
}
}
- private void createExternalTable(SchemaTableName schemaTableName, HiveStorageFormat hiveStorageFormat, List<Column> columns, List<Column> partitionColumns, Optional<HiveBucketProperty> bucketProperty, Path externalLocation)
+ private void createExternalTable(SchemaTableName schemaTableName, HiveStorageFormat hiveStorageFormat, List<Column> columns, List<Column> partitionColumns, Optional<HiveBucketProperty> bucketProperty, Location externalLocation)
{
try (Transaction transaction = newTransaction()) {
ConnectorSession session = newSession();
diff --git a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveCreateExternalTable.java b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveCreateExternalTable.java
index 6ca1d28257..e897747666 100644
--- a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveCreateExternalTable.java
+++ b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveCreateExternalTable.java
@@ -51,13 +51,13 @@ public class TestHiveCreateExternalTable
throws IOException
{
Path tempDir = createTempDirectory(null);
- Path tableLocation = tempDir.resolve("data");
+ String tableLocation = tempDir.resolve("data").toUri().toASCIIString();
@Language("SQL") String createTableSql = format("" +
"CREATE TABLE test_create_external " +
"WITH (external_location = '%s') AS " +
"SELECT * FROM tpch.tiny.nation",
- tableLocation.toUri().toASCIIString());
+ tableLocation);
assertUpdate(createTableSql, 25);
@@ -67,7 +67,7 @@ public class TestHiveCreateExternalTable
MaterializedResult result = computeActual("SELECT DISTINCT regexp_replace(\\"$path\\", '/[^/]*$', '/') FROM test_create_external");
String tablePath = (String) result.getOnlyValue();
- assertThat(tablePath).startsWith(tableLocation.toFile().toURI().toString());
+ assertThat(tablePath).startsWith(tableLocation);
assertUpdate("DROP TABLE test_create_external");
deleteRecursively(tempDir, ALLOW_INSECURE);
diff --git a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveS3AndGlueMetastoreTest.java b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveS3AndGlueMetastoreTest.java
index e0f2b5d797..78600d318c 100644
--- a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveS3AndGlueMetastoreTest.java
+++ b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveS3AndGlueMetastoreTest.java
@@ -24,11 +24,9 @@ import org.testng.annotations.Test;
import java.nio.file.Path;
import java.util.HashSet;
-import java.util.List;
import java.util.Optional;
import java.util.Set;
-import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.trino.plugin.hive.metastore.glue.GlueHiveMetastore.createTestingGlueHiveMetastore;
import static io.trino.spi.security.SelectedRole.Type.ROLE;
import static io.trino.testing.TestingNames.randomNameSuffix;
@@ -37,6 +35,7 @@ import static java.util.Objects.requireNonNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+// TODO Run this test also with Hive thrift metastore
public class TestHiveS3AndGlueMetastoreTest
extends BaseS3AndGlueMetastoreTest
{
@@ -254,14 +253,55 @@ public class TestHiveS3AndGlueMetastoreTest
.hasStackTraceContaining("Fragment is not allowed in a file system location");
}
+ @Test
+ public void testCreateTableWithDoubleSlash()
+ {
+ String schemaName = "test_create_table_with_double_slash_" + randomNameSuffix();
+ String schemaLocation = "s3://%s/%s/double_slash//test_schema".formatted(bucketName, schemaName);
+ String tableName = "test_create_table_with_double_slash_" + randomNameSuffix();
+ String schemaTableName = schemaName + "." + tableName;
+
+ // Previously, HiveLocationService replaced double slash with single slash
+ assertUpdate("CREATE SCHEMA " + schemaName + " WITH (location = '" + schemaLocation + "')");
+ String existingKey = "%s/double_slash/test_schema/%s".formatted(schemaName, tableName);
+ s3.putObject(bucketName, existingKey, "test content");
+
+ assertUpdate("CREATE TABLE " + schemaTableName + "(col_int int)");
+ assertUpdate("INSERT INTO " + schemaTableName + " VALUES 1", 1);
+ assertQuery("SELECT * FROM " + schemaTableName, "VALUES 1");
+ assertUpdate("DROP TABLE " + schemaTableName);
+ s3.deleteObject(bucketName, existingKey);
+ }
+
+ @Test
+ public void testCtasWithDoubleSlash()
+ {
+ String schemaName = "test_ctas_with_double_slash_" + randomNameSuffix();
+ String schemaLocation = "s3://%s/%s/double_slash//test_schema".formatted(bucketName, schemaName);
+ String tableName = "test_create_table_with_double_slash_" + randomNameSuffix();
+ String schemaTableName = schemaName + "." + tableName;
+
+ // Previously, HiveLocationService replaced double slash with single slash
+ assertUpdate("CREATE SCHEMA " + schemaName + " WITH (location = '" + schemaLocation + "')");
+ String existingKey = "%s/double_slash/test_schema/%s".formatted(schemaName, tableName);
+ s3.putObject(bucketName, existingKey, "test content");
+
+ assertUpdate("CREATE TABLE " + schemaTableName + " AS SELECT 1 AS col_int", 1);
+ assertQuery("SELECT * FROM " + schemaTableName, "VALUES 1");
+ assertUpdate("DROP TABLE " + schemaTableName);
+ s3.deleteObject(bucketName, existingKey);
+ }
+
@Test
public void testCreateSchemaWithIncorrectLocation()
{
String schemaName = "test_create_schema_with_incorrect_location_" + randomNameSuffix();
- String schemaLocation = "s3://%s/%2$s/a#hash/%2$s".formatted(bucketName, schemaName);
+ String key = "%1$s/a#hash/%1$s";
+ String schemaLocation = "s3://%s/%s".formatted(bucketName, key);
String tableName = "test_basic_operations_table_" + randomNameSuffix();
String qualifiedTableName = schemaName + "." + tableName;
+ // TODO Disallow creating a schema with incorrect location
assertUpdate("CREATE SCHEMA " + schemaName + " WITH (location = '" + schemaLocation + "')");
assertThat(getSchemaLocation(schemaName)).isEqualTo(schemaLocation);
@@ -272,6 +312,8 @@ public class TestHiveS3AndGlueMetastoreTest
.hasMessageContaining("Fragment is not allowed in a file system location");
assertUpdate("DROP SCHEMA " + schemaName);
+ // Delete S3 directory explicitly because the above DROP SCHEMA failed to delete it due to fragment in the location
+ s3.deleteObject(bucketName, key);
}
@Test
@@ -286,13 +328,4 @@ public class TestHiveS3AndGlueMetastoreTest
assertUpdate("DROP SCHEMA \\"" + schemaName + "\\"");
}
-
- @Override
- protected List<String> locationPatterns()
- {
- // TODO https://github.com/trinodb/trino/issues/17803 Fix correctness issue with double slash
- return super.locationPatterns().stream()
- .filter(location -> !location.contains("double_slash"))
- .collect(toImmutableList());
- }
}
diff --git a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestPartitionUpdate.java b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestPartitionUpdate.java
index 69031a976a..52cb3aa1ea 100644
--- a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestPartitionUpdate.java
+++ b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestPartitionUpdate.java
@@ -15,8 +15,8 @@ package io.trino.plugin.hive;
import com.google.common.collect.ImmutableList;
import io.airlift.json.JsonCodec;
+import io.trino.filesystem.Location;
import io.trino.plugin.hive.PartitionUpdate.UpdateMode;
-import org.apache.hadoop.fs.Path;
import org.testng.annotations.Test;
import static io.airlift.json.JsonCodec.jsonCodec;
@@ -43,8 +43,8 @@ public class TestPartitionUpdate
assertEquals(actual.getName(), "test");
assertEquals(actual.getUpdateMode(), UpdateMode.APPEND);
- assertEquals(actual.getWritePath(), new Path("/writePath"));
- assertEquals(actual.getTargetPath(), new Path("/targetPath"));
+ assertEquals(actual.getWritePath(), Location.of("/writePath"));
+ assertEquals(actual.getTargetPath(), Location.of("/targetPath"));
assertEquals(actual.getFileNames(), ImmutableList.of("file1", "file3"));
assertEquals(actual.getRowCount(), 123);
assertEquals(actual.getInMemoryDataSizeInBytes(), 456);
diff --git a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/TestSemiTransactionalHiveMetastore.java b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/TestSemiTransactionalHiveMetastore.java
index df0a3f1b1a..836b011568 100644
--- a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/TestSemiTransactionalHiveMetastore.java
+++ b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/TestSemiTransactionalHiveMetastore.java
@@ -15,13 +15,13 @@ package io.trino.plugin.hive.metastore;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import io.trino.filesystem.Location;
import io.trino.plugin.hive.HiveBucketProperty;
import io.trino.plugin.hive.HiveMetastoreClosure;
import io.trino.plugin.hive.HiveType;
import io.trino.plugin.hive.PartitionStatistics;
import io.trino.plugin.hive.acid.AcidTransaction;
import io.trino.plugin.hive.fs.FileSystemDirectoryLister;
-import org.apache.hadoop.fs.Path;
import org.testng.annotations.Test;
import java.util.List;
@@ -53,7 +53,7 @@ public class TestSemiTransactionalHiveMetastore
Optional.of("comment"));
private static final Storage TABLE_STORAGE = new Storage(
StorageFormat.create("serde", "input", "output"),
- Optional.of("location"),
+ Optional.of("file://location/"),
Optional.of(new HiveBucketProperty(ImmutableList.of("column"), BUCKETING_V1, 10, ImmutableList.of(new SortingColumn("column", SortingColumn.Order.ASCENDING)))),
true,
ImmutableMap.of("param", "value2"));
@@ -109,7 +109,7 @@ public class TestSemiTransactionalHiveMetastore
IntStream.range(0, tablesToUpdate).forEach(i -> semiTransactionalHiveMetastore.finishChangingExistingTable(INSERT, SESSION,
"database",
"table_" + i,
- new Path("location"),
+ Location.of("file://location/"),
ImmutableList.of(),
PartitionStatistics.empty(),
false));
diff --git a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/glue/TestHiveGlueMetastore.java b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/glue/TestHiveGlueMetastore.java
index 89da152872..c8e2264d22 100644
--- a/plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/glue/TestHiveGlueMetastore.java
+++ b/plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/glue/TestHiveGlueMetastore.java
@@ -30,6 +30,8 @@ import com.google.common.collect.ImmutableMap;
import io.airlift.concurrent.BoundedExecutor;
import io.airlift.log.Logger;
import io.airlift.slice.Slice;
+import io.trino.filesystem.hdfs.HdfsFileSystemFactory;
+import io.trino.hdfs.TrinoHdfsFileSystemStats;
import io.trino.plugin.hive.AbstractTestHiveLocal;
import io.trino.plugin.hive.HiveBasicStatistics;
import io.trino.plugin.hive.HiveMetastoreClosure;
@@ -232,6 +234,7 @@ public class TestHiveGlueMetastore
Executor executor = new BoundedExecutor(this.executor, 10);
GlueMetastoreStats stats = new GlueMetastoreStats();
return new GlueHiveMetastore(
+ new HdfsFileSystemFactory(HDFS_ENVIRONMENT, new TrinoHdfsFileSystemStats()),
HDFS_ENVIRONMENT,
glueConfig,
executor, | ['plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/TestSemiTransactionalHiveMetastore.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveMetadata.java', 'plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHiveLocal.java', 'plugin/trino-delta-lake/src/test/java/io/trino/plugin/deltalake/metastore/glue/TestDeltaLakeConcurrentModificationGlueMetastore.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/PartitionUpdate.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/glue/GlueHiveMetastore.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/SyncPartitionMetadataProcedure.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/BackgroundHiveSplitLoader.java', 'plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveCreateExternalTable.java', 'plugin/trino-hive/src/test/java/io/trino/plugin/hive/metastore/glue/TestHiveGlueMetastore.java', 'plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHive.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/SemiTransactionalHiveMetastore.java', 'plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestPartitionUpdate.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveWriter.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/procedure/RegisterPartitionProcedure.java', 'plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestHiveS3AndGlueMetastoreTest.java', 'plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveLocationService.java'] | {'.java': 17} | 17 | 17 | 0 | 0 | 17 | 38,138,403 | 7,631,131 | 995,195 | 6,473 | 17,841 | 3,222 | 218 | 9 | 325 | 48 | 82 | 9 | 0 | 1 | 2023-06-08T09:08:52 | 8,254 | Java | {'Java': 71658946, 'JavaScript': 233768, 'ANTLR': 56491, 'Shell': 49457, 'HTML': 30842, 'CSS': 13515, 'Scala': 10145, 'Python': 7379, 'Smarty': 1938, 'Dockerfile': 1723, 'Groovy': 1702, 'PLSQL': 85} | Apache License 2.0 |
8,249 | trinodb/trino/6186/6170 | trinodb | trino | https://github.com/trinodb/trino/issues/6170 | https://github.com/trinodb/trino/pull/6186 | https://github.com/trinodb/trino/pull/6186 | 1 | fixes | Iceberg catalog: connecting to Google Cloud Storage produced error | The [documentation](https://prestosql.io/docs/current/connector/iceberg.html) says that **Iceberg supports the same metastore configuration properties as the Hive connector.** However, when I provide the catalog `iceberg.properties` with
`connector.name=iceberg`
`hive.metastore.uri=thrift://hive-metastore:9083`
`hive.gcs.json-key-file-path=/gcs_keyfile.json`
I got the following error:
```
ERROR main io.prestosql.server.Server Configuration errors:
1) Error: Configuration property 'hive.gcs.json-key-file-path' was not used
1 error
io.airlift.bootstrap.ApplicationConfigurationException: Configuration errors:
1) Error: Configuration property 'hive.gcs.json-key-file-path' was not used
1 error
at io.airlift.bootstrap.Bootstrap.initialize(Bootstrap.java:239)
at io.prestosql.plugin.iceberg.InternalIcebergConnectorFactory.createConnector(InternalIcebergConnectorFactory.java:83)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.prestosql.plugin.iceberg.IcebergConnectorFactory.create(IcebergConnectorFactory.java:42)
at io.prestosql.connector.ConnectorManager.createConnector(ConnectorManager.java:353)
at io.prestosql.connector.ConnectorManager.createCatalog(ConnectorManager.java:212)
at io.prestosql.connector.ConnectorManager.createCatalog(ConnectorManager.java:204)
at io.prestosql.connector.ConnectorManager.createCatalog(ConnectorManager.java:190)
at io.prestosql.metadata.StaticCatalogStore.loadCatalog(StaticCatalogStore.java:88)
at io.prestosql.metadata.StaticCatalogStore.loadCatalogs(StaticCatalogStore.java:68)
at io.prestosql.server.Server.doStart(Server.java:119)
at io.prestosql.server.Server.lambda$start$0(Server.java:73)
at io.prestosql.$gen.Presto_347____20201201_174408_1.run(Unknown Source)
at io.prestosql.server.Server.start(Server.java:73)
at io.prestosql.server.PrestoServer.main(PrestoServer.java:38)
```
I am using Presto version 347.
I am not sure if this is a bug or I've done something wrong, any help or suggestions would be appreciated.
Kind regards, | ad4f8d542c7195fd8da91300a9d48f36e45632a3 | 7c6a9437ac9070e4ff0ccb0f1c94544c4a4c68cb | https://github.com/trinodb/trino/compare/ad4f8d542c7195fd8da91300a9d48f36e45632a3...7c6a9437ac9070e4ff0ccb0f1c94544c4a4c68cb | diff --git a/presto-iceberg/src/main/java/io/prestosql/plugin/iceberg/InternalIcebergConnectorFactory.java b/presto-iceberg/src/main/java/io/prestosql/plugin/iceberg/InternalIcebergConnectorFactory.java
index 8e01a261a6..2b2187d918 100644
--- a/presto-iceberg/src/main/java/io/prestosql/plugin/iceberg/InternalIcebergConnectorFactory.java
+++ b/presto-iceberg/src/main/java/io/prestosql/plugin/iceberg/InternalIcebergConnectorFactory.java
@@ -30,6 +30,8 @@ import io.prestosql.plugin.base.jmx.MBeanServerModule;
import io.prestosql.plugin.base.security.AllowAllAccessControl;
import io.prestosql.plugin.hive.NodeVersion;
import io.prestosql.plugin.hive.authentication.HiveAuthenticationModule;
+import io.prestosql.plugin.hive.azure.HiveAzureModule;
+import io.prestosql.plugin.hive.gcs.HiveGcsModule;
import io.prestosql.plugin.hive.metastore.HiveMetastore;
import io.prestosql.plugin.hive.metastore.HiveMetastoreModule;
import io.prestosql.plugin.hive.s3.HiveS3Module;
@@ -65,6 +67,8 @@ public final class InternalIcebergConnectorFactory
new IcebergModule(),
new IcebergMetastoreModule(),
new HiveS3Module(),
+ new HiveGcsModule(),
+ new HiveAzureModule(),
new HiveAuthenticationModule(),
new HiveMetastoreModule(metastore),
new MBeanServerModule(), | ['presto-iceberg/src/main/java/io/prestosql/plugin/iceberg/InternalIcebergConnectorFactory.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 26,082,340 | 5,240,335 | 697,768 | 4,758 | 193 | 45 | 4 | 1 | 2,365 | 128 | 558 | 43 | 1 | 1 | 2020-12-02T23:17:00 | 8,254 | Java | {'Java': 71658946, 'JavaScript': 233768, 'ANTLR': 56491, 'Shell': 49457, 'HTML': 30842, 'CSS': 13515, 'Scala': 10145, 'Python': 7379, 'Smarty': 1938, 'Dockerfile': 1723, 'Groovy': 1702, 'PLSQL': 85} | Apache License 2.0 |
8,248 | trinodb/trino/7212/7208 | trinodb | trino | https://github.com/trinodb/trino/issues/7208 | https://github.com/trinodb/trino/pull/7212 | https://github.com/trinodb/trino/pull/7212 | 1 | fixes | Unnecessary wrapping of TrinoException due to LazyConnection usage in CachingJdbcClient | https://github.com/trinodb/trino/pull/7069 introduced `LazyConnection` that opens a connection on first usage, not when it's acquired in the code path.
This changed how exceptions are handled in the `CachingJdbcClient`. Prior to that change when executing i.e. `show tables from mysql.default;` client would get:
```
trino> show tables from mysql.default;
Query 20210308_093838_00002_itbrt failed: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
```
Now it ends with:
```
trino> show tables from mysql.default;
Query 20210308_094545_00000_iaeyw failed: com.google.common.util.concurrent.UncheckedExecutionException: java.lang.RuntimeException: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
``` | 6395ff0ae44b86a27af7eac31c1397a20a32aa26 | 8ffe51d219c978abb83b034405234d36775695a8 | https://github.com/trinodb/trino/compare/6395ff0ae44b86a27af7eac31c1397a20a32aa26...8ffe51d219c978abb83b034405234d36775695a8 | diff --git a/plugin/trino-mysql/src/main/java/io/trino/plugin/mysql/MySqlClient.java b/plugin/trino-mysql/src/main/java/io/trino/plugin/mysql/MySqlClient.java
index 99a6bbd54f..16f8f41f9b 100644
--- a/plugin/trino-mysql/src/main/java/io/trino/plugin/mysql/MySqlClient.java
+++ b/plugin/trino-mysql/src/main/java/io/trino/plugin/mysql/MySqlClient.java
@@ -189,7 +189,7 @@ public class MySqlClient
return schemaNames.build();
}
catch (SQLException e) {
- throw new RuntimeException(e);
+ throw new TrinoException(JDBC_ERROR, e);
}
}
| ['plugin/trino-mysql/src/main/java/io/trino/plugin/mysql/MySqlClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,058,170 | 5,384,152 | 727,585 | 4,924 | 97 | 18 | 2 | 1 | 862 | 94 | 201 | 14 | 1 | 2 | 2021-03-08T12:37:52 | 8,254 | Java | {'Java': 71658946, 'JavaScript': 233768, 'ANTLR': 56491, 'Shell': 49457, 'HTML': 30842, 'CSS': 13515, 'Scala': 10145, 'Python': 7379, 'Smarty': 1938, 'Dockerfile': 1723, 'Groovy': 1702, 'PLSQL': 85} | Apache License 2.0 |
9,503 | thundernest/k-9/6591/6581 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/6581 | https://github.com/thundernest/k-9/pull/6591 | https://github.com/thundernest/k-9/pull/6591 | 1 | fixes | Opening message and hitting archive doesn't mark the email as read. | ### Checklist
- [X] I have used the search function to see if someone else has already submitted the same bug report.
- [X] I will describe the problem with as much detail as possible.
### App version
6.400
### Where did you get the app from?
F-Droid
### Android version
13 / OneUI 5.0
### Device model
Samsung Galaxy A52s 5G
### Steps to reproduce
This happens rarely
1. Open any unread message
2. Hit archive
### Expected behavior
The message should be marked as read and archived.
### Actual behavior
Sometimes (I havent found any pattern yet) some messages are archived but are still in unread state. I think it started with 6.400 version. I noticed it when opening Thunderbird on my computer and noticing that "archive" folder is in bold, indicating that there are unread messages (and I only archived read messages). I'm positive that those messages were archived using mobile/k9-mail. I'm fairly certain I did that when away from home, thus using mobile connection. I think it could be due to either poor network coverage or possibly it could happen when switching from wifi to mobile data.
### Logs
_No response_ | 14c5c07e3676f3dede03577d1e399c46fae5319c | 78d6e233629e6cfc598f349d2837c168c0909b1d | https://github.com/thundernest/k-9/compare/14c5c07e3676f3dede03577d1e399c46fae5319c...78d6e233629e6cfc598f349d2837c168c0909b1d | diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
index dfa2cc252..0d1f491f3 100644
--- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
+++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
@@ -952,11 +952,8 @@ public class MessagingController {
}
private void queueSetFlag(Account account, long folderId, boolean newState, Flag flag, List<String> uids) {
- putBackground("queueSetFlag", null, () -> {
- PendingCommand command = PendingSetFlag.create(folderId, newState, flag, uids);
- queuePendingCommand(account, command);
- processPendingCommands(account);
- });
+ PendingCommand command = PendingSetFlag.create(folderId, newState, flag, uids);
+ queuePendingCommand(account, command);
}
/**
@@ -969,11 +966,8 @@ public class MessagingController {
}
private void queueDelete(Account account, long folderId, List<String> uids) {
- putBackground("queueDelete", null, () -> {
- PendingCommand command = PendingDelete.create(folderId, uids);
- queuePendingCommand(account, command);
- processPendingCommands(account);
- });
+ PendingCommand command = PendingDelete.create(folderId, uids);
+ queuePendingCommand(account, command);
}
void processPendingDelete(PendingDelete command, Account account) throws MessagingException {
@@ -1044,12 +1038,9 @@ public class MessagingController {
setFlagInCache(account, messageIds, flag, newState);
- threadPool.execute(new Runnable() {
- @Override
- public void run() {
- setFlagSynchronous(account, messageIds, flag, newState, false);
- }
- });
+ putBackground("setFlag", null, () ->
+ setFlagSynchronous(account, messageIds, flag, newState, false)
+ );
}
public void setFlagForThreads(final Account account, final List<Long> threadRootIds,
@@ -1057,12 +1048,9 @@ public class MessagingController {
setFlagForThreadsInCache(account, threadRootIds, flag, newState);
- threadPool.execute(new Runnable() {
- @Override
- public void run() {
- setFlagSynchronous(account, threadRootIds, flag, newState, true);
- }
- });
+ putBackground("setFlagForThreads", null, () ->
+ setFlagSynchronous(account, threadRootIds, flag, newState, true)
+ );
}
private void setFlagSynchronous(final Account account, final List<Long> ids,
@@ -1284,36 +1272,49 @@ public class MessagingController {
}
public void markMessageAsOpened(Account account, LocalMessage message) {
- put("markMessageAsOpened", null, () -> {
- markMessageAsOpenedBlocking(account, message);
- });
- }
+ threadPool.execute(() ->
+ notificationController.removeNewMailNotification(account, message.makeMessageReference())
+ );
- private void markMessageAsOpenedBlocking(Account account, LocalMessage message) {
- notificationController.removeNewMailNotification(account,message.makeMessageReference());
+ if (message.isSet(Flag.SEEN)) {
+ // Nothing to do if the message is already marked as read
+ return;
+ }
- if (!message.isSet(Flag.SEEN)) {
- if (account.isMarkMessageAsReadOnView()) {
- markMessageAsReadOnView(account, message);
- } else {
- // Marking a message as read will automatically mark it as "not new". But if we don't mark the message
- // as read on opening, we have to manually mark it as "not new".
- markMessageAsNotNew(account, message);
+ boolean markMessageAsRead = account.isMarkMessageAsReadOnView();
+ if (markMessageAsRead) {
+ // Mark the message itself as read right away
+ try {
+ message.setFlagInternal(Flag.SEEN, true);
+ } catch (MessagingException e) {
+ Timber.e(e, "Error while marking message as read");
}
- }
- }
- private void markMessageAsReadOnView(Account account, LocalMessage message) {
- try {
+ // Also mark the message as read in the cache
List<Long> messageIds = Collections.singletonList(message.getDatabaseId());
- setFlag(account, messageIds, Flag.SEEN, true);
+ setFlagInCache(account, messageIds, Flag.SEEN, true);
+ }
- message.setFlagInternal(Flag.SEEN, true);
- } catch (MessagingException e) {
- Timber.e(e, "Error while marking message as read");
+ putBackground("markMessageAsOpened", null, () -> {
+ markMessageAsOpenedBlocking(account, message, markMessageAsRead);
+ });
+ }
+
+ private void markMessageAsOpenedBlocking(Account account, LocalMessage message, boolean markMessageAsRead) {
+ if (markMessageAsRead) {
+ markMessageAsRead(account, message);
+ } else {
+ // Marking a message as read will automatically mark it as "not new". But if we don't mark the message
+ // as read on opening, we have to manually mark it as "not new".
+ markMessageAsNotNew(account, message);
}
}
+ private void markMessageAsRead(Account account, LocalMessage message) {
+ List<Long> messageIds = Collections.singletonList(message.getDatabaseId());
+ setFlagSynchronous(account, messageIds, Flag.SEEN, true, false);
+ }
+
private void markMessageAsNotNew(Account account, LocalMessage message) {
MessageStore messageStore = messageStoreManager.getMessageStore(account);
long folderId = message.getFolder().getDatabaseId(); | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,181,715 | 437,634 | 59,663 | 329 | 4,204 | 838 | 87 | 1 | 1,141 | 195 | 256 | 39 | 0 | 0 | 2023-01-17T19:22:36 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,533 | thundernest/k-9/6255/6243 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/6243 | https://github.com/thundernest/k-9/pull/6255 | https://github.com/thundernest/k-9/pull/6255 | 1 | fixes | SecurityException on image shared to K-9 not caught | ### Checklist
- [X] I have used the search function to see if someone else has already submitted the same bug report.
- [X] I will describe the problem with as much detail as possible.
### App version
6.301
### Where did you get the app from?
F-Droid
### Android version
12
### Device model
Pixel 4a
### Steps to reproduce
1. Share an image from Firefox to a K-9 Direct Share contact (before [this](https://github.com/mozilla-mobile/android-components/pull/12649) change is rolled out) or an older version of chome (like 3 months old? not sure) or any app that forgets to call `intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)`
2. K-9 mail crashes.
### Expected behavior
K-9 communicates to the user that the attachement can't be opened.
### Actual behavior
K-9 mail crashes.
### Logs
```
08-12 22:06:59.152 31785 7754 E AndroidRuntime: FATAL EXCEPTION: ModernAsyncTask #2
08-12 22:06:59.152 31785 7754 E AndroidRuntime: Process: com.fsck.k9, PID: 31785
08-12 22:06:59.152 31785 7754 E AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at androidx.loader.content.ModernAsyncTask$3.done(ModernAsyncTask.java:164)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:271)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at java.lang.Thread.run(Thread.java:919)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: Caused by: java.lang.SecurityException: Permission Denial: opening provider mozilla.components.feature.downloads.provider.FileProvider from ProcessRecord{1846f0d 31785:com.fsck.k9/u0a153} (pid=31785, uid=10153) that is not exported from UID 10140
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.os.Parcel.createException(Parcel.java:2071)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.os.Parcel.readException(Parcel.java:2039)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1987)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.app.IActivityManager$Stub$Proxy.getContentProvider(IActivityManager.java:5056)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.app.ActivityThread.acquireProvider(ActivityThread.java:6561)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2725)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:2117)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.content.ContentResolver.query(ContentResolver.java:928)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.content.ContentResolver.query(ContentResolver.java:880)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.content.ContentResolver.query(ContentResolver.java:836)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at com.fsck.k9.activity.loader.AttachmentInfoLoader.loadInBackground(AttachmentInfoLoader.java:57)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at com.fsck.k9.activity.loader.AttachmentInfoLoader.loadInBackground(AttachmentInfoLoader.java:22)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at androidx.loader.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:307)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at androidx.loader.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:60)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at androidx.loader.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:48)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at androidx.loader.content.ModernAsyncTask$2.call(ModernAsyncTask.java:141)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: ... 3 more
08-12 22:06:59.152 31785 7754 E AndroidRuntime: Caused by: android.os.RemoteException: Remote stack trace:
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at com.android.server.am.ActivityManagerService.getContentProviderImpl(ActivityManagerService.java:6816)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at com.android.server.am.ActivityManagerService.getContentProvider(ActivityManagerService.java:7238)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:2078)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2742)
08-12 22:06:59.152 31785 7754 E AndroidRuntime: at android.os.Binder.execTransactInternal(Binder.java:1021)
08-12 22:06:59.152 31785 7754 E AndroidRuntime:
``` | 9cf73c99d09332a461ecb3830db86bca044bdf2e | fd396b183debe084a5cbdfba260bec1f6640bdbf | https://github.com/thundernest/k-9/compare/9cf73c99d09332a461ecb3830db86bca044bdf2e...fd396b183debe084a5cbdfba260bec1f6640bdbf | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java
index 6a420c812..19ceff5b6 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java
@@ -3,7 +3,6 @@ package com.fsck.k9.activity.loader;
import java.io.File;
import java.io.FileOutputStream;
-import java.io.IOException;
import java.io.InputStream;
import android.content.ContentResolver;
@@ -88,7 +87,7 @@ public class AttachmentContentLoader extends AsyncTaskLoader<Attachment> {
cachedResultAttachment = sourceAttachment.deriveWithLoadComplete(file.getAbsolutePath());
return cachedResultAttachment;
- } catch (IOException e) {
+ } catch (Exception e) {
Timber.e(e, "Error saving attachment!");
}
diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java
index 6750dd52b..9bbf2e61d 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java
@@ -46,63 +46,70 @@ public class AttachmentInfoLoader extends AsyncTaskLoader<Attachment> {
@Override
public Attachment loadInBackground() {
- Uri uri = sourceAttachment.uri;
- String contentType = sourceAttachment.contentType;
-
- long size = -1;
- String name = null;
-
- ContentResolver contentResolver = getContext().getContentResolver();
-
- Cursor metadataCursor = contentResolver.query(
- uri,
- new String[] { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE },
- null,
- null,
- null);
-
- if (metadataCursor != null) {
- try {
- if (metadataCursor.moveToFirst()) {
- name = metadataCursor.getString(0);
- size = metadataCursor.getInt(1);
+ try {
+ Uri uri = sourceAttachment.uri;
+ String contentType = sourceAttachment.contentType;
+
+ long size = -1;
+ String name = null;
+
+ ContentResolver contentResolver = getContext().getContentResolver();
+
+ Cursor metadataCursor = contentResolver.query(
+ uri,
+ new String[] { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE },
+ null,
+ null,
+ null);
+
+ if (metadataCursor != null) {
+ try {
+ if (metadataCursor.moveToFirst()) {
+ name = metadataCursor.getString(0);
+ size = metadataCursor.getInt(1);
+ }
+ } finally {
+ metadataCursor.close();
}
- } finally {
- metadataCursor.close();
}
- }
- if (name == null) {
- name = uri.getLastPathSegment();
- }
+ if (name == null) {
+ name = uri.getLastPathSegment();
+ }
- String usableContentType = contentResolver.getType(uri);
- if (usableContentType == null && contentType != null && contentType.indexOf('*') != -1) {
- usableContentType = contentType;
- }
+ String usableContentType = contentResolver.getType(uri);
+ if (usableContentType == null && contentType != null && contentType.indexOf('*') != -1) {
+ usableContentType = contentType;
+ }
- if (usableContentType == null) {
- usableContentType = MimeTypeUtil.getMimeTypeByExtension(name);
- }
+ if (usableContentType == null) {
+ usableContentType = MimeTypeUtil.getMimeTypeByExtension(name);
+ }
- if (!sourceAttachment.allowMessageType && MimeUtility.isMessageType(usableContentType)) {
- usableContentType = MimeTypeUtil.DEFAULT_ATTACHMENT_MIME_TYPE;
- }
+ if (!sourceAttachment.allowMessageType && MimeUtility.isMessageType(usableContentType)) {
+ usableContentType = MimeTypeUtil.DEFAULT_ATTACHMENT_MIME_TYPE;
+ }
- if (size <= 0) {
- String uriString = uri.toString();
- if (uriString.startsWith("file://")) {
- File f = new File(uriString.substring("file://".length()));
- size = f.length();
+ if (size <= 0) {
+ String uriString = uri.toString();
+ if (uriString.startsWith("file://")) {
+ File f = new File(uriString.substring("file://".length()));
+ size = f.length();
+ } else {
+ Timber.v("Not a file: %s", uriString);
+ }
} else {
- Timber.v("Not a file: %s", uriString);
+ Timber.v("old attachment.size: %d", size);
}
- } else {
- Timber.v("old attachment.size: %d", size);
- }
- Timber.v("new attachment.size: %d", size);
+ Timber.v("new attachment.size: %d", size);
+
+ cachedResultAttachment = sourceAttachment.deriveWithMetadataLoaded(usableContentType, name, size);
+ return cachedResultAttachment;
+ } catch (Exception e) {
+ Timber.e(e, "Error getting attachment meta data");
- cachedResultAttachment = sourceAttachment.deriveWithMetadataLoaded(usableContentType, name, size);
- return cachedResultAttachment;
+ cachedResultAttachment = sourceAttachment.deriveWithLoadCancelled();
+ return cachedResultAttachment;
+ }
}
} | ['app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentInfoLoader.java', 'app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,061,027 | 411,985 | 57,788 | 345 | 4,492 | 787 | 106 | 2 | 5,350 | 445 | 1,622 | 74 | 1 | 1 | 2022-08-25T14:17:10 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,564 | thundernest/k-9/5650/5592 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5592 | https://github.com/thundernest/k-9/pull/5650 | https://github.com/thundernest/k-9/pull/5650 | 1 | fixes | Sender name is not displayed | Please search to check for an existing issue (including closed issues, for which the fix may not have yet been released) before opening a new issue: https://github.com/k9mail/k-9/issues?q=is%3Aissue
If you are unsure whether or not you have found a bug please post to the support forum instead: https://forum.k9mail.app
**Describe the bug**
I see some issue about showing address instead of name but I can only see the address on some emails. I checked the email header and there is `From: "linsui (@linsui)" <[email protected]>` but only [email protected] is displayed though the contact picture is an L. When the header is `GitLab <[email protected]>` the name is displayed though.
**To Reproduce**
Steps to reproduce the behavior:
1. Receive an email from gitlab
4. See error
**Expected behavior**
The contact name is displayed.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment (please complete the following information):**
- K-9 Mail version: 5.804
- Android version: 11
- Device: Mi 6
- Account type: IMAP
**Additional context**
Add any other context about the problem here.
**Logs**
Please take some time to [retrieve logs](https://github.com/k9mail/k-9/wiki/LoggingErrors) and attach them here:
| c92baae802f6f87b300aeb00cb88a1a8a1c7fad4 | 9156e8f699f6ab8c47bd23fffc989f53068521e0 | https://github.com/thundernest/k-9/compare/c92baae802f6f87b300aeb00cb88a1a8a1c7fad4...9156e8f699f6ab8c47bd23fffc989f53068521e0 | diff --git a/app/core/src/main/java/com/fsck/k9/helper/MessageHelper.java b/app/core/src/main/java/com/fsck/k9/helper/MessageHelper.java
index 5595d47f8..cb9e865da 100644
--- a/app/core/src/main/java/com/fsck/k9/helper/MessageHelper.java
+++ b/app/core/src/main/java/com/fsck/k9/helper/MessageHelper.java
@@ -1,6 +1,8 @@
package com.fsck.k9.helper;
+import java.util.regex.Pattern;
+
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
@@ -27,6 +29,7 @@ public class MessageHelper {
* @see #toFriendly(Address[], com.fsck.k9.helper.Contacts)
*/
private static final int TOO_MANY_ADDRESSES = 50;
+ private static final Pattern SPOOF_ADDRESS_PATTERN = Pattern.compile("[^(]@");
private static MessageHelper sInstance;
@@ -143,6 +146,6 @@ public class MessageHelper {
}
private static boolean isSpoofAddress(String displayName) {
- return displayName.contains("@");
+ return displayName.contains("@") && SPOOF_ADDRESS_PATTERN.matcher(displayName).find();
}
}
diff --git a/app/core/src/test/java/com/fsck/k9/helper/MessageHelperTest.java b/app/core/src/test/java/com/fsck/k9/helper/MessageHelperTest.java
index f5b7cc0eb..85347a322 100644
--- a/app/core/src/test/java/com/fsck/k9/helper/MessageHelperTest.java
+++ b/app/core/src/test/java/com/fsck/k9/helper/MessageHelperTest.java
@@ -94,6 +94,20 @@ public class MessageHelperTest extends RobolectricTest {
assertEquals("[email protected]", friendly.toString());
}
+ @Test
+ public void toFriendly_atPrecededByOpeningParenthesisShouldNotTriggerSpoofPrevention() {
+ Address address = new Address("[email protected]", "username (@username)");
+ CharSequence friendly = MessageHelper.toFriendly(address, contacts);
+ assertEquals("username (@username)", friendly.toString());
+ }
+
+ @Test
+ public void toFriendly_nameStartingWithAtShouldNotTriggerSpoofPrevention() {
+ Address address = new Address("[email protected]", "@username");
+ CharSequence friendly = MessageHelper.toFriendly(address, contacts);
+ assertEquals("@username", friendly.toString());
+ }
+
@Test
public void toFriendly_spoofPreventionDoesntOverrideContact() {
Address address = new Address("[email protected]", "Tim Testor"); | ['app/core/src/test/java/com/fsck/k9/helper/MessageHelperTest.java', 'app/core/src/main/java/com/fsck/k9/helper/MessageHelper.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,324,966 | 462,034 | 65,311 | 373 | 257 | 48 | 5 | 1 | 1,297 | 183 | 310 | 31 | 3 | 0 | 2021-09-06T06:02:02 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,490 | thundernest/k-9/6001/5999 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5999 | https://github.com/thundernest/k-9/pull/6001 | https://github.com/thundernest/k-9/issues/5999#issuecomment-1087826808 | 2 | fixes | K-9 fails to import settings and then crashes | ### Checklist
- [X] I have used the search function to see if someone else has already submitted the same bug report.
- [X] I will describe the problem with as much detail as possible.
### App version
5.914 (git 0e78b8aae6bda14aca094298813b50759b50e8cb)
### Where did you get the app from?
Built from source
### Android version
API level 29
### Device model
Emulator
### Steps to reproduce
Export settings and immediately re-import. You get a toast "import failed".
Clearing the app data and trying to import the settings file also fails.
There is nothing particularly interesting about the settings, it's a standard IMAP/SMTP setup. The emulator is a bit slow due to RAM constraints so I'm wondering if there is a race when writing the newly created accounts to storage.
### Expected behavior
K-9 should import the settings
### Actual behavior
K-9 fails to import the settings with an error message. If you keep trying to import, K-9 completely crashes.
### Logs
logcat says
```
2022-04-04 16:32:55.897 7076-7076/com.fsck.k9.debug E/SettingsImportViewModel$startImportSettings: Error importing settings
com.fsck.k9.preferences.SettingsImportExportException: java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter account
at com.fsck.k9.preferences.SettingsImporter.importSettings(SettingsImporter.java:298)
at com.fsck.k9.ui.settings.import.SettingsImportViewModel.importSettings(SettingsImportViewModel.kt:363)
at com.fsck.k9.ui.settings.import.SettingsImportViewModel.access$importSettings(SettingsImportViewModel.kt:28)
at com.fsck.k9.ui.settings.import.SettingsImportViewModel$startImportSettings$1$1$1.invokeSuspend(SettingsImportViewModel.kt:282)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:39)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
Caused by: java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter account
at com.fsck.k9.mailstore.SpecialLocalFoldersCreator.createSpecialLocalFolders(Unknown Source:2)
at com.fsck.k9.preferences.SettingsImporter.importSettings(SettingsImporter.java:287)
at com.fsck.k9.ui.settings.import.SettingsImportViewModel.importSettings(SettingsImportViewModel.kt:363)
at com.fsck.k9.ui.settings.import.SettingsImportViewModel.access$importSettings(SettingsImportViewModel.kt:28)
at com.fsck.k9.ui.settings.import.SettingsImportViewModel$startImportSettings$1$1$1.invokeSuspend(SettingsImportViewModel.kt:282)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:39)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
``` | 0e78b8aae6bda14aca094298813b50759b50e8cb | 6721a1566322b80918a880a9cbeb87921d05f03f | https://github.com/thundernest/k-9/compare/0e78b8aae6bda14aca094298813b50759b50e8cb...6721a1566322b80918a880a9cbeb87921d05f03f | diff --git a/app/core/src/main/java/com/fsck/k9/preferences/SettingsImporter.java b/app/core/src/main/java/com/fsck/k9/preferences/SettingsImporter.java
index 1b28729f3..661ab013c 100644
--- a/app/core/src/main/java/com/fsck/k9/preferences/SettingsImporter.java
+++ b/app/core/src/main/java/com/fsck/k9/preferences/SettingsImporter.java
@@ -229,7 +229,7 @@ public class SettingsImporter {
editor = preferences.createStorageEditor();
String newUuid = importResult.imported.uuid;
- String oldAccountUuids = storage.getString("accountUuids", "");
+ String oldAccountUuids = preferences.getStorage().getString("accountUuids", "");
String newAccountUuids = (oldAccountUuids.length() > 0) ?
oldAccountUuids + "," + newUuid : newUuid;
| ['app/core/src/main/java/com/fsck/k9/preferences/SettingsImporter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,225,814 | 442,868 | 62,240 | 358 | 226 | 33 | 2 | 1 | 4,074 | 248 | 901 | 70 | 0 | 1 | 2022-04-04T17:31:05 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,611 | thundernest/k-9/4636/4620 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4620 | https://github.com/thundernest/k-9/pull/4636 | https://github.com/thundernest/k-9/pull/4636 | 1 | fixes | Crash when saving attachment because no Activity found for CREATE_DOCUMENT Intent | * I have set up an account with pgp (most messages like the one from logcat are only encrypted, not signed)
* The message text is not shown but a file to show or save is presented
* pressing save crashes
* open only suggests openkeychain
* Version is 5.707 from f-droid
* thunderbird opens the mail inline
```
<<< log_count = 45 >>>
[03-21 10:32:12.109 914:997 I/ActivityManager]
Start proc 14095:com.fsck.k9/u0a272 for service com.fsck.k9/androidx.work.impl.background.systemjob.SystemJobService
[03-21 10:32:12.116 14095:14095 E/com.fsck.k9]
Not starting debugger since process cannot load the jdwp agent.
[03-21 10:32:13.396 914:6215 I/ActivityManager]
START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.fsck.k9/.activity.MessageList bnds=[40,1240][312,1616]} from uid 10227
[03-21 10:32:13.699 914:993 I/ActivityManager]
Displayed com.fsck.k9/.activity.MessageList: +276ms
[03-21 10:32:13.830 480:1182 W/SurfaceFlinger]
Attempting to set client state on removed layer: Splash Screen com.fsck.k9#0
[03-21 10:32:13.830 480:1182 W/SurfaceFlinger]
Attempting to destroy on removed layer: Splash Screen com.fsck.k9#0
[03-21 10:32:16.281 14095:14095 I/com.fsck.k9]
The ClassLoaderContext is a special shared library.
[03-21 10:32:16.351 914:997 I/ActivityManager]
Start proc 14155:com.android.webview:sandboxed_process0/u0i20 for webview_service com.fsck.k9/org.chromium.content.app.SandboxedProcessService0
[03-21 10:32:17.568 914:7800 I/ActivityManager]
START u0 {act=android.intent.action.VIEW dat=content://com.fsck.k9.tempfileprovider/temp/9ca99f367b8b669c80ba814d052dbb6d73a0c320?mime_type=application/octet-stream typ=application/octet-stream flg=0x10080001 cmp=android/com.android.internal.app.ResolverActivity} from uid 10272
[03-21 10:32:18.348 14095:14103 I/chatty]
uid=10272(com.fsck.k9) FinalizerDaemon identical 1 line
[03-21 10:32:19.640 14095:14095 E/AndroidRuntime]
FATAL EXCEPTION: main
Process: com.fsck.k9, PID: 14095
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.CREATE_DOCUMENT cat=[android.intent.category.OPENABLE] typ= (has extras) }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2007)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4587)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675)
at androidx.core.app.ActivityCompat.startActivityForResult(ActivityCompat.java:234)
at androidx.fragment.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:795)
at androidx.fragment.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:932)
at androidx.fragment.app.Fragment.startActivityForResult(Fragment.java:1278)
at androidx.fragment.app.Fragment.startActivityForResult(Fragment.java:1266)
at com.fsck.k9.ui.messageview.MessageViewFragment.onSaveAttachment(MessageViewFragment.java:818)
at com.fsck.k9.ui.messageview.AttachmentView.onSaveButtonClick(AttachmentView.java:105)
at com.fsck.k9.ui.messageview.AttachmentView.onClick(AttachmentView.java:96)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25906)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
[03-21 10:32:19.646 914:3338 W/ActivityManager]
Force finishing activity com.fsck.k9/.activity.MessageList
[03-21 10:32:19.654 914:995 I/ActivityManager]
Showing crash dialog for package com.fsck.k9 u0
[03-21 10:32:20.149 914:994 W/ActivityManager]
Activity pause timeout for ActivityRecord{8bc72c4 u0 com.fsck.k9/.activity.MessageList t50 f}
[03-21 10:32:21.259 914:3338 W/ActivityManager]
Force finishing activity com.fsck.k9/.activity.MessageList
[03-21 10:32:21.263 914:3338 I/ActivityManager]
Killing 14095:com.fsck.k9/u0a272 (adj 0): crash
[03-21 10:32:21.270 480:1902 W/SurfaceFlinger]
Attempting to destroy on removed layer: 9fc3519 com.fsck.k9/com.fsck.k9.activity.MessageList#0
[03-21 10:32:21.333 914:997 I/ActivityManager]
Start proc 14216:com.fsck.k9/u0a272 for broadcast com.fsck.k9/.widget.list.MessageListWidgetProvider
[03-21 10:32:21.335 14216:14216 E/com.fsck.k9]
Not starting debugger since process cannot load the jdwp agent.
[03-21 10:32:21.454 480:1902 W/SurfaceFlinger]
Attempting to destroy on removed layer: 3a0ad17 Application Error: com.fsck.k9#0
[03-21 10:32:23.912 1434:1434 W/NotificationEntryMgr]
removeNotification for unknown key: 0|com.fsck.k9|5|null|10272
[03-21 10:32:26.428 14216:14229 I/com.fsck.k9]
Waiting for a blocking GC ProfileSaver
[03-21 10:32:26.439 14216:14229 I/com.fsck.k9]
WaitForGcToComplete blocked ProfileSaver on HeapTrim for 11.418ms
[03-21 10:32:29.961 1434:1434 W/NotificationEntryMgr]
removeNotification for unknown key: 0|com.fsck.k9|5|null|10272
[03-21 10:32:50.803 914:914 I/NotificationService]
Cannot find enqueued record for key: 0|com.fsck.k9|5|null|10272
[03-21 10:32:50.813 1434:1434 W/NotificationEntryMgr]
removeNotification for unknown key: 0|com.fsck.k9|5|null|10272
[03-21 10:32:52.834 1434:1434 W/NotificationEntryMgr]
removeNotification for unknown key: 0|com.fsck.k9|5|null|10272
[03-21 10:32:52.856 14216:14238 I/WM-WorkerWrapper]
Worker result SUCCESS for Work [ id=af96888a-282c-4d28-b868-08a0560ce31f, tags={ com.fsck.k9.job.MailSyncWorker, MailSync } ]
[03-21 10:35:54.955 914:13084 I/ActivityManager]
START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.fsck.k9/.activity.MessageList bnds=[40,1240][312,1616]} from uid 10227
[03-21 10:35:55.315 914:993 I/ActivityManager]
Displayed com.fsck.k9/.activity.MessageList: +339ms
[03-21 10:35:55.455 480:572 W/SurfaceFlinger]
Attempting to set client state on removed layer: Splash Screen com.fsck.k9#0
[03-21 10:35:55.455 480:572 W/SurfaceFlinger]
Attempting to destroy on removed layer: Splash Screen com.fsck.k9#0
[03-21 10:35:57.746 14216:14216 I/com.fsck.k9]
The ClassLoaderContext is a special shared library.
[03-21 10:35:57.820 914:997 I/ActivityManager]
Start proc 14534:com.android.webview:sandboxed_process0/u0i22 for webview_service com.fsck.k9/org.chromium.content.app.SandboxedProcessService0
[03-21 10:35:59.285 914:11057 I/ActivityManager]
START u0 {act=android.intent.action.VIEW dat=content://com.fsck.k9.tempfileprovider/temp/c7066efdfc06ce2bdf4c7aea9f03be3aab55a3f4?mime_type=application/octet-stream typ=application/octet-stream flg=0x10080001 cmp=android/com.android.internal.app.ResolverActivity} from uid 10272
[03-21 10:36:06.446 14216:14224 I/chatty]
uid=10272(com.fsck.k9) FinalizerDaemon identical 1 line
[03-21 10:41:01.212 914:3324 I/ActivityManager]
START u0 {act=android.intent.action.SEND dat=content://com.dp.logcatapp.file_provider/logs/logcat_03-21-2020_10-40-53.txt typ=text/plain flg=0xb080001 cmp=com.fsck.k9/.activity.MessageCompose clip={text/plain U:content://com.dp.logcatapp.file_provider/logs/logcat_03-21-2020_10-40-53.txt} (has extras)} from uid 10104
[03-21 10:41:01.583 914:993 I/ActivityManager]
Displayed com.fsck.k9/.activity.MessageCompose: +331ms
[03-21 10:41:01.708 480:514 W/SurfaceFlinger]
Attempting to set client state on removed layer: Splash Screen com.fsck.k9#0
[03-21 10:41:01.708 480:514 W/SurfaceFlinger]
Attempting to destroy on removed layer: Splash Screen com.fsck.k9#0
[03-21 10:41:01.709 480:1182 W/SurfaceFlinger]
Attempting to set client state on removed layer: Surface(name=1c390bc Splash Screen com.fsck.k9)/@0xf2def08 - animation-leash#0
[03-21 10:41:01.709 480:1182 W/SurfaceFlinger]
Attempting to destroy on removed layer: Surface(name=1c390bc Splash Screen com.fsck.k9)/@0xf2def08 - animation-leash#0
[03-21 10:41:10.470 480:1182 W/SurfaceFlinger]
Attempting to set client state on removed layer: com.fsck.k9/com.fsck.k9.activity.MessageCompose#0
[03-21 10:41:10.470 480:1182 W/SurfaceFlinger]
Attempting to destroy on removed layer: com.fsck.k9/com.fsck.k9.activity.MessageCompose#0
[03-21 10:41:13.984 914:8761 W/NotificationService]
Toast already killed. pkg=com.fsck.k9 callback=android.app.ITransientNotification$Stub$Proxy@2383cd4
``` | 68213ac717feb90a112202f40c6119bb0d807222 | e46c5bd966f72b389eaed88f87b8e93125ddf3ee | https://github.com/thundernest/k-9/compare/68213ac717feb90a112202f40c6119bb0d807222...e46c5bd966f72b389eaed88f87b8e93125ddf3ee | diff --git a/app/ui/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java b/app/ui/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
index a8d2c0165..e4e55485c 100644
--- a/app/ui/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
+++ b/app/ui/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
@@ -6,6 +6,7 @@ import java.util.Locale;
import android.app.Activity;
import android.app.DownloadManager;
+import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
@@ -822,7 +823,11 @@ public class MessageViewFragment extends Fragment implements ConfirmationDialogF
intent.putExtra(Intent.EXTRA_TITLE, attachment.displayName);
intent.addCategory(Intent.CATEGORY_OPENABLE);
- startActivityForResult(intent, REQUEST_CODE_CREATE_DOCUMENT);
+ try {
+ startActivityForResult(intent, REQUEST_CODE_CREATE_DOCUMENT);
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(requireContext(), R.string.error_activity_not_found, Toast.LENGTH_LONG).show();
+ }
}
private AttachmentController getAttachmentController(AttachmentViewInfo attachment) { | ['app/ui/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,016,992 | 594,615 | 83,878 | 465 | 379 | 57 | 7 | 1 | 8,689 | 650 | 2,745 | 173 | 0 | 1 | 2020-04-03T21:58:36 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,489 | thundernest/k-9/4474/4472 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4472 | https://github.com/thundernest/k-9/pull/4474 | https://github.com/thundernest/k-9/issues/4472#issuecomment-578148550 | 2 | fixes | Contact pictures not shown | ### Expected behavior
If a mail comes in from a contact with a picture in address book and the option "show contact picture" is set, the **picture from the address book should be displayed**.
### Actual behavior
Only a generic first-letter-of-name picture is displayed in the mail. If you click on it, the correct contact in contact app will be opened. **k9 has the contact permission**. I suppose the **contact is correctly linked** to the address, **but the picture wont show up**.
### Steps to reproduce
1. Add a contact to the address book with mail and picture
2. Receive a mail from that contact
3. Open the message list
### Environment
K-9 Mail version: 5.703
Android version: 9 (lineageos 16)
Account type: IMAP
*There was no usable information in the debug log.* | 28dadaf4683ebfeab0916369d5771642115df56e | 5b436adaeeb6c75cabcb0dd39015a4cdde6729a8 | https://github.com/thundernest/k-9/compare/28dadaf4683ebfeab0916369d5771642115df56e...5b436adaeeb6c75cabcb0dd39015a4cdde6729a8 | diff --git a/app/core/src/main/java/com/fsck/k9/helper/Contacts.java b/app/core/src/main/java/com/fsck/k9/helper/Contacts.java
index e9de1f814..94698809f 100644
--- a/app/core/src/main/java/com/fsck/k9/helper/Contacts.java
+++ b/app/core/src/main/java/com/fsck/k9/helper/Contacts.java
@@ -6,7 +6,6 @@ import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
-import android.database.AbstractCursor;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
@@ -268,11 +267,8 @@ public class Contacts {
}
private boolean hasContactPermission() {
- boolean canRead = ContextCompat.checkSelfPermission(mContext,
+ return ContextCompat.checkSelfPermission(mContext,
Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
- boolean canWrite = ContextCompat.checkSelfPermission(mContext,
- Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED;
- return canRead && canWrite;
}
/** | ['app/core/src/main/java/com/fsck/k9/helper/Contacts.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,094,671 | 609,924 | 86,111 | 477 | 372 | 54 | 6 | 1 | 795 | 133 | 184 | 19 | 0 | 0 | 2020-01-24T14:18:22 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,631 | thundernest/k-9/3756/3652 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3652 | https://github.com/thundernest/k-9/pull/3756 | https://github.com/thundernest/k-9/pull/3756 | 1 | fixes | Crash on open certain messages | Certain spam messages, not detected by German email provider GMX (false negative), causing k-9 to crash.
### Expected behavior
On tapping a message from folder list, the message should appear in detailed view.
### Actual behavior
On tapping a message from folder list, k-9 crashes
### Steps to reproduce
1. Try getting a spam message from GMX.
2. Account type doesn't matter.
3. Try to open the message.
### Environment
K-9 Mail version: 5.600
Android version: 8.1.0
Account type (IMAP, POP3, WebDAV/Exchange): IMAP/POP3
### Additional information
When opening the same message with Thunderbird, a blank page appears. The source view contains some crude HTML code. If needed, I can link the body's content.
Hope I hit the relevant error from **logcat**:
[logcat_10-08-2018_09-49-44.txt](https://github.com/k9mail/k-9/files/2455144/logcat_10-08-2018_09-49-44.txt)
| 0455157eb7e4c21e971f19ca39e8dcd29d440b13 | 4e6d642ddd8121f35bb596377f88d7fd6dd5afd6 | https://github.com/thundernest/k-9/compare/0455157eb7e4c21e971f19ca39e8dcd29d440b13...4e6d642ddd8121f35bb596377f88d7fd6dd5afd6 | diff --git a/mail/common/src/main/java/com/fsck/k9/mail/Address.java b/mail/common/src/main/java/com/fsck/k9/mail/Address.java
index 88c773913..7fd63782b 100644
--- a/mail/common/src/main/java/com/fsck/k9/mail/Address.java
+++ b/mail/common/src/main/java/com/fsck/k9/mail/Address.java
@@ -1,6 +1,7 @@
package com.fsck.k9.mail;
+import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import java.io.Serializable;
@@ -28,6 +29,7 @@ public class Address implements Serializable {
*/
private static final Address[] EMPTY_ADDRESS_ARRAY = new Address[0];
+ @NonNull
private String mAddress;
private String mPersonal;
@@ -46,10 +48,16 @@ public class Address implements Serializable {
}
private Address(String address, String personal, boolean parse) {
+ if (address == null) {
+ throw new IllegalArgumentException("address");
+ }
if (parse) {
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
if (tokens.length > 0) {
Rfc822Token token = tokens[0];
+ if (token.getAddress() == null) {
+ throw new IllegalArgumentException("token.getAddress()");
+ }
mAddress = token.getAddress();
String name = token.getName();
if (!TextUtils.isEmpty(name)) {
@@ -91,6 +99,9 @@ public class Address implements Serializable {
}
public void setAddress(String address) {
+ if (address == null) {
+ throw new IllegalArgumentException("address");
+ }
this.mAddress = address;
}
@@ -151,8 +162,7 @@ public class Address implements Serializable {
}
} catch (MimeException pe) {
Timber.e(pe, "MimeException in Address.parse()");
- //but we do an silent failover : we just use the given string as name with empty address
- addresses.add(new Address(null, addressList, false));
+ // broken addresses are never added to the resulting array
}
return addresses.toArray(EMPTY_ADDRESS_ARRAY);
}
diff --git a/mail/common/src/test/java/com/fsck/k9/mail/AddressTest.java b/mail/common/src/test/java/com/fsck/k9/mail/AddressTest.java
index 1fa329163..190bfc226 100644
--- a/mail/common/src/test/java/com/fsck/k9/mail/AddressTest.java
+++ b/mail/common/src/test/java/com/fsck/k9/mail/AddressTest.java
@@ -21,9 +21,7 @@ public class AddressTest {
public void parse_withMissingEmail__shouldSetPersonal() {
Address[] addresses = Address.parse("NAME ONLY");
- assertEquals(1, addresses.length);
- assertEquals(null, addresses[0].getAddress());
- assertEquals("NAME ONLY", addresses[0].getPersonal());
+ assertEquals(0, addresses.length);
}
/**
@@ -116,10 +114,9 @@ public class AddressTest {
@Test
public void hashCode_withoutAddress() throws Exception {
- Address address = Address.parse("name only")[0];
- assertNull(address.getAddress());
-
- address.hashCode();
+ Address[] addresses = Address.parse("name only");
+
+ assertEquals(0, addresses.length);
}
@Test
@@ -130,27 +127,6 @@ public class AddressTest {
address.hashCode();
}
- @Test
- public void equals_withoutAddress_matchesSame() throws Exception {
- Address address = Address.parse("name only")[0];
- Address address2 = Address.parse("name only")[0];
- assertNull(address.getAddress());
-
- boolean result = address.equals(address2);
-
- assertTrue(result);
- }
-
- @Test
- public void equals_withoutAddress_doesNotMatchWithAddress() throws Exception {
- Address address = Address.parse("name only")[0];
- Address address2 = Address.parse("name <alice.example.com>")[0];
-
- boolean result = address.equals(address2);
-
- assertFalse(result);
- }
-
@Test
public void equals_withoutPersonal_matchesSame() throws Exception {
Address address = Address.parse("[email protected]")[0];
@@ -172,15 +148,6 @@ public class AddressTest {
assertFalse(result);
}
- @Test
- public void getHostname_withoutAddress_isNull() throws Exception {
- Address address = Address.parse("Alice")[0];
-
- String result = address.getHostname();
-
- assertNull(result);
- }
-
@Test
public void handlesInvalidBase64Encoding() throws Exception {
Address address = Address.parse("=?utf-8?b?invalid#?= <[email protected]>")[0]; | ['mail/common/src/test/java/com/fsck/k9/mail/AddressTest.java', 'mail/common/src/main/java/com/fsck/k9/mail/Address.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,539,843 | 696,597 | 97,904 | 512 | 653 | 111 | 14 | 1 | 898 | 122 | 237 | 27 | 1 | 0 | 2018-11-27T13:19:27 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,488 | thundernest/k-9/4419/3266 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3266 | https://github.com/thundernest/k-9/pull/4419 | https://github.com/thundernest/k-9/pull/4419#issuecomment-570258591 | 1 | fixes | crash: reply to encrypted mail |
### Expected behavior
open new mail screen.
### Actual behavior
K9 displays new mail screen and crashes.
03-16 12:15:32.187 E/AndroidRuntime(31412): java.lang.NullPointerException: Attempt to invoke interface method 'com.fsck.k9.mail.Body com.fsck.k9.mail.Part.getBody()' on a null object reference
This seems related to I have no encryption add-on installed.
### Steps to reproduce
1. open encrypted mail (info: install add-on to view decrypted content)
2. press reply button
3. crash
### Environment
K-9 Mail version: 5.403
Android version: 7.1.2
Account type (IMAP, POP3, WebDAV/Exchange):
IMAP | 0aac541c273f0d3b7e88cf06e7c6331fdaad1ae6 | d937113b6b3ae91b213e2621c4a5623d8e27f008 | https://github.com/thundernest/k-9/compare/0aac541c273f0d3b7e88cf06e7c6331fdaad1ae6...d937113b6b3ae91b213e2621c4a5623d8e27f008 | diff --git a/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java b/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java
index 64ba2ca7c..35795fff2 100644
--- a/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java
+++ b/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java
@@ -4,8 +4,12 @@ package com.fsck.k9.mailstore;
import java.util.Collections;
import java.util.List;
+import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.Message;
+import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
+import com.fsck.k9.mail.internet.MimeBodyPart;
+import com.fsck.k9.mail.internet.TextBody;
public class MessageViewInfo {
@@ -50,7 +54,15 @@ public class MessageViewInfo {
}
public static MessageViewInfo createWithErrorState(Message message, boolean isMessageIncomplete) {
- return new MessageViewInfo(message, isMessageIncomplete, null, null, false, null, null, null, null, null, null);
+ try {
+ Body emptyBody = new TextBody("");
+ Part emptyPart = new MimeBodyPart(emptyBody, "text/plain");
+ String subject = message.getSubject();
+ return new MessageViewInfo(message, isMessageIncomplete, emptyPart, subject, false, null, null, null, null,
+ null, null);
+ } catch (MessagingException e) {
+ throw new AssertionError(e);
+ }
}
public static MessageViewInfo createForMetadataOnly(Message message, boolean isMessageIncomplete) { | ['app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,127,952 | 616,646 | 87,029 | 475 | 727 | 158 | 14 | 1 | 627 | 79 | 159 | 23 | 0 | 0 | 2020-01-02T16:09:58 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,487 | thundernest/k-9/2206/1932 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1932 | https://github.com/thundernest/k-9/pull/2206 | https://github.com/thundernest/k-9/pull/2206#issuecomment-280692550 | 1 | fix | Error Decrypting Email | ### Expected behavior
Expected decrypted email to show in cleartext
### Actual behavior
Error Eecrypting Email message shown with icon from OpenKeyChain
### Steps to reproduce
Send encrypted email to an account handled by K-9
Open email in k-9
Answer password request for decryption Key
See error message
### Environment
K-9 Mail version: 5.201
Android version: Android Version 6.0 - HTC M8
Account type (IMAP, POP3, WebDAV/Exchange):
Sending Account was IMAP
Receiving Account IMAP (gmail)
Both Public keys were imported from old AGP into OpenKeyChain.
Intentionally entering a wrong passphrase gives a different message: Wrong password.
Mail sent from either account to the other (encrypted) works in Thunderbird.
Mail sent from Thunderbird also yields "Error Decrypting mail".
Process: com.fsck.k9, PID: 17677 <---- in Log
[k9-log-5.txt](https://github.com/k9mail/k-9/files/681499/k9-log-5.txt)
| 19b7d4491d5a925a4f53f6d155619e674f16c5cc | 955d994bcea275bf793b67df964bb0062b4424db | https://github.com/thundernest/k-9/compare/19b7d4491d5a925a4f53f6d155619e674f16c5cc...955d994bcea275bf793b67df964bb0062b4424db | diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java
index d29b79181..b6d1d9346 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java
@@ -258,7 +258,7 @@ public class MessageLoaderHelper {
// process with crypto helper
private void startOrResumeCryptoOperation() {
- RetainFragment<MessageCryptoHelper> retainCryptoHelperFragment = getMessageCryptoHelperRetainFragment();
+ RetainFragment<MessageCryptoHelper> retainCryptoHelperFragment = getMessageCryptoHelperRetainFragment(true);
if (retainCryptoHelperFragment.hasData()) {
messageCryptoHelper = retainCryptoHelperFragment.getData();
} else {
@@ -270,7 +270,7 @@ public class MessageLoaderHelper {
}
private void cancelAndClearCryptoOperation() {
- RetainFragment<MessageCryptoHelper> retainCryptoHelperFragment = getMessageCryptoHelperRetainFragment();
+ RetainFragment<MessageCryptoHelper> retainCryptoHelperFragment = getMessageCryptoHelperRetainFragment(false);
if (retainCryptoHelperFragment != null) {
if (retainCryptoHelperFragment.hasData()) {
messageCryptoHelper = retainCryptoHelperFragment.getData();
@@ -281,8 +281,12 @@ public class MessageLoaderHelper {
}
}
- private RetainFragment<MessageCryptoHelper> getMessageCryptoHelperRetainFragment() {
- return RetainFragment.findOrCreate(fragmentManager, "crypto_helper_" + messageReference.hashCode());
+ private RetainFragment<MessageCryptoHelper> getMessageCryptoHelperRetainFragment(boolean createIfNotExists) {
+ if (createIfNotExists) {
+ return RetainFragment.findOrCreate(fragmentManager, "crypto_helper_" + messageReference.hashCode());
+ } else {
+ return RetainFragment.findOrNull(fragmentManager, "crypto_helper_" + messageReference.hashCode());
+ }
}
private MessageCryptoCallback messageCryptoCallback = new MessageCryptoCallback() {
diff --git a/k9mail/src/main/java/com/fsck/k9/helper/RetainFragment.java b/k9mail/src/main/java/com/fsck/k9/helper/RetainFragment.java
index c2560f759..d9406fb79 100644
--- a/k9mail/src/main/java/com/fsck/k9/helper/RetainFragment.java
+++ b/k9mail/src/main/java/com/fsck/k9/helper/RetainFragment.java
@@ -10,6 +10,7 @@ import android.os.Bundle;
public class RetainFragment<T> extends Fragment {
private T data;
+ private boolean cleared;
@Override
public void onCreate(Bundle savedInstanceState) {
@@ -30,11 +31,16 @@ public class RetainFragment<T> extends Fragment {
this.data = data;
}
+ public static <T> RetainFragment<T> findOrNull(FragmentManager fm, String tag) {
+ // noinspection unchecked, we know this is the the right type
+ return (RetainFragment<T>) fm.findFragmentByTag(tag);
+ }
+
public static <T> RetainFragment<T> findOrCreate(FragmentManager fm, String tag) {
// noinspection unchecked, we know this is the the right type
RetainFragment<T> retainFragment = (RetainFragment<T>) fm.findFragmentByTag(tag);
- if (retainFragment == null) {
+ if (retainFragment == null || retainFragment.cleared) {
retainFragment = new RetainFragment<>();
fm.beginTransaction()
.add(retainFragment, tag)
@@ -46,6 +52,7 @@ public class RetainFragment<T> extends Fragment {
public void clearAndRemove(FragmentManager fm) {
data = null;
+ cleared = true;
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1 && fm.isDestroyed()) {
return; | ['k9mail/src/main/java/com/fsck/k9/helper/RetainFragment.java', 'k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,474,872 | 689,617 | 95,086 | 439 | 1,455 | 280 | 21 | 2 | 941 | 125 | 232 | 30 | 1 | 0 | 2017-02-08T02:22:27 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,547 | thundernest/k-9/5931/5930 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5930 | https://github.com/thundernest/k-9/pull/5931 | https://github.com/thundernest/k-9/pull/5931 | 1 | fixes | Notification isn't removed when message is marked as read or deleted locally | ### Checklist
- [X] I have used the search function to see if someone else has already submitted the same bug report.
- [X] I will describe the problem with as much detail as possible.
### App version
5.911
### Where did you get the app from?
_No response_
### Android version
doesn't matter
### Device model
_No response_
### Steps to reproduce
1. Open the message list screen for a folder
2. Refresh the folder when there's a new message on the server so a 'new message' notification is created
3. Long-press the new message in the list to select it
4. Either mark the message as read or delete it
### Expected behavior
The notification for the message is removed.
### Actual behavior
The notification is not removed.
### Logs
_No response_ | 504062a5338f8e14b72556861fad0f52fd84f5e3 | e1c43beee1421409fc32e00b07e61cd7cb8644e2 | https://github.com/thundernest/k-9/compare/504062a5338f8e14b72556861fad0f52fd84f5e3...e1c43beee1421409fc32e00b07e61cd7cb8644e2 | diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
index ff1cb2fa4..12cd1439a 100644
--- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
+++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
@@ -1167,6 +1167,10 @@ public class MessagingController {
l.folderStatusChanged(account, folderId);
}
+ if (flag == Flag.SEEN && newState) {
+ cancelNotificationsForMessages(account, folderId, uids);
+ }
+
if (accountSupportsFlags) {
LocalFolder localFolder = localStore.getFolder(folderId);
try {
@@ -1183,6 +1187,13 @@ public class MessagingController {
}
}
+ private void cancelNotificationsForMessages(Account account, long folderId, List<String> uids) {
+ for (String uid : uids) {
+ MessageReference messageReference = new MessageReference(account.getUuid(), folderId, uid);
+ notificationController.removeNewMailNotification(account, messageReference);
+ }
+ }
+
/**
* Set or remove a flag for a set of messages in a specific folder.
* <p>
@@ -2050,6 +2061,8 @@ public class MessagingController {
List<LocalMessage> syncedMessages = new ArrayList<>();
List<String> syncedMessageUids = new ArrayList<>();
for (LocalMessage message : messages) {
+ notificationController.removeNewMailNotification(account, message.makeMessageReference());
+
String uid = message.getUid();
if (uid.startsWith(K9.LOCAL_UID_PREFIX)) {
localOnlyMessages.add(message); | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,232,542 | 444,140 | 62,418 | 358 | 602 | 106 | 13 | 1 | 764 | 134 | 173 | 40 | 0 | 0 | 2022-02-22T01:30:13 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,550 | thundernest/k-9/5881/5879 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5879 | https://github.com/thundernest/k-9/pull/5881 | https://github.com/thundernest/k-9/pull/5881 | 1 | fixes | Can't connect to POP3 server (IONOS, GMX, maybe others) | ### Checklist
- [X] I have used the search function to see if someone else has already submitted the same bug report.
- [X] I will describe the problem with as much detail as possible.
### App version
5.806
### Where did you get the app from?
Google Play
### Android version
8.0
### Device model
Shift 5me
### Steps to reproduce
Open K-9 mail inbox; start refreshing the view manually.
### Expected behavior
K-9 is supposed to load new mails. Or at least give some error message saying that something's wrong.
### Actual behavior
Nothing. K-9 shows the reload-icon for a second and nothing else happens. Checking the inbox settings reveals an actual error message which I try to translate from German: "Unable to finish setup. Connection to server not possible. (Unable to exectute pop3 command)"
But my server settings are fine. I didn't change anything and other mail clients work ok using the same settings. I also checked if sending a message works: It does.
Restarting the app doesn't help; restarting the phone doesn't help. Currently K-9 is useless for me.
### Logs
_No response_ | de15580e400b8101a10d824fbc6e8a111373880d | 251a221b3b3fd86b11b5f58f2a4fe197c45bf36e | https://github.com/thundernest/k-9/compare/de15580e400b8101a10d824fbc6e8a111373880d...251a221b3b3fd86b11b5f58f2a4fe197c45bf36e | diff --git a/mail/protocols/pop3/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Connection.java b/mail/protocols/pop3/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Connection.java
index 666d40065..2a0d004e2 100644
--- a/mail/protocols/pop3/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Connection.java
+++ b/mail/protocols/pop3/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Connection.java
@@ -175,40 +175,6 @@ class Pop3Connection {
private Pop3Capabilities getCapabilities() throws IOException {
Pop3Capabilities capabilities = new Pop3Capabilities();
- try {
- /*
- * Try sending an AUTH command with no arguments.
- *
- * The server may respond with a list of supported SASL
- * authentication mechanisms.
- *
- * Ref.: http://tools.ietf.org/html/draft-myers-sasl-pop3-05
- *
- * While this never became a standard, there are servers that
- * support it, and Thunderbird includes this check.
- */
- executeSimpleCommand(AUTH_COMMAND);
- String response;
- while ((response = readLine()) != null) {
- if (response.equals(".")) {
- break;
- }
- response = response.toUpperCase(Locale.US);
- switch (response) {
- case AUTH_PLAIN_CAPABILITY:
- capabilities.authPlain = true;
- break;
- case AUTH_CRAM_MD5_CAPABILITY:
- capabilities.cramMD5 = true;
- break;
- case AUTH_EXTERNAL_CAPABILITY:
- capabilities.external = true;
- break;
- }
- }
- } catch (MessagingException ignored) {
- // Assume AUTH command with no arguments is not supported.
- }
try {
executeSimpleCommand(CAPA_COMMAND);
String response;
@@ -231,6 +197,9 @@ class Pop3Connection {
if (saslAuthMechanisms.contains(AUTH_CRAM_MD5_CAPABILITY)) {
capabilities.cramMD5 = true;
}
+ if (saslAuthMechanisms.contains(AUTH_EXTERNAL_CAPABILITY)) {
+ capabilities.external = true;
+ }
}
}
diff --git a/mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3ConnectionTest.java b/mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3ConnectionTest.java
index 5bcab0b02..9f8d0b6e1 100644
--- a/mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3ConnectionTest.java
+++ b/mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3ConnectionTest.java
@@ -42,29 +42,19 @@ public class Pop3ConnectionTest {
private static String username = "user";
private static String password = "password";
private static final String INITIAL_RESPONSE = "+OK POP3 server greeting\\r\\n";
- private static final String AUTH = "AUTH\\r\\n";
- private static final String AUTH_HANDLE_RESPONSE =
- "+OK Listing of supported mechanisms follows\\r\\n" +
- "PLAIN\\r\\n" +
- "CRAM-MD5\\r\\n" +
- "EXTERNAL\\r\\n" +
- ".\\r\\n";
private static final String CAPA =
"CAPA\\r\\n";
private static final String CAPA_RESPONSE =
"+OK Listing of supported mechanisms follows\\r\\n" +
- "PLAIN\\r\\n" +
- "CRAM-MD5\\r\\n" +
- "EXTERNAL\\r\\n" +
+ "SASL PLAIN CRAM-MD5 EXTERNAL\\r\\n" +
".\\r\\n";
private static final String AUTH_PLAIN_WITH_LOGIN = "AUTH PLAIN\\r\\n" +
new String(Base64.encodeBase64(("\\000"+username+"\\000"+password).getBytes())) + "\\r\\n";
private static final String AUTH_PLAIN_AUTHENTICATED_RESPONSE = "+OK\\r\\n" + "+OK\\r\\n";
- private static final String SUCCESSFUL_PLAIN_AUTH = AUTH + CAPA + AUTH_PLAIN_WITH_LOGIN;
+ private static final String SUCCESSFUL_PLAIN_AUTH = CAPA + AUTH_PLAIN_WITH_LOGIN;
private static final String SUCCESSFUL_PLAIN_AUTH_RESPONSE =
INITIAL_RESPONSE +
- AUTH_HANDLE_RESPONSE +
CAPA_RESPONSE +
AUTH_PLAIN_AUTHENTICATED_RESPONSE;
/**
@@ -323,12 +313,9 @@ public class Pop3ConnectionTest {
private MockPop3Server setupUnavailableStartTLSConnection() throws IOException {new MockPop3Server();
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
+ server.output("SASL PLAIN");
server.output(".");
server.start();
settings.setHost(server.getHost());
@@ -339,13 +326,10 @@ public class Pop3ConnectionTest {
private void setupServerWithStartTLSAvailable(MockPop3Server server) {
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
server.output("STLS");
+ server.output("SASL PLAIN");
server.output(".");
}
@@ -357,17 +341,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL PLAIN CRAM-MD5 EXTERNAL");
server.output(".");
server.expect("AUTH PLAIN");
server.output("+OK");
@@ -385,17 +361,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL PLAIN CRAM-MD5 EXTERNAL");
server.output(".");
server.expect("AUTH PLAIN");
server.output("+OK");
@@ -416,15 +384,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL CRAM-MD5 EXTERNAL");
server.output(".");
server.expect("USER user");
server.output("+OK");
@@ -445,15 +407,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL CRAM-MD5 EXTERNAL");
server.output(".");
server.expect("USER user");
server.output("+OK");
@@ -471,17 +427,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL PLAIN CRAM-MD5 EXTERNAL");
server.output(".");
server.expect("AUTH CRAM-MD5");
server.output("+ abcd");
@@ -500,17 +448,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL PLAIN CRAM-MD5 EXTERNAL");
server.output(".");
server.expect("AUTH CRAM-MD5");
server.output("+ abcd");
@@ -531,15 +471,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK abc<a>abcd");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("EXTERNAL");
+ server.output("SASL PLAIN EXTERNAL");
server.output(".");
server.expect("APOP user c8e8c560e385faaa6367d4145572b8ea");
server.output("+OK");
@@ -556,15 +490,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK abc<a>abcd");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("EXTERNAL");
+ server.output("SASL PLAIN EXTERNAL");
server.output(".");
server.expect("APOP user c8e8c560e385faaa6367d4145572b8ea");
server.output("-ERR");
@@ -583,17 +511,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL CRAM-MD5 EXTERNAL");
server.output(".");
server.expect("AUTH EXTERNAL dXNlcg==");
server.output("+OK");
@@ -609,16 +529,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL PLAIN CRAM-MD5");
server.output(".");
try {
@@ -638,17 +551,9 @@ public class Pop3ConnectionTest {
MockPop3Server server = new MockPop3Server();
server.output("+OK POP3 server greeting");
- server.expect("AUTH");
- server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
- server.output(".");
server.expect("CAPA");
server.output("+OK Listing of supported mechanisms follows");
- server.output("PLAIN");
- server.output("CRAM-MD5");
- server.output("EXTERNAL");
+ server.output("SASL PLAIN CRAM-MD5 EXTERNAL");
server.output(".");
server.expect("AUTH EXTERNAL dXNlcg==");
server.output("-ERR Invalid certificate");
diff --git a/mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java b/mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java
index 6363592e4..d7021637c 100644
--- a/mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java
+++ b/mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java
@@ -28,17 +28,9 @@ import static org.mockito.Mockito.when;
public class Pop3StoreTest {
private static final String INITIAL_RESPONSE = "+OK POP3 server greeting\\r\\n";
- private static final String AUTH = "AUTH\\r\\n";
- private static final String AUTH_HANDLE_RESPONSE = "+OK Listing of supported mechanisms follows\\r\\n" +
- "PLAIN\\r\\n" +
- "CRAM-MD5\\r\\n" +
- "EXTERNAL\\r\\n" +
- ".\\r\\n";
private static final String CAPA = "CAPA\\r\\n";
private static final String CAPA_RESPONSE = "+OK Listing of supported mechanisms follows\\r\\n" +
- "PLAIN\\r\\n" +
- "CRAM-MD5\\r\\n" +
- "EXTERNAL\\r\\n" +
+ "SASL PLAIN CRAM-MD5 EXTERNAL\\r\\n" +
".\\r\\n";
private static final String AUTH_PLAIN_WITH_LOGIN = "AUTH PLAIN\\r\\n" +
new String(Base64.encodeBase64(("\\000user\\000password").getBytes())) + "\\r\\n";
@@ -94,7 +86,6 @@ public class Pop3StoreTest {
public void checkSetting_whenUidlUnsupported_shouldThrowMessagingException()
throws Exception {
String response = INITIAL_RESPONSE +
- AUTH_HANDLE_RESPONSE +
CAPA_RESPONSE +
AUTH_PLAIN_AUTHENTICATED_RESPONSE +
STAT_RESPONSE +
@@ -109,7 +100,6 @@ public class Pop3StoreTest {
public void checkSetting_whenUidlSupported_shouldReturn()
throws Exception {
String response = INITIAL_RESPONSE +
- AUTH_HANDLE_RESPONSE +
CAPA_RESPONSE +
AUTH_PLAIN_AUTHENTICATED_RESPONSE +
STAT_RESPONSE +
@@ -125,7 +115,6 @@ public class Pop3StoreTest {
@Test
public void open_withAuthResponseUsingAuthPlain_shouldRetrieveMessageCountOnAuthenticatedSocket() throws Exception {
String response = INITIAL_RESPONSE +
- AUTH_HANDLE_RESPONSE +
CAPA_RESPONSE +
AUTH_PLAIN_AUTHENTICATED_RESPONSE +
STAT_RESPONSE;
@@ -137,13 +126,12 @@ public class Pop3StoreTest {
folder.open();
assertEquals(20, folder.getMessageCount());
- assertEquals(AUTH + CAPA + AUTH_PLAIN_WITH_LOGIN + STAT, byteArrayOutputStream.toString("UTF-8"));
+ assertEquals(CAPA + AUTH_PLAIN_WITH_LOGIN + STAT, byteArrayOutputStream.toString("UTF-8"));
}
@Test(expected = AuthenticationFailedException.class)
public void open_withFailedAuth_shouldThrow() throws Exception {
String response = INITIAL_RESPONSE +
- AUTH_HANDLE_RESPONSE +
CAPA_RESPONSE +
AUTH_PLAIN_FAILED_RESPONSE;
when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes("UTF-8"))); | ['mail/protocols/pop3/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Connection.java', 'mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java', 'mail/protocols/pop3/src/test/java/com/fsck/k9/mail/store/pop3/Pop3ConnectionTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 2,274,800 | 452,593 | 63,876 | 364 | 1,547 | 251 | 37 | 1 | 1,109 | 187 | 250 | 40 | 0 | 0 | 2022-01-25T16:47:38 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,552 | thundernest/k-9/5864/5800 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5800 | https://github.com/thundernest/k-9/pull/5864 | https://github.com/thundernest/k-9/pull/5864 | 1 | fix | Username isn't trimmed | **Describe the bug**
When adding a new email account, the specified username is not trimmed. Thus when C&P'ing a username that happens to contain a space (at the end), the authentication will fail and it is very hard to figure out that the training space is the issue, since it is not rendered (as a visible character)
**Expected behavior**
The username should be trimmed to remove leading and training spaces. Alternatively leading or training whitespace should be highlighted so it is easier to spot.
**Environment (please complete the following information):**
- K-9 Mail version: 5.806
- Android version: 8
- Device: Shiftphone 6m
- Account type: IMAP | 722e6b923fcdb511a72234cb4d06a92759059c9c | 1ffc7ba02cfbba0b97c122433bc2d5b97c496bd2 | https://github.com/thundernest/k-9/compare/722e6b923fcdb511a72234cb4d06a92759059c9c...1ffc7ba02cfbba0b97c122433bc2d5b97c496bd2 | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java
index b5cba2113..c3f27bcf5 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java
@@ -21,6 +21,7 @@ import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.Toast;
+import androidx.annotation.NonNull;
import com.fsck.k9.Account;
import com.fsck.k9.DI;
import com.fsck.k9.LocalKeyStoreManager;
@@ -395,7 +396,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener
}
@Override
- public void onSaveInstanceState(Bundle outState) {
+ public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(EXTRA_ACCOUNT, mAccount.getUuid());
outState.putInt(STATE_SECURITY_TYPE_POSITION, mCurrentSecurityTypeViewPosition);
@@ -550,7 +551,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener
* Set the username and password for the outgoing settings to the username and
* password the user just set for incoming.
*/
- String username = mUsernameView.getText().toString();
+ String username = mUsernameView.getText().toString().trim();
String password = null;
String clientCertificateAlias = null;
@@ -579,7 +580,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener
try {
ConnectionSecurity connectionSecurity = getSelectedSecurity();
- String username = mUsernameView.getText().toString();
+ String username = mUsernameView.getText().toString().trim();
String password = null;
String clientCertificateAlias = null;
@@ -662,12 +663,7 @@ public class AccountSetupIncoming extends K9Activity implements OnClickListener
}
};
- OnClientCertificateChangedListener clientCertificateChangedListener = new OnClientCertificateChangedListener() {
- @Override
- public void onClientCertificateChanged(String alias) {
- validateFields();
- }
- };
+ OnClientCertificateChangedListener clientCertificateChangedListener = alias -> validateFields();
private AuthType getSelectedAuthType() {
AuthTypeHolder holder = (AuthTypeHolder) mAuthTypeView.getSelectedItem();
diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java
index 72eebcbed..8e64281ae 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java
@@ -22,6 +22,7 @@ import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.Toast;
+import androidx.annotation.NonNull;
import com.fsck.k9.Account;
import com.fsck.k9.DI;
import com.fsck.k9.LocalKeyStoreManager;
@@ -189,7 +190,7 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener,
}
mSecurityTypeView.setSelection(mCurrentSecurityTypeViewPosition, false);
- if (settings.username != null && !settings.username.isEmpty()) {
+ if (!settings.username.isEmpty()) {
mUsernameView.setText(settings.username);
mRequireLoginView.setChecked(true);
mRequireLoginSettingsView.setVisibility(View.VISIBLE);
@@ -316,7 +317,7 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener,
}
@Override
- public void onSaveInstanceState(Bundle outState) {
+ public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(EXTRA_ACCOUNT, mAccount.getUuid());
outState.putInt(STATE_SECURITY_TYPE_POSITION, mCurrentSecurityTypeViewPosition);
@@ -491,7 +492,7 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener,
clientCertificateAlias = mClientCertificateSpinner.getAlias();
}
if (mRequireLoginView.isChecked()) {
- username = mUsernameView.getText().toString();
+ username = mUsernameView.getText().toString().trim();
authType = getSelectedAuthType();
if (AuthType.EXTERNAL != authType) {
@@ -543,12 +544,7 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener,
}
};
- OnClientCertificateChangedListener clientCertificateChangedListener = new OnClientCertificateChangedListener() {
- @Override
- public void onClientCertificateChanged(String alias) {
- validateFields();
- }
- };
+ OnClientCertificateChangedListener clientCertificateChangedListener = alias -> validateFields();
private AuthType getSelectedAuthType() {
AuthTypeHolder holder = (AuthTypeHolder) mAuthTypeView.getSelectedItem(); | ['app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java', 'app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupIncoming.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,274,710 | 452,555 | 63,881 | 365 | 1,564 | 262 | 28 | 2 | 673 | 107 | 145 | 12 | 0 | 0 | 2022-01-13T19:06:22 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,553 | thundernest/k-9/5854/5851 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5851 | https://github.com/thundernest/k-9/pull/5854 | https://github.com/thundernest/k-9/pull/5854 | 1 | fixes | Outbox Refreshes Once Mail Sends But Leaves Numbers With Empty Outbox | Please search to check for an existing issue (including closed issues, for which the fix may not have yet been released) before opening a new issue: https://github.com/k9mail/k-9/issues?q=is%3Aissue
If you are unsure whether or not you have found a bug please post to the support forum instead: https://forum.k9mail.app
**Describe the bug**
Outbox numeric counts says there is items being sent when the outbox is empty. Only way to remove it is by refreshing the inbox or other folder.
**To Reproduce**
1. Send mail
2. Outbox contains being sent mail and once refreshes it still contains numeric count on empty outbox
3. Refresh inbox or other folder. Refreshing outbox doesn't fix it.
4. See error fixed in numeric count on outbox
**Expected behavior**
No numeric count on empty outbox. A refresh shouldn't need to be done on other folder to get numeric count gone on empty outbox.
**Screenshots**
None
**Environment (please complete the following information):**
- K-9 Mail version: 5.907
- Android version: 10
- Device: Galaxy S9 +
- Account type: IMAP (Does on POP3 too)
**Additional context**
None
**Logs**
None
| b05c0ea5c4f0f953ef1e4844b91a94192cec2aa4 | d68b3269941f14fb1076364ff465248420f7dfc5 | https://github.com/thundernest/k-9/compare/b05c0ea5c4f0f953ef1e4844b91a94192cec2aa4...d68b3269941f14fb1076364ff465248420f7dfc5 | diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
index 3e1a70258..ba4ca011e 100644
--- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
+++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
@@ -1662,6 +1662,10 @@ public class MessagingController {
processPendingCommands(account);
}
}
+
+ for (MessagingListener listener : getListeners()) {
+ listener.folderStatusChanged(account, account.getOutboxFolderId());
+ }
}
private void handleSendFailure(Account account, LocalFolder localFolder, Message message, Exception exception) | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,274,409 | 452,511 | 63,875 | 365 | 154 | 28 | 4 | 1 | 1,175 | 180 | 280 | 38 | 2 | 0 | 2022-01-09T07:17:48 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,613 | thundernest/k-9/4540/4498 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4498 | https://github.com/thundernest/k-9/pull/4540 | https://github.com/thundernest/k-9/pull/4540 | 1 | fixes | youtube loads in the message window | ### Expected behavior
When opening a message from a subscribed youtube channel and after pressing the video thumbnail or link, a popup should appear asking you which application to use to open the video link.
### Actual behavior
The video loads in the message window.
### Steps to reproduce
1. Open the message with the youtube link
2. Click on the thumbnail or video link
### Environment
K-9 Mail version: 5.704
Android version: 5.1
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
Please take some time to [retrieve logs](https://github.com/k9mail/k-9/wiki/LoggingErrors) and attach them here:
| 5dce1101edb40076423fa04c44e23b1a12958b40 | ce7b59addfa59e414db1cf6d9810a673df0aaa46 | https://github.com/thundernest/k-9/compare/5dce1101edb40076423fa04c44e23b1a12958b40...ce7b59addfa59e414db1cf6d9810a673df0aaa46 | diff --git a/app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java b/app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java
index 8fdc85179..29ef07e44 100644
--- a/app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java
+++ b/app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java
@@ -10,6 +10,7 @@ import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
+import android.os.Build;
import android.provider.Browser;
import android.text.TextUtils;
import android.webkit.WebResourceRequest;
@@ -19,6 +20,8 @@ import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.Nullable;
+import androidx.annotation.RequiresApi;
+
import com.fsck.k9.mailstore.AttachmentResolver;
import com.fsck.k9.ui.R;
import com.fsck.k9.view.MessageWebView.OnPageFinishedListener;
@@ -49,8 +52,17 @@ public class K9WebViewClient extends WebViewClient {
}
@Override
+ public boolean shouldOverrideUrlLoading(WebView webView, String url) {
+ return shouldOverrideUrlLoading(webView, Uri.parse(url));
+ }
+
+ @Override
+ @RequiresApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request) {
- Uri uri = request.getUrl();
+ return shouldOverrideUrlLoading(webView, request.getUrl());
+ }
+
+ private boolean shouldOverrideUrlLoading(WebView webView, Uri uri) {
if (CID_SCHEME.equals(uri.getScheme())) {
return false;
} | ['app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,065,884 | 603,974 | 85,212 | 472 | 465 | 90 | 14 | 1 | 620 | 91 | 144 | 19 | 1 | 0 | 2020-02-16T13:47:12 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,615 | thundernest/k-9/4506/4498 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4498 | https://github.com/thundernest/k-9/pull/4506 | https://github.com/thundernest/k-9/pull/4506 | 1 | fixes | youtube loads in the message window | ### Expected behavior
When opening a message from a subscribed youtube channel and after pressing the video thumbnail or link, a popup should appear asking you which application to use to open the video link.
### Actual behavior
The video loads in the message window.
### Steps to reproduce
1. Open the message with the youtube link
2. Click on the thumbnail or video link
### Environment
K-9 Mail version: 5.704
Android version: 5.1
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
Please take some time to [retrieve logs](https://github.com/k9mail/k-9/wiki/LoggingErrors) and attach them here:
| 79c06745fb27af807d894092d5001506aaaddf53 | 67e2029d56e2c2d13200d149196f6cdc04a4e71a | https://github.com/thundernest/k-9/compare/79c06745fb27af807d894092d5001506aaaddf53...67e2029d56e2c2d13200d149196f6cdc04a4e71a | diff --git a/app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java b/app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java
index aac73ba73..8fdc85179 100644
--- a/app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java
+++ b/app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java
@@ -16,9 +16,11 @@ import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
+import android.widget.Toast;
import androidx.annotation.Nullable;
import com.fsck.k9.mailstore.AttachmentResolver;
+import com.fsck.k9.ui.R;
import com.fsck.k9.view.MessageWebView.OnPageFinishedListener;
import timber.log.Timber;
@@ -56,15 +58,13 @@ public class K9WebViewClient extends WebViewClient {
Context context = webView.getContext();
Intent intent = createBrowserViewIntent(uri, context);
- boolean overridingUrlLoading = false;
try {
context.startActivity(intent);
- overridingUrlLoading = true;
} catch (ActivityNotFoundException ex) {
- // If no application can handle the URL, assume that the WebView can handle it.
+ Toast.makeText(context, R.string.error_activity_not_found, Toast.LENGTH_LONG).show();
}
- return overridingUrlLoading;
+ return true;
}
private Intent createBrowserViewIntent(Uri uri, Context context) { | ['app/ui/src/main/java/com/fsck/k9/view/K9WebViewClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,066,654 | 604,188 | 85,247 | 473 | 396 | 75 | 8 | 1 | 620 | 91 | 144 | 19 | 1 | 0 | 2020-02-06T13:14:46 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,520 | thundernest/k-9/6372/3937 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3937 | https://github.com/thundernest/k-9/pull/6372 | https://github.com/thundernest/k-9/pull/6372 | 1 | fixes | Message inadvertently sent twice | When sending emails through K-9 on a Xiaomi Mi Mix2, occasionally the same email is sent twice. This happens both on Wi-Fi and mobile data connections. It is unclear what triggers the issue, but it appears specific to K-9 running on a Xiaomi Mi Mix2, so either the application or the phone, or the combination of the two, may be a cause. The problem does not occur when sending emails through Xiaomi's native email client using the same account, or when using K-9 with the same account on a Xiaomi Mi4 and Xiaomi Mi Max2.
### Steps to reproduce
1. Send email from within K-9.
2. Check "Sent" folder of account where the message is sent from.
3. Check inbox of recipient account.
### Expected behaviour
One email is sent. The "Sent" folder should contain one copy of the message. The recipient should have received one copy of the message.
### Actual behaviour
When the issue occurs, two emails are sent. The "Sent" folder shows two messages with identical subject and body text but with different IDs and different time stamps. The recipient has received the same message twice.
### Environment
K-9 Mail version:
K-9 Mail Version 5.600
Installed via F-Droid
Note: K-9 is given full permissions and battery management is set to "unrestricted".
Android version:
Xiaomi Mi Mix2 (Chinese version)
MIUI 10.2.2.0
Android 8.0.0
Security patch level 2018-12-01
Kernel version 4.4.78-perf-g7ac6a25
Account type:
IMAP account at [FastMail](https://www.fastmail.com/)
### Log
A log illustrating the issue is attached. The problem occurs at timestamp "03-02 11:23" (two emails are sent), but it does not occur at "03-02 11:34" (only one email is sent).
[k9-log-subset.txt](https://github.com/k9mail/k-9/files/2921755/k9-log-subset.txt)
| e94a42f63f1f2b4858a5e749f39720fa92220d69 | 738ba9c112126c745cf0bd408427899db9d28d41 | https://github.com/thundernest/k-9/compare/e94a42f63f1f2b4858a5e749f39720fa92220d69...738ba9c112126c745cf0bd408427899db9d28d41 | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java
index 81b55765a..925edd1ed 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java
@@ -241,6 +241,8 @@ public class MessageCompose extends K9Activity implements OnClickListener,
private boolean navigateUp;
+ private boolean sendMessageHasBeenTriggered = false;
+
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -797,6 +799,12 @@ public class MessageCompose extends K9Activity implements OnClickListener,
}
public void performSendAfterChecks() {
+ if (sendMessageHasBeenTriggered) {
+ return;
+ }
+
+ sendMessageHasBeenTriggered = true;
+
currentMessageBuilder = createMessageBuilder(false);
if (currentMessageBuilder != null) {
changesMadeSinceLastSave = false;
@@ -1607,6 +1615,7 @@ public class MessageCompose extends K9Activity implements OnClickListener,
@Override
public void onMessageBuildCancel() {
+ sendMessageHasBeenTriggered = false;
currentMessageBuilder = null;
setProgressBarIndeterminateVisibility(false);
}
@@ -1616,6 +1625,7 @@ public class MessageCompose extends K9Activity implements OnClickListener,
Timber.e(me, "Error sending message");
Toast.makeText(MessageCompose.this,
getString(R.string.send_failed_reason, me.getLocalizedMessage()), Toast.LENGTH_LONG).show();
+ sendMessageHasBeenTriggered = false;
currentMessageBuilder = null;
setProgressBarIndeterminateVisibility(false);
} | ['app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,987,713 | 397,255 | 55,512 | 333 | 276 | 48 | 10 | 1 | 1,771 | 272 | 442 | 37 | 2 | 0 | 2022-10-09T18:38:29 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,629 | thundernest/k-9/3864/3862 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3862 | https://github.com/thundernest/k-9/pull/3864 | https://github.com/thundernest/k-9/pull/3864 | 1 | fixes | Fix ImapStore.listFolders() when SPECIAL-USE extension is present | `LIST (SPECIAL-USE) …` only lists special folders, not special folders and regular folders.
We probably want to switch back to using a regular LSUB/LIST, then querying the special folders and adding them to our list afterwards. That way we'll get to use a special folder, even if it wasn't included in the result list of the previous LIST command (because the user isn't subscribed to it or it's outside of the subtree specified by the IMAP path prefix). | 6a64d5e380d60ee6de6be8e22f5f016af407c015 | e4d7482bef618c76e9e52cf86aa636dfa29feb4e | https://github.com/thundernest/k-9/compare/6a64d5e380d60ee6de6be8e22f5f016af407c015...e4d7482bef618c76e9e52cf86aa636dfa29feb4e | diff --git a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
index 0758cf6ce..dde67c72f 100644
--- a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
+++ b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
@@ -694,11 +694,15 @@ class ImapConnection {
return isListResponse && hierarchyDelimiterValid;
}
- protected boolean hasCapability(String capability) {
+ protected boolean hasCapability(String capability) throws IOException, MessagingException {
+ if (!open) {
+ open();
+ }
+
return capabilities.contains(capability.toUpperCase(Locale.US));
}
- public boolean isCondstoreCapable() {
+ public boolean isCondstoreCapable() throws IOException, MessagingException {
return hasCapability(Capabilities.CONDSTORE);
}
@@ -886,7 +890,7 @@ class ImapConnection {
return response;
}
- int getLineLengthLimit() {
+ int getLineLengthLimit() throws IOException, MessagingException {
return isCondstoreCapable() ? LENGTH_LIMIT_WITH_CONDSTORE : LENGTH_LIMIT_WITHOUT_CONDSTORE;
}
}
diff --git a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
index dd06807b6..645ced912 100644
--- a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
+++ b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
@@ -162,19 +162,18 @@ public class ImapStore extends RemoteStore {
private List<FolderListItem> listFolders(ImapConnection connection, boolean subscribedOnly) throws IOException,
MessagingException {
- String command;
+ String commandFormat;
if (subscribedOnly) {
- command = "LSUB";
+ commandFormat = "LSUB \\"\\" %s";
} else if (connection.hasCapability(Capabilities.SPECIAL_USE) &&
connection.hasCapability(Capabilities.LIST_EXTENDED)) {
- command = "LIST (SPECIAL-USE)";
+ commandFormat = "LIST \\"\\" %s RETURN (SPECIAL-USE)";
} else {
- command = "LIST";
+ commandFormat = "LIST \\"\\" %s";
}
String encodedListPrefix = ImapUtility.encodeString(getCombinedPrefix() + "*");
- List<ImapResponse> responses = connection.executeSimpleCommand(
- String.format("%s \\"\\" %s", command, encodedListPrefix));
+ List<ImapResponse> responses = connection.executeSimpleCommand(String.format(commandFormat, encodedListPrefix));
List<ListResponse> listResponses = (subscribedOnly) ?
ListResponse.parseLsub(responses) :
diff --git a/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java b/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java
index 3d26c9cd3..6ace4f139 100644
--- a/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java
+++ b/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java
@@ -935,6 +935,19 @@ public class ImapConnectionTest {
server.verifyInteractionCompleted();
}
+ @Test
+ public void hasCapability_withNotYetOpenedConnection_shouldConnectAndFetchCapabilities() throws Exception {
+ MockImapServer server = new MockImapServer();
+ simpleOpenDialog(server, "X-SOMETHING");
+ ImapConnection imapConnection = startServerAndCreateImapConnection(server);
+
+ boolean capabilityPresent = imapConnection.hasCapability("X-SOMETHING");
+
+ assertTrue(capabilityPresent);
+ server.verifyConnectionStillOpen();
+ server.verifyInteractionCompleted();
+ }
+
private ImapConnection createImapConnection(ImapSettings settings, TrustedSocketFactory socketFactory,
ConnectivityManager connectivityManager, OAuth2TokenProvider oAuth2TokenProvider) {
return new ImapConnection(settings, socketFactory, connectivityManager, oAuth2TokenProvider,
diff --git a/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java b/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java
index be5177b7b..d7079fa16 100644
--- a/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java
+++ b/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java
@@ -115,7 +115,7 @@ public class ImapStoreTest {
createImapResponse("* LIST (\\\\HasNoChildren \\\\Trash) \\"/\\" \\"[Gmail]/Trash\\""),
createImapResponse("5 OK Success")
);
- when(imapConnection.executeSimpleCommand("LIST (SPECIAL-USE) \\"\\" \\"*\\"")).thenReturn(imapResponses);
+ when(imapConnection.executeSimpleCommand("LIST \\"\\" \\"*\\" RETURN (SPECIAL-USE)")).thenReturn(imapResponses);
imapStore.enqueueImapConnection(imapConnection);
List<ImapFolder> folders = imapStore.getPersonalNamespaces();
@@ -138,7 +138,7 @@ public class ImapStoreTest {
imapStore.getPersonalNamespaces();
- verify(imapConnection, never()).executeSimpleCommand("LIST (SPECIAL-USE) \\"\\" \\"*\\"");
+ verify(imapConnection, never()).executeSimpleCommand("LIST \\"\\" \\"*\\" RETURN (SPECIAL-USE)");
verify(imapConnection).executeSimpleCommand("LIST \\"\\" \\"*\\"");
}
@@ -151,7 +151,7 @@ public class ImapStoreTest {
imapStore.getPersonalNamespaces();
- verify(imapConnection, never()).executeSimpleCommand("LIST (SPECIAL-USE) \\"\\" \\"*\\"");
+ verify(imapConnection, never()).executeSimpleCommand("LIST \\"\\" \\"*\\" RETURN (SPECIAL-USE)");
verify(imapConnection).executeSimpleCommand("LIST \\"\\" \\"*\\"");
}
| ['mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java', 'mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java', 'mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java', 'mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 3,430,452 | 674,824 | 95,177 | 504 | 1,027 | 206 | 21 | 2 | 457 | 78 | 100 | 3 | 0 | 0 | 2019-01-07T01:08:46 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,627 | thundernest/k-9/4161/4160 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4160 | https://github.com/thundernest/k-9/pull/4161 | https://github.com/thundernest/k-9/pull/4161 | 1 | fixes | The application still has some bugs | Hello. I noticed some crashes in logs. The corresponding commit version of code is e85e91c, and application version is 5.6.
## 1.com.fsck.k9.activity.LauncherShortcuts
The exception trace is:
*FATAL EXCEPTION: main
android.util.SuperNotCalledException: Activity {com.fsck.k9/com.fsck.k9.activity.LauncherShortcuts} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)*
### The command to trigger it is: adb shell am start -n com.fsck.k9/com.fsck.k9.activity.LauncherShortcuts
## 2.com.fsck.k9.activity.MessageList
The exception trace is:
*FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fsck.k9/com.fsck.k9.activity.MessageList}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.fsck.k9.search.LocalSearch.addAccountUuid(LocalSearch.java:113)
at com.fsck.k9.activity.MessageList.decodeExtras(MessageList.java:424)
at com.fsck.k9.activity.MessageList.onCreate(MessageList.java:224)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)*
### And this is our test case "*action*: android.intent.action.SEARCH;; *category*: null;; *data*: null;; *type*: null;; *extradata*: String->query->abcde,Bundle->app_data->BundleObj,(,String->com.fsck.k9.search_folder->abcde,),"
## 3.com.fsck.k9.activity.Search
The exception trace is:
*FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fsck.k9/com.fsck.k9.activity.Search}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.fsck.k9.search.LocalSearch.addAccountUuid(LocalSearch.java:113)
at com.fsck.k9.activity.MessageList.decodeExtras(MessageList.java:424)
at com.fsck.k9.activity.MessageList.onCreate(MessageList.java:224)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)*
### And this is our test case "*action*: android.intent.action.SEARCH;; *category*: null;; *data*: null;; *type*: null;; *extradata*: String->query->abcde,Bundle->app_data->BundleObj,(,String->com.fsck.k9.search_folder->abcde,),"
Because all these activities are exported ones, i.e., be exposed to outside, they may receive unfriendly commands and then lead to app crash. After investigation, we found that the missing of null checkers causes those crashes.
Please help to confirm whether they are true bugs. We believe that fixing these bugs will further improve the robustness of this app. | 168e0908464f5fe8306d99119864438d66d1da8e | 4886f2f8fc943b2507bec8d6b9fb6affc25c163c | https://github.com/thundernest/k-9/compare/168e0908464f5fe8306d99119864438d66d1da8e...4886f2f8fc943b2507bec8d6b9fb6affc25c163c | diff --git a/app/ui/src/main/java/com/fsck/k9/activity/LauncherShortcuts.java b/app/ui/src/main/java/com/fsck/k9/activity/LauncherShortcuts.java
index 1e26574b7..990d24793 100644
--- a/app/ui/src/main/java/com/fsck/k9/activity/LauncherShortcuts.java
+++ b/app/ui/src/main/java/com/fsck/k9/activity/LauncherShortcuts.java
@@ -12,13 +12,12 @@ import com.fsck.k9.search.SearchAccount;
public class LauncherShortcuts extends AccountList {
@Override
public void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
+
// finish() immediately if we aren't supposed to be here
if (!Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())) {
finish();
- return;
}
-
- super.onCreate(icicle);
}
@Override
diff --git a/app/ui/src/main/java/com/fsck/k9/activity/MessageList.java b/app/ui/src/main/java/com/fsck/k9/activity/MessageList.java
index 02095f820..43f3f9954 100644
--- a/app/ui/src/main/java/com/fsck/k9/activity/MessageList.java
+++ b/app/ui/src/main/java/com/fsck/k9/activity/MessageList.java
@@ -53,6 +53,7 @@ import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.SearchCondition;
import com.fsck.k9.search.SearchSpecification.SearchField;
+import com.fsck.k9.ui.BuildConfig;
import com.fsck.k9.ui.K9Drawer;
import com.fsck.k9.ui.R;
import com.fsck.k9.ui.Theme;
@@ -437,10 +438,15 @@ public class MessageList extends K9Activity implements MessageListFragmentListen
Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
- search.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT));
- // searches started from a folder list activity will provide an account, but no folder
- if (appData.getString(EXTRA_SEARCH_FOLDER) != null) {
- search.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER));
+ String searchAccountUuid = appData.getString(EXTRA_SEARCH_ACCOUNT);
+ if (searchAccountUuid != null) {
+ search.addAccountUuid(searchAccountUuid);
+ // searches started from a folder list activity will provide an account, but no folder
+ if (appData.getString(EXTRA_SEARCH_FOLDER) != null) {
+ search.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER));
+ }
+ } else if (BuildConfig.DEBUG) {
+ throw new AssertionError("Invalid app data in search intent");
}
} else {
search.addAccountUuid(LocalSearch.ALL_ACCOUNTS);
@@ -466,14 +472,22 @@ public class MessageList extends K9Activity implements MessageListFragmentListen
}
if (search == null) {
- // We've most likely been started by an old unread widget
String accountUuid = intent.getStringExtra("account");
- String folderServerId = intent.getStringExtra("folder");
+ if (accountUuid != null) {
+ // We've most likely been started by an old unread widget
+ String folderServerId = intent.getStringExtra("folder");
+
+ search = new LocalSearch(folderServerId);
+ search.addAccountUuid(accountUuid);
+ if (folderServerId != null) {
+ search.addAllowedFolder(folderServerId);
+ }
+ } else {
+ if (BuildConfig.DEBUG) {
+ throw new AssertionError("MessageList started without required extras");
+ }
- search = new LocalSearch(folderServerId);
- search.addAccountUuid((accountUuid == null) ? "invalid" : accountUuid);
- if (folderServerId != null) {
- search.addAllowedFolder(folderServerId);
+ search = SearchAccount.createUnifiedInboxAccount().getRelatedSearch();
}
}
| ['app/ui/src/main/java/com/fsck/k9/activity/LauncherShortcuts.java', 'app/ui/src/main/java/com/fsck/k9/activity/MessageList.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,323,824 | 653,728 | 92,315 | 494 | 2,224 | 375 | 39 | 2 | 5,133 | 320 | 1,168 | 67 | 0 | 0 | 2019-08-15T14:53:32 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,626 | thundernest/k-9/4218/4121 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4121 | https://github.com/thundernest/k-9/pull/4218 | https://github.com/thundernest/k-9/pull/4218 | 1 | closes | Openpgp enable crash | ### Actual behavior
K9 crashes when enabling openpgp support without having a provider installed.
### Steps to reproduce
Click the following:
1. Settings
2. Account
3. End-to-end encryption
4. Enable
5. Install
### Environment
K-9 Mail version: master
Android version:9.0
```
07-23 15:58:10.701 2290 3255 I ActivityManager: START u0 {cmp=com.fsck.k9.debug/com.fsck.k9.ui.settings.account.OpenPgpAppSelectDialog (has extras)} from uid 10101
07-23 15:58:10.755 17399 17399 W ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@17623b1
07-23 15:58:10.855 564 605 D SurfaceFlinger: duplicate layer name: changing com.fsck.k9.debug/com.fsck.k9.ui.settings.account.OpenPgpAppSelectDialog to com.fsck.k9.debug/com.fsck.k9.ui.settings.account.OpenPgpAppSelectDialog#1
07-23 15:58:11.765 2290 3255 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=market://details?id=org.sufficientlysecure.keychain cmp=android/com.android.internal.app.ResolverActivity} from uid 10101
07-23 15:58:11.778 17399 17435 D OpenGLRenderer: endAllActiveAnimators on 0x74bec6d500 (RippleDrawable) with handle 0x74c1635480
07-23 15:58:11.788 17315 17315 W ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@b317974
07-23 15:58:11.799 17399 17399 D AndroidRuntime: Shutting down VM
07-23 15:58:11.800 17399 17399 E AndroidRuntime: FATAL EXCEPTION: main
07-23 15:58:11.800 17399 17399 E AndroidRuntime: Process: com.fsck.k9.debug, PID: 17399
07-23 15:58:11.800 17399 17399 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.fragment.app.FragmentActivity.finish()' on a null object reference
07-23 15:58:11.800 17399 17399 E AndroidRuntime: at com.fsck.k9.ui.settings.account.OpenPgpAppSelectDialog$OpenKeychainInfoFragment.onDismiss(OpenPgpAppSelectDialog.java:327)
07-23 15:58:11.800 17399 17399 E AndroidRuntime: at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java:1393)
07-23 15:58:11.800 17399 17399 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106)
07-23 15:58:11.800 17399 17399 E AndroidRuntime: at android.os.Looper.loop(Looper.java:193)
07-23 15:58:11.800 17399 17399 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6718)
07-23 15:58:11.800 17399 17399 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
07-23 15:58:11.800 17399 17399 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
07-23 15:58:11.800 17399 17399 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
07-23 15:58:11.805 2290 2396 I ActivityManager: Showing crash dialog for package com.fsck.k9.debug u0
``` | 4f85dc2220a378036238d7c5fe1edf2580cb3381 | b981cd0efd8d4c8faff13085226c9863ead8e15b | https://github.com/thundernest/k-9/compare/4f85dc2220a378036238d7c5fe1edf2580cb3381...b981cd0efd8d4c8faff13085226c9863ead8e15b | diff --git a/app/ui/src/main/java/com/fsck/k9/ui/settings/account/OpenPgpAppSelectDialog.java b/app/ui/src/main/java/com/fsck/k9/ui/settings/account/OpenPgpAppSelectDialog.java
index d94bc56b8..376f8b0fb 100644
--- a/app/ui/src/main/java/com/fsck/k9/ui/settings/account/OpenPgpAppSelectDialog.java
+++ b/app/ui/src/main/java/com/fsck/k9/ui/settings/account/OpenPgpAppSelectDialog.java
@@ -297,8 +297,8 @@ public class OpenPgpAppSelectDialog extends FragmentActivity {
builder.setPositiveButton(R.string.dialog_openkeychain_info_install, new OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
- startOpenKeychainInstallActivity();
dismiss();
+ startOpenKeychainInstallActivity();
}
});
| ['app/ui/src/main/java/com/fsck/k9/ui/settings/account/OpenPgpAppSelectDialog.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,324,156 | 653,699 | 92,300 | 494 | 113 | 16 | 2 | 1 | 2,797 | 245 | 877 | 38 | 0 | 1 | 2019-10-13T09:51:10 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,624 | thundernest/k-9/4255/4250 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4250 | https://github.com/thundernest/k-9/pull/4255 | https://github.com/thundernest/k-9/pull/4255 | 1 | fixes | Cannot connect to server (Invalid CAPABILITY response received) | ### Expected behavior
Fetch mail
### Actual behavior
Cannot connect to server (Invalid CAPABILITY response received)
### Steps to reproduce
Capabilities returned from the IMAP server
```
a capability
* CAPABILITY IMAP4rev1 STARTTLS AUTH=PLAIN AUTH=LOGIN ID APPENDLIMIT
a OK CAPABILITY completed
```
### Environment
K-9 Mail version: 5.600
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
Please take some time to [retrieve logs](https://github.com/k9mail/k-9/wiki/LoggingErrors) and attach them here:
TBD
| f62615bb577b0ee76cbfcbcca49dcd837d4225bd | b241201e88e27ee5361130dfffe4ca613ae0c98a | https://github.com/thundernest/k-9/compare/f62615bb577b0ee76cbfcbcca49dcd837d4225bd...b241201e88e27ee5361130dfffe4ca613ae0c98a | diff --git a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
index dde67c72f..3b866a0c4 100644
--- a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
+++ b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
@@ -265,31 +265,24 @@ class ImapConnection {
extractCapabilities(Collections.singletonList(initialResponse));
}
- private List<ImapResponse> extractCapabilities(List<ImapResponse> responses) {
+ private boolean extractCapabilities(List<ImapResponse> responses) {
CapabilityResponse capabilityResponse = CapabilityResponse.parse(responses);
- if (capabilityResponse != null) {
- Set<String> receivedCapabilities = capabilityResponse.getCapabilities();
- if (K9MailLib.isDebug()) {
- Timber.d("Saving %s capabilities for %s", receivedCapabilities, getLogId());
- }
- capabilities = receivedCapabilities;
+ if (capabilityResponse == null) {
+ return false;
}
- return responses;
+
+ Set<String> receivedCapabilities = capabilityResponse.getCapabilities();
+ Timber.d("Saving %s capabilities for %s", receivedCapabilities, getLogId());
+ capabilities = receivedCapabilities;
+
+ return true;
}
- private List<ImapResponse> extractOrRequestCapabilities(List<ImapResponse> responses)
- throws IOException, MessagingException {
- CapabilityResponse capabilityResponse = CapabilityResponse.parse(responses);
- if (capabilityResponse != null) {
- Set<String> receivedCapabilities = capabilityResponse.getCapabilities();
- Timber.d("Saving %s capabilities for %s", receivedCapabilities, getLogId());
- capabilities = receivedCapabilities;
- } else {
+ private void extractOrRequestCapabilities(List<ImapResponse> responses) throws IOException, MessagingException {
+ if (!extractCapabilities(responses)) {
Timber.i("Did not get capabilities in post-auth banner, requesting CAPABILITY for %s", getLogId());
requestCapabilities();
}
-
- return responses;
}
private void requestCapabilitiesIfNecessary() throws IOException, MessagingException {
@@ -303,8 +296,7 @@ class ImapConnection {
}
private void requestCapabilities() throws IOException, MessagingException {
- List<ImapResponse> responses = extractCapabilities(executeSimpleCommand(Commands.CAPABILITY));
- if (responses.size() != 2) {
+ if (!extractCapabilities(executeSimpleCommand(Commands.CAPABILITY))) {
throw new MessagingException("Invalid CAPABILITY response received");
}
}
diff --git a/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java b/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java
index 6ace4f139..281df9be0 100644
--- a/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java
+++ b/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java
@@ -691,6 +691,30 @@ public class ImapConnectionTest {
server.verifyInteractionCompleted();
}
+ @Test
+ public void open_withUntaggedCapabilityAfterStartTls_shouldNotThrow() throws Exception {
+ settings.setAuthType(AuthType.PLAIN);
+ settings.setConnectionSecurity(ConnectionSecurity.STARTTLS_REQUIRED);
+ MockImapServer server = new MockImapServer();
+ preAuthenticationDialog(server, "STARTTLS LOGINDISABLED");
+ server.expect("2 STARTTLS");
+ server.output("2 OK Begin TLS negotiation now");
+ server.startTls();
+ server.output("* CAPABILITY IMAP4REV1 IMAP4");
+ server.expect("3 CAPABILITY");
+ server.output("* CAPABILITY IMAP4 IMAP4REV1");
+ server.output("3 OK");
+ server.expect("4 LOGIN \\"" + USERNAME + "\\" \\"" + PASSWORD + "\\"");
+ server.output("4 OK [CAPABILITY IMAP4REV1] LOGIN completed");
+ simplePostAuthenticationDialog(server, 5);
+ ImapConnection imapConnection = startServerAndCreateImapConnection(server);
+
+ imapConnection.open();
+
+ server.verifyConnectionStillOpen();
+ server.verifyInteractionCompleted();
+ }
+
@Test
public void open_withNegativeResponseToStartTlsCommand_shouldThrow() throws Exception {
settings.setAuthType(AuthType.PLAIN); | ['mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java', 'mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,235,879 | 638,269 | 90,039 | 491 | 1,756 | 321 | 32 | 1 | 533 | 66 | 133 | 23 | 1 | 1 | 2019-11-15T13:47:08 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,623 | thundernest/k-9/4271/4248 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4248 | https://github.com/thundernest/k-9/pull/4271 | https://github.com/thundernest/k-9/pull/4271 | 1 | fixes | master branch crashes on start when trying to add an IMAP account | ### Expected behavior
k9 should allow to create an IMAP account without crashing
### Actual behavior
After entering the details for the incoming server, the screen for outgoing server settings appears shortly, but then k9 crashes with following errors:
```
E/AndroidRuntime: FATAL EXCEPTION: MessagingController
Process: com.fsck.k9.debug, PID: 24126
java.lang.AssertionError: Tried to create folder 'Junk' that already exists in the database as 'Junk' (8)
at com.fsck.k9.mailstore.LocalStore$19.doDbWork(LocalStore.java:897)
at com.fsck.k9.mailstore.LocalStore$19.doDbWork(LocalStore.java:880)
at com.fsck.k9.mailstore.LockableDatabase.execute(LockableDatabase.java:273)
at com.fsck.k9.mailstore.LocalStore.createFolders(LocalStore.java:880)
at com.fsck.k9.mailstore.K9BackendStorage.createFolders(K9BackendStorage.kt:41)
at com.fsck.k9.backend.imap.CommandRefreshFolderList.refreshFolderList(CommandRefreshFolderList.kt:25)
at com.fsck.k9.backend.imap.ImapBackend.refreshFolderList(ImapBackend.java:112)
at com.fsck.k9.controller.MessagingController.refreshRemoteSynchronous(MessagingController.java:454)
at com.fsck.k9.controller.MessagingController$5.run(MessagingController.java:444)
at com.fsck.k9.controller.MessagingController.runInBackground(MessagingController.java:222)
at com.fsck.k9.controller.MessagingController.access$000(MessagingController.java:115)
at com.fsck.k9.controller.MessagingController$1.run(MessagingController.java:165)
at java.lang.Thread.run(Thread.java:761)
```
### Steps to reproduce
1. Clone git repository, open the project in Android studio, Build, start debug, wait for the start screen ("welcome to K-9 Mail) to appear
2. Click on "Next", then the screen "Set up a new account" shows up
3. enter email address and Password
4. Click on "MANUAL SETUP", then "Account type" shows up
5. click on "IMAP", then "Incoming server settings" shows up
6. Enter your server details
7. Click on "NEXT", then a screen appears with "checking incoming server settings..."
8. When the outgoing server settings screen appears, the app crashes
### Environment
K-9 Mail version: 5.700-SNAPSHOT, master on 2019-11-12
Android version: 7.1.2
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| b396c801143583e1eb4b41b5080f662e71db1362 | d4def08551f5efaaf9ce7bbe98f3f696fa24af46 | https://github.com/thundernest/k-9/compare/b396c801143583e1eb4b41b5080f662e71db1362...d4def08551f5efaaf9ce7bbe98f3f696fa24af46 | diff --git a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
index e15b62709..b723fa9ce 100644
--- a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
+++ b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
@@ -179,7 +179,7 @@ public class ImapStore extends RemoteStore {
ListResponse.parseLsub(responses) :
ListResponse.parseList(responses);
- List<FolderListItem> folders = new ArrayList<>(listResponses.size());
+ Map<String, FolderListItem> folderMap = new HashMap<>(listResponses.size());
for (ListResponse listResponse : listResponses) {
String decodedFolderName;
try {
@@ -235,10 +235,15 @@ public class ImapStore extends RemoteStore {
type = FolderType.REGULAR;
}
- folders.add(new FolderListItem(folder, type));
+ FolderListItem existingItem = folderMap.get(folder);
+ if (existingItem == null || existingItem.getType() == FolderType.REGULAR) {
+ folderMap.put(folder, new FolderListItem(folder, type));
+ }
}
+ List<FolderListItem> folders = new ArrayList<>(folderMap.size() + 1);
folders.add(new FolderListItem(ImapFolder.INBOX, FolderType.INBOX));
+ folders.addAll(folderMap.values());
return folders;
}
diff --git a/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java b/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java
index d7079fa16..13ceadc6e 100644
--- a/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java
+++ b/mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java
@@ -241,6 +241,31 @@ public class ImapStoreTest {
assertEquals(Sets.newSet("INBOX", "FolderOne"), extractFolderNames(result));
}
+ @Test
+ public void getPersonalNamespaces_withDuplicateFolderNames_shouldRemoveDuplicatesAndKeepFolderType()
+ throws Exception {
+ ImapConnection imapConnection = mock(ImapConnection.class);
+ when(imapConnection.hasCapability(Capabilities.LIST_EXTENDED)).thenReturn(true);
+ when(imapConnection.hasCapability(Capabilities.SPECIAL_USE)).thenReturn(true);
+ List<ImapResponse> imapResponses = Arrays.asList(
+ createImapResponse("* LIST () \\".\\" \\"INBOX\\""),
+ createImapResponse("* LIST (\\\\HasNoChildren) \\".\\" \\"Junk\\""),
+ createImapResponse("* LIST (\\\\Junk) \\".\\" \\"Junk\\""),
+ createImapResponse("* LIST (\\\\HasNoChildren) \\".\\" \\"Junk\\""),
+ createImapResponse("5 OK Success")
+ );
+ when(imapConnection.executeSimpleCommand("LIST \\"\\" \\"*\\" RETURN (SPECIAL-USE)")).thenReturn(imapResponses);
+ imapStore.enqueueImapConnection(imapConnection);
+
+ List<ImapFolder> result = imapStore.getPersonalNamespaces();
+
+ assertNotNull(result);
+ assertEquals(2, result.size());
+ ImapFolder junkFolder = getFolderByName(result, "Junk");
+ assertNotNull(junkFolder);
+ assertEquals(FolderType.SPAM, junkFolder.getType());
+ }
+
@Test
public void getPersonalNamespaces_withoutException_shouldLeaveImapConnectionOpen() throws Exception {
ImapConnection imapConnection = mock(ImapConnection.class);
@@ -367,6 +392,15 @@ public class ImapStoreTest {
return folderNames;
}
+ private ImapFolder getFolderByName(List<ImapFolder> result, String folderName) {
+ for (ImapFolder imapFolder : result) {
+ if (imapFolder.getName().equals(folderName)) {
+ return imapFolder;
+ }
+ }
+ return null;
+ }
+
private Map<String, ImapFolder> toFolderMap(List<ImapFolder> folders) {
Map<String, ImapFolder> folderMap = new HashMap<>();
for (ImapFolder folder : folders) { | ['mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java', 'mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/ImapStoreTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,224,126 | 635,536 | 89,700 | 488 | 592 | 113 | 9 | 1 | 2,368 | 205 | 574 | 43 | 0 | 1 | 2019-11-19T22:18:00 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,616 | thundernest/k-9/4447/4436 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4436 | https://github.com/thundernest/k-9/pull/4447 | https://github.com/thundernest/k-9/pull/4447 | 2 | fixes | Non-existent folder in PendingMoveOrCopy | Note: maybe related or duplicated with #4420 , but opening a new issue since I'm not sure.
Hello,
Thanks for working and offering k-9 mail, it's very useful piece of software.
I use the F-Droid version and recently upgraded from 5.600 to 5.700 (and then the next ones. Currently I'm using 5.703).
I use K-9 in telephone with Lineage 14 (Android 7.1.2), and I have several IMAP accounts configured.
For one of them, I'm experiencing an issue: when I mark as read a message, or I open to read it, it appears as "read" in K-9, but it seems that such status does not propagate to the server: when I refresh or obtain new mail, the messages that I've read in K-9 become "unread" again.
If I do the opposite (mark a read message as "not read"), when I refresh, the message becomes "read" again.
The same happens when I star/unstar a message.
I'm attaching a log of the action of reading several mails, and then, refreshing to receive new mail if available.
[k9-log-failure.txt](https://github.com/k9mail/k-9/files/4045387/k9-log-failure.txt)
The strange thing is that this happens only with this account (which receives dozens of mails daily). I have another account configured with much less traffic (1-2 mails each several days) and I cannot reproduce the problem in this second account. Both accounts are from the same provider (Gandi).
I have tried to uninstall K-9 and install again, and configure the account manually, but the problem persist. I have reviewed all the settings (general and account settings) to try to figure out if it was some setting by mistake, but I cannot find anything related to the issue.
Thanks!
| 6ad0d66d43b99bc1bbe25b382f26877bc5f08f32 | a939eca6d55b6375e9f12c8bc07a2602415b4e79 | https://github.com/thundernest/k-9/compare/6ad0d66d43b99bc1bbe25b382f26877bc5f08f32...a939eca6d55b6375e9f12c8bc07a2602415b4e79 | diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
index b21b0c00d..d15b60eb5 100644
--- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
+++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
@@ -2255,7 +2255,8 @@ public class MessagingController {
processPendingCommands(account);
} else if (!syncedMessageUids.isEmpty()) {
if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) {
- if (folder.equals(account.getTrashFolder()) || !backend.isDeleteMoveToTrash()) {
+ if (!account.hasTrashFolder() || folder.equals(account.getTrashFolder()) ||
+ !backend.isDeleteMoveToTrash()) {
queueDelete(account, folder, syncedMessageUids);
} else if (account.isMarkMessageAsReadOnDelete()) {
queueMoveOrCopy(account, folder, account.getTrashFolder(), | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,116,381 | 614,189 | 86,751 | 477 | 261 | 48 | 3 | 1 | 1,652 | 273 | 394 | 23 | 1 | 0 | 2020-01-13T15:27:27 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,505 | thundernest/k-9/6586/6582 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/6582 | https://github.com/thundernest/k-9/pull/6586 | https://github.com/thundernest/k-9/pull/6586 | 1 | fixes | "Delete spam messages immediately without moving them to the trash folder" doesn't delete Email in Spam Folder | ### Checklist
- [X] I have used the search function to see if someone else has already submitted the same bug report.
- [X] I will describe the problem with as much detail as possible.
### App version
6.501
### Where did you get the app from?
Other
### Android version
13
### Device model
Pixel 5
### Steps to reproduce
"Delete spam messages immediately without moving them to the trash folder" doesn't delete Email in Spam Folder, just removes it in the K9 Spam Folder.
Go to Spam Folder.
Delete Spam Emails.
All looks OK.
Open email account in web browser or IMAPSize.
The Spam Emails are still in the Spam / Junk folder. K9 just don't show them any more.
### Expected behavior
I'd expected K9 to delete message and expunge the mailbox.
### Actual behavior
The Spam Emails are still in the Spam / Junk folder. K9 just don't show them any more.
### Logs
No Logs needed. Simple to reproduce. | e797da026efc9c5799d7df6ebae55c49d9233be9 | 3a04190aa223a4292e0c4af4815b0aca5cfc7c41 | https://github.com/thundernest/k-9/compare/e797da026efc9c5799d7df6ebae55c49d9233be9...3a04190aa223a4292e0c4af4815b0aca5cfc7c41 | diff --git a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
index 16944e743..dfa2cc252 100644
--- a/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
+++ b/app/core/src/main/java/com/fsck/k9/controller/MessagingController.java
@@ -2025,10 +2025,13 @@ public class MessagingController {
Map<String, String> uidMap = null;
Long trashFolderId = account.getTrashFolderId();
boolean isSpamFolder = account.hasSpamFolder() && account.getSpamFolderId() == folderId;
+ boolean doNotMoveToTrashFolder = skipTrashFolder ||
+ !account.hasTrashFolder() || folderId == trashFolderId ||
+ isSpamFolder ||
+ (backend.getSupportsTrashFolder() && !backend.isDeleteMoveToTrash());
LocalFolder localTrashFolder = null;
- if (skipTrashFolder || !account.hasTrashFolder() || folderId == trashFolderId || isSpamFolder ||
- (backend.getSupportsTrashFolder() && !backend.isDeleteMoveToTrash())) {
+ if (doNotMoveToTrashFolder) {
Timber.d("Not moving deleted messages to local Trash folder. Removing local copies.");
if (!localOnlyMessages.isEmpty()) {
@@ -2092,8 +2095,7 @@ public class MessagingController {
// Nothing to do on the remote side
} else if (!syncedMessageUids.isEmpty()) {
if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) {
- if (!account.hasTrashFolder() || folderId == trashFolderId ||
- !backend.isDeleteMoveToTrash()) {
+ if (doNotMoveToTrashFolder) {
queueDelete(account, folderId, syncedMessageUids);
} else if (account.isMarkMessageAsReadOnDelete()) {
queueMoveOrCopy(account, folderId, trashFolderId, | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,181,712 | 437,631 | 59,661 | 329 | 702 | 150 | 10 | 1 | 924 | 164 | 214 | 46 | 0 | 0 | 2023-01-17T11:29:43 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,671 | thundernest/k-9/1013/871 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/871 | https://github.com/thundernest/k-9/pull/1013 | https://github.com/thundernest/k-9/pull/1013 | 1 | fixes | Crash during reading of an email | I receive an email which crashes the app.
After some research, I found that mBody for the file Version_texte.txt is null (LocalBodyPart with minetype "text/plain") and OpenPgpUtils.parseMessage crashes with a null value.
I also tried a new email with this file but mBody is not null.
So I think the issue is located in the loading process.
You can find the mail here : http://guillaume.smaha.net/contrib/k9mail/TestCrashEmail.eml
| ac131a2919040f5ef34b7d30cdb815f0a31b83aa | 15571b597665aeddddf65db2337ff7b4210c7844 | https://github.com/thundernest/k-9/compare/ac131a2919040f5ef34b7d30cdb815f0a31b83aa...15571b597665aeddddf65db2337ff7b4210c7844 | diff --git a/k9mail/src/main/java/com/fsck/k9/crypto/MessageDecryptVerifier.java b/k9mail/src/main/java/com/fsck/k9/crypto/MessageDecryptVerifier.java
index e11e86a32..761dc2e39 100644
--- a/k9mail/src/main/java/com/fsck/k9/crypto/MessageDecryptVerifier.java
+++ b/k9mail/src/main/java/com/fsck/k9/crypto/MessageDecryptVerifier.java
@@ -7,6 +7,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
+import android.text.TextUtils;
+
import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.BodyPart;
import com.fsck.k9.mail.MessagingException;
@@ -86,6 +88,9 @@ public class MessageDecryptVerifier {
if (isSameMimeType(mimeType, TEXT_PLAIN)) {
String text = MessageExtractor.getTextFromPart(part);
+ if (TextUtils.isEmpty(text)) {
+ continue;
+ }
switch (OpenPgpUtils.parseMessage(text)) {
case OpenPgpUtils.PARSE_RESULT_MESSAGE:
case OpenPgpUtils.PARSE_RESULT_SIGNED_MESSAGE: | ['k9mail/src/main/java/com/fsck/k9/crypto/MessageDecryptVerifier.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,238,666 | 642,061 | 88,696 | 328 | 131 | 18 | 5 | 1 | 431 | 65 | 105 | 7 | 1 | 0 | 2016-01-09T16:24:49 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,670 | thundernest/k-9/1017/899 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/899 | https://github.com/thundernest/k-9/pull/1017 | https://github.com/thundernest/k-9/pull/1017 | 1 | fixes | backslash in username does not work for IMAP login | I need to access an exchange server via IMAP. My username has the form username@domain\\special_mailbox .
Authentication with just username for the personal mailbox works fine but not for the special mailbox with the backslash syntax above.
I tried two backslashes since I suspected some java string escaping problem, but that did not work either.
| ac131a2919040f5ef34b7d30cdb815f0a31b83aa | 0366633ff83086f3c7620a618ae7b3b5cc6ade1a | https://github.com/thundernest/k-9/compare/ac131a2919040f5ef34b7d30cdb815f0a31b83aa...0366633ff83086f3c7620a618ae7b3b5cc6ade1a | diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
index a81408755..ada1a1f53 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java
@@ -364,6 +364,14 @@ class ImapConnection {
}
}
+ protected void saslAuthPlainWithLoginFallback() throws IOException, MessagingException {
+ try {
+ saslAuthPlain();
+ } catch (AuthenticationFailedException e) {
+ login();
+ }
+ }
+
protected ImapResponse readContinuationResponse(String tag)
throws IOException, MessagingException {
ImapResponse response;
@@ -510,7 +518,7 @@ class ImapConnection {
case PLAIN:
if (hasCapability(CAPABILITY_AUTH_PLAIN)) {
- saslAuthPlain();
+ saslAuthPlainWithLoginFallback();
} else if (!hasCapability(CAPABILITY_LOGINDISABLED)) {
login();
} else { | ['k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,238,666 | 642,061 | 88,696 | 328 | 326 | 58 | 10 | 1 | 347 | 55 | 68 | 4 | 0 | 0 | 2016-01-11T18:39:42 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,669 | thundernest/k-9/1126/1110 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1110 | https://github.com/thundernest/k-9/pull/1126 | https://github.com/thundernest/k-9/pull/1126 | 1 | fixes | Notification stays after reading e-mail | ### Expected behaviour
Notification disappears after reading an e-mail.
### Actual behaviour
The notification stays after reading the e-mail, when the e-mail was received by refreshing the inbox out of the inbox.
### Steps to reproduce
1. Go to the inbox, where you expect to get an e-mail in.
2. Refresh the inbox, so you receive the e-mail.
3. Click on the new e-mail to read it.
4. (optional) Go back to the inbox by any back button. You see the e-mail is definitely marked unread.
5. Press the home button to leave K-9.
### Environment
K-9 Mail version: 5.008
Android version: 5.1.1
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| e27205873d661d5a192d2838e210605fafdf620f | 41a32bd3472a25a392037bc9cb71730395cd3e9f | https://github.com/thundernest/k-9/compare/e27205873d661d5a192d2838e210605fafdf620f...41a32bd3472a25a392037bc9cb71730395cd3e9f | diff --git a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java
index 8f51a5222..efc039033 100644
--- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java
+++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java
@@ -2871,6 +2871,7 @@ public class MessagingController implements Runnable {
localFolder.fetch(Collections.singletonList(message), fp, null);
localFolder.close();
+ notificationController.removeNewMailNotification(account, message.makeMessageReference());
markMessageAsReadOnView(account, message);
return message; | ['k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,407,629 | 676,626 | 93,646 | 377 | 99 | 14 | 1 | 1 | 641 | 109 | 166 | 20 | 0 | 0 | 2016-02-26T04:31:30 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,494 | thundernest/k-9/6972/6816 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/6816 | https://github.com/thundernest/k-9/pull/6972 | https://github.com/thundernest/k-9/pull/6972 | 1 | fixes | Inconsistent recipient names when composing a message | ### Checklist
- [X] I have used the search function to see if someone else has already submitted the same bug report.
- [X] I will describe the problem with as much detail as possible.
### App version
6.400
### Where did you get the app from?
F-Droid
### Android version
13
### Device model
_No response_
### Steps to reproduce
1. Have a contact with the nickname different from the name.
2. Create a new message in K9
3. Start typing in "To"
4. If you type the nick name and use the autocomplete/sugestion, the e-mail is in the form of `"Nickname" <[email protected]>`
5. If you type the name and use the autocomplete/sugestion, the e-mail is in the form of `"Firstname Lastname" <[email protected]>`
### Expected behavior
No matter how I find the contact, the recipient address is always in the same form `"Firstname Lastname" <[email protected]>`.
### Actual behavior
Depending on which field of the contact was matched the name changes.
### Logs
_Not relevant_ | 4bc2afa9ad88c319f9d237872f3038633efb9554 | ff79ee70fc2cd49a3c7dc8630b85908d5fc782e5 | https://github.com/thundernest/k-9/compare/4bc2afa9ad88c319f9d237872f3038633efb9554...ff79ee70fc2cd49a3c7dc8630b85908d5fc782e5 | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java
index e5fd41de2..e3931375f 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java
@@ -72,11 +72,9 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
private static final String[] PROJECTION_NICKNAME = {
ContactsContract.Data.CONTACT_ID,
- ContactsContract.CommonDataKinds.Nickname.NAME
};
private static final int INDEX_CONTACT_ID_FOR_NICKNAME = 0;
- private static final int INDEX_NICKNAME = 1;
private static final String[] PROJECTION_CRYPTO_ADDRESSES = {
"address",
@@ -377,8 +375,7 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
Cursor cursor = contentResolver
.query(queryUri, PROJECTION, selection, new String[] { id }, SORT_ORDER);
- String contactNickname = nicknameCursor.getString(INDEX_NICKNAME);
- fillContactDataFromCursor(cursor, recipients, recipientMap, contactNickname, null);
+ fillContactDataFromCursor(cursor, recipients, recipientMap, null);
hasContact = true;
}
@@ -403,7 +400,7 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
return recipients;
}
- fillContactDataFromCursor(cursor, recipients, new HashMap<>(), null, maxRecipients);
+ fillContactDataFromCursor(cursor, recipients, new HashMap<>(), maxRecipients);
return recipients;
}
@@ -437,15 +434,14 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
private void fillContactDataFromCursor(Cursor cursor, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
- fillContactDataFromCursor(cursor, recipients, recipientMap, null, null);
+ fillContactDataFromCursor(cursor, recipients, recipientMap, null);
}
private void fillContactDataFromCursor(Cursor cursor, List<Recipient> recipients,
- Map<String, Recipient> recipientMap, @Nullable String prefilledName, @Nullable Integer maxRecipients) {
+ Map<String, Recipient> recipientMap, @Nullable Integer maxRecipients) {
while (cursor.moveToNext() && (maxRecipients == null || recipients.size() < maxRecipients)) {
- String name = prefilledName != null ? prefilledName : cursor.getString(INDEX_NAME);
-
+ String name = cursor.getString(INDEX_NAME);
String email = cursor.getString(INDEX_EMAIL);
// already exists? just skip then
diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientLoaderTest.java b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientLoaderTest.java
index 6d9894552..c16e444c8 100644
--- a/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientLoaderTest.java
+++ b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientLoaderTest.java
@@ -49,8 +49,7 @@ public class RecipientLoaderTest extends RobolectricTest {
ContactsContract.Contacts.STARRED
};
static final String[] PROJECTION_NICKNAME = {
- ContactsContract.Data.CONTACT_ID,
- ContactsContract.CommonDataKinds.Nickname.NAME
+ ContactsContract.Data.CONTACT_ID
};
static final String[] PROJECTION_CRYPTO_ADDRESSES = { "address", "uid_address" };
static final String[] PROJECTION_CRYPTO_STATUS = { "address", "uid_key_status", "autocrypt_key_status" };
@@ -66,7 +65,7 @@ public class RecipientLoaderTest extends RobolectricTest {
static final String[] CONTACT_WITH_NICKNAME_NOT_CONTACTED =
new String[] { "0", "Eve_notContacted", "eve_notContacted", "[email protected]", TYPE, null, "2",
null, "0", "Eve", "0" };
- static final String[] NICKNAME_NOT_CONTACTED = new String[] { "2", "Eves_Nickname_Bob" };
+ static final String[] NICKNAME_NOT_CONTACTED = new String[] { "2" };
static final String QUERYSTRING = "querystring";
| ['app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java', 'app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientLoaderTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,002,696 | 401,935 | 54,851 | 301 | 1,076 | 214 | 14 | 1 | 1,020 | 165 | 235 | 40 | 0 | 0 | 2023-06-09T19:40:33 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,668 | thundernest/k-9/1133/811 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/811 | https://github.com/thundernest/k-9/pull/1133 | https://github.com/thundernest/k-9/pull/1133 | 1 | fixes | ClassCastException on IMAP sync | On a fresh install of k9Mail on a new phone, one of my IMAP accounts stops suddenly with the below error. It worked like a charm for a few days prior to that. I've another IMAP account on the same server which still works and isn't affected.
K9-Mail version: 5.006
Device make: motorola
Device model: MotoG3
Android version: 5.1.1
java.lang.ClassCastException: com.fsck.k9.mail.store.ImapResponseParser$ImapList cannot be cast to java.lang.String
at com.fsck.k9.mail.store.ImapResponseParser.readTokens(ImapResponseParser.java:69)
at com.fsck.k9.mail.store.ImapResponseParser.readResponse(ImapResponseParser.java:51)
at com.fsck.k9.mail.store.ImapResponseParser.readResponse(ImapResponseParser.java:29)
at com.fsck.k9.mail.store.ImapStore$ImapConnection.readStatusResponse(ImapStore.java:2775)
at com.fsck.k9.mail.store.ImapStore$ImapConnection.saslAuthPlain(ImapStore.java:2727)
at com.fsck.k9.mail.store.ImapStore$ImapConnection.open(ImapStore.java:2530)
at com.fsck.k9.mail.store.ImapStore$ImapConnection.sendCommand(ImapStore.java:2872)
at com.fsck.k9.mail.store.ImapStore$ImapConnection.executeSimpleCommand(ImapStore.java:2921)
at com.fsck.k9.mail.store.ImapStore$ImapConnection.executeSimpleCommand(ImapStore.java:2902)
at com.fsck.k9.mail.store.ImapStore$ImapFolder.executeSimpleCommand(ImapStore.java:858)
at com.fsck.k9.mail.store.ImapStore$ImapFolder.internalOpen(ImapStore.java:904)
at com.fsck.k9.mail.store.ImapStore$ImapFolder.open(ImapStore.java:867)
at com.fsck.k9.controller.MessagingController.synchronizeMailboxSynchronous(MessagingController.java:1041)
at com.fsck.k9.controller.MessagingController.access$400(MessagingController.java:111)
at com.fsck.k9.controller.MessagingController$8.run(MessagingController.java:934)
at com.fsck.k9.controller.MessagingController.run(MessagingController.java:435)
at java.lang.Thread.run(Thread.java:818)
| 916e83d4d9cfa9767c3912fb720d3a981b79d4a1 | 14054ec977f94d42c8648acd6d05ef295ce598a8 | https://github.com/thundernest/k-9/compare/916e83d4d9cfa9767c3912fb720d3a981b79d4a1...14054ec977f94d42c8648acd6d05ef295ce598a8 | diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapResponseParser.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapResponseParser.java
index 7b70d41f4..b508bad7e 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapResponseParser.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapResponseParser.java
@@ -127,12 +127,16 @@ class ImapResponseParser {
private void readTokens(ImapResponse response) throws IOException {
response.clear();
- String firstToken = (String) readToken(response);
- response.add(firstToken);
+ Object firstToken = readToken(response);
- if (isStatusResponse(firstToken)) {
+ checkTokenIsString(firstToken);
+ String symbol = (String) firstToken;
+
+ response.add(symbol);
+
+ if (isStatusResponse(symbol)) {
parseResponseText(response);
- } else if (equalsIgnoreCase(firstToken, Responses.LIST) || equalsIgnoreCase(firstToken, Responses.LSUB)) {
+ } else if (equalsIgnoreCase(symbol, Responses.LIST) || equalsIgnoreCase(symbol, Responses.LSUB)) {
parseListResponse(response);
} else {
Object token;
@@ -452,4 +456,10 @@ class ImapResponseParser {
return symbol.equalsIgnoreCase((String) token);
}
+
+ private void checkTokenIsString(Object token) throws IOException {
+ if (!(token instanceof String)) {
+ throw new IOException("Unexpected non-string token: " + token);
+ }
+ }
}
diff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/store/imap/ImapResponseParserTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/store/imap/ImapResponseParserTest.java
index 82330798e..861fa2718 100644
--- a/k9mail-library/src/test/java/com/fsck/k9/mail/store/imap/ImapResponseParserTest.java
+++ b/k9mail-library/src/test/java/com/fsck/k9/mail/store/imap/ImapResponseParserTest.java
@@ -17,6 +17,7 @@ import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
@RunWith(RobolectricTestRunner.class)
@@ -312,6 +313,18 @@ public class ImapResponseParserTest {
assertEquals("TAG", responseTwo.getTag());
}
+ @Test
+ public void readResponse_withListAsFirstToken_shouldThrow() throws Exception {
+ ImapResponseParser parser = createParser("* [1 2] 3\\r\\n");
+
+ try {
+ parser.readResponse();
+ fail("Expected exception");
+ } catch (IOException e) {
+ assertEquals("Unexpected non-string token: [1, 2]", e.getMessage());
+ }
+ }
+
@Test
public void testFetchResponse() throws Exception {
ImapResponseParser parser = createParser("* 1 FETCH (" + | ['k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapResponseParser.java', 'k9mail-library/src/test/java/com/fsck/k9/mail/store/imap/ImapResponseParserTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,404,894 | 677,863 | 94,218 | 395 | 787 | 154 | 18 | 1 | 1,934 | 100 | 527 | 26 | 0 | 0 | 2016-02-28T07:46:03 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,656 | thundernest/k-9/1883/1874 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1874 | https://github.com/thundernest/k-9/pull/1883 | https://github.com/thundernest/k-9/pull/1883 | 1 | fixes | Crash: NPE in Address.hashCode() | Via Play Developer Console
App version: 5.200
```
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.fsck.k9.mail.Address.hashCode(Address.java:176)
at java.util.Collections.secondaryHash(Collections.java:3405)
at java.util.LinkedHashMap.get(LinkedHashMap.java:250)
at android.support.v4.util.LruCache.get(LruCache.java:84)
at com.fsck.k9.activity.misc.ContactPictureLoader.getBitmapFromCache(ContactPictureLoader.java:213)
at com.fsck.k9.activity.misc.ContactPictureLoader.loadContactPicture(ContactPictureLoader.java:133)
at com.fsck.k9.activity.compose.RecipientAdapter.setContactPhotoOrPlaceholder(RecipientAdapter.java:137)
at com.fsck.k9.view.RecipientSelectView.bindObjectView(RecipientSelectView.java:128)
at com.fsck.k9.view.RecipientSelectView.getViewForObject(RecipientSelectView.java:112)
at com.fsck.k9.view.RecipientSelectView.buildSpanForObject(RecipientSelectView.java:437)
at com.fsck.k9.view.RecipientSelectView.buildSpanForObject(RecipientSelectView.java:47)
at com.tokenautocomplete.TokenCompleteTextView.insertSpan(TokenCompleteTextView.java:1031)
at com.tokenautocomplete.TokenCompleteTextView.access$700(TokenCompleteTextView.java:54)
at com.tokenautocomplete.TokenCompleteTextView$3.run(TokenCompleteTextView.java:924)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
``` | b2ed230b322277f6e366fc3f1510043ccba45836 | 40e5f038044f208b345842bf726e009aea86c87e | https://github.com/thundernest/k-9/compare/b2ed230b322277f6e366fc3f1510043ccba45836...40e5f038044f208b345842bf726e009aea86c87e | diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java b/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java
index dfb778a4a..5b6b3885c 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/Address.java
@@ -173,7 +173,10 @@ public class Address implements Serializable {
@Override
public int hashCode() {
- int hash = mAddress.hashCode();
+ int hash = 0;
+ if (mAddress != null) {
+ hash += mAddress.hashCode();
+ }
if (mPersonal != null) {
hash += 3 * mPersonal.hashCode();
}
diff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java
index ba21a4844..33eff0d1b 100644
--- a/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java
+++ b/k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java
@@ -7,6 +7,7 @@ import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
@RunWith(RobolectricTestRunner.class)
@@ -89,4 +90,20 @@ public class AddressTest {
assertEquals("\\"sa\\"mp\\"le\\"", Address.quoteString("\\"sa\\"mp\\"le\\""));
assertEquals("\\"\\"\\"", Address.quoteString("\\""));
}
+
+ @Test
+ public void hashCode_withoutAddress() throws Exception {
+ Address address = Address.parse("name only")[0];
+ assertNull(address.getAddress());
+
+ address.hashCode();
+ }
+
+ @Test
+ public void hashCode_withoutPersonal() throws Exception {
+ Address address = Address.parse("[email protected]")[0];
+ assertNull(address.getPersonal());
+
+ address.hashCode();
+ }
} | ['k9mail-library/src/test/java/com/fsck/k9/mail/AddressTest.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/Address.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,440,332 | 682,537 | 94,166 | 420 | 149 | 33 | 5 | 1 | 1,843 | 67 | 412 | 28 | 0 | 1 | 2016-12-28T21:27:01 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,610 | thundernest/k-9/4671/4435 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4435 | https://github.com/thundernest/k-9/pull/4671 | https://github.com/thundernest/k-9/pull/4671 | 1 | fixes | Do not save unmodified new message as draft | ### Expected behavior
After having pressing the compose new message button, the compose view opens. If you close/background the app at this point, without changing/inputting anything at all, K-9 should not have saved the message as a draft.
### Actual behavior
The empty new message is saved as a draft.
### Steps to reproduce
1. From the accounts view, press the compose new message button near the bottom centre of the screen (envelope icon with a little plus sign).
2. Background the app and wait for Android to terminate it, or close it from app selection screen.
3. Check drafts folder. An empty draft has been stored (i.e., no subject, no text, no recipients).
### Environment
K-9 Mail version: 5.600
Android version: 10
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
I do not believe attaching error logs is necessary in this case since this is not an application error per se, more of a UI issue.
The reason why the current behaviour is an annoyance is that the compose new button is placed so that it is easy to press it when what you want to do is to change to another app. This is because the Android 10 gesture for switching between apps is to swipe up from the bottom of the screen, and the compose new button is placed at the centre near the bottom. Thus I seem to end up accidentally entering the new message view quite frequently. If I then re-try the swipe gesture successfully immediately after, i.e., when the new message view has opened, I end up with an empty draft being saved. Because of this my drafts folder is accumulating a number of these empty drafts over time.
To me it does not seem to be any value in saving empty/unmodified drafts, so the solution is simple: just don't. | 3459ab526748a6e3ee17813603903c2cd91b792e | fc49fb9d67f469c14b508237d8315508179a692c | https://github.com/thundernest/k-9/compare/3459ab526748a6e3ee17813603903c2cd91b792e...fc49fb9d67f469c14b508237d8315508179a692c | diff --git a/app/ui/src/main/java/com/fsck/k9/activity/MessageCompose.java b/app/ui/src/main/java/com/fsck/k9/activity/MessageCompose.java
index ef8be534c..d078a3a5c 100644
--- a/app/ui/src/main/java/com/fsck/k9/activity/MessageCompose.java
+++ b/app/ui/src/main/java/com/fsck/k9/activity/MessageCompose.java
@@ -120,8 +120,7 @@ import timber.log.Timber;
public class MessageCompose extends K9Activity implements OnClickListener,
CancelListener, AttachmentDownloadCancelListener, OnFocusChangeListener,
OnOpenPgpInlineChangeListener, OnOpenPgpSignOnlyChangeListener, MessageBuilder.Callback,
- AttachmentPresenter.AttachmentsChangedListener, RecipientPresenter.RecipientsChangedListener,
- OnOpenPgpDisableListener {
+ AttachmentPresenter.AttachmentsChangedListener, OnOpenPgpDisableListener {
private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1;
private static final int DIALOG_CONFIRM_DISCARD_ON_BACK = 2;
@@ -309,7 +308,7 @@ public class MessageCompose extends K9Activity implements OnClickListener,
OpenPgpApiManager openPgpApiManager = new OpenPgpApiManager(getApplicationContext(), this);
recipientPresenter = new RecipientPresenter(getApplicationContext(), getSupportLoaderManager(),
openPgpApiManager, recipientMvpView, account, composePgpInlineDecider, composePgpEnableByDefaultDecider,
- AutocryptStatusInteractor.getInstance(), new ReplyToParser(), this,
+ AutocryptStatusInteractor.getInstance(), new ReplyToParser(),
DI.get(AutocryptDraftStateHeaderParser.class));
recipientPresenter.asyncUpdateCryptoStatus();
@@ -950,11 +949,6 @@ public class MessageCompose extends K9Activity implements OnClickListener,
changesMadeSinceLastSave = true;
}
- @Override
- public void onRecipientsChanged() {
- changesMadeSinceLastSave = true;
- }
-
@Override
public void onClick(View view) {
if (view.getId() == R.id.identity) {
diff --git a/app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java b/app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java
index 644a5fc02..13be2049f 100644
--- a/app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java
+++ b/app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java
@@ -3,7 +3,9 @@ package com.fsck.k9.activity.compose;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
import android.app.PendingIntent;
import androidx.loader.app.LoaderManager;
@@ -13,6 +15,7 @@ import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
+import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;
@@ -49,6 +52,7 @@ public class RecipientMvpView implements OnFocusChangeListener, OnClickListener
private final ToolableViewAnimator cryptoStatusView;
private final ViewAnimator recipientExpanderContainer;
private final ToolableViewAnimator cryptoSpecialModeIndicator;
+ private final Set<TextWatcher> textWatchers = new HashSet<>();
private RecipientPresenter presenter;
@@ -146,11 +150,25 @@ public class RecipientMvpView implements OnFocusChangeListener, OnClickListener
}
public void addTextChangedListener(TextWatcher textWatcher) {
+ textWatchers.add(textWatcher);
+
toView.addTextChangedListener(textWatcher);
ccView.addTextChangedListener(textWatcher);
bccView.addTextChangedListener(textWatcher);
}
+ private void removeAllTextChangedListeners(TextView view) {
+ for (TextWatcher textWatcher : textWatchers) {
+ view.removeTextChangedListener(textWatcher);
+ }
+ }
+
+ private void addAllTextChangedListeners(TextView view) {
+ for (TextWatcher textWatcher : textWatchers) {
+ view.addTextChangedListener(textWatcher);
+ }
+ }
+
public void setRecipientTokensShowCryptoEnabled(boolean isEnabled) {
toView.setShowCryptoEnabled(isEnabled);
ccView.setShowCryptoEnabled(isEnabled);
@@ -199,18 +217,34 @@ public class RecipientMvpView implements OnFocusChangeListener, OnClickListener
}
}
- public void removeBccAddresses(Address[] addressesToRemove) {
+ public void silentlyAddBccAddresses(Recipient... recipients) {
+ removeAllTextChangedListeners(bccView);
+
+ // The actual modification of the view is deferred via View.post()…
+ bccView.addRecipients(recipients);
+
+ // … so we do the same to add back the listeners.
+ bccView.post(() -> addAllTextChangedListeners(bccView));
+ }
+
+ public void silentlyRemoveBccAddresses(Address[] addressesToRemove) {
if (addressesToRemove.length == 0) {
return;
}
List<Recipient> bccRecipients = new ArrayList<>(getBccRecipients());
for (Recipient recipient : bccRecipients) {
+ removeAllTextChangedListeners(bccView);
+
for (Address address : addressesToRemove) {
if (recipient.address.equals(address)) {
+ // The actual modification of the view is deferred via View.post()…
bccView.removeObject(recipient);
}
}
+
+ // … so we do the same to add back the listeners.
+ bccView.post(() -> addAllTextChangedListeners(bccView));
}
}
diff --git a/app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java b/app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
index 4b70877f6..2df86333f 100644
--- a/app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
+++ b/app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
@@ -73,7 +73,6 @@ public class RecipientPresenter {
private final ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider;
private final ComposePgpInlineDecider composePgpInlineDecider;
private final AutocryptStatusInteractor autocryptStatusInteractor;
- private final RecipientsChangedListener listener;
private final OpenPgpApiManager openPgpApiManager;
private final AutocryptDraftStateHeaderParser draftStateHeaderParser;
private ReplyToParser replyToParser;
@@ -96,15 +95,13 @@ public class RecipientPresenter {
ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
- ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener,
- AutocryptDraftStateHeaderParser draftStateHeaderParser) {
+ ReplyToParser replyToParser, AutocryptDraftStateHeaderParser draftStateHeaderParser) {
this.recipientMvpView = recipientMvpView;
this.context = context;
this.autocryptStatusInteractor = autocryptStatusInteractor;
this.composePgpInlineDecider = composePgpInlineDecider;
this.composePgpEnableByDefaultDecider = composePgpEnableByDefaultDecider;
this.replyToParser = replyToParser;
- this.listener = recipientsChangedListener;
this.openPgpApiManager = openPgpApiManager;
this.draftStateHeaderParser = draftStateHeaderParser;
@@ -295,12 +292,22 @@ public class RecipientPresenter {
public void addAlwaysBcc() {
alwaysBccAddresses = Address.parse(account.getAlwaysBcc());
- addRecipientsFromAddresses(RecipientType.BCC, alwaysBccAddresses);
+
+ new RecipientLoader(context, account.getOpenPgpProvider(), alwaysBccAddresses) {
+ @Override
+ public void deliverResult(List<Recipient> result) {
+ Recipient[] recipientArray = result.toArray(new Recipient[result.size()]);
+ recipientMvpView.silentlyAddBccAddresses(recipientArray);
+
+ stopLoading();
+ abandon();
+ }
+ }.startLoading();
}
private void removeAlwaysBcc() {
if (alwaysBccAddresses != null) {
- recipientMvpView.removeBccAddresses(alwaysBccAddresses);
+ recipientMvpView.silentlyRemoveBccAddresses(alwaysBccAddresses);
}
}
@@ -495,47 +502,38 @@ public class RecipientPresenter {
void onToTokenAdded() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
void onToTokenRemoved() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
void onToTokenChanged() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
void onCcTokenAdded() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
void onCcTokenRemoved() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
void onCcTokenChanged() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
void onBccTokenAdded() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
void onBccTokenRemoved() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
void onBccTokenChanged() {
asyncUpdateCryptoStatus();
- listener.onRecipientsChanged();
}
public void onCryptoModeChanged(CryptoMode cryptoMode) {
@@ -847,10 +845,6 @@ public class RecipientPresenter {
return cachedCryptoStatus == null || !cachedCryptoStatus.isEncryptionEnabled();
}
- public interface RecipientsChangedListener {
- void onRecipientsChanged();
- }
-
private final OpenPgpApiManagerCallback openPgpCallback = new OpenPgpApiManagerCallback() {
@Override
public void onOpenPgpProviderStatusChanged() {
diff --git a/app/ui/src/test/java/com/fsck/k9/activity/compose/RecipientPresenterTest.java b/app/ui/src/test/java/com/fsck/k9/activity/compose/RecipientPresenterTest.java
index 285c6aa6a..8e1fd8515 100644
--- a/app/ui/src/test/java/com/fsck/k9/activity/compose/RecipientPresenterTest.java
+++ b/app/ui/src/test/java/com/fsck/k9/activity/compose/RecipientPresenterTest.java
@@ -66,7 +66,6 @@ public class RecipientPresenterTest extends K9RobolectricTest {
private ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider;
private Account account;
private RecipientMvpView recipientMvpView;
- private RecipientPresenter.RecipientsChangedListener listener;
private AutocryptStatusInteractor autocryptStatusInteractor;
private RecipientAutocryptStatus noRecipientsAutocryptResult;
private OpenPgpApiManager openPgpApiManager;
@@ -86,13 +85,12 @@ public class RecipientPresenterTest extends K9RobolectricTest {
autocryptStatusInteractor = mock(AutocryptStatusInteractor.class);
replyToParser = mock(ReplyToParser.class);
LoaderManager loaderManager = mock(LoaderManager.class);
- listener = mock(RecipientPresenter.RecipientsChangedListener.class);
when(openPgpApiManager.getOpenPgpProviderState()).thenReturn(OpenPgpProviderState.UNCONFIGURED);
recipientPresenter = new RecipientPresenter(
context, loaderManager, openPgpApiManager, recipientMvpView, account, composePgpInlineDecider,
- composePgpEnableByDefaultDecider, autocryptStatusInteractor, replyToParser, listener,
+ composePgpEnableByDefaultDecider, autocryptStatusInteractor, replyToParser,
DI.get(AutocryptDraftStateHeaderParser.class)
);
@@ -279,60 +277,6 @@ public class RecipientPresenterTest extends K9RobolectricTest {
assertTrue(status.isPgpInlineModeEnabled());
}
- @Test
- public void onToTokenAdded_notifiesListenerOfRecipientChange() {
- recipientPresenter.onToTokenAdded();
- verify(listener).onRecipientsChanged();
- }
-
- @Test
- public void onToTokenChanged_notifiesListenerOfRecipientChange() {
- recipientPresenter.onToTokenChanged();
- verify(listener).onRecipientsChanged();
- }
-
- @Test
- public void onToTokenRemoved_notifiesListenerOfRecipientChange() {
- recipientPresenter.onToTokenRemoved();
- verify(listener).onRecipientsChanged();
- }
-
- @Test
- public void onCcTokenAdded_notifiesListenerOfRecipientChange() {
- recipientPresenter.onCcTokenAdded();
- verify(listener).onRecipientsChanged();
- }
-
- @Test
- public void onCcTokenChanged_notifiesListenerOfRecipientChange() {
- recipientPresenter.onCcTokenChanged();
- verify(listener).onRecipientsChanged();
- }
-
- @Test
- public void onCcTokenRemoved_notifiesListenerOfRecipientChange() {
- recipientPresenter.onCcTokenRemoved();
- verify(listener).onRecipientsChanged();
- }
-
- @Test
- public void onBccTokenAdded_notifiesListenerOfRecipientChange() {
- recipientPresenter.onBccTokenAdded();
- verify(listener).onRecipientsChanged();
- }
-
- @Test
- public void onBccTokenChanged_notifiesListenerOfRecipientChange() {
- recipientPresenter.onBccTokenChanged();
- verify(listener).onRecipientsChanged();
- }
-
- @Test
- public void onBccTokenRemoved_notifiesListenerOfRecipientChange() {
- recipientPresenter.onBccTokenRemoved();
- verify(listener).onRecipientsChanged();
- }
-
private void runBackgroundTask() {
boolean taskRun = Robolectric.getBackgroundThreadScheduler().runOneTask();
assertTrue(taskRun); | ['app/ui/src/test/java/com/fsck/k9/activity/compose/RecipientPresenterTest.java', 'app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java', 'app/ui/src/main/java/com/fsck/k9/activity/MessageCompose.java', 'app/ui/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 2,853,108 | 562,316 | 79,533 | 422 | 3,386 | 638 | 78 | 3 | 1,737 | 304 | 379 | 24 | 0 | 0 | 2020-04-17T18:07:19 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,658 | thundernest/k-9/1689/1609 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1609 | https://github.com/thundernest/k-9/pull/1689 | https://github.com/thundernest/k-9/pull/1689 | 1 | fixes | Quoted-printable encoding inserts unnecessary line breaks | K-9 Mail created a message that contained unnecessary line breaks in the encoded message body.
(v5.111)
```
[...]
Content-Type: text/plain;
charset=utf-8
Content-Transfer-Encoding: quoted-printable
MIME-Version: 1.0
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
[...]
-----BEGIN PGP SIGNATURE-----
iQI0BAEBCgAeFxxCZXJuZCA8dGVzdEBja2V0dGkuZGU=
+BQJX1LDSAAoJEG2bO4IG
m2wDJ6YQAIc3oA5JPv122U0IdBWN0c0CPr0bm6e+Z7dlAOCmNdhO/=
WxhMTEI1u4v
AL9AySWQIeek3tWZJSgSfhULXCC1ZUU2tWA/1cpf9PMpdXknJvi8y34osV+0SnU=
/
LhIkMPUK2wGUYmDUvBL2g9Zbx4giknta+2/IbaGMljRHQuDV1XpHEVDKzRE73VID
xn7F7CSI=
xkQGPI6mNOuM70BsaVyCwrTRiSW4rnwe2CgLf+RVSePCnveTjxC6xZyC
Q7z1LBKGNEvw0PRKjM=
1IbNeFSJ3y73RBS4y1cDYECWxKPjDJ5PR9x2QzcTdqKbXp
pVXJEv/8SzurR99V1OvlTS3s2tdS=
fSLpd9uP1hqxK71Dek5fcMUHQqgsIz2mmiEa
dExWc9dItBjgH9dPyBXn9m/G5UnF1E8FbqlS7J=
swgfiW0KNAkYEsFyvjp7q7W6TK
qkYnxJCENCG4Hf+lofDEzHth/uu23Z7cHhjkzZDet0dMGpA+=
B1jH9ZVu4aEoWLGQ
VJ3Lfjqy4ZysAmziR8iKcg3V/q0vmL+zC+3s9U+UaXPbpI2JD/hr89WIkG=
zVnNpG
8hInOIgLOJhui5PFEB7XNdpBJj+O2NYigV76Fvhb4boyCt7VdhRe01C7cohusPHB
/TO=
wbqG+0w+z6eL8tyxZ2HVWFyfgHyarnwGquIxYjxE5OzfS+LN4
=3DS8iC
-----END PGP SIGN=
ATURE-----
```
| fc79b290d03bad5a20347c8bc12c467ad6700dcf | ce249bf07ef7c8a83dac6b17681de238b45e77ba | https://github.com/thundernest/k-9/compare/fc79b290d03bad5a20347c8bc12c467ad6700dcf...ce249bf07ef7c8a83dac6b17681de238b45e77ba | diff --git a/k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java b/k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java
index b0c5d10b9..11638b6e0 100644
--- a/k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java
+++ b/k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java
@@ -20,6 +20,7 @@ import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.BodyPart;
import com.fsck.k9.mail.BoundaryGenerator;
import com.fsck.k9.mail.MessagingException;
+import com.fsck.k9.mail.filter.EOLConvertingOutputStream;
import com.fsck.k9.mail.internet.BinaryTempFileBody;
import com.fsck.k9.mail.internet.MessageIdGenerator;
import com.fsck.k9.mail.internet.MimeBodyPart;
@@ -193,6 +194,9 @@ public class PgpMessageBuilder extends MessageBuilder {
pgpResultTempBody = new BinaryTempFileBody(
capturedOutputPartIs7Bit ? MimeUtil.ENC_7BIT : MimeUtil.ENC_8BIT);
outputStream = pgpResultTempBody.getOutputStream();
+ // OpenKeychain/BouncyCastle at this point use the system newline for formatting, which is LF on android.
+ // we need this to be CRLF, so we convert the data after receiving.
+ outputStream = new EOLConvertingOutputStream(outputStream);
} catch (IOException e) {
throw new MessagingException("could not allocate temp file for storage!", e);
} | ['k9mail/src/main/java/com/fsck/k9/message/PgpMessageBuilder.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,539,371 | 707,429 | 97,689 | 433 | 343 | 68 | 4 | 1 | 1,135 | 63 | 671 | 43 | 0 | 1 | 2016-10-07T19:19:36 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,659 | thundernest/k-9/1687/1666 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1666 | https://github.com/thundernest/k-9/pull/1687 | https://github.com/thundernest/k-9/pull/1687 | 1 | fix | Switching from dark to light theme (or vise versa) inside message doesn't work | ### Expected behavior
When `fixed message theme` option is disabled, switching the theme when viewing a message should switch the theme immediately.
### Actual behavior
After switching the theme inside the message, the message view reloads but the theme stays the same. I need to leave the message and open it again to get the other theme.
### Steps to reproduce
1. Disable `fixed message theme` option
2. Open message and switch to dark / light theme
### Environment
K-9 Mail version: v5.111 + v5.112 (iirc, before v5.111 I didn't have this problem)
Android version: 6.0.1
Account type : IMAP
| c7b5a506360089630aac685aa050ff2924501db1 | 22e8f4cedb71dbd85b40bdf5ceb665ec549d9262 | https://github.com/thundernest/k-9/compare/c7b5a506360089630aac685aa050ff2924501db1...22e8f4cedb71dbd85b40bdf5ceb665ec549d9262 | diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java
index c6be46a1d..d29b79181 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java
@@ -146,6 +146,8 @@ public class MessageLoaderHelper {
* asyncStartOrResumeLoadingMessage in a new instance of this class. */
@UiThread
public void onDestroyChangingConfigurations() {
+ cancelAndClearDecodeLoader();
+
if (messageCryptoHelper != null) {
messageCryptoHelper.detachCallback();
} | ['k9mail/src/main/java/com/fsck/k9/activity/MessageLoaderHelper.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,537,988 | 707,124 | 97,651 | 433 | 40 | 7 | 2 | 1 | 597 | 100 | 144 | 15 | 0 | 0 | 2016-10-07T16:46:28 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,660 | thundernest/k-9/1678/1625 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1625 | https://github.com/thundernest/k-9/pull/1678 | https://github.com/thundernest/k-9/pull/1678 | 1 | fixes | Wrong order for multipart/alternative children | We create `multipart/alternative` parts with a `text/html` part as first child and `text/plain` as second child. This isn't what other clients do. And it seems to confuse Thunderbird which then only displays the `text/plain` part.
Affected version: 5.111
| dbb6cc4d887058a1318ce872fbc29e0e00eb7043 | 0cd52bc26b1c1f34d569d7370216b81b9369bbb4 | https://github.com/thundernest/k-9/compare/dbb6cc4d887058a1318ce872fbc29e0e00eb7043...0cd52bc26b1c1f34d569d7370216b81b9369bbb4 | diff --git a/k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java b/k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java
index 775513aed..3c365fcd1 100644
--- a/k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java
+++ b/k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java
@@ -152,10 +152,11 @@ public abstract class MessageBuilder {
// This is the compiled MIME part for an HTML message.
MimeMultipart composedMimeMessage = createMimeMultipart();
- composedMimeMessage.setSubType("alternative"); // Let the receiver select either the text or the HTML part.
- composedMimeMessage.addBodyPart(new MimeBodyPart(body, "text/html"));
+ composedMimeMessage.setSubType("alternative");
+ // Let the receiver select either the text or the HTML part.
bodyPlain = buildText(isDraft, SimpleMessageFormat.TEXT);
composedMimeMessage.addBodyPart(new MimeBodyPart(bodyPlain, "text/plain"));
+ composedMimeMessage.addBodyPart(new MimeBodyPart(body, "text/html"));
if (hasAttachments) {
// If we're HTML and have attachments, we have a MimeMultipart container to hold the
diff --git a/k9mail/src/test/java/com/fsck/k9/message/MessageBuilderTest.java b/k9mail/src/test/java/com/fsck/k9/message/MessageBuilderTest.java
index b488de2ba..72d5b68b9 100644
--- a/k9mail/src/test/java/com/fsck/k9/message/MessageBuilderTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/message/MessageBuilderTest.java
@@ -8,6 +8,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
+import java.util.List;
import android.app.Application;
@@ -15,12 +16,14 @@ import com.fsck.k9.Account.QuoteStyle;
import com.fsck.k9.Identity;
import com.fsck.k9.activity.misc.Attachment;
import com.fsck.k9.mail.Address;
+import com.fsck.k9.mail.BodyPart;
import com.fsck.k9.mail.BoundaryGenerator;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.internet.MessageIdGenerator;
import com.fsck.k9.mail.internet.MimeMessage;
+import com.fsck.k9.mail.internet.MimeMultipart;
import com.fsck.k9.message.MessageBuilder.Callback;
import org.junit.Before;
import org.junit.Test;
@@ -187,6 +190,25 @@ public class MessageBuilderTest {
assertEquals(MESSAGE_HEADERS + MESSAGE_CONTENT_WITH_ATTACH, bos.toString());
}
+ @Test
+ public void build__usingHtmlFormat__shouldUseMultipartAlternativeInCorrectOrder() {
+ MessageBuilder messageBuilder = createHtmlMessageBuilder();
+ Callback mockCallback = mock(Callback.class);
+ messageBuilder.buildAsync(mockCallback);
+ ArgumentCaptor<MimeMessage> mimeMessageCaptor = ArgumentCaptor.forClass(MimeMessage.class);
+ verify(mockCallback).onMessageBuildSuccess(mimeMessageCaptor.capture(), eq(false));
+ verifyNoMoreInteractions(mockCallback);
+
+ MimeMessage mimeMessage = mimeMessageCaptor.getValue();
+
+ assertEquals(MimeMultipart.class, mimeMessage.getBody().getClass());
+ assertEquals("multipart/alternative", ((MimeMultipart) mimeMessage.getBody()).getMimeType());
+ List<BodyPart> parts = ((MimeMultipart) mimeMessage.getBody()).getBodyParts();
+ //RFC 1341 - 7.2.3 - Best type is last displayable
+ assertEquals("text/plain", parts.get(0).getMimeType());
+ assertEquals("text/html", parts.get(1).getMimeType());
+ }
+
@Test
public void build__withMessageAttachment__shouldAttachAsApplicationOctetStream() throws Exception {
MessageBuilder messageBuilder = createSimpleMessageBuilder();
@@ -320,4 +342,42 @@ public class MessageBuilderTest {
return b;
}
+
+ private MessageBuilder createHtmlMessageBuilder() {
+ MessageBuilder b = new SimpleMessageBuilder(context, messageIdGenerator, boundaryGenerator);
+
+ Identity identity = new Identity();
+ identity.setName(TEST_IDENTITY_ADDRESS.getPersonal());
+ identity.setEmail(TEST_IDENTITY_ADDRESS.getAddress());
+ identity.setDescription("test identity");
+ identity.setSignatureUse(false);
+
+ b.setSubject(TEST_SUBJECT)
+ .setSentDate(SENT_DATE)
+ .setHideTimeZone(true)
+ .setTo(Arrays.asList(TEST_TO))
+ .setCc(Arrays.asList(TEST_CC))
+ .setBcc(Arrays.asList(TEST_BCC))
+ .setInReplyTo("inreplyto")
+ .setReferences("references")
+ .setRequestReadReceipt(false)
+ .setIdentity(identity)
+ .setMessageFormat(SimpleMessageFormat.HTML)
+ .setText(TEST_MESSAGE_TEXT)
+ .setAttachments(new ArrayList<Attachment>())
+ .setSignature("signature")
+ .setQuoteStyle(QuoteStyle.PREFIX)
+ .setQuotedTextMode(QuotedTextMode.NONE)
+ .setQuotedText("quoted text")
+ .setQuotedHtmlContent(new InsertableHtmlContent())
+ .setReplyAfterQuote(false)
+ .setSignatureBeforeQuotedText(false)
+ .setIdentityChanged(false)
+ .setSignatureChanged(false)
+ .setCursorPosition(0)
+ .setMessageReference(null)
+ .setDraft(false);
+
+ return b;
+ }
} | ['k9mail/src/test/java/com/fsck/k9/message/MessageBuilderTest.java', 'k9mail/src/main/java/com/fsck/k9/message/MessageBuilder.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,536,841 | 706,845 | 97,622 | 433 | 422 | 86 | 5 | 1 | 256 | 38 | 61 | 4 | 0 | 0 | 2016-10-07T00:11:01 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,661 | thundernest/k-9/1608/1607 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1607 | https://github.com/thundernest/k-9/pull/1608 | https://github.com/thundernest/k-9/pull/1608 | 1 | fixes | Composer crashes when an invalid mail address is about to be shown in recipient selector | ### Steps to reproduce
1. create a contact with a name and an invalid mail address, e. g. "(none)"
2. click '+' to compose new message
3. type first letters of the contact name until it should be shown
### Logcat
```
09-09 22:12:26.740 10531 10531 E AndroidRuntime: FATAL EXCEPTION: main
09-09 22:12:26.740 10531 10531 E AndroidRuntime: Process: com.fsck.k9, PID: 10531
09-09 22:12:26.740 10531 10531 E AndroidRuntime: Theme: themes:{default=overlay:com.brit.swiftdark, fontPkg:com.brit.swiftdark, com.android.systemui=overlay:com.brit.s
wiftdark, com.android.systemui.navbar=overlay:com.brit.swiftdark}
09-09 22:12:26.740 10531 10531 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null obj
ect reference
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.text.SpannableString.<init>(SpannableString.java:30)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.text.Spannable$Factory.newSpannable(Spannable.java:67)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at com.fsck.k9.activity.compose.RecipientAdapter.highlightText(RecipientAdapter.java:182)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at com.fsck.k9.activity.compose.RecipientAdapter.bindView(RecipientAdapter.java:92)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at com.fsck.k9.activity.compose.RecipientAdapter.getView(RecipientAdapter.java:72)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.AbsListView.obtainView(AbsListView.java:2346)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.ListPopupWindow$DropDownListView.obtainView(ListPopupWindow.java:1734)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.ListView.measureHeightOfChildren(ListView.java:1281)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.ListPopupWindow.buildDropDown(ListPopupWindow.java:1209)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.ListPopupWindow.show(ListPopupWindow.java:584)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.AutoCompleteTextView.showDropDown(AutoCompleteTextView.java:1106)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at com.fsck.k9.view.RecipientSelectView.showDropDown(RecipientSelectView.java:226)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.AutoCompleteTextView.updateDropDownForFilter(AutoCompleteTextView.java:975)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.AutoCompleteTextView.-wrap2(AutoCompleteTextView.java)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.widget.AutoCompleteTextView$PopupDataSetObserver$1.run(AutoCompleteTextView.java:1300)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5463)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
09-09 22:12:26.740 10531 10531 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-09 22:12:26.741 1716 4127 W ActivityManager: Force finishing activity com.fsck.k9/.activity.MessageCompose
```
### Environment
K-9 Mail version: 5.111 (master)
Android version:
6.0.1
| 82f5fc6b30947894054c099d0c841e9d0cc80794 | 192ce7e7700f34f75d92e2c7f40f9a281087dd20 | https://github.com/thundernest/k-9/compare/82f5fc6b30947894054c099d0c841e9d0cc80794...192ce7e7700f34f75d92e2c7f40f9a281087dd20 | diff --git a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java
index bd359924f..60df445fd 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java
@@ -238,12 +238,14 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
}
}
- Uri photoUri = cursor.isNull(INDEX_PHOTO_URI) ? null : Uri.parse(cursor.getString(INDEX_PHOTO_URI));
Recipient recipient = new Recipient(name, email, addressLabel, contactId, lookupKey);
- recipient.photoThumbnailUri = photoUri;
+ if (recipient.isValidEmailAddress()) {
+ Uri photoUri = cursor.isNull(INDEX_PHOTO_URI) ? null : Uri.parse(cursor.getString(INDEX_PHOTO_URI));
- recipientMap.put(email, recipient);
- recipients.add(recipient);
+ recipient.photoThumbnailUri = photoUri;
+ recipientMap.put(email, recipient);
+ recipients.add(recipient);
+ }
}
cursor.close();
diff --git a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java
index 34066918c..28ca83b25 100644
--- a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java
+++ b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java
@@ -550,6 +550,10 @@ public class RecipientSelectView extends TokenCompleteTextView<Recipient> implem
return address.getAddress();
}
+ public boolean isValidEmailAddress() {
+ return (address.getAddress() != null);
+ }
+
public String getDisplayNameOrUnknown(Context context) {
String displayName = getDisplayName();
if (displayName != null) { | ['k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java', 'k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,526,875 | 702,474 | 97,599 | 433 | 698 | 122 | 14 | 2 | 3,805 | 291 | 1,156 | 44 | 0 | 1 | 2016-09-09T20:56:35 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,662 | thundernest/k-9/1584/1582 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1582 | https://github.com/thundernest/k-9/pull/1584 | https://github.com/thundernest/k-9/pull/1584 | 1 | fixes | Crash while moving message | Reported via Google Play:
```
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:1, request=1, result=-1, data=Intent { (has extras) }} to activity {com.fsck.k9/com.fsck.k9.activity.MessageList}: java.lang.IllegalStateException: got an activity result that wasn't meant for us. this is a bug!
at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
Caused by: java.lang.IllegalStateException: got an activity result that wasn't meant for us. this is a bug!
at com.fsck.k9.ui.messageview.MessageCryptoPresenter.onActivityResult(MessageCryptoPresenter.java:158)
at com.fsck.k9.ui.messageview.MessageViewFragment.onActivityResult(MessageViewFragment.java:405)
at android.app.Activity.dispatchActivityResult(Activity.java:6197)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
... 11 more
```
User messages:
- moved a message that was opened to a different folder.
- Crash on moving opened email to another IMAP folder. Crash after selecting target folder.
- crash at moving message to different folder. is consistent problem
- tried to move a message to another folder, crash. happens wavy time I select move and a folder in the refile menu.
| 4e7f93c3e3657921293d4615c49f5f5f54d9b985 | 5a1776890e26c73fe267ca857f6596996e1dc76d | https://github.com/thundernest/k-9/compare/4e7f93c3e3657921293d4615c49f5f5f54d9b985...5a1776890e26c73fe267ca857f6596996e1dc76d | diff --git a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
index 0616ccaa4..996b222c2 100644
--- a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
+++ b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
@@ -209,19 +209,6 @@ public class MessageViewFragment extends Fragment implements ConfirmationDialogF
mFragmentListener.updateMenu();
}
- public void onPendingIntentResult(int requestCode, int resultCode, Intent data) {
- if ((requestCode & REQUEST_MASK_LOADER_HELPER) == REQUEST_MASK_LOADER_HELPER) {
- requestCode ^= REQUEST_MASK_LOADER_HELPER;
- messageLoaderHelper.onActivityResult(requestCode, resultCode, data);
- return;
- }
-
- if ((requestCode & REQUEST_MASK_CRYPTO_PRESENTER) == REQUEST_MASK_CRYPTO_PRESENTER) {
- requestCode ^= REQUEST_MASK_CRYPTO_PRESENTER;
- messageCryptoPresenter.onActivityResult(requestCode, resultCode, data);
- }
- }
-
private void hideKeyboard() {
Activity activity = getActivity();
if (activity == null) {
@@ -396,13 +383,27 @@ public class MessageViewFragment extends Fragment implements ConfirmationDialogF
startActivityForResult(intent, activity);
}
+ public void onPendingIntentResult(int requestCode, int resultCode, Intent data) {
+ if ((requestCode & REQUEST_MASK_LOADER_HELPER) == REQUEST_MASK_LOADER_HELPER) {
+ requestCode ^= REQUEST_MASK_LOADER_HELPER;
+ messageLoaderHelper.onActivityResult(requestCode, resultCode, data);
+ return;
+ }
+
+ if ((requestCode & REQUEST_MASK_CRYPTO_PRESENTER) == REQUEST_MASK_CRYPTO_PRESENTER) {
+ requestCode ^= REQUEST_MASK_CRYPTO_PRESENTER;
+ messageCryptoPresenter.onActivityResult(requestCode, resultCode, data);
+ }
+ }
+
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
- messageCryptoPresenter.onActivityResult(requestCode, resultCode, data);
+ // Note: because fragments do not have a startIntentSenderForResult method, pending intent activities are
+ // launched through the MessageList activity, and delivered back via onPendingIntentResult()
switch (requestCode) {
case ACTIVITY_CHOOSE_DIRECTORY: { | ['k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,526,740 | 702,446 | 97,598 | 433 | 1,511 | 264 | 29 | 1 | 1,969 | 149 | 453 | 30 | 0 | 1 | 2016-08-30T11:21:28 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,663 | thundernest/k-9/1537/819 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/819 | https://github.com/thundernest/k-9/pull/1537 | https://github.com/thundernest/k-9/pull/1537 | 1 | fix | forward a mail with attachment failed | ### Actual behaviour
there's two cases:
1.get a mail with inline images
2.get a mail with attachment
Two mail has been down fully in my k9 client.
When forward,both toast:"Some attachments cannot be forwarded because they have not been downloaded.".
If ignore this error to forward,the inline images or attachment can not be send to others.
### Expected behaviour
The two case should forward correctly
### Steps to reproduce
1.forward a mail to somebody with inline images or with attachment.
2.both toast "Some attachments cannot be forwarded because they have not been downloaded.".
3.click forward btn ok
4.login in somebody's mail to get these two mails
5.images inline can not show and also without attachements
### Environment
K-9 Mail version:
check out from github on 28.9.2015
Android version:
4.3
Account type (IMAP, POP3, WebDAV/Exchange):
POP3
| 81468ac2b34d2b670ea74e2186424fcd06d3c513 | d276bbda3ea65284487d92caa3577db0dd5ae1e6 | https://github.com/thundernest/k-9/compare/81468ac2b34d2b670ea74e2186424fcd06d3c513...d276bbda3ea65284487d92caa3577db0dd5ae1e6 | diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java
index 563d9cc96..c40ce1622 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java
@@ -1276,7 +1276,7 @@ public class MessageCompose extends K9Activity implements OnClickListener,
}
if (!mSourceMessageProcessed) {
- attachmentPresenter.loadAttachments(message, 0);
+ attachmentPresenter.loadNonInlineAttachments(messageViewInfo);
}
// Decode the identity header when loading a draft.
diff --git a/k9mail/src/main/java/com/fsck/k9/activity/compose/AttachmentPresenter.java b/k9mail/src/main/java/com/fsck/k9/activity/compose/AttachmentPresenter.java
index 6535391dd..b5a569b28 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/compose/AttachmentPresenter.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/compose/AttachmentPresenter.java
@@ -21,15 +21,8 @@ import com.fsck.k9.activity.loader.AttachmentContentLoader;
import com.fsck.k9.activity.loader.AttachmentInfoLoader;
import com.fsck.k9.activity.misc.Attachment;
import com.fsck.k9.activity.misc.Attachment.LoadingState;
-import com.fsck.k9.mail.Flag;
-import com.fsck.k9.mail.MessagingException;
-import com.fsck.k9.mail.Multipart;
-import com.fsck.k9.mail.Part;
-import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mailstore.AttachmentViewInfo;
-import com.fsck.k9.mailstore.LocalBodyPart;
import com.fsck.k9.mailstore.MessageViewInfo;
-import com.fsck.k9.provider.AttachmentProvider;
public class AttachmentPresenter {
@@ -158,16 +151,27 @@ public class AttachmentPresenter {
addAttachmentAndStartLoader(attachment);
}
- public void processMessageToForward(MessageViewInfo messageViewInfo) {
- if (messageViewInfo.message.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
- attachmentMvpView.showMissingAttachmentsPartialMessageWarning();
- return;
- }
+ public boolean loadNonInlineAttachments(MessageViewInfo messageViewInfo) {
+ boolean allPartsAvailable = true;
for (AttachmentViewInfo attachmentViewInfo : messageViewInfo.attachments) {
- if (!attachmentViewInfo.inlineAttachment) {
- addAttachment(attachmentViewInfo);
+ if (attachmentViewInfo.inlineAttachment) {
+ continue;
+ }
+ if (!attachmentViewInfo.isContentAvailable) {
+ allPartsAvailable = false;
+ continue;
}
+ addAttachment(attachmentViewInfo);
+ }
+
+ return allPartsAvailable;
+ }
+
+ public void processMessageToForward(MessageViewInfo messageViewInfo) {
+ boolean isMissingParts = !loadNonInlineAttachments(messageViewInfo);
+ if (isMissingParts) {
+ attachmentMvpView.showMissingAttachmentsPartialMessageWarning();
}
}
@@ -300,45 +304,6 @@ public class AttachmentPresenter {
}
}
- /**
- * Add all attachments of an existing message as if they were added by hand.
- *
- * @param part
- * The message part to check for being an attachment. This method will recurse if it's
- * a multipart part.
- * @param depth
- * The recursion depth. Currently unused.
- *
- * @return {@code true} if all attachments were able to be attached, {@code false} otherwise.
- */
- public boolean loadAttachments(Part part, int depth) {
- if (part.getBody() instanceof Multipart) {
- Multipart mp = (Multipart) part.getBody();
- boolean ret = true;
- for (int i = 0, count = mp.getCount(); i < count; i++) {
- if (!loadAttachments(mp.getBodyPart(i), depth + 1)) {
- ret = false;
- }
- }
- return ret;
- }
-
- String contentType = part.getContentType();
- String name = MimeUtility.getHeaderParameter(contentType, "name");
- if (name != null) {
- if (part instanceof LocalBodyPart) {
- LocalBodyPart localBodyPart = (LocalBodyPart) part;
- String accountUuid = localBodyPart.getAccountUuid();
- long attachmentId = localBodyPart.getId();
- Uri uri = AttachmentProvider.getAttachmentUri(accountUuid, attachmentId);
- addAttachment(uri);
- return true;
- }
- return false;
- }
- return true;
- }
-
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
void addAttachmentsFromResultIntent(Intent data) {
// TODO draftNeedsSaving = true
diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentViewInfo.java b/k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentViewInfo.java
index cd1d0ef49..585f549f4 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentViewInfo.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentViewInfo.java
@@ -23,14 +23,16 @@ public class AttachmentViewInfo {
public final Uri uri;
public final boolean inlineAttachment;
public final Part part;
+ public final boolean isContentAvailable;
public AttachmentViewInfo(String mimeType, String displayName, long size, Uri uri, boolean inlineAttachment,
- Part part) {
+ Part part, boolean isContentAvailable) {
this.mimeType = mimeType;
this.displayName = displayName;
this.size = size;
this.uri = uri;
this.inlineAttachment = inlineAttachment;
this.part = part;
+ this.isContentAvailable = isContentAvailable;
}
}
diff --git a/k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java b/k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java
index 9c024b1b4..05bb270e6 100644
--- a/k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java
+++ b/k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java
@@ -61,17 +61,21 @@ public class AttachmentInfoExtractor {
public AttachmentViewInfo extractAttachmentInfo(Part part) throws MessagingException {
Uri uri;
long size;
+ boolean isContentAvailable;
+
if (part instanceof LocalPart) {
LocalPart localPart = (LocalPart) part;
String accountUuid = localPart.getAccountUuid();
long messagePartId = localPart.getId();
size = localPart.getSize();
+ isContentAvailable = part.getBody() != null;
uri = AttachmentProvider.getAttachmentUri(accountUuid, messagePartId);
} else if (part instanceof LocalMessage) {
LocalMessage localMessage = (LocalMessage) part;
String accountUuid = localMessage.getAccount().getUuid();
long messagePartId = localMessage.getMessagePartId();
size = localMessage.getSize();
+ isContentAvailable = part.getBody() != null;
uri = AttachmentProvider.getAttachmentUri(accountUuid, messagePartId);
} else {
Body body = part.getBody();
@@ -79,13 +83,13 @@ public class AttachmentInfoExtractor {
DeferredFileBody decryptedTempFileBody = (DeferredFileBody) body;
size = decryptedTempFileBody.getSize();
uri = getDecryptedFileProviderUri(decryptedTempFileBody, part.getMimeType());
- return extractAttachmentInfo(part, uri, size);
+ isContentAvailable = true;
} else {
throw new IllegalArgumentException("Unsupported part type provided");
}
}
- return extractAttachmentInfo(part, uri, size);
+ return extractAttachmentInfo(part, uri, size, isContentAvailable);
}
@Nullable
@@ -104,11 +108,13 @@ public class AttachmentInfoExtractor {
}
public AttachmentViewInfo extractAttachmentInfoForDatabase(Part part) throws MessagingException {
- return extractAttachmentInfo(part, Uri.EMPTY, AttachmentViewInfo.UNKNOWN_SIZE);
+ boolean isContentAvailable = part.getBody() != null;
+ return extractAttachmentInfo(part, Uri.EMPTY, AttachmentViewInfo.UNKNOWN_SIZE, isContentAvailable);
}
@WorkerThread
- private AttachmentViewInfo extractAttachmentInfo(Part part, Uri uri, long size) throws MessagingException {
+ private AttachmentViewInfo extractAttachmentInfo(Part part, Uri uri, long size, boolean isContentAvailable)
+ throws MessagingException {
boolean inlineAttachment = false;
String mimeType = part.getMimeType();
@@ -139,7 +145,7 @@ public class AttachmentInfoExtractor {
long attachmentSize = extractAttachmentSize(contentDisposition, size);
- return new AttachmentViewInfo(mimeType, name, attachmentSize, uri, inlineAttachment, part);
+ return new AttachmentViewInfo(mimeType, name, attachmentSize, uri, inlineAttachment, part, isContentAvailable);
}
@WorkerThread
diff --git a/k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java b/k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java
index a9ae28bb2..38d22695d 100644
--- a/k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java
+++ b/k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java
@@ -55,7 +55,7 @@ public class AttachmentController {
}
public void viewAttachment() {
- if (needsDownloading()) {
+ if (!attachment.isContentAvailable) {
downloadAndViewAttachment((LocalPart) attachment.part);
} else {
viewLocalAttachment();
@@ -70,18 +70,6 @@ public class AttachmentController {
saveAttachmentTo(new File(directory));
}
- private boolean needsDownloading() {
- return isPartMissing() && isLocalPart();
- }
-
- private boolean isPartMissing() {
- return attachment.part.getBody() == null;
- }
-
- private boolean isLocalPart() {
- return attachment.part instanceof LocalPart;
- }
-
private void downloadAndViewAttachment(LocalPart localPart) {
downloadAttachment(localPart, new Runnable() {
@Override
@@ -133,7 +121,7 @@ public class AttachmentController {
return;
}
- if (needsDownloading()) {
+ if (!attachment.isContentAvailable) {
downloadAndSaveAttachmentTo((LocalPart) attachment.part, directory);
} else {
saveLocalAttachmentTo(directory);
diff --git a/k9mail/src/test/java/com/fsck/k9/mailstore/AttachmentResolverTest.java b/k9mail/src/test/java/com/fsck/k9/mailstore/AttachmentResolverTest.java
index da792d333..7dd1d2b12 100644
--- a/k9mail/src/test/java/com/fsck/k9/mailstore/AttachmentResolverTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/mailstore/AttachmentResolverTest.java
@@ -86,14 +86,15 @@ public class AttachmentResolverTest {
subPart1.setHeader(MimeHeader.HEADER_CONTENT_ID, "cid-1");
subPart2.setHeader(MimeHeader.HEADER_CONTENT_ID, "cid-2");
- when(attachmentInfoExtractor.extractAttachmentInfo(subPart1)).thenReturn(
- new AttachmentViewInfo(null, null, AttachmentViewInfo.UNKNOWN_SIZE, ATTACHMENT_TEST_URI_1, false, subPart1));
- when(attachmentInfoExtractor.extractAttachmentInfo(subPart2)).thenReturn(
- new AttachmentViewInfo(null, null, AttachmentViewInfo.UNKNOWN_SIZE, ATTACHMENT_TEST_URI_2, false, subPart2));
+ when(attachmentInfoExtractor.extractAttachmentInfo(subPart1)).thenReturn(new AttachmentViewInfo(
+ null, null, AttachmentViewInfo.UNKNOWN_SIZE, ATTACHMENT_TEST_URI_1, false, subPart1, true));
+ when(attachmentInfoExtractor.extractAttachmentInfo(subPart2)).thenReturn(new AttachmentViewInfo(
+ null, null, AttachmentViewInfo.UNKNOWN_SIZE, ATTACHMENT_TEST_URI_2, false, subPart2, true));
Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, multipartPart);
+
assertEquals(2, result.size());
assertEquals(ATTACHMENT_TEST_URI_1, result.get("cid-1"));
assertEquals(ATTACHMENT_TEST_URI_2, result.get("cid-2"));
diff --git a/k9mail/src/test/java/com/fsck/k9/message/extractors/AttachmentInfoExtractorTest.java b/k9mail/src/test/java/com/fsck/k9/message/extractors/AttachmentInfoExtractorTest.java
index ff283ae01..a5912715f 100644
--- a/k9mail/src/test/java/com/fsck/k9/message/extractors/AttachmentInfoExtractorTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/message/extractors/AttachmentInfoExtractorTest.java
@@ -8,6 +8,7 @@ import android.support.annotation.Nullable;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.internet.MimeBodyPart;
import com.fsck.k9.mail.internet.MimeHeader;
+import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mailstore.AttachmentViewInfo;
import com.fsck.k9.mailstore.LocalBodyPart;
import com.fsck.k9.mailstore.DeferredFileBody;
@@ -162,6 +163,25 @@ public class AttachmentInfoExtractorTest {
assertEquals(AttachmentViewInfo.UNKNOWN_SIZE, attachmentViewInfo.size);
}
+ @Test
+ public void extractInfoForDb__withNoBody__shouldReturnContentNotAvailable() throws Exception {
+ MimeBodyPart part = new MimeBodyPart();
+
+ AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part);
+
+ assertFalse(attachmentViewInfo.isContentAvailable);
+ }
+
+ @Test
+ public void extractInfoForDb__withNoBody__shouldReturnContentAvailable() throws Exception {
+ MimeBodyPart part = new MimeBodyPart();
+ part.setBody(new TextBody("data"));
+
+ AttachmentViewInfo attachmentViewInfo = attachmentInfoExtractor.extractAttachmentInfoForDatabase(part);
+
+ assertTrue(attachmentViewInfo.isContentAvailable);
+ }
+
@Test
public void extractInfo__withDeferredFileBody() throws Exception {
attachmentInfoExtractor = new AttachmentInfoExtractor(context) {
@@ -187,5 +207,6 @@ public class AttachmentInfoExtractorTest {
assertEquals(TEST_SIZE, attachmentViewInfo.size);
assertEquals(TEST_MIME_TYPE, attachmentViewInfo.mimeType);
assertFalse(attachmentViewInfo.inlineAttachment);
+ assertTrue(attachmentViewInfo.isContentAvailable);
}
} | ['k9mail/src/main/java/com/fsck/k9/ui/messageview/AttachmentController.java', 'k9mail/src/main/java/com/fsck/k9/activity/compose/AttachmentPresenter.java', 'k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java', 'k9mail/src/test/java/com/fsck/k9/mailstore/AttachmentResolverTest.java', 'k9mail/src/main/java/com/fsck/k9/mailstore/AttachmentViewInfo.java', 'k9mail/src/test/java/com/fsck/k9/message/extractors/AttachmentInfoExtractorTest.java', 'k9mail/src/main/java/com/fsck/k9/message/extractors/AttachmentInfoExtractor.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 3,529,396 | 703,410 | 97,677 | 430 | 4,835 | 935 | 109 | 5 | 867 | 135 | 200 | 29 | 0 | 0 | 2016-08-01T14:56:49 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,664 | thundernest/k-9/1536/1495 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1495 | https://github.com/thundernest/k-9/pull/1536 | https://github.com/thundernest/k-9/pull/1536 | 1 | fixes | "To" field does not convert typed email addresses to tokens on send | ### Expected behavior
Autocomplete address field "To" should convert typed email addresses to tokens when clicking send
### Actual behavior
It does not, shows "Recipient field contains incomplete input!"
### Steps to reproduce
1. compose mail
2. write body subject and in the last step write email address into "To" field without selecting an email address from the dropdown
3. click send
### Environment
K-9 Mail version: 5.110
Android version: 6
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| 81468ac2b34d2b670ea74e2186424fcd06d3c513 | b3f2974962df4789331578f1afdeef3baef5f311 | https://github.com/thundernest/k-9/compare/81468ac2b34d2b670ea74e2186424fcd06d3c513...b3f2974962df4789331578f1afdeef3baef5f311 | diff --git a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java
index a8889a388..cb04bb62e 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java
@@ -258,6 +258,18 @@ public class RecipientMvpView implements OnFocusChangeListener, OnClickListener
return bccView.hasUncompletedText();
}
+ public boolean recipientToTryPerformCompletion() {
+ return toView.tryPerformCompletion();
+ }
+
+ public boolean recipientCcTryPerformCompletion() {
+ return ccView.tryPerformCompletion();
+ }
+
+ public boolean recipientBccTryPerformCompletion() {
+ return bccView.tryPerformCompletion();
+ }
+
public void showToUncompletedError() {
toView.setError(toView.getContext().getString(R.string.compose_error_incomplete_recipient));
}
diff --git a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
index a6610e9b9..f16b788e7 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
@@ -116,6 +116,13 @@ public class RecipientPresenter implements PermissionPingCallback {
}
public boolean checkRecipientsOkForSending() {
+ boolean performedAnyCompletion = recipientMvpView.recipientToTryPerformCompletion() ||
+ recipientMvpView.recipientCcTryPerformCompletion() ||
+ recipientMvpView.recipientBccTryPerformCompletion();
+ if (performedAnyCompletion) {
+ return true;
+ }
+
if (recipientMvpView.recipientToHasUncompletedText()) {
recipientMvpView.showToUncompletedError();
return true;
diff --git a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java
index e7dc78918..3c5dee446 100644
--- a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java
+++ b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java
@@ -364,6 +364,21 @@ public class RecipientSelectView extends TokenCompleteTextView<Recipient> implem
}
}
+ public boolean tryPerformCompletion() {
+ if (!hasUncompletedText()) {
+ return false;
+ }
+ int previousNumRecipients = getTokenCount();
+ performCompletion();
+ int numRecipients = getTokenCount();
+
+ return previousNumRecipients != numRecipients;
+ }
+
+ private int getTokenCount() {
+ return getObjects().size();
+ }
+
public boolean hasUncompletedText() {
String currentCompletionText = currentCompletionText();
return !TextUtils.isEmpty(currentCompletionText) && !isPlaceholderText(currentCompletionText); | ['k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java', 'k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java', 'k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientMvpView.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,529,396 | 703,410 | 97,677 | 430 | 1,049 | 198 | 34 | 3 | 502 | 77 | 118 | 18 | 0 | 0 | 2016-08-01T13:33:36 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,665 | thundernest/k-9/1262/1250 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1250 | https://github.com/thundernest/k-9/pull/1262 | https://github.com/thundernest/k-9/pull/1262 | 1 | fixes | Reply flag is not set anymore when replying to a mail | ### Expected behaviour
Reply flag is set when replying to a mail.
### Actual behaviour
When replying to a mail I do not see a reply flag for the original mail I replied to. When checking the account with a different client (web/Thunderbird) I do not see a flag, too. So it is no frontend bug, the flag is not set anymore, beginning with 5.108.
### Steps to reproduce
See above.
### Environment
K-9 Mail version: 5.108
Android version: CM 12.1
Account type (IMAP, POP3, WebDAV/Exchange):
IMAP
| f794cc1f896a9755c535370c8527c49be88ed2f1 | 7f724e9e04a4df93362712ac894ef757025981f3 | https://github.com/thundernest/k-9/compare/f794cc1f896a9755c535370c8527c49be88ed2f1...7f724e9e04a4df93362712ac894ef757025981f3 | diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java
index cd7cde46f..5072c6e5f 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java
@@ -2454,18 +2454,21 @@ public class MessageCompose extends K9Activity implements OnClickListener,
}
static class SendMessageTask extends AsyncTask<Void, Void, Void> {
- Context context;
- Account account;
- Contacts contacts;
- Message message;
- Long draftId;
-
- SendMessageTask(Context context, Account account, Contacts contacts, Message message, Long draftId) {
+ final Context context;
+ final Account account;
+ final Contacts contacts;
+ final Message message;
+ final Long draftId;
+ final MessageReference messageReference;
+
+ SendMessageTask(Context context, Account account, Contacts contacts, Message message,
+ Long draftId, MessageReference messageReference) {
this.context = context;
this.account = account;
this.contacts = contacts;
this.message = message;
this.draftId = draftId;
+ this.messageReference = messageReference;
}
@Override
@@ -2474,6 +2477,7 @@ public class MessageCompose extends K9Activity implements OnClickListener,
contacts.markAsContacted(message.getRecipients(RecipientType.TO));
contacts.markAsContacted(message.getRecipients(RecipientType.CC));
contacts.markAsContacted(message.getRecipients(RecipientType.BCC));
+ updateReferencedMessage();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e);
}
@@ -2486,6 +2490,26 @@ public class MessageCompose extends K9Activity implements OnClickListener,
return null;
}
+
+ /**
+ * Set the flag on the referenced message(indicated we replied / forwarded the message)
+ **/
+ private void updateReferencedMessage() {
+ if (messageReference != null && messageReference.getFlag() != null) {
+ if (K9.DEBUG) {
+ Log.d(K9.LOG_TAG, "Setting referenced message (" +
+ messageReference.getFolderName() + ", " +
+ messageReference.getUid() + ") flag to " +
+ messageReference.getFlag());
+ }
+ final Account account = Preferences.getPreferences(context)
+ .getAccount(messageReference.getAccountUuid());
+ final String folderName = messageReference.getFolderName();
+ final String sourceMessageUid = messageReference.getUid();
+ MessagingController.getInstance(context).setFlag(account, folderName,
+ sourceMessageUid, messageReference.getFlag(), true);
+ }
+ }
}
class Listener extends MessagingListener {
@@ -2981,7 +3005,7 @@ public class MessageCompose extends K9Activity implements OnClickListener,
} else {
currentMessageBuilder = null;
new SendMessageTask(getApplicationContext(), mAccount, mContacts, message,
- mDraftId != INVALID_DRAFT_ID ? mDraftId : null).execute();
+ mDraftId != INVALID_DRAFT_ID ? mDraftId : null, mMessageReference).execute();
finish();
}
} | ['k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,421,870 | 682,236 | 94,810 | 409 | 1,979 | 328 | 40 | 1 | 498 | 87 | 133 | 18 | 0 | 0 | 2016-04-05T23:28:14 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,666 | thundernest/k-9/1247/1227 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1227 | https://github.com/thundernest/k-9/pull/1247 | https://github.com/thundernest/k-9/pull/1247 | 1 | fixes | Crash on screen rotate with OpenPGP handled message | ### Expected behaviour
Message should be re-rendered in landscape.
### Actual behaviour
Application crashes with following exception.
```
03-29 08:40:55.041 12045-12045/com.fsck.k9.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fsck.k9.debug, PID: 12045
java.util.NoSuchElementException
at java.util.ArrayDeque.removeFirst(ArrayDeque.java:248)
at com.fsck.k9.ui.crypto.MessageCryptoHelper.onCryptoFinished(MessageCryptoHelper.java:454)
at com.fsck.k9.ui.crypto.MessageCryptoHelper.onCryptoSuccess(MessageCryptoHelper.java:438)
at com.fsck.k9.ui.crypto.MessageCryptoHelper.handleCryptoOperationSuccess(MessageCryptoHelper.java:420)
at com.fsck.k9.ui.crypto.MessageCryptoHelper.handleCryptoOperationResult(MessageCryptoHelper.java:379)
at com.fsck.k9.ui.crypto.MessageCryptoHelper.onCryptoOperationReturned(MessageCryptoHelper.java:353)
at com.fsck.k9.ui.crypto.MessageCryptoHelper.access$400(MessageCryptoHelper.java:49)
at com.fsck.k9.ui.crypto.MessageCryptoHelper$4.onReturn(MessageCryptoHelper.java:250)
at org.openintents.openpgp.util.OpenPgpApi$OpenPgpAsyncTask.onPostExecute(OpenPgpApi.java:298)
at org.openintents.openpgp.util.OpenPgpApi$OpenPgpAsyncTask.onPostExecute(OpenPgpApi.java:279)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
```
Email available on request.
### Steps to reproduce
1. Receive a message that has been signed
2. Open the message.
3. Rotate the phone to landscape
### Environment
K-9 Mail version: commit 74c6e76 (current master)
OpenKeychain version: 3.9.4
Android version: 6.0.1
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| 74c6e764338d312dab49bb6e5499ee82d2c86c83 | fd89879f384c0d3e55d9ab98f9401ea98247c225 | https://github.com/thundernest/k-9/compare/74c6e764338d312dab49bb6e5499ee82d2c86c83...fd89879f384c0d3e55d9ab98f9401ea98247c225 | diff --git a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
index fccf71fd9..bd535fa89 100644
--- a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
+++ b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
@@ -734,6 +734,7 @@ public class MessageViewFragment extends Fragment implements ConfirmationDialogF
} else {
onLoadMessageFromDatabaseFinished(message);
}
+ getLoaderManager().destroyLoader(LOCAL_MESSAGE_LOADER_ID);
}
@Override | ['k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,420,444 | 681,947 | 94,777 | 409 | 71 | 14 | 1 | 1 | 3,543 | 117 | 548 | 45 | 0 | 1 | 2016-04-01T14:49:07 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,667 | thundernest/k-9/1233/615 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/615 | https://github.com/thundernest/k-9/pull/1233 | https://github.com/thundernest/k-9/pull/1233 | 1 | fixes | Account listed multiple times | I have three email accounts, which were before listed like this:
```
AccountA
AccountB
AccountC
```
After long-pressing the last account and choosing "Move up", I got two copies of the account that I tried to move, like this:
```
AccountA
AccountC
AccountB
AccountC
```
This state persisted after restarting the app (I think, the app was not listed in task manager), but problem went away after restarting phone, and `AccountC` is now in the middle as expected. Problem is not reproducible, I can now move them around as I please. When I had the problem I moved the account shortly after creating it.
K-9 Mail version: 5.004
Android version: 4.4.2
Phone: LG G2
| e738e4b28dd92bc74efed0d239c355c8a34447f2 | 9284243fb47ca5eca19fdc65bde20d395bebdfdf | https://github.com/thundernest/k-9/compare/e738e4b28dd92bc74efed0d239c355c8a34447f2...9284243fb47ca5eca19fdc65bde20d395bebdfdf | diff --git a/k9mail/src/main/java/com/fsck/k9/Preferences.java b/k9mail/src/main/java/com/fsck/k9/Preferences.java
index 05b839c5f..dcfc6bba8 100644
--- a/k9mail/src/main/java/com/fsck/k9/Preferences.java
+++ b/k9mail/src/main/java/com/fsck/k9/Preferences.java
@@ -61,7 +61,9 @@ public class Preferences {
}
if ((newAccount != null) && newAccount.getAccountNumber() != -1) {
accounts.put(newAccount.getUuid(), newAccount);
- accountsInOrder.add(newAccount);
+ if (!accountsInOrder.contains(newAccount)) {
+ accountsInOrder.add(newAccount);
+ }
newAccount = null;
}
} | ['k9mail/src/main/java/com/fsck/k9/Preferences.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,421,580 | 682,184 | 94,805 | 409 | 168 | 29 | 4 | 1 | 666 | 114 | 170 | 23 | 0 | 2 | 2016-03-30T16:33:47 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,657 | thundernest/k-9/1704/1699 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1699 | https://github.com/thundernest/k-9/pull/1704 | https://github.com/thundernest/k-9/pull/1704 | 1 | fixes | NPE in k9 and empty list when querying messages from 3rd party application (Gadgetbridge) | ### Expected behavior
We should get a list of messages
### Actual behavior
We get an empty list and k9 logs a NPE
`
java.lang.NullPointerException: Attempt to invoke virtual method 'com.fsck.k9.Account com.fsck.k9.mailstore.LocalMessage.getAccount()' on a null object reference
at com.fsck.k9.provider.MessageProvider$MesssageInfoHolderRetrieverListener.listLocalMessagesAddMessages(MessageProvider.java:939)
at com.fsck.k9.controller.MessagingController$6.messageFinished(MessagingController.java:534)
at com.fsck.k9.controller.MessagingController$6.messageFinished(MessagingController.java:520)
at com.fsck.k9.mailstore.LocalStore$13.doDbWork(LocalStore.java:610)
at com.fsck.k9.mailstore.LocalStore$13.doDbWork(LocalStore.java:596)
at com.fsck.k9.mailstore.LockableDatabase.execute(LockableDatabase.java:275)
at com.fsck.k9.mailstore.LocalStore.getMessages(LocalStore.java:596)
at com.fsck.k9.mailstore.LocalStore.searchForMessages(LocalStore.java:583)
at com.fsck.k9.controller.MessagingController.searchLocalMessagesSynchronous(MessagingController.java:548)
at com.fsck.k9.controller.MessagingController$5.run(MessagingController.java:500)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
`
### Steps to reproduce
`
try (Cursor c = context.getContentResolver().query(Uri.parse("content://com.fsck.k9.messageprovider/inbox_messages", messagesProjection, null, null, null)) {
// c.getCount() will be 0
}
`
### Environment
K-9 Mail version: 5.113
Android version: CM13 (6.0.1)
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| 54bf6f7bd548a0c7502a9149f942cfad63494e57 | dae6be34dfa2c21472ce007c3b6815e1e3693e9f | https://github.com/thundernest/k-9/compare/54bf6f7bd548a0c7502a9149f942cfad63494e57...dae6be34dfa2c21472ce007c3b6815e1e3693e9f | diff --git a/k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java b/k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java
index 760dc0660..20e2e3e3c 100644
--- a/k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java
+++ b/k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java
@@ -935,8 +935,8 @@ public class MessageProvider extends ContentProvider {
for (final LocalMessage message : messages) {
final MessageInfoHolder messageInfoHolder = new MessageInfoHolder();
final LocalFolder messageFolder = message.getFolder();
+ final Account messageAccount = message.getAccount();
- final Account messageAccount = messageInfoHolder.message.getAccount();
helper.populate(messageInfoHolder, message, new FolderInfoHolder(context,
messageFolder, messageAccount), messageAccount);
| ['k9mail/src/main/java/com/fsck/k9/provider/MessageProvider.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,539,944 | 707,545 | 97,696 | 433 | 157 | 21 | 2 | 1 | 2,420 | 102 | 430 | 39 | 0 | 0 | 2016-10-11T11:55:58 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,644 | thundernest/k-9/2777/2776 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2776 | https://github.com/thundernest/k-9/pull/2777 | https://github.com/thundernest/k-9/pull/2777 | 1 | fixes | S/MIME signed emails in sent folder misleadingly shown as PGP encrypted mails | ### Expected behavior
I am using S/MIME to sign e-mails on my computer. When I open sent mails in k9 mail app on my smartphone the mail body is shown correctly, I can read the sent message, because it is just signed. I also see the attachment (signature file" smime.p7s") there.
### Actual behavior
Since last update the S/MIME signed mails are shown correctly in AutoPreview (I see text there), but after clicking on them to open the mail and read the full message. Instead a message "this mail is encrypted / This e-mail is with OpenPGP encrypted. To read it you need compatible OpenPGP-App installed and configured / Choose OpenPGPG app" appeaers and I have no chance to read the message.
### Steps to reproduce
1. use a s/mime to sign e-mails from your computer
2. open the sent mail on your smartphone with k9 mail app
3. then this message appears
### Environment
K-9 Mail version: 5.300 (installed 11th Sept. 2017)
Android version: 7.0
Account type (IMAP, POP3, WebDAV/Exchange): IMAP | e266547bfc6db2f7af1dc84a07e954e20636adec | ac628a265daa6583bbe0c425163db5697a9b527e | https://github.com/thundernest/k-9/compare/e266547bfc6db2f7af1dc84a07e954e20636adec...ac628a265daa6583bbe0c425163db5697a9b527e | diff --git a/k9mail/src/main/java/com/fsck/k9/crypto/MessageCryptoStructureDetector.java b/k9mail/src/main/java/com/fsck/k9/crypto/MessageCryptoStructureDetector.java
index 974811957..cd8bd7034 100644
--- a/k9mail/src/main/java/com/fsck/k9/crypto/MessageCryptoStructureDetector.java
+++ b/k9mail/src/main/java/com/fsck/k9/crypto/MessageCryptoStructureDetector.java
@@ -233,7 +233,7 @@ public class MessageCryptoStructureDetector {
return dataUnavailable || protocolMatches;
}
- private static boolean isPartMultipartEncrypted(Part part) {
+ public static boolean isPartMultipartEncrypted(Part part) {
if (!isSameMimeType(part.getMimeType(), MULTIPART_ENCRYPTED)) {
return false;
}
diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java
index f89ff127c..9934447f9 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java
@@ -1,6 +1,7 @@
package com.fsck.k9.mailstore;
+import java.util.Collections;
import java.util.List;
import com.fsck.k9.mail.Message;
@@ -36,24 +37,24 @@ public class MessageViewInfo {
this.extraAttachments = extraAttachments;
}
- public static MessageViewInfo createWithExtractedContent(
- Message message, boolean isMessageIncomplete, Part rootPart,
- String text, List<AttachmentViewInfo> attachments,
- CryptoResultAnnotation cryptoResultAnnotation,
- AttachmentResolver attachmentResolver,
- String extraText, List<AttachmentViewInfo> extraAttachments
- ) {
+ static MessageViewInfo createWithExtractedContent(Message message, boolean isMessageIncomplete,
+ String text, List<AttachmentViewInfo> attachments, AttachmentResolver attachmentResolver) {
return new MessageViewInfo(
- message, isMessageIncomplete, rootPart,
- text, attachments,
- cryptoResultAnnotation,
- attachmentResolver,
- extraText, extraAttachments
- );
+ message, isMessageIncomplete, message, text, attachments, null, attachmentResolver, null,
+ Collections.<AttachmentViewInfo>emptyList());
}
public static MessageViewInfo createWithErrorState(Message message, boolean isMessageIncomplete) {
return new MessageViewInfo(message, isMessageIncomplete, null, null, null, null, null, null, null);
}
+ MessageViewInfo withCryptoData(CryptoResultAnnotation rootPartAnnotation, String extraViewableText,
+ List<AttachmentViewInfo> extraAttachmentInfos) {
+ return new MessageViewInfo(
+ message, isMessageIncomplete, rootPart, text, attachments,
+ rootPartAnnotation,
+ attachmentResolver,
+ extraViewableText, extraAttachmentInfos
+ );
+ }
}
diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java
index 8d318ca69..feeb06946 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java
@@ -12,22 +12,24 @@ import android.support.annotation.VisibleForTesting;
import android.support.annotation.WorkerThread;
import com.fsck.k9.Globals;
+import com.fsck.k9.K9;
import com.fsck.k9.R;
+import com.fsck.k9.crypto.MessageCryptoStructureDetector;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.internet.MessageExtractor;
+import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.Viewable;
import com.fsck.k9.mail.internet.Viewable.Flowed;
+import com.fsck.k9.mailstore.CryptoResultAnnotation.CryptoError;
import com.fsck.k9.mailstore.util.FlowedMessageUtils;
import com.fsck.k9.message.extractors.AttachmentInfoExtractor;
import com.fsck.k9.message.html.HtmlConverter;
import com.fsck.k9.message.html.HtmlProcessor;
import com.fsck.k9.ui.crypto.MessageCryptoAnnotations;
-import com.fsck.k9.ui.crypto.MessageCryptoSplitter;
-import com.fsck.k9.ui.crypto.MessageCryptoSplitter.CryptoMessageParts;
import org.openintents.openpgp.util.OpenPgpUtils;
import timber.log.Timber;
@@ -69,45 +71,61 @@ public class MessageViewInfoExtractor {
}
@WorkerThread
- public MessageViewInfo extractMessageForView(Message message, @Nullable MessageCryptoAnnotations annotations)
+ public MessageViewInfo extractMessageForView(Message message, @Nullable MessageCryptoAnnotations cryptoAnnotations)
throws MessagingException {
- Part rootPart;
- CryptoResultAnnotation cryptoResultAnnotation;
- List<Part> extraParts;
-
- CryptoMessageParts cryptoMessageParts = MessageCryptoSplitter.split(message, annotations);
- if (cryptoMessageParts != null) {
- rootPart = cryptoMessageParts.contentPart;
- cryptoResultAnnotation = cryptoMessageParts.contentCryptoAnnotation;
- extraParts = cryptoMessageParts.extraParts;
- } else {
- if (annotations != null && !annotations.isEmpty()) {
- Timber.e("Got message annotations but no crypto root part!");
+ ArrayList<Part> extraParts = new ArrayList<>();
+ Part cryptoContentPart = MessageCryptoStructureDetector.findPrimaryEncryptedOrSignedPart(message, extraParts);
+
+ if (cryptoContentPart == null) {
+ if (cryptoAnnotations != null && !cryptoAnnotations.isEmpty()) {
+ Timber.e("Got crypto message cryptoContentAnnotations but no crypto root part!");
}
- rootPart = message;
- cryptoResultAnnotation = null;
- extraParts = null;
+ return extractSimpleMessageForView(message, message);
}
- List<AttachmentViewInfo> attachmentInfos = new ArrayList<>();
- ViewableExtractedText viewable = extractViewableAndAttachments(
- Collections.singletonList(rootPart), attachmentInfos);
+ boolean isOpenPgpEncrypted = (MessageCryptoStructureDetector.isPartMultipartEncrypted(cryptoContentPart) &&
+ MessageCryptoStructureDetector.isMultipartEncryptedOpenPgpProtocol(cryptoContentPart)) ||
+ MessageCryptoStructureDetector.isPartPgpInlineEncrypted(cryptoContentPart);
+ if (!K9.isOpenPgpProviderConfigured() && isOpenPgpEncrypted) {
+ CryptoResultAnnotation noProviderAnnotation = CryptoResultAnnotation.createErrorAnnotation(
+ CryptoError.OPENPGP_ENCRYPTED_NO_PROVIDER, null);
+ return MessageViewInfo.createWithErrorState(message, false)
+ .withCryptoData(noProviderAnnotation, null, null);
+ }
- List<AttachmentViewInfo> extraAttachmentInfos = new ArrayList<>();
- String extraViewableText = null;
- if (extraParts != null) {
- ViewableExtractedText extraViewable =
- extractViewableAndAttachments(extraParts, extraAttachmentInfos);
- extraViewableText = extraViewable.text;
+ CryptoResultAnnotation cryptoContentPartAnnotation =
+ cryptoAnnotations != null ? cryptoAnnotations.get(cryptoContentPart) : null;
+ if (cryptoContentPartAnnotation != null) {
+ return extractCryptoMessageForView(message, extraParts, cryptoContentPart, cryptoContentPartAnnotation);
+ }
+
+ return extractSimpleMessageForView(message, message);
+ }
+
+ private MessageViewInfo extractCryptoMessageForView(Message message,
+ ArrayList<Part> extraParts, Part cryptoContentPart, CryptoResultAnnotation cryptoContentPartAnnotation)
+ throws MessagingException {
+ if (cryptoContentPartAnnotation != null && cryptoContentPartAnnotation.hasReplacementData()) {
+ cryptoContentPart = cryptoContentPartAnnotation.getReplacementData();
}
- AttachmentResolver attachmentResolver = AttachmentResolver.createFromPart(rootPart);
+ List<AttachmentViewInfo> extraAttachmentInfos = new ArrayList<>();
+ ViewableExtractedText extraViewable = extractViewableAndAttachments(extraParts, extraAttachmentInfos);
+
+ MessageViewInfo messageViewInfo = extractSimpleMessageForView(message, cryptoContentPart);
+ return messageViewInfo.withCryptoData(cryptoContentPartAnnotation, extraViewable.text, extraAttachmentInfos);
+ }
- boolean isMessageIncomplete = !message.isSet(Flag.X_DOWNLOADED_FULL) ||
- MessageExtractor.hasMissingParts(message);
+ private MessageViewInfo extractSimpleMessageForView(Message message, Part contentPart) throws MessagingException {
+ List<AttachmentViewInfo> attachmentInfos = new ArrayList<>();
+ ViewableExtractedText viewable = extractViewableAndAttachments(
+ Collections.singletonList(contentPart), attachmentInfos);
+ AttachmentResolver attachmentResolver = AttachmentResolver.createFromPart(contentPart);
+ boolean isMessageIncomplete =
+ !message.isSet(Flag.X_DOWNLOADED_FULL) || MessageExtractor.hasMissingParts(message);
- return MessageViewInfo.createWithExtractedContent(message, isMessageIncomplete, rootPart, viewable.html,
- attachmentInfos, cryptoResultAnnotation, attachmentResolver, extraViewableText, extraAttachmentInfos);
+ return MessageViewInfo.createWithExtractedContent(
+ message, isMessageIncomplete, viewable.html, attachmentInfos, attachmentResolver);
}
private ViewableExtractedText extractViewableAndAttachments(List<Part> parts,
diff --git a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoAnnotations.java b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoAnnotations.java
index d0e58f129..a450b28d4 100644
--- a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoAnnotations.java
+++ b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoAnnotations.java
@@ -12,11 +12,7 @@ import com.fsck.k9.mailstore.CryptoResultAnnotation;
public class MessageCryptoAnnotations {
private HashMap<Part, CryptoResultAnnotation> annotations = new HashMap<>();
- MessageCryptoAnnotations() {
- // Package-private constructor
- }
-
- void put(Part part, CryptoResultAnnotation annotation) {
+ public void put(Part part, CryptoResultAnnotation annotation) {
annotations.put(part, annotation);
}
diff --git a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoSplitter.java b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoSplitter.java
deleted file mode 100644
index 02c439eff..000000000
--- a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoSplitter.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.fsck.k9.ui.crypto;
-
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
-
-import com.fsck.k9.crypto.MessageCryptoStructureDetector;
-import com.fsck.k9.mail.Message;
-import com.fsck.k9.mail.Part;
-import com.fsck.k9.mailstore.CryptoResultAnnotation;
-import com.fsck.k9.mailstore.CryptoResultAnnotation.CryptoError;
-
-
-public class MessageCryptoSplitter {
- private MessageCryptoSplitter() { }
-
- @Nullable
- public static CryptoMessageParts split(@NonNull Message message, @Nullable MessageCryptoAnnotations annotations) {
- ArrayList<Part> extraParts = new ArrayList<>();
- Part primaryPart = MessageCryptoStructureDetector.findPrimaryEncryptedOrSignedPart(message, extraParts);
- if (primaryPart == null) {
- return null;
- }
-
- if (annotations == null) {
- CryptoResultAnnotation rootPartAnnotation =
- CryptoResultAnnotation.createErrorAnnotation(CryptoError.OPENPGP_ENCRYPTED_NO_PROVIDER, null);
- return new CryptoMessageParts(primaryPart, rootPartAnnotation, extraParts);
- }
-
- CryptoResultAnnotation rootPartAnnotation = annotations.get(primaryPart);
- Part rootPart;
- if (rootPartAnnotation != null && rootPartAnnotation.hasReplacementData()) {
- rootPart = rootPartAnnotation.getReplacementData();
- } else {
- rootPart = primaryPart;
- }
-
- return new CryptoMessageParts(rootPart, rootPartAnnotation, extraParts);
- }
-
- public static class CryptoMessageParts {
- public final Part contentPart;
- @Nullable
- public final CryptoResultAnnotation contentCryptoAnnotation;
-
- public final List<Part> extraParts;
-
- CryptoMessageParts(Part contentPart, @Nullable CryptoResultAnnotation contentCryptoAnnotation, List<Part> extraParts) {
- this.contentPart = contentPart;
- this.contentCryptoAnnotation = contentCryptoAnnotation;
- this.extraParts = Collections.unmodifiableList(extraParts);
- }
- }
-
-}
diff --git a/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java b/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java
index 45588eef4..2d799629d 100644
--- a/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java
@@ -9,11 +9,14 @@ import java.util.Locale;
import java.util.TimeZone;
import android.app.Application;
+import android.support.annotation.NonNull;
import com.fsck.k9.GlobalsHelper;
import com.fsck.k9.K9RobolectricTestRunner;
import com.fsck.k9.activity.K9ActivityCommon;
import com.fsck.k9.mail.Address;
+import com.fsck.k9.mail.BodyPart;
+import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
@@ -26,8 +29,11 @@ import com.fsck.k9.mail.internet.MimeMultipart;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mail.internet.Viewable;
import com.fsck.k9.mail.internet.Viewable.MessageHeader;
+import com.fsck.k9.mailstore.CryptoResultAnnotation.CryptoError;
import com.fsck.k9.mailstore.MessageViewInfoExtractor.ViewableExtractedText;
+import com.fsck.k9.message.extractors.AttachmentInfoExtractor;
import com.fsck.k9.message.html.HtmlProcessor;
+import com.fsck.k9.ui.crypto.MessageCryptoAnnotations;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,13 +41,21 @@ import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RuntimeEnvironment;
+import static com.fsck.k9.message.TestMessageConstructionUtils.bodypart;
+import static com.fsck.k9.message.TestMessageConstructionUtils.messageFromBody;
+import static com.fsck.k9.message.TestMessageConstructionUtils.multipart;
import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertSame;
+import static junit.framework.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
+@SuppressWarnings("WeakerAccess")
@RunWith(K9RobolectricTestRunner.class)
public class MessageViewInfoExtractorTest {
public static final String BODY_TEXT = "K-9 Mail rocks :>";
@@ -51,6 +65,7 @@ public class MessageViewInfoExtractorTest {
private MessageViewInfoExtractor messageViewInfoExtractor;
private Application context;
+ private AttachmentInfoExtractor attachmentInfoExtractor;
@Before
@@ -60,7 +75,8 @@ public class MessageViewInfoExtractorTest {
GlobalsHelper.setContext(context);
HtmlProcessor htmlProcessor = createFakeHtmlProcessor();
- messageViewInfoExtractor = new MessageViewInfoExtractor(context,null, htmlProcessor);
+ attachmentInfoExtractor = spy(AttachmentInfoExtractor.getInstance());
+ messageViewInfoExtractor = new MessageViewInfoExtractor(context, attachmentInfoExtractor, htmlProcessor);
}
@Test
@@ -359,6 +375,190 @@ public class MessageViewInfoExtractorTest {
assertEquals(expectedHtmlText, firstMessageExtractedText.html);
}
+ @Test
+ public void extractMessage_withAttachment() throws Exception {
+ BodyPart attachmentPart = bodypart("application/octet-stream");
+ Message message = messageFromBody(multipart("mixed",
+ bodypart("text/plain", "text"),
+ attachmentPart
+ ));
+ AttachmentViewInfo attachmentViewInfo = mock(AttachmentViewInfo.class);
+ setupAttachmentInfoForPart(attachmentPart, attachmentViewInfo);
+
+
+ MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, null);
+
+
+ assertEquals("<pre class=\\"k9mail\\">text</pre>", messageViewInfo.text);
+ assertSame(attachmentViewInfo, messageViewInfo.attachments.get(0));
+ assertNull(messageViewInfo.cryptoResultAnnotation);
+ assertTrue(messageViewInfo.extraAttachments.isEmpty());
+ }
+
+ @Test
+ public void extractMessage_withCryptoAnnotation() throws Exception {
+ Message message = messageFromBody(multipart("signed", "protocol=\\"application/pgp-signature\\"",
+ bodypart("text/plain", "text"),
+ bodypart("application/pgp-signature")
+ ));
+ CryptoResultAnnotation annotation = CryptoResultAnnotation.createOpenPgpResultAnnotation(
+ null, null, null, null, null, false);
+ MessageCryptoAnnotations messageCryptoAnnotations = createAnnotations(message, annotation);
+
+
+ MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, messageCryptoAnnotations);
+
+
+ assertEquals("<pre class=\\"k9mail\\">text</pre>", messageViewInfo.text);
+ assertSame(annotation, messageViewInfo.cryptoResultAnnotation);
+ assertTrue(messageViewInfo.attachments.isEmpty());
+ assertTrue(messageViewInfo.extraAttachments.isEmpty());
+ }
+
+ @Test
+ public void extractMessage_withCryptoAnnotation_andReplacementPart() throws Exception {
+ Message message = messageFromBody(multipart("signed", "protocol=\\"application/pgp-signature\\"",
+ bodypart("text/plain", "text"),
+ bodypart("application/pgp-signature")
+ ));
+ MimeBodyPart replacementPart = bodypart("text/plain", "replacement text");
+ CryptoResultAnnotation annotation = CryptoResultAnnotation.createOpenPgpResultAnnotation(
+ null, null, null, null, replacementPart, false);
+ MessageCryptoAnnotations messageCryptoAnnotations = createAnnotations(message, annotation);
+
+
+ MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, messageCryptoAnnotations);
+
+
+ assertEquals("<pre class=\\"k9mail\\">replacement text</pre>", messageViewInfo.text);
+ assertSame(annotation, messageViewInfo.cryptoResultAnnotation);
+ assertTrue(messageViewInfo.attachments.isEmpty());
+ assertTrue(messageViewInfo.extraAttachments.isEmpty());
+ }
+
+ @Test
+ public void extractMessage_withCryptoAnnotation_andExtraText() throws Exception {
+ MimeBodyPart signedPart = multipart("signed", "protocol=\\"application/pgp-signature\\"",
+ bodypart("text/plain", "text"),
+ bodypart("application/pgp-signature")
+ );
+ BodyPart extraText = bodypart("text/plain", "extra text");
+ Message message = messageFromBody(multipart("mixed",
+ signedPart,
+ extraText
+ ));
+ CryptoResultAnnotation annotation = CryptoResultAnnotation.createOpenPgpResultAnnotation(
+ null, null, null, null, null, false);
+ MessageCryptoAnnotations messageCryptoAnnotations = createAnnotations(signedPart, annotation);
+
+
+ MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, messageCryptoAnnotations);
+
+
+ assertEquals("<pre class=\\"k9mail\\">text</pre>", messageViewInfo.text);
+ assertSame(annotation, messageViewInfo.cryptoResultAnnotation);
+ assertEquals("extra text", messageViewInfo.extraText);
+ assertTrue(messageViewInfo.attachments.isEmpty());
+ assertTrue(messageViewInfo.extraAttachments.isEmpty());
+ }
+
+ @Test
+ public void extractMessage_withCryptoAnnotation_andExtraAttachment() throws Exception {
+ MimeBodyPart signedPart = multipart("signed", "protocol=\\"application/pgp-signature\\"",
+ bodypart("text/plain", "text"),
+ bodypart("application/pgp-signature")
+ );
+ BodyPart extraAttachment = bodypart("application/octet-stream");
+ Message message = messageFromBody(multipart("mixed",
+ signedPart,
+ extraAttachment
+ ));
+ CryptoResultAnnotation annotation = CryptoResultAnnotation.createOpenPgpResultAnnotation(
+ null, null, null, null, null, false);
+ MessageCryptoAnnotations messageCryptoAnnotations = createAnnotations(signedPart, annotation);
+
+ AttachmentViewInfo attachmentViewInfo = mock(AttachmentViewInfo.class);
+ setupAttachmentInfoForPart(extraAttachment, attachmentViewInfo);
+
+
+ MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, messageCryptoAnnotations);
+
+
+ assertEquals("<pre class=\\"k9mail\\">text</pre>", messageViewInfo.text);
+ assertSame(annotation, messageViewInfo.cryptoResultAnnotation);
+ assertSame(attachmentViewInfo, messageViewInfo.extraAttachments.get(0));
+ assertTrue(messageViewInfo.attachments.isEmpty());
+ }
+
+ @Test
+ public void extractMessage_openPgpEncrypted_withoutAnnotations() throws Exception {
+ Message message = messageFromBody(
+ multipart("encrypted", "protocol=\\"application/pgp-encrypted\\"",
+ bodypart("application/pgp-encrypted"),
+ bodypart("application/octet-stream")
+ )
+ );
+
+ MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, null);
+
+ assertEquals(CryptoError.OPENPGP_ENCRYPTED_NO_PROVIDER, messageViewInfo.cryptoResultAnnotation.getErrorType());
+ assertNull(messageViewInfo.text);
+ assertNull(messageViewInfo.attachments);
+ assertNull(messageViewInfo.extraAttachments);
+ }
+
+ @Test
+ public void extractMessage_multipartSigned_UnknownProtocol() throws Exception {
+ Message message = messageFromBody(
+ multipart("signed", "protocol=\\"application/pkcs7-signature\\"",
+ bodypart("text/plain", "text"),
+ bodypart("application/pkcs7-signature", "signature")
+ )
+ );
+
+ MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, null);
+
+ assertEquals("<pre class=\\"k9mail\\">text</pre>", messageViewInfo.text);
+ assertNull(messageViewInfo.cryptoResultAnnotation);
+ assertTrue(messageViewInfo.attachments.isEmpty());
+ assertTrue(messageViewInfo.extraAttachments.isEmpty());
+ }
+
+ @Test
+ public void extractMessage_multipartSigned_UnknownProtocol_withExtraAttachments() throws Exception {
+ BodyPart extraAttachment = bodypart("application/octet-stream");
+ Message message = messageFromBody(
+ multipart("mixed",
+ multipart("signed", "protocol=\\"application/pkcs7-signature\\"",
+ bodypart("text/plain", "text"),
+ bodypart("application/pkcs7-signature", "signature")
+ ),
+ extraAttachment
+ )
+ );
+ AttachmentViewInfo mock = mock(AttachmentViewInfo.class);
+ setupAttachmentInfoForPart(extraAttachment, mock);
+
+ MessageViewInfo messageViewInfo = messageViewInfoExtractor.extractMessageForView(message, null);
+
+ assertEquals("<pre class=\\"k9mail\\">text</pre>", messageViewInfo.text);
+ assertNull(messageViewInfo.cryptoResultAnnotation);
+ assertSame(mock, messageViewInfo.attachments.get(0));
+ assertTrue(messageViewInfo.extraAttachments.isEmpty());
+ }
+
+ void setupAttachmentInfoForPart(BodyPart extraAttachment, AttachmentViewInfo attachmentViewInfo)
+ throws MessagingException {
+ doReturn(attachmentViewInfo).when(attachmentInfoExtractor).extractAttachmentInfo(extraAttachment);
+ }
+
+ @NonNull
+ MessageCryptoAnnotations createAnnotations(Part part, CryptoResultAnnotation annotation) {
+ MessageCryptoAnnotations messageCryptoAnnotations = new MessageCryptoAnnotations();
+ messageCryptoAnnotations.put(part, annotation);
+ return messageCryptoAnnotations;
+ }
+
HtmlProcessor createFakeHtmlProcessor() {
HtmlProcessor htmlProcessor = mock(HtmlProcessor.class);
diff --git a/k9mail/src/test/java/com/fsck/k9/message/TestMessageConstructionUtils.java b/k9mail/src/test/java/com/fsck/k9/message/TestMessageConstructionUtils.java
index 45ee4b908..07e813eaa 100644
--- a/k9mail/src/test/java/com/fsck/k9/message/TestMessageConstructionUtils.java
+++ b/k9mail/src/test/java/com/fsck/k9/message/TestMessageConstructionUtils.java
@@ -45,7 +45,7 @@ public class TestMessageConstructionUtils {
return new MimeBodyPart(null, type);
}
- public static BodyPart bodypart(String type, String text) throws MessagingException {
+ public static MimeBodyPart bodypart(String type, String text) throws MessagingException {
TextBody textBody = new TextBody(text);
return new MimeBodyPart(textBody, type);
} | ['k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java', 'k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java', 'k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoAnnotations.java', 'k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoSplitter.java', 'k9mail/src/main/java/com/fsck/k9/crypto/MessageCryptoStructureDetector.java', 'k9mail/src/test/java/com/fsck/k9/message/TestMessageConstructionUtils.java', 'k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 3,587,196 | 705,508 | 98,663 | 483 | 9,508 | 1,743 | 177 | 5 | 1,017 | 172 | 253 | 20 | 0 | 0 | 2017-09-17T23:53:56 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,581 | thundernest/k-9/5189/5187 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5187 | https://github.com/thundernest/k-9/pull/5189 | https://github.com/thundernest/k-9/pull/5189 | 1 | fixes | Crash when editing outgoing server settings | **Describe the bug**
Ever since the [5.728](https://github.com/k9mail/k-9/releases/tag/5.728) update (with the long awaited [Add support for client certificate and password authentication](https://github.com/k9mail/k-9/issues/793#event-4298863970)) change, K-9 crashes when trying to send email over a (TLS-enabled) SMTP server.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to Settings => Account settings => Sending mail => Outgoing server
2. Optional: disable "require sign-in"
3. Tap on "Next"
4. K-9 crashes and goes back to the "Sending mail" screen.
5. Click "Next" again and K9 crashes and the Android "K-9 Mail keeps stopping" screen comes up.
**Expected behavior**
K-9 should not crash :-)
**Environment (please complete the following information):**
- K-9 Mail version: [5.731](https://github.com/k9mail/k-9/releases/tag/5.731) (Beta)
- Android version: 11 (February 2021)
- Device: Google Pixel 4a
- Account type: IMAP + SMTP
**Logs**
When the "Next" button is pressed (and K-9 crashes), the following is being captured by `logcat`:
```
--------- beginning of crash
03-02 09:28:43.426 10303 10303 E AndroidRuntime: FATAL EXCEPTION: main
03-02 09:28:43.426 10303 10303 E AndroidRuntime: Process: com.fsck.k9, PID: 10303
03-02 09:28:43.426 10303 10303 E AndroidRuntime: java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, paramet
er authenticationType
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at com.fsck.k9.mail.ServerSettings.<init>(Unknown Source:12)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at com.fsck.k9.mail.ServerSettings.<init>(ServerSettings.kt:17)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at com.fsck.k9.mail.ServerSettings.<init>(Unknown Source:18)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at com.fsck.k9.activity.setup.AccountSetupOutgoing.onNext(AccountSetupOutgoing.java:494)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at com.fsck.k9.activity.setup.AccountSetupOutgoing.onClick(AccountSetupOutgoing.java:503)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at android.view.View.performClick(View.java:7448)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at android.view.View.performClickInternal(View.java:7425)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at android.view.View.access$3600(View.java:810)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at android.view.View$PerformClick.run(View.java:28305)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:938)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at android.os.Looper.loop(Looper.java:223)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:7660)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
03-02 09:28:43.426 10303 10303 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
```
The crash looked a bit like the one reported in #5134, but the behaviour is different. K-9 works fine, _fetching_ and _reading_ mail works fine, only _sending_ crashes the application.
And, after the crash:
```
$ adb logcat -d --pid=$(adb shell pgrep k9)
--------- beginning of main
03-03 22:01:45.842 25439 25439 I libc : SetHeapTaggingLevel: tag level set to 0
03-03 22:01:45.847 25439 25439 E com.fsck.k9: Not starting debugger since process cannot load the jdwp agent.
03-03 22:01:45.879 25439 25439 D ApplicationLoaders: Returning zygote-cached class loader: /system/framework/android.test.base.jar
03-03 22:01:45.893 25439 25439 D NetworkSecurityConfig: No Network Security Config specified, using platform default
03-03 22:01:45.893 25439 25439 D NetworkSecurityConfig: No Network Security Config specified, using platform default
03-03 22:01:45.922 25439 25439 I TetheringManager: registerTetheringEventCallback:com.fsck.k9
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: QUALCOMM build : 0905e9f, Ia11ce2d146
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: Build Date : 09/02/20
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: OpenGL ES Shader Compiler Version: EV031.31.04.00
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: Local Branch : gfx-adreno.lnx.2.0
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: Remote Branch :
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: Remote Branch :
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: Reconstruct Branch :
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: Build Config : S P 10.0.4 AArch64
03-03 22:01:46.006 25439 25463 I AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
03-03 22:01:46.010 25439 25439 W ListPreference: Setting a summary with a String formatting marker is no longer supported. You should use a SummaryProvider instead.
03-03 22:01:46.010 25439 25463 I AdrenoGLES-0: PFP: 0x016ee189, ME: 0x00000000
03-03 22:01:46.011 25439 25463 W AdrenoUtils: <ReadGpuID_from_sysfs:197>: Failed to open /sys/class/kgsl/kgsl-3d0/gpu_model
03-03 22:01:46.012 25439 25463 W AdrenoUtils: <ReadGpuID:221>: Failed to read chip ID from gpu_model. Fallback to use the GSL path
03-03 22:01:46.023 25439 25439 W ListPreference: Setting a summary with a String formatting marker is no longer supported. You should use a SummaryProvider instead.
03-03 22:01:46.042 25439 25463 I Gralloc4: mapper 4.x is not supported
``` | 51e25a0bddb140d1f8ad9c3afbd03c70967ea488 | 3002964f0ae796b97a2b3418cb5e1635016cd21f | https://github.com/thundernest/k-9/compare/51e25a0bddb140d1f8ad9c3afbd03c70967ea488...3002964f0ae796b97a2b3418cb5e1635016cd21f | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java
index 443c4f9f8..e1c021243 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java
@@ -18,7 +18,6 @@ import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
-import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
@@ -472,10 +471,10 @@ public class AccountSetupOutgoing extends K9Activity implements OnClickListener,
protected void onNext() {
ConnectionSecurity securityType = getSelectedSecurity();
- String username = null;
+ String username = "";
String password = null;
String clientCertificateAlias = null;
- AuthType authType = null;
+ AuthType authType = AuthType.AUTOMATIC;
if ((ConnectionSecurity.STARTTLS_REQUIRED == securityType) ||
(ConnectionSecurity.SSL_TLS_REQUIRED == securityType)) {
clientCertificateAlias = mClientCertificateSpinner.getAlias(); | ['app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupOutgoing.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,539,062 | 502,020 | 70,866 | 403 | 180 | 36 | 5 | 1 | 5,966 | 633 | 1,883 | 76 | 3 | 2 | 2021-03-03T21:31:27 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,652 | thundernest/k-9/1955/1915 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1915 | https://github.com/thundernest/k-9/pull/1955 | https://github.com/thundernest/k-9/pull/1955 | 1 | fixes | message subject no longer shown on message view | ### Expected behavior
the message subject should be shown in the message view
### Actual behavior
the message view no longer shows the message subject
### Steps to reproduce
1. open a message
2. try to read the message subject in the message view
### Environment
K-9 Mail version: 5.201
Android version: 7.1.1
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| a56f12f1bef60cee0f94be879ed2b7a0b27e65c6 | 10a252e6b99cc089fbdc6e0ee2dc3d00ec6bd24a | https://github.com/thundernest/k-9/compare/a56f12f1bef60cee0f94be879ed2b7a0b27e65c6...10a252e6b99cc089fbdc6e0ee2dc3d00ec6bd24a | diff --git a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java
index c0a6098a6..65cf011b4 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java
@@ -1435,6 +1435,8 @@ public class MessageList extends K9Activity implements MessageListFragmentListen
public void displayMessageSubject(String subject) {
if (mDisplayMode == DisplayMode.MESSAGE_VIEW) {
mActionBarSubject.setText(subject);
+ } else {
+ mActionBarSubject.showSubjectInMessageHeader();
}
}
diff --git a/k9mail/src/main/java/com/fsck/k9/view/MessageTitleView.java b/k9mail/src/main/java/com/fsck/k9/view/MessageTitleView.java
index dea974b85..a6cccd4ef 100644
--- a/k9mail/src/main/java/com/fsck/k9/view/MessageTitleView.java
+++ b/k9mail/src/main/java/com/fsck/k9/view/MessageTitleView.java
@@ -51,7 +51,7 @@ public class MessageTitleView extends TextView {
if (getLayout().getLineCount() > MAX_LINES) {
int lineEndIndex = getLayout().getLineEnd(MAX_LINES - 1);
setText(getText().subSequence(0, lineEndIndex - 2) + ELLIPSIS);
- mHeader.showSubjectLine();
+ showSubjectInMessageHeader();
}
mNeedEllipsizeCheck = false;
}
@@ -62,4 +62,8 @@ public class MessageTitleView extends TextView {
public void setMessageHeader(final MessageHeader header) {
mHeader = header;
}
+
+ public void showSubjectInMessageHeader() {
+ mHeader.showSubjectLine();
+ }
} | ['k9mail/src/main/java/com/fsck/k9/activity/MessageList.java', 'k9mail/src/main/java/com/fsck/k9/view/MessageTitleView.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,453,031 | 685,304 | 94,469 | 422 | 273 | 48 | 8 | 2 | 380 | 59 | 95 | 17 | 0 | 0 | 2017-01-04T06:28:56 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,595 | thundernest/k-9/4994/3767 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3767 | https://github.com/thundernest/k-9/pull/4994 | https://github.com/thundernest/k-9/pull/4994 | 1 | closes | There is an archive entry in the context entry of the mail in the archive | Please search to check for an existing issue (including closed issues, for which the fix may not have yet been released) before opening a new issue: https://github.com/k9mail/k-9/issues?q=is%3Aissue
### Expected behavior
When I move my mail to the archive, the item to keep in spite of the archive is registered in the context menu.
### Actual behavior
Delete or unarchive archived items in content menu of the archive
### Steps to reproduce
1.Move the mail in your Inbox to the Inbox.
### Environment
K-9 Mail version: 5.600
Android version: 8.0.0
Account type (IMAP, POP3, ##WebDAV/Exchange):
| 8685da31d44ba2d5623c2f05531af728e53699a2 | 617dd1641ec6cfff9e48e41122f873a0a6f0a3cc | https://github.com/thundernest/k-9/compare/8685da31d44ba2d5623c2f05531af728e53699a2...617dd1641ec6cfff9e48e41122f873a0a6f0a3cc | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/fragment/MessageListFragment.java b/app/ui/legacy/src/main/java/com/fsck/k9/fragment/MessageListFragment.java
index 54affea70..f480bab24 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/fragment/MessageListFragment.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/fragment/MessageListFragment.java
@@ -1707,11 +1707,17 @@ public class MessageListFragment extends Fragment implements OnItemClickListener
menu.findItem(R.id.spam).setVisible(false);
}
- if (!account.hasArchiveFolder()) {
+ Long archiveFolderId = account.getArchiveFolderId();
+ boolean hideArchiveAction = archiveFolderId == null ||
+ (singleFolderMode && currentFolder.databaseId == archiveFolderId);
+ if (hideArchiveAction) {
menu.findItem(R.id.archive).setVisible(false);
}
- if (!account.hasSpamFolder()) {
+ Long spamFolderId = account.getSpamFolderId();
+ boolean hideSpamAction = spamFolderId == null ||
+ (singleFolderMode && currentFolder.databaseId == spamFolderId);
+ if (hideSpamAction) {
menu.findItem(R.id.spam).setVisible(false);
}
} | ['app/ui/legacy/src/main/java/com/fsck/k9/fragment/MessageListFragment.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,734,879 | 539,277 | 76,391 | 416 | 634 | 118 | 10 | 1 | 620 | 94 | 151 | 18 | 1 | 0 | 2020-10-08T20:56:41 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,653 | thundernest/k-9/1954/1938 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1938 | https://github.com/thundernest/k-9/pull/1954 | https://github.com/thundernest/k-9/pull/1954 | 1 | fixes | BCC not working as expected | ### Expected behavior
I wrote the mail with BBC on my Android 6.0.1.
So other people from CC shouldn't know that there are e-mail on BBC
### Actual behavior
All were able to read that there was bbc
### Steps to reproduce
1. Write mail with BBC
2. See their smiling faces when they discovers that boss e-mail is on BBC.
### Environment
K-9 Mail version: 5.201
Android version:6.0.1.
Account type (IMAP, POP3, WebDAV/Exchange): IMAP and SMTP on zoho.com
| b516af2af0e9d1161c3eea8b31a2d55c28d96e98 | 4323ca3419a149b7a1693d16a9abae4a77db87b9 | https://github.com/thundernest/k-9/compare/b516af2af0e9d1161c3eea8b31a2d55c28d96e98...4323ca3419a149b7a1693d16a9abae4a77db87b9 | diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java
index 8b1ce0ee7..c739a88a4 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java
@@ -2,6 +2,8 @@ package com.fsck.k9.mailstore;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
import java.util.Date;
import android.content.ContentValues;
@@ -40,6 +42,7 @@ public class LocalMessage extends MimeMessage {
private long messagePartId;
private String mimeType;
private PreviewType previewType;
+ private boolean headerNeedsUpdating = false;
private LocalMessage(LocalStore localStore) {
@@ -128,10 +131,12 @@ public class LocalMessage extends MimeMessage {
} else {
Log.d(K9.LOG_TAG, "No headers available for this message!");
}
+
+ headerNeedsUpdating = false;
}
@VisibleForTesting
- public void setMessagePartId(long messagePartId) {
+ void setMessagePartId(long messagePartId) {
this.messagePartId = messagePartId;
}
@@ -165,12 +170,14 @@ public class LocalMessage extends MimeMessage {
@Override
public void setSubject(String subject) {
mSubject = subject;
+ headerNeedsUpdating = true;
}
@Override
public void setMessageId(String messageId) {
mMessageId = messageId;
+ headerNeedsUpdating = true;
}
@Override
@@ -191,6 +198,7 @@ public class LocalMessage extends MimeMessage {
@Override
public void setFrom(Address from) {
this.mFrom = new Address[] { from };
+ headerNeedsUpdating = true;
}
@@ -201,6 +209,8 @@ public class LocalMessage extends MimeMessage {
} else {
mReplyTo = replyTo;
}
+
+ headerNeedsUpdating = true;
}
@@ -231,6 +241,8 @@ public class LocalMessage extends MimeMessage {
} else {
throw new IllegalArgumentException("Unrecognized recipient type.");
}
+
+ headerNeedsUpdating = true;
}
public void setFlagInternal(Flag flag, boolean set) throws MessagingException {
@@ -507,10 +519,17 @@ public class LocalMessage extends MimeMessage {
LocalMessage message = new LocalMessage(localStore);
super.copy(message);
+ message.mReference = mReference;
message.mId = mId;
message.mAttachmentCount = mAttachmentCount;
message.mSubject = mSubject;
message.mPreview = mPreview;
+ message.mThreadId = mThreadId;
+ message.mRootId = mRootId;
+ message.messagePartId = messagePartId;
+ message.mimeType = mimeType;
+ message.previewType = previewType;
+ message.headerNeedsUpdating = headerNeedsUpdating;
return message;
}
@@ -534,14 +553,6 @@ public class LocalMessage extends MimeMessage {
return mReference;
}
- @Override
- protected void copy(MimeMessage destination) {
- super.copy(destination);
- if (destination instanceof LocalMessage) {
- ((LocalMessage)destination).mReference = mReference;
- }
- }
-
@Override
public LocalFolder getFolder() {
return (LocalFolder) super.getFolder();
@@ -551,6 +562,33 @@ public class LocalMessage extends MimeMessage {
return "email://messages/" + getAccount().getAccountNumber() + "/" + getFolder().getName() + "/" + getUid();
}
+ @Override
+ public void writeTo(OutputStream out) throws IOException, MessagingException {
+ if (headerNeedsUpdating) {
+ updateHeader();
+ }
+
+ super.writeTo(out);
+ }
+
+ private void updateHeader() {
+ super.setSubject(mSubject);
+ super.setReplyTo(mReplyTo);
+ super.setRecipients(RecipientType.TO, mTo);
+ super.setRecipients(RecipientType.CC, mCc);
+ super.setRecipients(RecipientType.BCC, mBcc);
+
+ if (mFrom != null && mFrom.length > 0) {
+ super.setFrom(mFrom[0]);
+ }
+
+ if (mMessageId != null) {
+ super.setMessageId(mMessageId);
+ }
+
+ headerNeedsUpdating = false;
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) { | ['k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,453,516 | 685,396 | 94,488 | 422 | 1,741 | 354 | 56 | 1 | 474 | 79 | 126 | 18 | 0 | 0 | 2017-01-04T05:36:22 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,635 | thundernest/k-9/3219/632 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/632 | https://github.com/thundernest/k-9/pull/3219 | https://github.com/thundernest/k-9/pull/3219 | 1 | fixes | Case sensitivity problem in account>folders settings | I have an IMAP account with two directories, one named "Spam", and other named "spam".
In K9Mail I go to Account Preferences, Folders, Spam folder, and try to choose the lower case "spam".
After that, marking a message as spam, K9Mail will still move it to the "Spam" folder, instead of "spam".
I suppose the problem is case sensitivity?
| ddc048b56b647c35e066b4255c0982ae80e065f3 | 95b046bbf6057dcff124be4dfcc0b6281f8e0aa5 | https://github.com/thundernest/k-9/compare/ddc048b56b647c35e066b4255c0982ae80e065f3...95b046bbf6057dcff124be4dfcc0b6281f8e0aa5 | diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapFolder.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapFolder.java
index 14cec2a31..f80e58c05 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapFolder.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapFolder.java
@@ -41,6 +41,7 @@ import static com.fsck.k9.mail.store.imap.ImapUtility.getLastResponse;
class ImapFolder extends Folder<ImapMessage> {
+ static final String INBOX = "INBOX";
private static final ThreadLocal<SimpleDateFormat> RFC3501_DATE = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
@@ -78,7 +79,7 @@ class ImapFolder extends Folder<ImapMessage> {
private String getPrefixedName() throws MessagingException {
String prefixedName = "";
- if (!store.getStoreConfig().getInboxFolderName().equalsIgnoreCase(name)) {
+ if (!INBOX.equalsIgnoreCase(name)) {
ImapConnection connection;
synchronized (this) {
if (this.connection == null) {
@@ -391,7 +392,7 @@ class ImapFolder extends Folder<ImapMessage> {
return;
}
- if (trashFolderName == null || getName().equalsIgnoreCase(trashFolderName)) {
+ if (trashFolderName == null || getName().equals(trashFolderName)) {
setFlags(messages, Collections.singleton(Flag.DELETED), true);
} else {
ImapFolder remoteTrashFolder = getStore().getFolder(trashFolderName);
@@ -1369,7 +1370,7 @@ class ImapFolder extends Folder<ImapMessage> {
public boolean equals(Object other) {
if (other instanceof ImapFolder) {
ImapFolder otherFolder = (ImapFolder) other;
- return otherFolder.getName().equalsIgnoreCase(getName());
+ return otherFolder.getName().equals(getName());
}
return super.equals(other);
diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
index 9888dff00..966c8e515 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java
@@ -197,7 +197,7 @@ public class ImapStore extends RemoteStore {
combinedPrefix = null;
}
- if (folder.equalsIgnoreCase(mStoreConfig.getInboxFolderName())) {
+ if (ImapFolder.INBOX.equalsIgnoreCase(folder)) {
continue;
} else if (folder.equals(mStoreConfig.getOutboxFolderName())) {
/*
@@ -216,12 +216,14 @@ public class ImapStore extends RemoteStore {
}
}
- folderNames.add(mStoreConfig.getInboxFolderName());
+ folderNames.add(ImapFolder.INBOX);
return folderNames;
}
void autoconfigureFolders(final ImapConnection connection) throws IOException, MessagingException {
+ mStoreConfig.setInboxFolderName(ImapFolder.INBOX);
+
if (!connection.hasCapability(Capabilities.SPECIAL_USE)) {
if (K9MailLib.isDebug()) {
Timber.d("No detected folder auto-configuration methods.");
diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Folder.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Folder.java
index f7ae94be2..20eb7cebc 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Folder.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Folder.java
@@ -31,6 +31,9 @@ import static com.fsck.k9.mail.store.pop3.Pop3Commands.*;
* POP3 only supports one folder, "Inbox". So the folder name is the ID here.
*/
class Pop3Folder extends Folder<Pop3Message> {
+ static final String INBOX = "INBOX";
+
+
private Pop3Store pop3Store;
private Map<String, Pop3Message> uidToMsgMap = new HashMap<>();
@SuppressLint("UseSparseArrays")
@@ -44,10 +47,6 @@ class Pop3Folder extends Folder<Pop3Message> {
super();
this.pop3Store = pop3Store;
this.name = name;
-
- if (this.name.equalsIgnoreCase(pop3Store.getConfig().getInboxFolderName())) {
- this.name = pop3Store.getConfig().getInboxFolderName();
- }
}
@Override
@@ -56,7 +55,7 @@ class Pop3Folder extends Folder<Pop3Message> {
return;
}
- if (!name.equalsIgnoreCase(pop3Store.getConfig().getInboxFolderName())) {
+ if (!INBOX.equals(name)) {
throw new MessagingException("Folder does not exist");
}
@@ -113,7 +112,7 @@ class Pop3Folder extends Folder<Pop3Message> {
@Override
public boolean exists() throws MessagingException {
- return name.equalsIgnoreCase(pop3Store.getConfig().getInboxFolderName());
+ return INBOX.equals(name);
}
@Override
diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java
index 2b3dde34b..ed07707e1 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java
@@ -201,13 +201,15 @@ public class Pop3Store extends RemoteStore {
@Override
public List<Pop3Folder> getPersonalNamespaces(boolean forceListAll) throws MessagingException {
List<Pop3Folder> folders = new LinkedList<>();
- folders.add(getFolder(mStoreConfig.getInboxFolderName()));
+ folders.add(getFolder(Pop3Folder.INBOX));
return folders;
}
@Override
public void checkSettings() throws MessagingException {
- Pop3Folder folder = new Pop3Folder(this, mStoreConfig.getInboxFolderName());
+ mStoreConfig.setInboxFolderName(Pop3Folder.INBOX);
+
+ Pop3Folder folder = new Pop3Folder(this, Pop3Folder.INBOX);
try {
folder.open(Folder.OPEN_MODE_RW);
folder.requestUidl();
diff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3FolderTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3FolderTest.java
index 56f31b60a..fc00ab566 100644
--- a/k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3FolderTest.java
+++ b/k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3FolderTest.java
@@ -6,8 +6,6 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
import java.util.List;
import com.fsck.k9.mail.FetchProfile;
@@ -49,10 +47,10 @@ public class Pop3FolderTest {
mockStoreConfig = mock(StoreConfig.class);
mockListener = mock(MessageRetrievalListener.class);
when(mockStore.getConfig()).thenReturn(mockStoreConfig);
- when(mockStoreConfig.getInboxFolderName()).thenReturn("Inbox");
+ when(mockStoreConfig.getInboxFolderName()).thenReturn(Pop3Folder.INBOX);
when(mockStore.createConnection()).thenReturn(mockConnection);
when(mockConnection.executeSimpleCommand(Pop3Commands.STAT_COMMAND)).thenReturn("+OK 10 0");
- folder = new Pop3Folder(mockStore, "Inbox");
+ folder = new Pop3Folder(mockStore, Pop3Folder.INBOX);
BinaryTempFileBody.setTempDirectory(new File(System.getProperty("java.io.tmpdir")));
}
diff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java
index 4a9c2601e..f17d739f5 100644
--- a/k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java
+++ b/k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java
@@ -66,7 +66,7 @@ public class Pop3StoreTest {
public void setUp() throws Exception {
//Using a SSL socket allows us to mock it
when(mockStoreConfig.getStoreUri()).thenReturn("pop3+ssl+://PLAIN:user:password@server:12345");
- when(mockStoreConfig.getInboxFolderName()).thenReturn("Inbox");
+ when(mockStoreConfig.getInboxFolderName()).thenReturn(Pop3Folder.INBOX);
when(mockTrustedSocketFactory.createSocket(null, "server", 12345, null)).thenReturn(mockSocket);
when(mockSocket.isConnected()).thenReturn(true);
when(mockSocket.isClosed()).thenReturn(false);
@@ -187,7 +187,7 @@ public class Pop3StoreTest {
List<Pop3Folder> folders = store.getPersonalNamespaces(true);
assertEquals(1, folders.size());
- assertEquals("Inbox", folders.get(0).getName());
+ assertEquals("INBOX", folders.get(0).getName());
}
@Test
@@ -247,7 +247,7 @@ public class Pop3StoreTest {
when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes("UTF-8")));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
when(mockSocket.getOutputStream()).thenReturn(byteArrayOutputStream);
- Pop3Folder folder = store.getFolder("Inbox");
+ Pop3Folder folder = store.getFolder(Pop3Folder.INBOX);
folder.open(Folder.OPEN_MODE_RW);
@@ -262,7 +262,7 @@ public class Pop3StoreTest {
CAPA_RESPONSE +
AUTH_PLAIN_FAILED_RESPONSE;
when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes("UTF-8")));
- Pop3Folder folder = store.getFolder("Inbox");
+ Pop3Folder folder = store.getFolder(Pop3Folder.INBOX);
folder.open(Folder.OPEN_MODE_RW);
}
diff --git a/k9mail/src/main/java/com/fsck/k9/Account.java b/k9mail/src/main/java/com/fsck/k9/Account.java
index ba56293b9..8dd6e8ea9 100644
--- a/k9mail/src/main/java/com/fsck/k9/Account.java
+++ b/k9mail/src/main/java/com/fsck/k9/Account.java
@@ -1075,7 +1075,7 @@ public class Account implements BaseAccount, StoreConfig {
}
public boolean isSpecialFolder(String folderName) {
- return (folderName != null && (folderName.equalsIgnoreCase(getInboxFolderName()) ||
+ return (folderName != null && (folderName.equals(getInboxFolderName()) ||
folderName.equals(getTrashFolderName()) ||
folderName.equals(getDraftsFolderName()) ||
folderName.equals(getArchiveFolderName()) ||
@@ -1097,7 +1097,7 @@ public class Account implements BaseAccount, StoreConfig {
* @return true if account has a drafts folder set.
*/
public synchronized boolean hasDraftsFolder() {
- return !K9.FOLDER_NONE.equalsIgnoreCase(draftsFolderName);
+ return !K9.FOLDER_NONE.equals(draftsFolderName);
}
public synchronized String getSentFolderName() {
@@ -1113,7 +1113,7 @@ public class Account implements BaseAccount, StoreConfig {
* @return true if account has a sent folder set.
*/
public synchronized boolean hasSentFolder() {
- return !K9.FOLDER_NONE.equalsIgnoreCase(sentFolderName);
+ return !K9.FOLDER_NONE.equals(sentFolderName);
}
@@ -1130,7 +1130,7 @@ public class Account implements BaseAccount, StoreConfig {
* @return true if account has a trash folder set.
*/
public synchronized boolean hasTrashFolder() {
- return !K9.FOLDER_NONE.equalsIgnoreCase(trashFolderName);
+ return !K9.FOLDER_NONE.equals(trashFolderName);
}
public synchronized String getArchiveFolderName() {
@@ -1146,7 +1146,7 @@ public class Account implements BaseAccount, StoreConfig {
* @return true if account has an archive folder set.
*/
public synchronized boolean hasArchiveFolder() {
- return !K9.FOLDER_NONE.equalsIgnoreCase(archiveFolderName);
+ return !K9.FOLDER_NONE.equals(archiveFolderName);
}
public synchronized String getSpamFolderName() {
@@ -1162,7 +1162,7 @@ public class Account implements BaseAccount, StoreConfig {
* @return true if account has a spam folder set.
*/
public synchronized boolean hasSpamFolder() {
- return !K9.FOLDER_NONE.equalsIgnoreCase(spamFolderName);
+ return !K9.FOLDER_NONE.equals(spamFolderName);
}
public synchronized String getOutboxFolderName() {
diff --git a/k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java b/k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java
index 93631085d..2990d731a 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java
@@ -85,9 +85,9 @@ public class ActivityListener extends SimpleMessagingListener {
}
if (account != null) {
- if (displayName.equalsIgnoreCase(account.getInboxFolderName())) {
+ if (displayName.equals(account.getInboxFolderName())) {
displayName = context.getString(R.string.special_mailbox_name_inbox);
- } else if (displayName.equalsIgnoreCase(account.getOutboxFolderName())) {
+ } else if (displayName.equals(account.getOutboxFolderName())) {
displayName = context.getString(R.string.special_mailbox_name_outbox);
}
}
diff --git a/k9mail/src/main/java/com/fsck/k9/activity/ChooseFolder.java b/k9mail/src/main/java/com/fsck/k9/activity/ChooseFolder.java
index 1a4082145..efb753400 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/ChooseFolder.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/ChooseFolder.java
@@ -279,10 +279,7 @@ public class ChooseFolder extends K9ListActivity {
for (Folder folder : folders) {
String name = folder.getName();
- // Inbox needs to be compared case-insensitively
- if (mHideCurrentFolder && (name.equals(mFolder) || (
- mAccount.getInboxFolderName().equalsIgnoreCase(mFolder) &&
- mAccount.getInboxFolderName().equalsIgnoreCase(name)))) {
+ if (mHideCurrentFolder && name.equals(mFolder)) {
continue;
}
Folder.FolderClass fMode = folder.getDisplayClass();
@@ -335,7 +332,7 @@ public class ChooseFolder extends K9ListActivity {
try {
int position = 0;
for (String name : localFolders) {
- if (mAccount.getInboxFolderName().equalsIgnoreCase(name)) {
+ if (mAccount.getInboxFolderName().equals(name)) {
folderList.add(getString(R.string.special_mailbox_name_inbox));
mHeldInbox = name;
} else if (!account.getOutboxFolderName().equals(name)) {
@@ -351,9 +348,7 @@ public class ChooseFolder extends K9ListActivity {
if (name.equals(mSelectFolder)) {
selectedFolder = position;
}
- } else if (name.equals(mFolder) || (
- mAccount.getInboxFolderName().equalsIgnoreCase(mFolder) &&
- mAccount.getInboxFolderName().equalsIgnoreCase(name))) {
+ } else if (name.equals(mFolder)) {
selectedFolder = position;
}
position++;
diff --git a/k9mail/src/main/java/com/fsck/k9/activity/FolderInfoHolder.java b/k9mail/src/main/java/com/fsck/k9/activity/FolderInfoHolder.java
index ef52d8b28..b7c63d434 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/FolderInfoHolder.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/FolderInfoHolder.java
@@ -121,8 +121,7 @@ public class FolderInfoHolder implements Comparable<FolderInfoHolder> {
context.getString(R.string.special_mailbox_name_drafts_fmt), name);
} else if (name.equals(account.getOutboxFolderName())) {
displayName = context.getString(R.string.special_mailbox_name_outbox);
- // FIXME: We really shouldn't do a case-insensitive comparison here
- } else if (name.equalsIgnoreCase(account.getInboxFolderName())) {
+ } else if (name.equals(account.getInboxFolderName())) {
displayName = context.getString(R.string.special_mailbox_name_inbox);
} else {
displayName = name;
diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java
index 84b603124..f5ab99975 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java
@@ -989,7 +989,7 @@ public class AccountSettings extends K9PreferenceActivity {
}
private String translateFolder(String in) {
- if (account.getInboxFolderName().equalsIgnoreCase(in)) {
+ if (account.getInboxFolderName().equals(in)) {
return getString(R.string.special_mailbox_name_inbox);
} else {
return in;
diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java
index 92204244d..d3ac2f170 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java
@@ -917,7 +917,7 @@ public class LocalStore extends Store {
if (account.isSpecialFolder(name)) {
prefHolder.inTopGroup = true;
prefHolder.displayClass = LocalFolder.FolderClass.FIRST_CLASS;
- if (name.equalsIgnoreCase(account.getInboxFolderName())) {
+ if (name.equals(account.getInboxFolderName())) {
prefHolder.integrate = true;
prefHolder.notifyClass = LocalFolder.FolderClass.FIRST_CLASS;
prefHolder.pushClass = LocalFolder.FolderClass.FIRST_CLASS;
@@ -925,8 +925,7 @@ public class LocalStore extends Store {
prefHolder.pushClass = LocalFolder.FolderClass.INHERITED;
}
- if (name.equalsIgnoreCase(account.getInboxFolderName()) ||
- name.equalsIgnoreCase(account.getDraftsFolderName())) {
+ if (name.equals(account.getInboxFolderName()) || name.equals(account.getDraftsFolderName())) {
prefHolder.syncClass = LocalFolder.FolderClass.FIRST_CLASS;
} else {
prefHolder.syncClass = LocalFolder.FolderClass.NO_CLASS;
diff --git a/k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java b/k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java
index ea446b4e7..5def5fc8c 100644
--- a/k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java
+++ b/k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java
@@ -233,7 +233,7 @@ public class NotificationActionService extends CoreService {
private boolean isMovePossible(MessagingController controller, Account account,
String destinationFolderName) {
- boolean isSpecialFolderConfigured = !K9.FOLDER_NONE.equalsIgnoreCase(destinationFolderName);
+ boolean isSpecialFolderConfigured = !K9.FOLDER_NONE.equals(destinationFolderName);
return isSpecialFolderConfigured && controller.isMoveCapable(account);
}
diff --git a/k9mail/src/main/java/com/fsck/k9/notification/WearNotifications.java b/k9mail/src/main/java/com/fsck/k9/notification/WearNotifications.java
index fe9d9ce55..780ed27c1 100644
--- a/k9mail/src/main/java/com/fsck/k9/notification/WearNotifications.java
+++ b/k9mail/src/main/java/com/fsck/k9/notification/WearNotifications.java
@@ -240,7 +240,7 @@ class WearNotifications extends BaseNotifications {
}
private boolean isMovePossible(Account account, String destinationFolderName) {
- if (K9.FOLDER_NONE.equalsIgnoreCase(destinationFolderName)) {
+ if (K9.FOLDER_NONE.equals(destinationFolderName)) {
return false;
}
diff --git a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
index da52ab507..8732a1c65 100644
--- a/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
+++ b/k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java
@@ -301,7 +301,7 @@ public class MessageViewFragment extends Fragment implements ConfirmationDialogF
return;
}
- if (K9.FOLDER_NONE.equalsIgnoreCase(dstFolder)) {
+ if (K9.FOLDER_NONE.equals(dstFolder)) {
return;
}
| ['k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java', 'k9mail/src/main/java/com/fsck/k9/activity/ActivityListener.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapFolder.java', 'k9mail/src/main/java/com/fsck/k9/activity/ChooseFolder.java', 'k9mail/src/main/java/com/fsck/k9/notification/WearNotifications.java', 'k9mail/src/main/java/com/fsck/k9/Account.java', 'k9mail/src/main/java/com/fsck/k9/notification/NotificationActionService.java', 'k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3FolderTest.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapStore.java', 'k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSettings.java', 'k9mail/src/main/java/com/fsck/k9/mailstore/LocalStore.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Folder.java', 'k9mail/src/main/java/com/fsck/k9/activity/FolderInfoHolder.java', 'k9mail/src/main/java/com/fsck/k9/ui/messageview/MessageViewFragment.java', 'k9mail-library/src/test/java/com/fsck/k9/mail/store/pop3/Pop3StoreTest.java'] | {'.java': 15} | 15 | 15 | 0 | 0 | 15 | 3,644,613 | 714,329 | 99,963 | 501 | 4,712 | 945 | 73 | 13 | 341 | 59 | 85 | 8 | 0 | 0 | 2018-02-26T03:51:19 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,634 | thundernest/k-9/3292/3289 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3289 | https://github.com/thundernest/k-9/pull/3292 | https://github.com/thundernest/k-9/pull/3292 | 1 | fixes | selecting key from openkeychain fails | k-9 does not accept the cryptographic key from openkeychain.
The key has been created newly by openkeychain using plain defaults from the
wizzard, except for uploading to the internet being off (as these are tests
yet only).
Steps in detail:
In k-9, after selecting the key from the list, the app takes a short breath
for about 1 sec. and then simply behaves as if it was newly started. Looks
like a quick app restart after a crash or so (but there is no crash message).
When entering the menu Cryptography / My key, there is still "no key
selected".
Tried with K-9/OpenKeyChain 5.502/4.9.2 as well as 5.403/4.9.
Android version: 7.1.2 / LineageOS. Security options were off for both
for both apps.
| 5e1291344bf061a5ff0d5609ba28ef25746f4f88 | 44d1a1a454621f968689e90bcb274e7cf901e102 | https://github.com/thundernest/k-9/compare/5e1291344bf061a5ff0d5609ba28ef25746f4f88...44d1a1a454621f968689e90bcb274e7cf901e102 | diff --git a/plugins/openpgp-api-lib/openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpKeyPreference.java b/plugins/openpgp-api-lib/openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpKeyPreference.java
index 15eb44693..dd4b5373d 100644
--- a/plugins/openpgp-api-lib/openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpKeyPreference.java
+++ b/plugins/openpgp-api-lib/openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpKeyPreference.java
@@ -73,6 +73,15 @@ public class OpenPgpKeyPreference extends Preference {
@Override
protected void onClick() {
+ bindServiceAndGetSignKeyId(new Intent());
+ }
+
+ private void bindServiceAndGetSignKeyId(final Intent data) {
+ if (mServiceConnection != null && mServiceConnection.isBound()) {
+ getSignKeyId(data);
+ return;
+ }
+
// bind to service
mServiceConnection = new OpenPgpServiceConnection(
getContext().getApplicationContext(),
@@ -81,7 +90,7 @@ public class OpenPgpKeyPreference extends Preference {
@Override
public void onBound(IOpenPgpService2 service) {
- getSignKeyId(new Intent());
+ getSignKeyId(data);
}
@Override
@@ -252,7 +261,7 @@ public class OpenPgpKeyPreference extends Preference {
public SavedState(Parcel source) {
super(source);
- keyId = source.readInt();
+ keyId = source.readLong();
openPgpProvider = source.readString();
defaultUserId = source.readString();
}
@@ -284,11 +293,11 @@ public class OpenPgpKeyPreference extends Preference {
public boolean handleOnActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_KEY_PREFERENCE && resultCode == Activity.RESULT_OK) {
- getSignKeyId(data);
+ bindServiceAndGetSignKeyId(data);
return true;
} else {
return false;
}
}
-}
\\ No newline at end of file
+} | ['plugins/openpgp-api-lib/openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpKeyPreference.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,641,038 | 712,930 | 99,690 | 493 | 529 | 95 | 17 | 1 | 724 | 122 | 188 | 20 | 0 | 0 | 2018-03-29T13:40:38 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,589 | thundernest/k-9/5078/5077 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5077 | https://github.com/thundernest/k-9/pull/5078 | https://github.com/thundernest/k-9/pull/5078 | 1 | fixes | Crash due to Parcelable problem | Crash when restoring AccountSetupBasics instance state
Steps to reproduce the behavior:
1. In developer options: enable don't keep activities" to easily reproduce the bug
2. Go to AccountSetupBasics activity
3. Click home button to quit the app
4. Use recent app to go back to K9
5. The app crash
**Environment (please complete the following information):**
- K-9 Mail version: [5.725]
- Android version: [10]
- Device: [Tablet ordissimo celia]
I suspect the parcelable part in FoldableLinearLayout
**Logs**
2020-12-22 15:11:54.427 15426-15426/com.fsck.k9.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fsck.k9.debug, PID: 15426
java.lang.RuntimeException: Parcel android.os.Parcel@3b63efa: Unmarshalling unknown type code 2131362261 at offset 1852
at android.os.Parcel.readValue(Parcel.java:2945)
at android.os.Parcel.readSparseArrayInternal(Parcel.java:3329)
at android.os.Parcel.readSparseArray(Parcel.java:2484)
at android.os.Parcel.readValue(Parcel.java:2923)
at android.os.Parcel.readArrayMapInternal(Parcel.java:3246)
at android.os.BaseBundle.initializeFromParcelLocked(BaseBundle.java:292)
at android.os.BaseBundle.unparcel(BaseBundle.java:236)
at android.os.Bundle.getSparseParcelableArray(Bundle.java:1029)
at com.android.internal.policy.PhoneWindow.restoreHierarchyState(PhoneWindow.java:2156)
at android.app.Activity.onRestoreInstanceState(Activity.java:1590)
at com.fsck.k9.activity.setup.AccountSetupBasics.onRestoreInstanceState(AccountSetupBasics.java:119)
at android.app.Activity.performRestoreInstanceState(Activity.java:1545)
at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1353)
| f03f962156df460dda4c86ec62b0c409cce31a3e | 1f65982263a2de884b97c6c9eb84110198289e6c | https://github.com/thundernest/k-9/compare/f03f962156df460dda4c86ec62b0c409cce31a3e...1f65982263a2de884b97c6c9eb84110198289e6c | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/view/FoldableLinearLayout.java b/app/ui/legacy/src/main/java/com/fsck/k9/view/FoldableLinearLayout.java
index 997167a64..5d0e84ae8 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/view/FoldableLinearLayout.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/view/FoldableLinearLayout.java
@@ -121,9 +121,9 @@ public class FoldableLinearLayout extends LinearLayout {
}
}
- static class SavedState extends BaseSavedState {
+ public static class SavedState extends BaseSavedState {
- static final Parcelable.Creator<SavedState> CREATOR =
+ public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<FoldableLinearLayout.SavedState>() {
@Override | ['app/ui/legacy/src/main/java/com/fsck/k9/view/FoldableLinearLayout.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,576,377 | 509,280 | 71,963 | 412 | 247 | 46 | 4 | 1 | 1,804 | 126 | 418 | 35 | 0 | 0 | 2020-12-22T16:58:52 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,588 | thundernest/k-9/5079/5063 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5063 | https://github.com/thundernest/k-9/pull/5079 | https://github.com/thundernest/k-9/pull/5079 | 1 | fixes | Read messages keep changing status back to unread | > Sounds like the "mark as read" commands either fail or are stuck in the local command queue and never sent to the server.
Having the same problem with k9 5.724 and an IMAP account. Accidently I tried to move mails to a mail folder which is a directory on the server and can therefore not store any mails. This move command got stuck in the local command queue:
https://gist.github.com/sevenrock/f307d73819455c55ccc30300220d0a0f
and blocks other commands, like changing the read-status of mails.
Is there a way to clear the local command queue without reinstalling k9?
_Originally posted by @sevenrock in https://github.com/k9mail/k-9/issues/1130#issuecomment-734443921_ | 938a2654646ea40f17e760a22e5d2f01a62b962f | 7ae88bb61d417fc6141a5be07bd017b4f3cbe93a | https://github.com/thundernest/k-9/compare/938a2654646ea40f17e760a22e5d2f01a62b962f...7ae88bb61d417fc6141a5be07bd017b4f3cbe93a | diff --git a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/FolderNotFoundException.java b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/FolderNotFoundException.java
index 871b321a5..3b15551d7 100644
--- a/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/FolderNotFoundException.java
+++ b/mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/FolderNotFoundException.java
@@ -9,7 +9,7 @@ public class FolderNotFoundException extends MessagingException {
public FolderNotFoundException(String folderServerId) {
- super("Folder not found: " + folderServerId);
+ super("Folder not found: " + folderServerId, true);
this.folderServerId = folderServerId;
}
| ['mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/FolderNotFoundException.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,575,629 | 509,141 | 71,938 | 412 | 115 | 28 | 2 | 1 | 682 | 99 | 167 | 9 | 2 | 0 | 2020-12-23T00:24:24 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |