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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,587 | thundernest/k-9/5110/5106 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5106 | https://github.com/thundernest/k-9/pull/5110 | https://github.com/thundernest/k-9/pull/5110 | 1 | fixes | Import functionality is almost broken | **Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
### 1
1. Export k9s_settings on older App version.
2. Remove older App version.
3. Install build v5.727.
4. Have firewall block App from internet.
5. Import all previously exported settings.
6. (Optional) Enable Internet access for App.
7. All Mail accounts have only an empty "Outbox" folder.
### 2
1. Export k9s_settings on older App version.
2. Remove older App version.
3. Install build v5.727.
4. Let App have internet access.
5. Import all previously exported settings.
6. Provide wrong password for any amount of mail accounts.
7. All Mail accounts, that were provided with a wrong password, have only an empty "Outbox" folder.
8. Remove faulty Mail account.
9. Re-import this faulty mail account, only.
10. The empty "Outbox" folder is now the default folder on top of all folders.
11. Every time you change to this mail account, the "Outbox" folder will _always_ be the first one opened on top.
12. There is no way to set the "Inbox" folder back to top.
This is only a summary of all the issues. There are more very similar issues, that I do not want to repeat here.
In short, the Import functionality is almost broken; if you just make 1 mistake, you have to uninstall and re-install the whole application. This is no way to treat imports.
**Expected behavior**
Importing works smoothly.
**Environment (please complete the following information):**
- K-9 Mail version: v5.727
- Android version: 11
- Device: POCO X3
- Account type: Generic IMAP
**Additional context**
The "stable" version always crashes, when I try to import settings. That's why I am using the newest "Pre-Release" version.
**Logs**
Please take some time to [retrieve logs](https://github.com/k9mail/k-9/wiki/LoggingErrors) and attach them here:
No, I will not uninstall and re-install the App for the 7th time.
| 2b769f8db3d1c68c286792fb9f7fee6cace901aa | 71e2d24fbbe8301bcaea363ff0b930d8ff3327d5 | https://github.com/thundernest/k-9/compare/2b769f8db3d1c68c286792fb9f7fee6cace901aa...71e2d24fbbe8301bcaea363ff0b930d8ff3327d5 | 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 67c365a44..38fb82ca2 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
@@ -2356,6 +2356,8 @@ public class MessagingController {
sendPendingMessages(account, listener);
+ refreshFolderListIfStale(account);
+
try {
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode(); | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,574,874 | 509,020 | 71,922 | 412 | 45 | 9 | 2 | 1 | 1,972 | 315 | 473 | 48 | 1 | 0 | 2021-01-27T07:08:57 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,586 | thundernest/k-9/5131/5004 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5004 | https://github.com/thundernest/k-9/pull/5131 | https://github.com/thundernest/k-9/pull/5131 | 1 | fixes | Email address too long for line | **Describe the bug**
A mail address that is too long to fit on the display won't be accepted as one address but two (or more) addresses.
**To Reproduce**
Try to send an email to an address that is too long for your display width, for example `[email protected]`. The app will now display the address in two lines, in my case like this:
`abcdefghijklmnopqrstuvwxyz@outlook.
com`
The app will now see every line as single address and think you want to send mails to `abcdefghijklmnopqrstuvwxyz@outlook.` and `com`.
**Expected behavior**
The app should see the address as a single one, even after a new line.
**Environment**
- K-9 Mail version: 5.721
- Android version: 10
- Device: Samsung Galaxy A9 | 5655bf3c03147f2d145e750057e12cd1530eacfd | 09ab26f763ca53f0dd146636cd72add74647ce3a | https://github.com/thundernest/k-9/compare/5655bf3c03147f2d145e750057e12cd1530eacfd...09ab26f763ca53f0dd146636cd72add74647ce3a | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java b/app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java
index 8e5452e08..72e46e091 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java
@@ -204,6 +204,10 @@ public class RecipientSelectView extends TokenCompleteTextView<Recipient> implem
@Override
public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
+ if (!hasFocus) {
+ performCompletion();
+ }
+
super.onFocusChanged(hasFocus, direction, previous);
if (hasFocus) {
displayKeyboard(); | ['app/ui/legacy/src/main/java/com/fsck/k9/view/RecipientSelectView.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,559,059 | 505,701 | 71,434 | 406 | 72 | 13 | 4 | 1 | 739 | 117 | 167 | 16 | 0 | 0 | 2021-02-08T16:57:28 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,582 | thundernest/k-9/5146/4125 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4125 | https://github.com/thundernest/k-9/pull/5146 | https://github.com/thundernest/k-9/pull/5146 | 1 | fixes | Not handling reject response correctly when multiple recipients | ### Similar issues found
#3616
### Root Cause
My mail server is enforcing a 'reject' rule on unknown recipient domain. So any email containing unknown domain will **not** be accepted.
It works with other MUA I tested, and indeed the 450 error is raised and no mail is sent until the list of recipients is sanitized.
In the case of K9-Mail, I end up with a **mangled header missing multiple fields** (From / Date) and with an 'unexpected end of header'.
For Googlemail, the server respond waving RFC 5322 and refuse to accept the email.
Others will discard and send a report to the recipient regarding the bad formatted email, and Outlook/Microsoft will accept it but it will be blank for the recipient.
On K9-Mail side, the email will be stuck forever in the Outbox, trying to resend the botched email every now and then, never succeeding (as expected).
### Expected behavior
Whenever a recipient is rejected, the MUA should handle it gracefully. Testing with Thunderbird and SOGo, they both raise the error and do not try further attempts to deliver the email until the 'bad' recipients have been removed from the list.
K9-Mail should do the same and stop all attempt on receiving the reject from the mail server until the list of recipients has been sanitized.
### Actual behavior
Mail server rejects the email, with and from=<> as per bouncing standards, however K9-Mail basically integrate that bad-formatted header and use it to try sending the email to the rest of the recipients.
### Steps to reproduce
0. Enforce reject rule on unknown recipient domains on your mail server (**before** any permit rule)
1. Prepare an email to multiple recipients with at least one 'bad' recipient (ex: unknown domain. Ex: [email protected])
2. Send it from K9-Mail
3. Check your Outbox in K9-Mail and your logs on the mail server
### Environment
K-9 Mail version: 5.500
Android version: 8.1.0
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:
Logs from the mail server:
```
Jul 23 09:44:35 myhost postfix/smtpd[26369]: connect from XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137]
Jul 23 09:44:35 myhost postfix/smtpd[26369]: Anonymous TLS connection established from XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137]: TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)
Jul 23 09:44:35 myhost postfix/smtpd[26369]: CEC231003: client=XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137], sasl_method=PLAIN, [email protected]
Jul 23 09:44:35 myhost postfix/smtpd[26369]: CEC231003: reject: RCPT from XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137]: 450 4.1.2 <[email protected]>: <b>Recipient address rejected: Domain not found</b>; from=<[email protected]> to=<[email protected]> proto=ESMTP helo=<[XXX.XXX.XXX.119]>
Jul 23 09:44:36 myhost postfix/cleanup[26374]: CEC231003: message-id=<>
Jul 23 09:44:36 myhost opendkim[32642]: <b>CEC231003: can't determine message sender; accepting</b>
Jul 23 09:44:36 myhost opendmarc[619]: CEC231003: RFC5322 requirement error: missing From field; accepting
Jul 23 09:44:36 myhost postfix/qmgr[26269]: CEC231003: from=<[email protected]>, size=213, nrcpt=2 (queue active)
Jul 23 09:44:36 myhost postfix/smtp[26375]: Untrusted TLS connection established to gmail-smtp-in.l.google.com[2a00:1450:400c:c0a::1b]:25: TLSv1.2 with cipher ECDHE-RSA-CHACHA20-POLY1305 (256/256 bits)
Jul 23 09:44:36 myhost postfix/smtpd[26369]: disconnect from XXX.XXX.XXX.137.threembb.co.uk[XXX.XXX.XXX.137] ehlo=2 starttls=1 auth=1 mail=1 rcpt=2/3 data=1 quit=1 commands=9/10
Jul 23 09:44:36 myhost postfix/smtp[26375]: CEC231003: to=<[email protected]>, relay=gmail-smtp-in.l.google.com[2a00:1450:400c:c0a::1b]:25, delay=0.99, delays=0.4/0.01/0.16/0.43, dsn=5.7.1, status=bounced (host gmail-smtp-in.l.google.com[2a00:1450:400c:c0a::1b] said: 550-5.7.1 [2a01:4f8:10a:2493:b827:a8ff:fe4b:b71c 11] Our system has 550-5.7.1 detected that this message is not RFC 5322 compliant: 550-5.7.1 'From' header is missing. 550-5.7.1 To reduce the amount of spam sent to Gmail, this message has been 550-5.7.1 blocked. Please visit 550-5.7.1 https://support.google.com/mail/?p=RfcMessageNonCompliant 550 5.7.1 and review RFC 5322 specifications for more information. y4si40902182wrr.356 - gsmtp (in reply to end of DATA command))
```
| 3457f69c562f47ca1fe5daebfbdb5a02b7c856c4 | 987325d226dc225c8f9158e4534a3120c938b0e5 | https://github.com/thundernest/k-9/compare/3457f69c562f47ca1fe5daebfbdb5a02b7c856c4...987325d226dc225c8f9158e4534a3120c938b0e5 | diff --git a/mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java b/mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java
index aeaff52f6..001919834 100644
--- a/mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java
+++ b/mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java
@@ -413,7 +413,6 @@ public class SmtpTransport extends Transport {
pipelinedCommands.add(String.format("RCPT TO:<%s>", address));
}
- pipelinedCommands.add("DATA");
executePipelinedCommands(pipelinedCommands);
readPipelinedResponse(pipelinedCommands);
} else {
@@ -422,10 +421,10 @@ public class SmtpTransport extends Transport {
for (String address : addresses) {
executeCommand("RCPT TO:<%s>", address);
}
-
- executeCommand("DATA");
}
+ executeCommand("DATA");
+
EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream(
new LineWrapOutputStream(new SmtpDataStuffing(outputStream), 1000));
@@ -618,35 +617,23 @@ public class SmtpTransport extends Transport {
private void readPipelinedResponse(Queue<String> pipelinedCommands) throws IOException, MessagingException {
String responseLine;
List<String> results = new ArrayList<>();
- NegativeSmtpReplyException firstNegativeResponse = null;
- boolean dataCommandOk = true;
- for (String command : pipelinedCommands) {
+ MessagingException firstException = null;
+ for (int i = 0, size = pipelinedCommands.size(); i < size; i++) {
results.clear();
responseLine = readCommandResponseLine(results);
try {
responseLineToCommandResponse(responseLine, results);
} catch (MessagingException exception) {
- if (command.equals("DATA")) {
- dataCommandOk = false;
- }
- if (firstNegativeResponse == null) {
- firstNegativeResponse = (NegativeSmtpReplyException) exception;
+ if (firstException == null) {
+ firstException = exception;
}
}
}
- if (firstNegativeResponse != null) {
- try {
- if (dataCommandOk) {
- executeCommand(".");
- }
- throw firstNegativeResponse;
- } catch (NegativeSmtpReplyException e) {
- throw firstNegativeResponse;
- }
+ if (firstException != null) {
+ throw firstException;
}
-
}
private CommandResponse responseLineToCommandResponse(String line, List<String> results) throws MessagingException {
diff --git a/mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java b/mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java
index 06aa6f9e7..33a4025c4 100644
--- a/mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java
+++ b/mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java
@@ -692,9 +692,9 @@ public class SmtpTransportTest {
MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING");
server.expect("MAIL FROM:<user@localhost>");
server.expect("RCPT TO:<user2@localhost>");
- server.expect("DATA");
server.output("250 OK");
server.output("250 OK");
+ server.expect("DATA");
server.output("354 End data with <CR><LF>.<CR><LF>");
server.expect("[message data]");
server.expect(".");
@@ -740,12 +740,8 @@ public class SmtpTransportTest {
MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING");
server.expect("MAIL FROM:<user@localhost>");
server.expect("RCPT TO:<user2@localhost>");
- server.expect("DATA");
server.output("250 OK");
server.output("550 remote mail to <user2@localhost> not allowed");
- server.output("354 End data with <CR><LF>.<CR><LF>");
- server.expect(".");
- server.output("554 no valid recipients");
server.expect("QUIT");
server.output("221 BYE");
server.closeConnection();
@@ -770,10 +766,8 @@ public class SmtpTransportTest {
MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING");
server.expect("MAIL FROM:<user@localhost>");
server.expect("RCPT TO:<user2@localhost>");
- server.expect("DATA");
server.output("250 OK");
server.output("550 remote mail to <user2@localhost> not allowed");
- server.output("554 no valid recipients given");
server.expect("QUIT");
server.output("221 BYE");
server.closeConnection();
@@ -798,13 +792,9 @@ public class SmtpTransportTest {
server.expect("MAIL FROM:<user@localhost>");
server.expect("RCPT TO:<user2@localhost>");
server.expect("RCPT TO:<user3@localhost>");
- server.expect("DATA");
server.output("250 OK");
server.output("550 remote mail to <user2@localhost> not allowed");
server.output("550 remote mail to <user3@localhost> not allowed");
- server.output("354 End data with <CR><LF>.<CR><LF>");
- server.expect(".");
- server.output("554 no valid recipients given");
server.expect("QUIT");
server.output("221 BYE");
server.closeConnection();
@@ -829,13 +819,9 @@ public class SmtpTransportTest {
server.expect("MAIL FROM:<user@localhost>");
server.expect("RCPT TO:<user2@localhost>");
server.expect("RCPT TO:<user3@localhost>");
- server.expect("DATA");
server.output("250 OK");
server.output("250 OK");
server.output("550 remote mail to <user3@localhost> not allowed");
- server.output("354 End data with <CR><LF>.<CR><LF>");
- server.expect(".");
- server.output("250 OK");
server.expect("QUIT");
server.output("221 BYE");
server.closeConnection(); | ['mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.java', 'mail/protocols/smtp/src/test/java/com/fsck/k9/mail/transport/smtp/SmtpTransportTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,558,990 | 505,695 | 71,435 | 406 | 1,158 | 212 | 29 | 1 | 4,451 | 551 | 1,382 | 49 | 2 | 1 | 2021-02-16T13:16:03 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,580 | thundernest/k-9/5216/5204 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5204 | https://github.com/thundernest/k-9/pull/5216 | https://github.com/thundernest/k-9/pull/5216 | 1 | fixes | Crash when sending to address with an umlaut | I haven't done any variation testing, as I just finally found out. What I had was:
A contact which I accidentially typed an `ü` instead of `ue`, used the contact suggestion feature for recepient. As soon as I hit send, Android's "Application has stopped working" window popped up, after a restart it's as if nothing had happened.
Replacing the character in my contacts helped, but It took me probably a month to figure out what the issue was. | cc2413a180af45b76fa12d4440111d34a1e92c94 | 12213b53165ff051552483ff32caa4eddef91b14 | https://github.com/thundernest/k-9/compare/cc2413a180af45b76fa12d4440111d34a1e92c94...12213b53165ff051552483ff32caa4eddef91b14 | 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 e2cf5893e..d9ca0307c 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
@@ -28,6 +28,7 @@ import com.fsck.k9.ui.R;
import com.fsck.k9.mail.Address;
import com.fsck.k9.view.RecipientSelectView.Recipient;
import com.fsck.k9.view.RecipientSelectView.RecipientCryptoStatus;
+import org.apache.james.mime4j.util.CharsetUtil;
import timber.log.Timber;
import static java.lang.String.CASE_INSENSITIVE_ORDER;
@@ -240,13 +241,14 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
Address[] addresses = Address.parseUnencoded(uid);
for (Address address : addresses) {
- if (recipientMap.containsKey(address.getAddress())) {
+ String emailAddress = address.getAddress();
+ if (!isSupportedEmailAddress(emailAddress) || recipientMap.containsKey(emailAddress)) {
continue;
}
Recipient recipient = new Recipient(address);
recipients.add(recipient);
- recipientMap.put(address.getAddress(), recipient);
+ recipientMap.put(emailAddress, recipient);
}
}
@@ -256,10 +258,12 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
private void fillContactDataFromAddresses(Address[] addresses, List<Recipient> recipients,
Map<String, Recipient> recipientMap) {
for (Address address : addresses) {
- // TODO actually query contacts - not sure if this is possible in a single query tho :(
- Recipient recipient = new Recipient(address);
- recipients.add(recipient);
- recipientMap.put(address.getAddress(), recipient);
+ if (isSupportedEmailAddress(address.getAddress())) {
+ // TODO actually query contacts - not sure if this is possible in a single query tho :(
+ Recipient recipient = new Recipient(address);
+ recipients.add(recipient);
+ recipientMap.put(address.getAddress(), recipient);
+ }
}
}
@@ -438,7 +442,7 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
String email = cursor.getString(INDEX_EMAIL);
// already exists? just skip then
- if (email == null || recipientMap.containsKey(email)) {
+ if (email == null || !isSupportedEmailAddress(email) || recipientMap.containsKey(email)) {
// TODO We should probably merging contacts with the same email address
continue;
}
@@ -583,4 +587,7 @@ public class RecipientLoader extends AsyncTaskLoader<List<Recipient>> {
}
}
+ private boolean isSupportedEmailAddress(String address) {
+ return CharsetUtil.isASCII(address);
+ }
} | ['app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientLoader.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,528,405 | 500,145 | 70,553 | 402 | 1,328 | 220 | 21 | 1 | 448 | 78 | 100 | 5 | 0 | 0 | 2021-03-25T21:19:33 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,651 | thundernest/k-9/2003/1965 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1965 | https://github.com/thundernest/k-9/pull/2003 | https://github.com/thundernest/k-9/pull/2003 | 1 | fixes | CC/BCC Disappear if you tap subject first | ### Expected behavior
While composing a new email, if I type the subject first, and compose the email, THEN go back and fill out the addresses of BCC and CC.
### Actual behavior
While composing a new email, if I type the subject first, the BCC and CC address fields disappear (have them configured to show by default). No way to get them back because the BCC/CC icon is missing (see previous issue)
### Steps to reproduce
1. Tap to compose a new email
2. Tap and type a subject
3. BCC/CC address fields disappear
### Environment
K-9 Mail version: 5.201
Android version: 6.0
Account type (IMAP, POP3, WebDAV/Exchange):IMAP
| 6beb9902dade44b5f6dce8e8e8a2638e7be9e6ef | 963645cad626c3ea2f732ebf66390b072aa444f5 | https://github.com/thundernest/k-9/compare/6beb9902dade44b5f6dce8e8e8a2638e7be9e6ef...963645cad626c3ea2f732ebf66390b072aa444f5 | 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 cf805041d..be62c922a 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
@@ -541,7 +541,9 @@ public class RecipientPresenter implements PermissionPingCallback {
}
public void onNonRecipientFieldFocused() {
- hideEmptyExtendedRecipientFields();
+ if (!account.isAlwaysShowCcBcc()) {
+ hideEmptyExtendedRecipientFields();
+ }
}
public void onClickCryptoStatus() { | ['k9mail/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,455,426 | 685,807 | 94,549 | 422 | 149 | 28 | 4 | 1 | 655 | 109 | 168 | 18 | 0 | 0 | 2017-01-07T17:02:58 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,578 | thundernest/k-9/5262/5261 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5261 | https://github.com/thundernest/k-9/pull/5262 | https://github.com/thundernest/k-9/pull/5262 | 1 | fixes | Crash when clicking compose button in message list widget | **Describe the bug**
Clicking the envelope icon in the message list widget crashes the app.
**To Reproduce**
Steps to reproduce the behavior:
1. Set up an account
2. Drag the message list widget to a home screen
3. Click the envelope icon (compose message) in the upper right of the home screen widget
4. Observe app crash
**Environment (please complete the following information):**
- K-9 Mail version: 5.734-SNAPSHOT
**Logs**
```
Caused by: java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter accountUuid
at com.fsck.k9.Preferences.getAccount(Unknown Source:2)
at com.fsck.k9.activity.MessageCompose.onCreate(MessageCompose.java:284)
``` | f58860f8bbe3a59e180cc87dc410e16b295592f7 | 034e1fbd790dc4af6f60bd980f59489e375a31fe | https://github.com/thundernest/k-9/compare/f58860f8bbe3a59e180cc87dc410e16b295592f7...034e1fbd790dc4af6f60bd980f59489e375a31fe | 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 0601958fd..c2cb3fd28 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
@@ -281,7 +281,9 @@ public class MessageCompose extends K9Activity implements OnClickListener,
relatedMessageReference.getAccountUuid() :
intent.getStringExtra(EXTRA_ACCOUNT);
- account = preferences.getAccount(accountUuid);
+ if (accountUuid != null) {
+ account = preferences.getAccount(accountUuid);
+ }
if (account == null) {
account = preferences.getDefaultAccount(); | ['app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageCompose.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,515,829 | 497,753 | 70,226 | 402 | 162 | 27 | 4 | 1 | 759 | 89 | 171 | 19 | 0 | 1 | 2021-04-19T19:31:47 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,655 | thundernest/k-9/1890/1879 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1879 | https://github.com/thundernest/k-9/pull/1890 | https://github.com/thundernest/k-9/pull/1890 | 1 | fixes | Crash: OOM during migration | Via Play Developer Console
App version: 5.200
```
java.lang.OutOfMemoryError: Failed to allocate a 2060 byte allocation with 1974 free bytes and 1974B until OOM
at org.apache.james.mime4j.stream.MimeEntity.advanceToBoundary(MimeEntity.java:387)
at org.apache.james.mime4j.stream.MimeEntity.advance(MimeEntity.java:331)
at org.apache.james.mime4j.stream.MimeTokenStream.next(MimeTokenStream.java:360)
at org.apache.james.mime4j.parser.MimeStreamParser.parse(MimeStreamParser.java:176)
at com.fsck.k9.mail.message.MessageHeaderParser.parse(MessageHeaderParser.java:24)
at com.fsck.k9.mailstore.LocalMessage.populateFromGetMessageCursor(LocalMessage.java:127)
at com.fsck.k9.mailstore.LocalStore$13.doDbWork(LocalStore.java:638)
at com.fsck.k9.mailstore.LocalStore$13.doDbWork(LocalStore.java:615)
at com.fsck.k9.mailstore.LockableDatabase.execute(LockableDatabase.java:275)
at com.fsck.k9.mailstore.LocalStore.getMessages(LocalStore.java:615)
at com.fsck.k9.mailstore.LocalFolder$10.doDbWork(LocalFolder.java:880)
at com.fsck.k9.mailstore.LocalFolder$10.doDbWork(LocalFolder.java:875)
at com.fsck.k9.mailstore.LockableDatabase.execute(LockableDatabase.java:275)
at com.fsck.k9.mailstore.LocalFolder.getMessages(LocalFolder.java:875)
at com.fsck.k9.mailstore.migrations.MigrationTo55.createFtsSearchTable(MigrationTo55.java:36)
at com.fsck.k9.mailstore.migrations.Migrations.upgradeDatabase(Migrations.java:66)
at com.fsck.k9.mailstore.StoreSchemaDefinition.upgradeDatabase(StoreSchemaDefinition.java:60)
at com.fsck.k9.mailstore.StoreSchemaDefinition.doDbUpgrade(StoreSchemaDefinition.java:36)
at com.fsck.k9.mailstore.LockableDatabase.openOrCreateDataspace(LockableDatabase.java:381)
at com.fsck.k9.mailstore.LockableDatabase.open(LockableDatabase.java:354)
at com.fsck.k9.mailstore.LocalStore.<init>(LocalStore.java:210)
at com.fsck.k9.mailstore.LocalStore.getInstance(LocalStore.java:235)
at com.fsck.k9.Account.getLocalStore(Account.java:1278)
at com.fsck.k9.controller.MessagingController.setupPushing(MessagingController.java:4322)
at com.fsck.k9.service.MailService.setupPushers(MailService.java:349)
at com.fsck.k9.service.MailService.reschedulePushers(MailService.java:338)
at com.fsck.k9.service.MailService.access$100(MailService.java:24)
at com.fsck.k9.service.MailService$1.run(MailService.java:194)
at com.fsck.k9.service.CoreService$1.run(CoreService.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
``` | 50d81f7034e60e50cbd67007144bf7e23137aa87 | b0574804813c978d9826380667cf01b8e50429de | https://github.com/thundernest/k-9/compare/50d81f7034e60e50cbd67007144bf7e23137aa87...b0574804813c978d9826380667cf01b8e50429de | diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java
index e9458479a..9cd8f2319 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java
@@ -896,6 +896,42 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
}
}
+ public List<String> getAllMessageUids() throws MessagingException {
+ try {
+ return localStore.database.execute(false, new DbCallback<List<String>>() {
+ @Override
+ public List<String> doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
+ Cursor cursor = null;
+ ArrayList<String> result = new ArrayList<>();
+
+ try {
+ open(OPEN_MODE_RO);
+
+ cursor = db.rawQuery(
+ "SELECT uid " +
+ "FROM messages " +
+ "WHERE empty = 0 AND deleted = 0 AND " +
+ "folder_id = ? ORDER BY date DESC",
+ new String[] { Long.toString(mFolderId) });
+
+ while (cursor.moveToNext()) {
+ String uid = cursor.getString(0);
+ result.add(uid);
+ }
+ } catch (MessagingException e) {
+ throw new WrappedException(e);
+ } finally {
+ Utility.closeQuietly(cursor);
+ }
+
+ return result;
+ }
+ });
+ } catch (WrappedException e) {
+ throw(MessagingException) e.getCause();
+ }
+ }
+
public List<LocalMessage> getMessagesByUids(@NonNull List<String> uids) throws MessagingException {
open(OPEN_MODE_RW);
List<LocalMessage> messages = new ArrayList<>();
diff --git a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java
index 4f8f7e5dc..e9fb197ab 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java
@@ -1,9 +1,7 @@
package com.fsck.k9.mailstore.migrations;
-import java.util.ArrayList;
import java.util.Collections;
-import java.util.Iterator;
import java.util.List;
import android.content.ContentValues;
@@ -20,8 +18,8 @@ import com.fsck.k9.mailstore.LocalStore;
import com.fsck.k9.message.extractors.MessageFulltextCreator;
-public class MigrationTo55 {
- public static void createFtsSearchTable(SQLiteDatabase db, MigrationsHelper migrationsHelper) {
+class MigrationTo55 {
+ static void createFtsSearchTable(SQLiteDatabase db, MigrationsHelper migrationsHelper) {
db.execSQL("CREATE VIRTUAL TABLE messages_fulltext USING fts4 (fulltext)");
LocalStore localStore = migrationsHelper.getLocalStore();
@@ -33,13 +31,11 @@ public class MigrationTo55 {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
for (LocalFolder folder : folders) {
- Iterator<LocalMessage> localMessages = new ArrayList<>(folder.getMessages(null, false)).iterator();
- while (localMessages.hasNext()) {
- LocalMessage localMessage = localMessages.next();
- // The LocalMessage objects are heavy once they have been loaded, so we free them asap
- localMessages.remove();
-
+ List<String> messageUids = folder.getAllMessageUids();
+ for (String messageUid : messageUids) {
+ LocalMessage localMessage = folder.getMessage(messageUid);
folder.fetch(Collections.singletonList(localMessage), fp, null);
+
String fulltext = fulltextCreator.createFulltext(localMessage);
if (!TextUtils.isEmpty(fulltext)) {
Log.d(K9.LOG_TAG, "fulltext for msg id " + localMessage.getId() + " is " + fulltext.length() + " chars long"); | ['k9mail/src/main/java/com/fsck/k9/mailstore/LocalFolder.java', 'k9mail/src/main/java/com/fsck/k9/mailstore/migrations/MigrationTo55.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,440,397 | 682,554 | 94,169 | 420 | 2,413 | 385 | 52 | 2 | 2,654 | 89 | 677 | 38 | 0 | 1 | 2016-12-30T19:58:49 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,654 | thundernest/k-9/1891/1878 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1878 | https://github.com/thundernest/k-9/pull/1891 | https://github.com/thundernest/k-9/pull/1891 | 1 | fixes | Crash: NPE in MessageCryptoHelper.addCryptoResultAnnotationToMessage() | Via Play Developer Console
App version: 5.200
```
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65916, result=0, data=null} to activity {com.fsck.k9/com.fsck.k9.activity.MessageList}: java.lang.NullPointerException: Attempt to read from field 'com.fsck.k9.mail.Part com.fsck.k9.ui.crypto.MessageCryptoHelper$CryptoPart.part' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3733)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
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)
Caused by: java.lang.NullPointerException: Attempt to read from field 'com.fsck.k9.mail.Part com.fsck.k9.ui.crypto.MessageCryptoHelper$CryptoPart.part' on a null object reference
at com.fsck.k9.ui.crypto.MessageCryptoHelper.addCryptoResultAnnotationToMessage(MessageCryptoHelper.java:575)
at com.fsck.k9.ui.crypto.MessageCryptoHelper.onCryptoOperationCanceled(MessageCryptoHelper.java:558)
at com.fsck.k9.ui.crypto.MessageCryptoHelper.onActivityResult(MessageCryptoHelper.java:536)
at com.fsck.k9.activity.MessageLoaderHelper.onActivityResult(MessageLoaderHelper.java:168)
at com.fsck.k9.ui.messageview.MessageViewFragment.onPendingIntentResult(MessageViewFragment.java:393)
at com.fsck.k9.activity.MessageList.onActivityResult(MessageList.java:1600)
at android.app.Activity.dispatchActivityResult(Activity.java:6456)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3729)
... 9 more
``` | 50d81f7034e60e50cbd67007144bf7e23137aa87 | 97e9e3267f35a67eeb1ff6542224825dad6f9aba | https://github.com/thundernest/k-9/compare/50d81f7034e60e50cbd67007144bf7e23137aa87...97e9e3267f35a67eeb1ff6542224825dad6f9aba | diff --git a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java
index 28387c9f7..2600ddcf0 100644
--- a/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java
+++ b/k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java
@@ -58,13 +58,14 @@ import org.openintents.openpgp.util.OpenPgpUtils;
public class MessageCryptoHelper {
private static final int INVALID_OPENPGP_RESULT_CODE = -1;
private static final MimeBodyPart NO_REPLACEMENT_PART = null;
- public static final int REQUEST_CODE_USER_INTERACTION = 124;
- public static final int PROGRESS_SIZE_THRESHOLD = 4096;
+ private static final int REQUEST_CODE_USER_INTERACTION = 124;
+ private static final int PROGRESS_SIZE_THRESHOLD = 4096;
private final Context context;
private final String openPgpProviderPackage;
private final Object callbackLock = new Object();
+ private final Deque<CryptoPart> partsToDecryptOrVerify = new ArrayDeque<>();
@Nullable
private MessageCryptoCallback callback;
@@ -76,7 +77,6 @@ public class MessageCryptoHelper {
private MessageCryptoAnnotations messageAnnotations;
- private Deque<CryptoPart> partsToDecryptOrVerify = new ArrayDeque<>();
private CryptoPart currentCryptoPart;
private Intent currentCryptoResult;
private Intent userInteractionResultIntent;
@@ -554,8 +554,12 @@ public class MessageCryptoHelper {
}
private void onCryptoOperationCanceled() {
- CryptoResultAnnotation errorPart = CryptoResultAnnotation.createOpenPgpCanceledAnnotation();
- addCryptoResultAnnotationToMessage(errorPart);
+ // there are weird states that get us here when we're not actually processing any part. just skip in that case
+ // see https://github.com/k9mail/k-9/issues/1878
+ if (currentCryptoPart != null) {
+ CryptoResultAnnotation errorPart = CryptoResultAnnotation.createOpenPgpCanceledAnnotation();
+ addCryptoResultAnnotationToMessage(errorPart);
+ }
onCryptoFinished();
}
@@ -579,8 +583,17 @@ public class MessageCryptoHelper {
}
private void onCryptoFinished() {
- currentCryptoPart = null;
- partsToDecryptOrVerify.removeFirst();
+ boolean currentPartIsFirstInQueue = partsToDecryptOrVerify.peekFirst() == currentCryptoPart;
+ if (!currentPartIsFirstInQueue) {
+ throw new IllegalStateException(
+ "Trying to remove part from queue that is not the currently processed one!");
+ }
+ if (currentCryptoPart != null) {
+ partsToDecryptOrVerify.removeFirst();
+ currentCryptoPart = null;
+ } else {
+ Log.e(K9.LOG_TAG, "Got to onCryptoFinished() with no part in processing!", new Throwable());
+ }
decryptOrVerifyNextPart();
}
@@ -594,7 +607,7 @@ public class MessageCryptoHelper {
}
private void cleanupAfterProcessingFinished() {
- partsToDecryptOrVerify = null;
+ partsToDecryptOrVerify.clear();
openPgpApi = null;
if (openPgpServiceConnection != null) {
openPgpServiceConnection.unbindFromService();
@@ -613,11 +626,13 @@ public class MessageCryptoHelper {
throw new AssertionError("Callback may only be reattached for the same message!");
}
synchronized (callbackLock) {
- if (queuedResult != null) {
- Log.d(K9.LOG_TAG, "Returning cached result to reattached callback");
- }
this.callback = callback;
- deliverResult();
+
+ boolean hasCachedResult = queuedResult != null || queuedPendingIntent != null;
+ if (hasCachedResult) {
+ Log.d(K9.LOG_TAG, "Returning cached result or pending intent to reattached callback");
+ deliverResult();
+ }
}
}
@@ -663,6 +678,8 @@ public class MessageCryptoHelper {
callback.startPendingIntentForCryptoHelper(
queuedPendingIntent.getIntentSender(), REQUEST_CODE_USER_INTERACTION, null, 0, 0, 0);
queuedPendingIntent = null;
+ } else {
+ throw new IllegalStateException("deliverResult() called with no result!");
}
}
| ['k9mail/src/main/java/com/fsck/k9/ui/crypto/MessageCryptoHelper.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,440,397 | 682,554 | 94,169 | 420 | 2,260 | 447 | 41 | 1 | 1,969 | 88 | 443 | 26 | 0 | 1 | 2016-12-30T20:08:31 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,570 | thundernest/k-9/5546/5545 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/5545 | https://github.com/thundernest/k-9/pull/5546 | https://github.com/thundernest/k-9/pull/5546 | 1 | fixes | v5.802 doesn't retract android notification on delete of unread message | **Describe the bug**
Separate IMAP client deletes unread message, v5.802 does not retract New Message notification previously posted when IMAP PUSH saw new msg arrive
**To Reproduce**
1. send message to an account watched via IMAP PUSH by K-9 v5.802
2. K-9 posts a notification immediately (cool)
3. via another IMAP client (desktop, even K-9 v5.600 on another android), delete the message before marking it read
4. Android notification previously posted by K-9 v5.802 is not retracted and stays visible (note that v5.600 properly retracts in such a case)
**Expected behavior**
A message never marked read but deleted by another client should retract K-9's previously posted new-message notification.
**Environment:**
- K-9 Mail version: v5.802
- Android version: 8.0 // old, I know
- Device: LG V20 // old, I know
- Account type: IMAP (gmail)
**Additional context**
Note as mentioned above, v5.600 (K-9) does retract notifications in such cases
A work-around that the end-user may practice is as follows:
Whichever separate non-K9(v5.802) IMAP client is being used (desktop client of some form on another machine, K-9 v5.600 itself on another Android device), if you FIRST mark the newest message read, THEN delete that newest message, K-9 v5.802 DOES properly retract the previously posted new-msg android-notification.
So I'm wondering if K-9 v5.802 could be changed to treat a message deletion (for a message just received and for which the android system notification was posted, and which is still an unread message) as experiencing both an "is read" and "is deleted" state change?
I realize, having briefly scanned the issues list here that there are many challenges surrounding android notifications, and that this may not be an easy thing to track down and solve. I hope I've provided enough info.
In summary:
message arrives, remains new/unread, is deleted from another IMAP client, K-9 v5.802 leaves the android notif up (while 5.600 removes the notif under the same conditions).
conversely:
message arrives, remains new/unrerad, is first marked read from another IMAP client, then deleted from another IMAP client, K-9 v5.802 tears down the android notif previously posted for the new message.
| 11c85745d0369db1b2d7e3a7bffbbf2ee6fbdc61 | 04d68624ada65bc96ee8b5102f02d9022c7fdbe7 | https://github.com/thundernest/k-9/compare/11c85745d0369db1b2d7e3a7bffbbf2ee6fbdc61...04d68624ada65bc96ee8b5102f02d9022c7fdbe7 | 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 d84f5ec96..716322605 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
@@ -2775,6 +2775,11 @@ public class MessagingController {
for (MessagingListener messagingListener : getListeners(listener)) {
messagingListener.synchronizeMailboxRemovedMessage(account, folderServerId, messageServerId);
}
+
+ String accountUuid = account.getUuid();
+ long folderId = getFolderIdOrThrow(account, folderServerId);
+ MessageReference messageReference = new MessageReference(accountUuid, folderId, messageServerId, null);
+ notificationController.removeNewMailNotification(account, messageReference);
}
@Override | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,505,728 | 495,533 | 69,968 | 400 | 335 | 59 | 5 | 1 | 2,263 | 348 | 532 | 38 | 0 | 0 | 2021-08-07T19:55:01 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,633 | thundernest/k-9/3315/3138 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3138 | https://github.com/thundernest/k-9/pull/3315 | https://github.com/thundernest/k-9/pull/3315 | 1 | fixes | twitter background image - td element | the background images (for previewing videos in the twitter e-mails) aren't displayed for some reason.
[twitter.zip](https://github.com/k9mail/k-9/files/1667936/twitter.zip)
Could you pls take a look? :)
Regards,
Djfe
| fd07e1a2264988f5c67f21cd92a88874dd11800c | 9cad669af8bc0a4c64e4b896beed6b21b15053b7 | https://github.com/thundernest/k-9/compare/fd07e1a2264988f5c67f21cd92a88874dd11800c...9cad669af8bc0a4c64e4b896beed6b21b15053b7 | diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
index 1707f7c9e..ad11115fc 100644
--- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
+++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
@@ -17,13 +17,13 @@ public class HtmlSanitizer {
.addAttributes("font", "color", "face", "size")
.addAttributes("table", "align", "background", "bgcolor", "border", "cellpadding", "cellspacing",
"width")
- .addAttributes("tr", "align", "bgcolor", "valign")
+ .addAttributes("tr", "align", "background", "bgcolor", "valign")
.addAttributes("th",
- "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted",
- "valign", "width")
+ "align", "background", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope",
+ "sorted", "valign", "width")
.addAttributes("td",
- "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign",
- "width")
+ "align", "background", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope",
+ "valign", "width")
.addAttributes("map", "name")
.addAttributes("area", "shape", "coords", "href", "alt")
.addProtocols("area", "href", "http", "https") | ['k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,651,204 | 716,146 | 100,113 | 503 | 801 | 189 | 10 | 1 | 229 | 25 | 58 | 9 | 1 | 0 | 2018-04-08T17:28:59 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,650 | thundernest/k-9/2025/1908 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1908 | https://github.com/thundernest/k-9/pull/2025 | https://github.com/thundernest/k-9/pull/2025 | 1 | fixes | Cannot zoom HTML messages properly if at all | ### Expected behavior
HTML mail should pinch zoom as it always has
### Actual behavior
In 5.201 I tried zooming a few HTML emails. Nether would pinch zoom (though double tapping made them a tiny bit bigger). At least once this led to a crash of the app.
I reverted to 5.010 and zoom works just fine with the same mail - in fact, it never had any such issue so I'm not upgrading until this is fixed.
### Steps to reproduce
Open html email e.g. from Xbox.com
Pinch zoom
Either nothing happens, it moves a tiny bit, or it ends up crashing.
### Environment
K-9 Mail version:
5.201 is broken for this. Works fine in 5.010
Android version:
7.0 on Nexus 6
IMAP
| 217c61430d55949316a645d23f24717f7bc098bb | c7c0ad0b7b77db1960dcf8956e54e549d9599644 | https://github.com/thundernest/k-9/compare/217c61430d55949316a645d23f24717f7bc098bb...c7c0ad0b7b77db1960dcf8956e54e549d9599644 | diff --git a/k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java b/k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java
index 5897c3b22..d97ec9ced 100644
--- a/k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java
+++ b/k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java
@@ -100,25 +100,14 @@ public class NonLockingScrollView extends ScrollView {
@Override
protected void onFinishInflate() {
super.onFinishInflate();
- excludeChildrenFromInterceptions(this);
+ setupDelegationOfTouchAndHierarchyChangeEvents();
}
-
- /**
- * Traverses the view tree for {@link WebView}s so they can be excluded from touch
- * interceptions and receive all events.
- */
- private void excludeChildrenFromInterceptions(View node) {
- // If additional types of children should be excluded (e.g. horizontal scrolling banners),
- // this needs to be modified accordingly.
- if (node instanceof WebView) {
- mChildrenNeedingAllTouches.add(node);
- } else if (node instanceof ViewGroup) {
- ViewGroup viewGroup = (ViewGroup) node;
- final int childCount = viewGroup.getChildCount();
- for (int i = 0; i < childCount; i++) {
- final View child = viewGroup.getChildAt(i);
- excludeChildrenFromInterceptions(child);
- }
+
+ private void setupDelegationOfTouchAndHierarchyChangeEvents() {
+ OnHierarchyChangeListener listener = new HierarchyTreeChangeListener();
+ setOnHierarchyChangeListener(listener);
+ for (int i = 0, childCount = getChildCount(); i < childCount; i++) {
+ listener.onChildViewAdded(this, getChildAt(i));
}
}
@@ -167,4 +156,32 @@ public class NonLockingScrollView extends ScrollView {
super.requestChildFocus(child, focused);
}
}
+
+ class HierarchyTreeChangeListener implements OnHierarchyChangeListener {
+ @Override
+ public void onChildViewAdded(View parent, View child) {
+ if (child instanceof WebView) {
+ mChildrenNeedingAllTouches.add(child);
+ } else if (child instanceof ViewGroup) {
+ ViewGroup childGroup = (ViewGroup) child;
+ childGroup.setOnHierarchyChangeListener(this);
+ for (int i = 0, childCount = childGroup.getChildCount(); i < childCount; i++) {
+ onChildViewAdded(childGroup, childGroup.getChildAt(i));
+ }
+ }
+ }
+
+ @Override
+ public void onChildViewRemoved(View parent, View child) {
+ if (child instanceof WebView) {
+ mChildrenNeedingAllTouches.remove(child);
+ } else if (child instanceof ViewGroup) {
+ ViewGroup childGroup = (ViewGroup) child;
+ for (int i = 0, childCount = childGroup.getChildCount(); i < childCount; i++) {
+ onChildViewRemoved(childGroup, childGroup.getChildAt(i));
+ }
+ childGroup.setOnHierarchyChangeListener(null);
+ }
+ }
+ }
} | ['k9mail/src/main/java/com/fsck/k9/view/NonLockingScrollView.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,455,680 | 685,885 | 94,555 | 423 | 2,536 | 481 | 53 | 1 | 681 | 124 | 170 | 22 | 0 | 0 | 2017-01-09T22:53:43 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,649 | thundernest/k-9/2037/1950 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1950 | https://github.com/thundernest/k-9/pull/2037 | https://github.com/thundernest/k-9/pull/2037 | 1 | fixes | Contact auto selecting first item | If there are "[email protected]" and "[email protected]" in my Contacts and i type "[email protected]" then app selects first entry from contacts and i cannot send email to "[email protected]". Previous versions allowed me type address and select one from suggestions if i want. Work around is to end the address with a comma & a space so new address object is created.
K-9 Mail version:
5.201
| 92196c012823b626d92e13349d160e8516e4abc2 | bb514f7140052ea9a0b85cb4ba34c275419c7013 | https://github.com/thundernest/k-9/compare/92196c012823b626d92e13349d160e8516e4abc2...bb514f7140052ea9a0b85cb4ba34c275419c7013 | 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 28ca83b25..bae224116 100644
--- a/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java
+++ b/k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java
@@ -229,14 +229,9 @@ public class RecipientSelectView extends TokenCompleteTextView<Recipient> implem
@Override
public void performCompletion() {
if (getListSelection() == ListView.INVALID_POSITION && enoughToFilter()) {
- Object bestGuess;
- if (getAdapter().getCount() > 0) {
- bestGuess = getAdapter().getItem(0);
- } else {
- bestGuess = defaultObject(currentCompletionText());
- }
- if (bestGuess != null) {
- replaceText(convertSelectionToString(bestGuess));
+ Object recipientText = defaultObject(currentCompletionText());
+ if (recipientText != null) {
+ replaceText(convertSelectionToString(recipientText));
}
} else {
super.performCompletion(); | ['k9mail/src/main/java/com/fsck/k9/view/RecipientSelectView.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,456,480 | 686,030 | 94,572 | 423 | 532 | 94 | 11 | 1 | 409 | 64 | 91 | 6 | 0 | 0 | 2017-01-10T23:04:20 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,600 | thundernest/k-9/4931/4914 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4914 | https://github.com/thundernest/k-9/pull/4931 | https://github.com/thundernest/k-9/pull/4931 | 1 | fixes | Wrong OpenPGP key used when sending signed-only email | I have recently noticed that if I set the sending of an email with the openpgp signature only option, I don't have the possibility to choose which identity to use. k9 v5.718 uses the first signature key available in openkeychain although it is not even that of the email from which I send. then an email is sent with the address xxx @ xxx signed by a yyyu @ yyy identity how to choose which signature key to use? I have no choices | 22cdb8c41fc58c865c853c6d7efc6db61724fbf0 | d718b33ef62c5b728a85ea563561f210aa1acfb3 | https://github.com/thundernest/k-9/compare/22cdb8c41fc58c865c853c6d7efc6db61724fbf0...d718b33ef62c5b728a85ea563561f210aa1acfb3 | diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java b/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
index a9e1ace70..66b261bed 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java
@@ -364,6 +364,7 @@ public class RecipientPresenter {
public void onSwitchIdentity(Identity identity) {
// TODO decide what actually to do on identity switch?
+ asyncUpdateCryptoStatus();
/*
if (mIdentityChanged) {
mBccWrapper.setVisibility(View.VISIBLE); | ['app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,740,265 | 540,532 | 76,542 | 417 | 35 | 6 | 1 | 1 | 433 | 83 | 102 | 1 | 0 | 0 | 2020-09-01T01:04:24 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,601 | thundernest/k-9/4921/4918 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4918 | https://github.com/thundernest/k-9/pull/4921 | https://github.com/thundernest/k-9/pull/4921 | 1 | fixes | Umlauts in encrypted headings | When I sent a mail with the heading "Test verschlüsselt", it after receiving it read "?ISO-8859-1?Q?Test_verschl=FCsselt_?=". | 753e03aa22a1f1d97e426f719de0844874ce7521 | bdbd8d98b2592d5dbf1e236ddeb81fd0dccb2444 | https://github.com/thundernest/k-9/compare/753e03aa22a1f1d97e426f719de0844874ce7521...bdbd8d98b2592d5dbf1e236ddeb81fd0dccb2444 | diff --git a/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java b/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java
index 3d902654e..4499e955b 100644
--- a/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java
+++ b/app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java
@@ -107,7 +107,7 @@ public class MessageViewInfoExtractor {
boolean hasProtectedSubject = "v1".equalsIgnoreCase(protectedHeadersParam) && protectedSubjectHeader.length > 0;
if (hasProtectedSubject) {
- return protectedSubjectHeader[0];
+ return MimeUtility.unfoldAndDecode(protectedSubjectHeader[0]);
}
return null; | ['app/core/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,785,395 | 549,471 | 77,730 | 424 | 122 | 23 | 2 | 1 | 126 | 16 | 42 | 1 | 0 | 0 | 2020-08-25T15:18:13 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,603 | thundernest/k-9/4795/4790 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4790 | https://github.com/thundernest/k-9/pull/4795 | https://github.com/thundernest/k-9/pull/4795 | 2 | fixes | Crash when attachment file is changed while TC document picker dialog is open | ### Expected behavior
error message "File not found"
or
Folder rescan when switching back to file picker (TC issue)
### Actual behavior
short glimpse of mail editor with attached file, then app crash
### Steps to reproduce
1. Compose mail
2. open file attachment dialog
3. select "Total Commander"
5. navigate to folder X
6. Switch to some file browser and rename file Y in folder X
7. Switch back to K-9, select file Y (under old filename), attach
- with "TotalCmd (file://url)" - nothing is attached
- same with Picasa
- stock album or "Simple Gallery" manage to attach the image anyway, but under a generic number
### Environment
K-9 Mail version:
5.6
Android version:
7.1.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:
[k9-log.txt](https://github.com/k9mail/k-9/files/4688569/k9-log.txt)
| b9eba6971fa86b95a4855caddbfa7144e5c23884 | a2287ce31cee3b6d229c782cc6cb00f6be0470d8 | https://github.com/thundernest/k-9/compare/b9eba6971fa86b95a4855caddbfa7144e5c23884...a2287ce31cee3b6d229c782cc6cb00f6be0470d8 | 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 1da4ce6e5..5c699dcf8 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
@@ -60,6 +60,13 @@ public class AttachmentContentLoader extends AsyncTaskLoader<Attachment> {
SafeContentResolver safeContentResolver = SafeContentResolver.newInstance(context);
InputStream in = safeContentResolver.openInputStream(sourceAttachment.uri);
+ if (in == null) {
+ Timber.w("Error opening attachment for reading: %s", sourceAttachment.uri);
+
+ cachedResultAttachment = sourceAttachment.deriveWithLoadCancelled();
+ return cachedResultAttachment;
+ }
+
try {
FileOutputStream out = new FileOutputStream(file);
try { | ['app/ui/legacy/src/main/java/com/fsck/k9/activity/loader/AttachmentContentLoader.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,831,249 | 558,404 | 78,943 | 423 | 276 | 46 | 7 | 1 | 947 | 135 | 246 | 32 | 2 | 0 | 2020-05-29T11:05:29 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,604 | thundernest/k-9/4743/4742 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4742 | https://github.com/thundernest/k-9/pull/4743 | https://github.com/thundernest/k-9/pull/4743 | 1 | fixes | when replying to a message, original message is not quoted | ### Expected behavior
upon selecting "reply" or "reply all", i expect the original email to be quoted in the compose message interface.
(this was also the previous behavior before i updated to 5.711)
### Actual behavior
the compose message interface is empty and looks like crafting a new message.
### Steps to reproduce
1. receive an email
2. reply to that email
### Environment
K-9 Mail version: 5.711
Android version: 10
Account type: imap
| 5a4a269926116a4f373699510bf868a848cdb8d8 | e830656d80c62f9d667a83aafde11cd1dc2d157c | https://github.com/thundernest/k-9/compare/5a4a269926116a4f373699510bf868a848cdb8d8...e830656d80c62f9d667a83aafde11cd1dc2d157c | 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 bae37949f..ef0f6eb1a 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
@@ -671,12 +671,6 @@ public class MessagingController {
notificationController.showAuthenticationErrorNotification(account, incoming);
}
- private static void closeFolder(LocalFolder f) {
- if (f != null) {
- f.close();
- }
- }
-
private void queuePendingCommand(Account account, PendingCommand command) {
try {
LocalStore localStore = localStoreProvider.getInstance(account);
@@ -756,74 +750,70 @@ public class MessagingController {
LocalStore localStore = localStoreProvider.getInstance(account);
long folderId = command.folderId;
LocalFolder localFolder = localStore.getFolder(folderId);
- try {
- localFolder.open();
-
- String folderServerId = localFolder.getServerId();
- String uid = command.uid;
+ localFolder.open();
- LocalMessage localMessage = localFolder.getMessage(uid);
- if (localMessage == null) {
- return;
- }
+ String folderServerId = localFolder.getServerId();
+ String uid = command.uid;
- if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) {
- //FIXME: This should never happen. Throw in debug builds.
- return;
- }
+ LocalMessage localMessage = localFolder.getMessage(uid);
+ if (localMessage == null) {
+ return;
+ }
- Backend backend = getBackend(account);
+ if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) {
+ //FIXME: This should never happen. Throw in debug builds.
+ return;
+ }
- if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) {
- Timber.w("Local message with uid %s has flag %s already set, checking for remote message with " +
- "same message id", localMessage.getUid(), X_REMOTE_COPY_STARTED);
+ Backend backend = getBackend(account);
- String messageServerId = backend.findByMessageId(folderServerId, localMessage.getMessageId());
- if (messageServerId != null) {
- Timber.w("Local message has flag %s already set, and there is a remote message with uid %s, " +
- "assuming message was already copied and aborting this copy",
- X_REMOTE_COPY_STARTED, messageServerId);
+ if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED)) {
+ Timber.w("Local message with uid %s has flag %s already set, checking for remote message with " +
+ "same message id", localMessage.getUid(), X_REMOTE_COPY_STARTED);
- String oldUid = localMessage.getUid();
- localMessage.setUid(messageServerId);
- localFolder.changeUid(localMessage);
+ String messageServerId = backend.findByMessageId(folderServerId, localMessage.getMessageId());
+ if (messageServerId != null) {
+ Timber.w("Local message has flag %s already set, and there is a remote message with uid %s, " +
+ "assuming message was already copied and aborting this copy",
+ X_REMOTE_COPY_STARTED, messageServerId);
- for (MessagingListener l : getListeners()) {
- l.messageUidChanged(account, folderId, oldUid, localMessage.getUid());
- }
+ String oldUid = localMessage.getUid();
+ localMessage.setUid(messageServerId);
+ localFolder.changeUid(localMessage);
- return;
- } else {
- Timber.w("No remote message with message-id found, proceeding with append");
+ for (MessagingListener l : getListeners()) {
+ l.messageUidChanged(account, folderId, oldUid, localMessage.getUid());
}
+
+ return;
+ } else {
+ Timber.w("No remote message with message-id found, proceeding with append");
}
+ }
- /*
- * If the message does not exist remotely we just upload it and then
- * update our local copy with the new uid.
- */
- FetchProfile fp = new FetchProfile();
- fp.add(FetchProfile.Item.BODY);
- localFolder.fetch(Collections.singletonList(localMessage), fp, null);
- String oldUid = localMessage.getUid();
- localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
+ /*
+ * If the message does not exist remotely we just upload it and then
+ * update our local copy with the new uid.
+ */
+ FetchProfile fp = new FetchProfile();
+ fp.add(FetchProfile.Item.BODY);
+ localFolder.fetch(Collections.singletonList(localMessage), fp, null);
+ String oldUid = localMessage.getUid();
+ localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
- String messageServerId = backend.uploadMessage(folderServerId, localMessage);
+ String messageServerId = backend.uploadMessage(folderServerId, localMessage);
- if (messageServerId == null) {
- // We didn't get the server UID of the uploaded message. Remove the local message now. The uploaded
- // version will be downloaded during the next sync.
- localFolder.destroyMessages(Collections.singletonList(localMessage));
- } else {
- localMessage.setUid(messageServerId);
- localFolder.changeUid(localMessage);
+ if (messageServerId == null) {
+ // We didn't get the server UID of the uploaded message. Remove the local message now. The uploaded
+ // version will be downloaded during the next sync.
+ localFolder.destroyMessages(Collections.singletonList(localMessage));
+ } else {
+ localMessage.setUid(messageServerId);
+ localFolder.changeUid(localMessage);
- for (MessagingListener l : getListeners()) {
- l.messageUidChanged(account, folderId, oldUid, localMessage.getUid());
- }
+ for (MessagingListener l : getListeners()) {
+ l.messageUidChanged(account, folderId, oldUid, localMessage.getUid());
}
- } finally {
- localFolder.close();
}
}
@@ -1012,26 +1002,21 @@ public class MessagingController {
LocalStore localStore = localStoreProvider.getInstance(account);
LocalFolder localFolder = localStore.getFolder(command.folderId);
- String folderServerId;
- try {
- localFolder.open();
- folderServerId = localFolder.getServerId();
+ localFolder.open();
+ String folderServerId = localFolder.getServerId();
- Timber.i("Marking all messages in %s:%s as read", account, folderServerId);
+ Timber.i("Marking all messages in %s:%s as read", account, folderServerId);
- // TODO: Make this one database UPDATE operation
- List<LocalMessage> messages = localFolder.getMessages(null, false);
- for (Message message : messages) {
- if (!message.isSet(Flag.SEEN)) {
- message.setFlag(Flag.SEEN, true);
- }
+ // TODO: Make this one database UPDATE operation
+ List<LocalMessage> messages = localFolder.getMessages(null, false);
+ for (Message message : messages) {
+ if (!message.isSet(Flag.SEEN)) {
+ message.setFlag(Flag.SEEN, true);
}
+ }
- for (MessagingListener l : getListeners()) {
- l.folderStatusChanged(account, folderServerId);
- }
- } finally {
- localFolder.close();
+ for (MessagingListener l : getListeners()) {
+ l.folderStatusChanged(account, folderServerId);
}
Backend backend = getBackend(account);
@@ -1137,10 +1122,9 @@ public class MessagingController {
public void setFlag(Account account, long folderId, List<LocalMessage> messages, Flag flag, boolean newState) {
// TODO: Put this into the background, but right now some callers depend on the message
// objects being modified right after this method returns.
- LocalFolder localFolder = null;
try {
LocalStore localStore = localStoreProvider.getInstance(account);
- localFolder = localStore.getFolder(folderId);
+ LocalFolder localFolder = localStore.getFolder(folderId);
localFolder.open();
// Update the messages in the local store
@@ -1163,8 +1147,6 @@ public class MessagingController {
processPendingCommands(account);
} catch (MessagingException me) {
throw new RuntimeException(me);
- } finally {
- closeFolder(localFolder);
}
}
@@ -1172,10 +1154,9 @@ public class MessagingController {
* Set or remove a flag for a message referenced by message UID.
*/
public void setFlag(Account account, long folderId, String uid, Flag flag, boolean newState) {
- LocalFolder localFolder = null;
try {
LocalStore localStore = localStoreProvider.getInstance(account);
- localFolder = localStore.getFolder(folderId);
+ LocalFolder localFolder = localStore.getFolder(folderId);
localFolder.open();
LocalMessage message = localFolder.getMessage(uid);
@@ -1184,8 +1165,6 @@ public class MessagingController {
}
} catch (MessagingException me) {
throw new RuntimeException(me);
- } finally {
- closeFolder(localFolder);
}
}
@@ -1214,10 +1193,9 @@ public class MessagingController {
private void loadMessageRemoteSynchronous(Account account, long folderId, String uid,
MessagingListener listener, boolean loadPartialFromSearch) {
- LocalFolder localFolder = null;
try {
LocalStore localStore = localStoreProvider.getInstance(account);
- localFolder = localStore.getFolder(folderId);
+ LocalFolder localFolder = localStore.getFolder(folderId);
localFolder.open();
String folderServerId = localFolder.getServerId();
@@ -1265,8 +1243,6 @@ public class MessagingController {
}
notifyUserIfCertificateProblem(account, e, true);
Timber.e(e, "Error while loading remote message");
- } finally {
- closeFolder(localFolder);
}
}
@@ -1284,7 +1260,6 @@ public class MessagingController {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(Collections.singletonList(message), fp, null);
- localFolder.close();
notificationController.removeNewMailNotification(account, message.makeMessageReference());
markMessageAsReadOnView(account, message);
@@ -1306,7 +1281,6 @@ public class MessagingController {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
localFolder.fetch(Collections.singletonList(message), fp, null);
- localFolder.close();
return message;
}
@@ -1328,12 +1302,11 @@ public class MessagingController {
put("loadAttachment", listener, new Runnable() {
@Override
public void run() {
- LocalFolder localFolder = null;
try {
String folderServerId = message.getFolder().getServerId();
LocalStore localStore = localStoreProvider.getInstance(account);
- localFolder = localStore.getFolder(folderServerId);
+ LocalFolder localFolder = localStore.getFolder(folderServerId);
ProgressBodyFactory bodyFactory = new ProgressBodyFactory(new ProgressListener() {
@Override
@@ -1359,8 +1332,6 @@ public class MessagingController {
l.loadAttachmentFailed(account, message, part, me.getMessage());
}
notifyUserIfCertificateProblem(account, me, true);
- } finally {
- closeFolder(localFolder);
}
}
});
@@ -1385,7 +1356,6 @@ public class MessagingController {
if (plaintextSubject != null) {
localMessage.setCachedDecryptedSubject(plaintextSubject);
}
- localFolder.close();
OutboxStateRepository outboxStateRepository = localStore.getOutboxStateRepository();
outboxStateRepository.initializeOutboxState(messageId);
@@ -1454,9 +1424,8 @@ public class MessagingController {
}
private boolean messagesPendingSend(final Account account) {
- LocalFolder localFolder = null;
try {
- localFolder = localStoreProvider.getInstance(account).getFolder(account.getOutboxFolderId());
+ LocalFolder localFolder = localStoreProvider.getInstance(account).getFolder(account.getOutboxFolderId());
if (!localFolder.exists()) {
return false;
}
@@ -1468,8 +1437,6 @@ public class MessagingController {
}
} catch (Exception e) {
Timber.e(e, "Exception while checking for unsent messages");
- } finally {
- closeFolder(localFolder);
}
return false;
}
@@ -1479,13 +1446,12 @@ public class MessagingController {
*/
@VisibleForTesting
protected void sendPendingMessagesSynchronous(final Account account) {
- LocalFolder localFolder = null;
Exception lastFailure = null;
boolean wasPermanentFailure = false;
try {
LocalStore localStore = localStoreProvider.getInstance(account);
OutboxStateRepository outboxStateRepository = localStore.getOutboxStateRepository();
- localFolder = localStore.getFolder(account.getOutboxFolderId());
+ LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderId());
if (!localFolder.exists()) {
Timber.v("Outbox does not exist");
return;
@@ -1614,7 +1580,6 @@ public class MessagingController {
if (lastFailure == null) {
notificationController.clearSendFailedNotification(account);
}
- closeFolder(localFolder);
}
}
@@ -1885,7 +1850,6 @@ public class MessagingController {
}
public void deleteDraft(final Account account, long id) {
- LocalFolder localFolder = null;
try {
Long folderId = account.getDraftsFolderId();
if (folderId == null) {
@@ -1894,7 +1858,7 @@ public class MessagingController {
}
LocalStore localStore = localStoreProvider.getInstance(account);
- localFolder = localStore.getFolder(folderId);
+ LocalFolder localFolder = localStore.getFolder(folderId);
localFolder.open();
String uid = localFolder.getMessageUidById(id);
if (uid != null) {
@@ -1903,8 +1867,6 @@ public class MessagingController {
}
} catch (MessagingException me) {
Timber.e(me, "Error deleting draft");
- } finally {
- closeFolder(localFolder);
}
}
@@ -2007,8 +1969,6 @@ public class MessagingController {
private void deleteMessagesSynchronous(final Account account, final String folder,
final List<LocalMessage> messages,
MessagingListener listener) {
- LocalFolder localFolder = null;
- LocalFolder localTrashFolder = null;
try {
List<LocalMessage> localOnlyMessages = new ArrayList<>();
List<LocalMessage> syncedMessages = new ArrayList<>();
@@ -2026,12 +1986,13 @@ public class MessagingController {
Backend backend = getBackend(account);
LocalStore localStore = localStoreProvider.getInstance(account);
- localFolder = localStore.getFolder(folder);
+ LocalFolder localFolder = localStore.getFolder(folder);
localFolder.open();
long folderId = localFolder.getDatabaseId();
Map<String, String> uidMap = null;
Long trashFolderId = account.getTrashFolderId();
+ LocalFolder localTrashFolder = null;
if (!account.hasTrashFolder() || folderId == trashFolderId ||
(backend.getSupportsTrashFolder() && !backend.isDeleteMoveToTrash())) {
Timber.d("Not moving deleted messages to local Trash folder. Removing local copies.");
@@ -2097,9 +2058,6 @@ public class MessagingController {
throw new UnavailableAccountException(e);
} catch (MessagingException me) {
throw new RuntimeException("Error deleting message from local store.", me);
- } finally {
- closeFolder(localFolder);
- closeFolder(localTrashFolder);
}
}
@@ -2139,7 +2097,6 @@ public class MessagingController {
putBackground("emptyTrash", listener, new Runnable() {
@Override
public void run() {
- LocalFolder localFolder = null;
try {
Long trashFolderId = account.getTrashFolderId();
if (trashFolderId == null) {
@@ -2148,7 +2105,7 @@ public class MessagingController {
}
LocalStore localStore = localStoreProvider.getInstance(account);
- localFolder = localStore.getFolder(trashFolderId);
+ LocalFolder localFolder = localStore.getFolder(trashFolderId);
localFolder.open();
String trashFolderServerId = localFolder.getServerId();
@@ -2174,8 +2131,6 @@ public class MessagingController {
throw new UnavailableAccountException(e);
} catch (Exception e) {
Timber.e(e, "emptyTrash failed");
- } finally {
- closeFolder(localFolder);
}
}
});
@@ -2189,9 +2144,8 @@ public class MessagingController {
@VisibleForTesting
protected void clearFolderSynchronous(Account account, long folderId) {
- LocalFolder localFolder = null;
try {
- localFolder = localStoreProvider.getInstance(account).getFolder(folderId);
+ LocalFolder localFolder = localStoreProvider.getInstance(account).getFolder(folderId);
localFolder.open();
localFolder.clearAllMessages();
} catch (UnavailableStorageException e) {
@@ -2199,8 +2153,6 @@ public class MessagingController {
throw new UnavailableAccountException(e);
} catch (Exception e) {
Timber.e(e, "clearFolder failed");
- } finally {
- closeFolder(localFolder);
}
}
diff --git a/app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java b/app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java
index f3c797d1e..413f2f80b 100644
--- a/app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java
+++ b/app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java
@@ -60,7 +60,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -324,10 +323,6 @@ public class LocalFolder {
boolean integrate = isIntegrate;
}
- public void close() {
- databaseId = -1;
- }
-
public int getMessageCount() throws MessagingException {
try {
return this.localStore.getDatabase().execute(false, new DbCallback<Integer>() {
diff --git a/app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java b/app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java
index f7d1df7d1..9aede2d19 100644
--- a/app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java
+++ b/app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java
@@ -196,7 +196,6 @@ public class RawMessageProvider extends ContentProvider {
FetchProfile fetchProfile = new FetchProfile();
fetchProfile.add(FetchProfile.Item.BODY);
localFolder.fetch(Collections.singletonList(message), fetchProfile, null);
- localFolder.close();
return message;
} catch (MessagingException e) {
diff --git a/app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java b/app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java
index d281594b4..895ca05ac 100644
--- a/app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java
+++ b/app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java
@@ -170,13 +170,6 @@ public class MessagingControllerTest extends K9RobolectricTest {
verify(localFolder).clearAllMessages();
}
- @Test
- public void clearFolderSynchronous_shouldCloseTheFolder() throws MessagingException {
- controller.clearFolderSynchronous(account, FOLDER_ID);
-
- verify(localFolder, atLeastOnce()).close();
- }
-
@Test(expected = UnavailableAccountException.class)
public void clearFolderSynchronous_whenStorageUnavailable_shouldThrowUnavailableAccountException() throws MessagingException {
doThrow(new UnavailableStorageException("Test")).when(localFolder).open();
@@ -184,18 +177,6 @@ public class MessagingControllerTest extends K9RobolectricTest {
controller.clearFolderSynchronous(account, FOLDER_ID);
}
- @Test()
- public void clearFolderSynchronous_whenExceptionThrown_shouldStillCloseFolder() throws MessagingException {
- doThrow(new RuntimeException("Test")).when(localFolder).open();
-
- try {
- controller.clearFolderSynchronous(account, FOLDER_ID);
- } catch (Exception ignored){
- }
-
- verify(localFolder, atLeastOnce()).close();
- }
-
@Test
public void refreshRemoteSynchronous_shouldCallBackend() throws MessagingException {
controller.refreshFolderListSynchronous(account); | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java', 'app/core/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java', 'app/core/src/main/java/com/fsck/k9/mailstore/LocalFolder.java', 'app/core/src/main/java/com/fsck/k9/provider/RawMessageProvider.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 2,834,763 | 558,975 | 79,051 | 424 | 10,104 | 1,850 | 196 | 3 | 473 | 74 | 104 | 22 | 0 | 0 | 2020-05-08T17:52:19 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,606 | thundernest/k-9/4702/4100 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4100 | https://github.com/thundernest/k-9/pull/4702 | https://github.com/thundernest/k-9/pull/4702 | 1 | fixes | Remove placeholder in database when message deletion on server is finished | The "Clear messages (Dangerous!)" option in mailbox action popup menu suggests that ALL messages are deleted (either for privacy or to recreate corrupted mail-queue). However the placeholders are not deleted - exposing potentially sensitive information about deleted conversations.
I dont know if the clear() method here is used only by "Remove messages (dangerous!)" sub-menu so I decided to open an issue rather than simply removing "deleted = 0" from here:
https://github.com/k9mail/k-9/blob/c053964fefe1c758251aeab902563f8ec7dc454c/app/core/src/main/java/com/fsck/k9/mailstore/LocalStore.java#L327 | 447dbe1bf0c977e6bab0d03659a5807586ad2da4 | d33643ba99aa50b2d5de5c37e2afe327e910a9ed | https://github.com/thundernest/k-9/compare/447dbe1bf0c977e6bab0d03659a5807586ad2da4...d33643ba99aa50b2d5de5c37e2afe327e910a9ed | 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 13a25745f..1c6dfe0a9 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
@@ -40,6 +40,7 @@ import com.fsck.k9.K9.Intents;
import com.fsck.k9.Preferences;
import com.fsck.k9.backend.BackendManager;
import com.fsck.k9.backend.api.Backend;
+import com.fsck.k9.backend.api.BuildConfig;
import com.fsck.k9.backend.api.SyncConfig;
import com.fsck.k9.backend.api.SyncListener;
import com.fsck.k9.cache.EmailProviderCache;
@@ -881,10 +882,13 @@ public class MessagingController {
throw new RuntimeException("Unsupported messaging operation");
}
- if (operation != MoveOrCopyFlavor.COPY && backend.getSupportsExpunge()
- && account.getExpungePolicy() == Expunge.EXPUNGE_IMMEDIATELY) {
- Timber.i("processingPendingMoveOrCopy expunging folder %s:%s", account.getDescription(), srcFolderServerId);
- backend.expungeMessages(srcFolderServerId, uids);
+ if (operation != MoveOrCopyFlavor.COPY) {
+ if (backend.getSupportsExpunge() && account.getExpungePolicy() == Expunge.EXPUNGE_IMMEDIATELY) {
+ Timber.i("processingPendingMoveOrCopy expunging folder %s:%s", account.getDescription(), srcFolderServerId);
+ backend.expungeMessages(srcFolderServerId, uids);
+ }
+
+ destroyPlaceholderMessages(localSourceFolder, uids);
}
// TODO: Change Backend interface to ensure we never receive null for remoteUidMap
@@ -917,6 +921,26 @@ public class MessagingController {
}
}
+ private void destroyPlaceholderMessages(LocalFolder localFolder, List<String> uids) throws MessagingException {
+ for (String uid : uids) {
+ LocalMessage placeholderMessage = localFolder.getMessage(uid);
+ if (placeholderMessage == null) {
+ continue;
+ }
+
+ if (placeholderMessage.isSet(Flag.DELETED)) {
+ placeholderMessage.destroy();
+ } else {
+ Timber.w("Expected local message %s in folder %s to be a placeholder, but DELETE flag wasn't set",
+ uid, localFolder.getServerId());
+
+ if (BuildConfig.DEBUG) {
+ throw new AssertionError("Placeholder message must have the DELETED flag set");
+ }
+ }
+ }
+ }
+
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); | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,838,565 | 559,204 | 79,086 | 425 | 1,647 | 326 | 32 | 1 | 607 | 71 | 141 | 5 | 1 | 0 | 2020-04-27T10:05:14 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,608 | thundernest/k-9/4686/4678 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/4678 | https://github.com/thundernest/k-9/pull/4686 | https://github.com/thundernest/k-9/pull/4686 | 1 | fixes | POP3: trash folder remains empty | Hi,
When i delete a mail, the trash folder remains empty
[log.txt](https://github.com/k9mail/k-9/files/4505545/log.txt)
### Expected behavior
Deleted mail should be found in the trash folder
### Actual behavior
No mail is found in the trash folder
### Steps to reproduce
1. delete a mail
2. go to the trash folder
3. see if the deleted mail is in the folder
### Environment
K-9 Mail version: 5.708
Android version: 10
Account type (IMAP, POP3, WebDAV/Exchange): pop3
| 2530dea98acd8df04bbcac37c6451fe27df111db | d1c3cca21373ba79eed444c654660097668f9d46 | https://github.com/thundernest/k-9/compare/2530dea98acd8df04bbcac37c6451fe27df111db...d1c3cca21373ba79eed444c654660097668f9d46 | 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 337b8c54a..785bd60e5 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
@@ -2034,7 +2034,7 @@ public class MessagingController {
localFolder = localStore.getFolder(folder);
Map<String, String> uidMap = null;
if (folder.equals(account.getTrashFolder()) || !account.hasTrashFolder() ||
- !backend.isDeleteMoveToTrash()) {
+ (backend.getSupportsTrashFolder() && !backend.isDeleteMoveToTrash())) {
Timber.d("Not moving deleted messages to local Trash folder. Removing local copies.");
if (!localOnlyMessages.isEmpty()) { | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,835,761 | 558,523 | 78,991 | 418 | 147 | 29 | 2 | 1 | 496 | 74 | 132 | 23 | 1 | 0 | 2020-04-23T19:02:20 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,609 | thundernest/k-9/4683/2705 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2705 | https://github.com/thundernest/k-9/pull/4683 | https://github.com/thundernest/k-9/pull/4683 | 1 | fixes | Deleted mail from inbox is doubled in trash directory | 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 deleting one or more mails from inbox, I expect every deleted mail one time in trash directory.
### Actual behavior
When deleting one or more mails from inbox, every deleted mail exist in trash two times.
### Steps to reproduce
1. Wait for incomaing mail (or send a test mail)
2. Delete a mail from inbox using symbol 'trash can' on left bottom.
3. Change to 'trash' directory.
In first moment the deleted mail appears only one time. After short time the deleted mail appears a
second time in trash directory.
After manually syncing the doubled mail disappears - the mail is only shown one time.
### Environment
K-9 Mail version: 5.207
I use the same email account with thunderbird on my desktop pc. These problems do not occur
using thunderbird on pc.
Android version: 7.0.0
Account type (IMAP, POP3, WebDAV/Exchange):
It is an IMAP Account.
| 2530dea98acd8df04bbcac37c6451fe27df111db | 2dccbb7c480a0e6435580533b6f0caefc177e7aa | https://github.com/thundernest/k-9/compare/2530dea98acd8df04bbcac37c6451fe27df111db...2dccbb7c480a0e6435580533b6f0caefc177e7aa | 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 337b8c54a..1e49338d9 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
@@ -89,6 +89,7 @@ import timber.log.Timber;
import static com.fsck.k9.K9.MAX_SEND_ATTEMPTS;
import static com.fsck.k9.helper.ExceptionHelper.getRootCauseMessage;
+import static com.fsck.k9.helper.Preconditions.checkNotNull;
import static com.fsck.k9.mail.Flag.X_REMOTE_COPY_STARTED;
import static com.fsck.k9.search.LocalSearchExtensions.getAccountsFromLocalSearch;
@@ -843,10 +844,10 @@ public class MessagingController {
@VisibleForTesting
void processPendingMoveOrCopy(Account account, String srcFolder, String destFolder, List<String> uids,
MoveOrCopyFlavor operation, Map<String, String> newUidMap) throws MessagingException {
- LocalFolder localDestFolder;
+ checkNotNull(newUidMap);
LocalStore localStore = localStoreProvider.getInstance(account);
- localDestFolder = localStore.getFolder(destFolder);
+ LocalFolder localDestFolder = localStore.getFolder(destFolder);
Backend backend = getBackend(account);
@@ -871,28 +872,32 @@ public class MessagingController {
backend.expungeMessages(srcFolder, uids);
}
- /*
- * This next part is used to bring the local UIDs of the local destination folder
- * upto speed with the remote UIDs of remote destination folder.
- */
- if (newUidMap != null && remoteUidMap != null && !remoteUidMap.isEmpty()) {
- Timber.i("processingPendingMoveOrCopy: changing local uids of %d messages", remoteUidMap.size());
- for (Entry<String, String> entry : remoteUidMap.entrySet()) {
- String remoteSrcUid = entry.getKey();
- String newUid = entry.getValue();
- String localDestUid = newUidMap.get(remoteSrcUid);
- if (localDestUid == null) {
- continue;
- }
+ // TODO: Change Backend interface to ensure we never receive null for remoteUidMap
+ if (remoteUidMap == null) {
+ remoteUidMap = Collections.emptyMap();
+ }
- Message localDestMessage = localDestFolder.getMessage(localDestUid);
- if (localDestMessage != null) {
- localDestMessage.setUid(newUid);
- localDestFolder.changeUid((LocalMessage) localDestMessage);
- for (MessagingListener l : getListeners()) {
- l.messageUidChanged(account, destFolder, localDestUid, newUid);
- }
+ // Update local messages (that currently have local UIDs) with new server IDs
+ for (String uid : uids) {
+ String localUid = newUidMap.get(uid);
+ String newUid = remoteUidMap.get(uid);
+
+ LocalMessage localMessage = localDestFolder.getMessage(localUid);
+ if (localMessage == null) {
+ // Local message no longer exists
+ continue;
+ }
+
+ if (newUid != null) {
+ // Update local message with new server ID
+ localMessage.setUid(newUid);
+ localDestFolder.changeUid(localMessage);
+ for (MessagingListener l : getListeners()) {
+ l.messageUidChanged(account, destFolder, localUid, newUid);
}
+ } else {
+ // New server ID wasn't provided. Remove local message.
+ localMessage.destroy();
}
}
} | ['app/core/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,835,761 | 558,523 | 78,991 | 418 | 2,557 | 484 | 49 | 1 | 1,116 | 177 | 259 | 27 | 1 | 0 | 2020-04-23T02:02:56 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,643 | thundernest/k-9/2862/2856 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2856 | https://github.com/thundernest/k-9/pull/2862 | https://github.com/thundernest/k-9/pull/2862 | 1 | fixes | 5.301 plain-text body rendering issues | It appears that somewhere between 5.208 and 5.301 some issues were
introduced in the rendering the body of (single-part) plain-text messages.
For instance, a message that ends with:
Davide
------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot
_______________________________________________
Bacula-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/bacula-users
is displayed in 5.301 as:
DavideCheck out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdotBacula-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/bacula-users
If I forward the message from a 5.301 client the bottom text block is displayed correctly in the draft.
There additionally appears to be a problem with hyperlinking. If the "http://" or "https://"" starts in column one it is not hyperlinked. If it starts in column 2+ it is.
In 5.208 the message renders correctly and all "http://" and "https://" urls are hyperlinked regardless of their column start position.
| 27bc562ebe37bc139b84c13142681dbfe5640688 | 77f821cbbe5b6e01742fd8ba8f556a735b0e818a | https://github.com/thundernest/k-9/compare/27bc562ebe37bc139b84c13142681dbfe5640688...77f821cbbe5b6e01742fd8ba8f556a735b0e818a | diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
index 1b9cbf737..fc74be844 100644
--- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
+++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
@@ -13,7 +13,7 @@ public class HtmlSanitizer {
HtmlSanitizer() {
Whitelist whitelist = Whitelist.relaxed()
- .addTags("font")
+ .addTags("font", "hr")
.addAttributes("table", "align", "bgcolor", "border", "cellpadding", "cellspacing", "width")
.addAttributes(":all", "class", "style", "id")
.addProtocols("img", "src", "http", "https", "cid", "data");
diff --git a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java
index 23714a4e8..f4b86c2a1 100644
--- a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java
@@ -158,4 +158,13 @@ public class HtmlSanitizerTest {
"<tr><td>Hmailserver service shutdown:</td><td>Ok</td></tr>" +
"</tbody></table></body></html>", toCompactString(result));
}
+
+ @Test
+ public void shouldKeepHrTags() throws Exception {
+ String html = "<html><head></head><body>one<hr>two<hr />three</body></html>";
+
+ Document result = htmlSanitizer.sanitize(html);
+
+ assertEquals("<html><head></head><body>one<hr>two<hr>three</body></html>", toCompactString(result));
+ }
} | ['k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,600,094 | 707,876 | 98,981 | 484 | 73 | 17 | 2 | 1 | 1,342 | 148 | 282 | 29 | 4 | 0 | 2017-10-25T02:53:39 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,642 | thundernest/k-9/2863/2861 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2861 | https://github.com/thundernest/k-9/pull/2863 | https://github.com/thundernest/k-9/pull/2863 | 1 | fixes | URL at the beginning of a line in plain text body isn't linkified | This happens because we first convert the plain text to HTML and end up with something like:
```html
<br>http://uri.example.org<br>
```
But right now only supported schemes preceded by a space, a newline, or an opening parenthesis are candidates for linkifying.
https://github.com/k9mail/k-9/blob/27bc562ebe37bc139b84c13142681dbfe5640688/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java#L16 | 27bc562ebe37bc139b84c13142681dbfe5640688 | 2e20ddf6a5a5783ee483a5070eadf4c8b98a1ee2 | https://github.com/thundernest/k-9/compare/27bc562ebe37bc139b84c13142681dbfe5640688...2e20ddf6a5a5783ee483a5070eadf4c8b98a1ee2 | diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java b/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java
index 815acc5ce..3d2565f27 100644
--- a/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java
+++ b/k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java
@@ -13,7 +13,7 @@ import android.text.TextUtils;
public class UriLinkifier {
private static final Pattern URI_SCHEME;
private static final Map<String, UriParser> SUPPORTED_URIS;
- private static final String SCHEME_SEPARATORS = " (\\\\n";
+ private static final String SCHEME_SEPARATORS = " (\\\\n>";
private static final String ALLOWED_SEPARATORS_PATTERN = "(?:^|[" + SCHEME_SEPARATORS + "])";
static {
diff --git a/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java
index 3b02dc035..81abbbb34 100644
--- a/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java
@@ -136,4 +136,13 @@ public class UriLinkifierTest {
"<a href=\\"http://uri2.example.org/path\\">http://uri2.example.org/path</a> postfix",
outputBuffer.toString());
}
+
+ @Test
+ public void uriSurroundedByHtmlTags() {
+ String text = "<br>http://uri.example.org<hr>";
+
+ UriLinkifier.linkifyText(text, outputBuffer);
+
+ assertEquals("<br><a href=\\"http://uri.example.org\\">http://uri.example.org</a><hr>", outputBuffer.toString());
+ }
} | ['k9mail/src/test/java/com/fsck/k9/message/html/UriLinkifierTest.java', 'k9mail/src/main/java/com/fsck/k9/message/html/UriLinkifier.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,600,094 | 707,876 | 98,981 | 484 | 124 | 32 | 2 | 1 | 416 | 41 | 108 | 9 | 2 | 1 | 2017-10-25T03:01:37 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,648 | thundernest/k-9/2203/2143 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2143 | https://github.com/thundernest/k-9/pull/2203 | https://github.com/thundernest/k-9/pull/2203 | 1 | fixes | Clear local messages -> freeze | ### Expected behavior
"Clear local messages" should clear the locally stored messages, allowing one to re-download the messages from the server.
### Actual behavior
Freeze.
### Steps to reproduce
1. Have a folder with some large amount of messages. A few hundred should suffice.
2. Make sure it's NOT up-to-date with the server
3. Clear its local messages.
### Environment
K-9 Mail version: 5.203
Android version: 6.0.1
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| c150bafac3aa1137376af532bba1b13dfac85fd2 | 4161b914415aef08ab645387893812d13356bda3 | https://github.com/thundernest/k-9/compare/c150bafac3aa1137376af532bba1b13dfac85fd2...4161b914415aef08ab645387893812d13356bda3 | diff --git a/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java b/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java
index 4235018bf..203b6eb54 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/FolderList.java
@@ -476,31 +476,9 @@ public class FolderList extends K9ListActivity {
}
private void onClearFolder(Account account, String folderName) {
- // There has to be a cheaper way to get at the localFolder object than this
- LocalFolder localFolder = null;
- try {
- if (account == null || folderName == null || !account.isAvailable(FolderList.this)) {
- Log.i(K9.LOG_TAG, "not clear folder of unavailable account");
- return;
- }
- localFolder = account.getLocalStore().getFolder(folderName);
- localFolder.open(Folder.OPEN_MODE_RW);
- localFolder.clearAllMessages();
- } catch (Exception e) {
- Log.e(K9.LOG_TAG, "Exception while clearing folder", e);
- } finally {
- if (localFolder != null) {
- localFolder.close();
- }
- }
-
- onRefresh(!REFRESH_REMOTE);
+ MessagingController.getInstance(getApplication()).clearFolder(account, folderName, mAdapter.mListener);
}
-
-
-
-
private void sendMail(Account account) {
MessagingController.getInstance(getApplication()).sendPendingMessages(account, mAdapter.mListener);
}
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 3f0af1a22..51d1d8a23 100644
--- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java
+++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java
@@ -53,6 +53,7 @@ import com.fsck.k9.K9;
import com.fsck.k9.K9.Intents;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
+import com.fsck.k9.activity.ActivityListener;
import com.fsck.k9.activity.MessageReference;
import com.fsck.k9.activity.setup.AccountSetupCheckSettings.CheckDirection;
import com.fsck.k9.cache.EmailProviderCache;
@@ -3513,6 +3514,36 @@ public class MessagingController {
});
}
+ public void clearFolder(final Account account, final String folderName, final ActivityListener listener) {
+ putBackground("clearFolder", listener, new Runnable() {
+ @Override
+ public void run() {
+ clearFolderSynchronous(account, folderName, listener);
+ }
+ });
+ }
+
+ @VisibleForTesting
+ protected void clearFolderSynchronous(Account account, String folderName, MessagingListener listener) {
+ LocalFolder localFolder = null;
+ try {
+ localFolder = account.getLocalStore().getFolder(folderName);
+ localFolder.open(Folder.OPEN_MODE_RW);
+ localFolder.clearAllMessages();
+ } catch (UnavailableStorageException e) {
+ Log.i(K9.LOG_TAG, "Failed to clear folder because storage is not available - trying again later.");
+ throw new UnavailableAccountException(e);
+ } catch (Exception e) {
+ Log.e(K9.LOG_TAG, "clearFolder failed", e);
+ addErrorMessage(account, null, e);
+ } finally {
+ closeFolder(localFolder);
+ }
+
+ listFoldersSynchronous(account, false, listener);
+ }
+
+
/**
* Find out whether the account type only supports a local Trash folder.
*
diff --git a/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java b/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java
index e0254d7a1..8429a6cea 100644
--- a/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java
@@ -13,6 +13,7 @@ import android.content.Context;
import com.fsck.k9.Account;
import com.fsck.k9.AccountStats;
+import com.fsck.k9.K9;
import com.fsck.k9.K9RobolectricTestRunner;
import com.fsck.k9.Preferences;
import com.fsck.k9.helper.Contacts;
@@ -26,6 +27,7 @@ import com.fsck.k9.mail.Store;
import com.fsck.k9.mailstore.LocalFolder;
import com.fsck.k9.mailstore.LocalMessage;
import com.fsck.k9.mailstore.LocalStore;
+import com.fsck.k9.mailstore.UnavailableStorageException;
import com.fsck.k9.notification.NotificationController;
import com.fsck.k9.search.LocalSearch;
import org.junit.After;
@@ -51,6 +53,7 @@ import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -80,6 +83,8 @@ public class MessagingControllerTest {
@Mock
private LocalFolder localFolder;
@Mock
+ private LocalFolder errorFolder;
+ @Mock
private Folder remoteFolder;
@Mock
private LocalStore localStore;
@@ -130,6 +135,62 @@ public class MessagingControllerTest {
controller.stop();
}
+ @Test
+ public void clearFolderSynchronous_shouldOpenFolderForWriting() throws MessagingException {
+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);
+
+ verify(localFolder).open(Folder.OPEN_MODE_RW);
+ }
+
+ @Test
+ public void clearFolderSynchronous_shouldClearAllMessagesInTheFolder() throws MessagingException {
+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);
+
+ verify(localFolder).clearAllMessages();
+ }
+
+ @Test
+ public void clearFolderSynchronous_shouldCloseTheFolder() throws MessagingException {
+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);
+
+ verify(localFolder, atLeastOnce()).close();
+ }
+
+ @Test(expected = UnavailableAccountException.class)
+ public void clearFolderSynchronous_whenStorageUnavailable_shouldThrowUnavailableAccountException() throws MessagingException {
+ doThrow(new UnavailableStorageException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW);
+
+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);
+ }
+
+ @Test()
+ public void clearFolderSynchronous_whenExceptionThrown_shouldAddErrorMessage() throws MessagingException {
+ doThrow(new RuntimeException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW);
+
+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);
+
+ verify(errorFolder).appendMessages(any(List.class));
+ }
+
+ @Test()
+ public void clearFolderSynchronous_whenExceptionThrown_shouldStillCloseFolder() throws MessagingException {
+ doThrow(new RuntimeException("Test")).when(localFolder).open(Folder.OPEN_MODE_RW);
+
+ try {
+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);
+ } catch (Exception ignored){
+ }
+
+ verify(localFolder, atLeastOnce()).close();
+ }
+
+ @Test()
+ public void clearFolderSynchronous_shouldListFolders() throws MessagingException {
+ controller.clearFolderSynchronous(account, FOLDER_NAME, listener);
+
+ verify(listener, atLeastOnce()).listFoldersStarted(account);
+ }
+
@Test
public void listFoldersSynchronous_shouldNotifyTheListenerListingStarted() throws MessagingException {
List<LocalFolder> folders = Collections.singletonList(localFolder);
@@ -758,11 +819,15 @@ public class MessagingControllerTest {
when(account.getLocalStore()).thenReturn(localStore);
when(account.getStats(any(Context.class))).thenReturn(accountStats);
when(account.getMaximumAutoDownloadMessageSize()).thenReturn(MAXIMUM_SMALL_MESSAGE_SIZE);
+ when(account.getErrorFolderName()).thenReturn(K9.ERROR_FOLDER_NAME);
+ when(account.getEmail()).thenReturn("[email protected]");
}
- private void configureLocalStore() {
+ private void configureLocalStore() throws MessagingException {
when(localStore.getFolder(FOLDER_NAME)).thenReturn(localFolder);
when(localFolder.getName()).thenReturn(FOLDER_NAME);
+ when(localStore.getFolder(K9.ERROR_FOLDER_NAME)).thenReturn(errorFolder);
+ when(localStore.getPersonalNamespaces(false)).thenReturn(Collections.singletonList(localFolder));
}
private void configureRemoteStoreWithFolder() throws MessagingException { | ['k9mail/src/main/java/com/fsck/k9/activity/FolderList.java', 'k9mail/src/test/java/com/fsck/k9/controller/MessagingControllerTest.java', 'k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,476,576 | 690,051 | 95,154 | 439 | 2,165 | 412 | 55 | 2 | 491 | 73 | 120 | 18 | 0 | 0 | 2017-02-07T21:38:13 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,636 | thundernest/k-9/3174/2164 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2164 | https://github.com/thundernest/k-9/pull/3174 | https://github.com/thundernest/k-9/pull/3174 | 1 | fixes | Drafts deleted when syncronizing with IMAP server | 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 "Save as Draft" is selected, draft should be remain saved either locally or on the server for future access.
### Actual behavior
Either draft is automatically completely deleted and no longer available upon server sync, or the draft remains in the "drafts" folder but when opening the compose window, the text is no longer available. It seems this is dependent on the encryption setting; everytime I re-open the draft I have to re-select "Don't encrypt" because the default is always "encrypt if possible". The last selection should be remembered. If "encypt if possible" or "encrypt" is selected, the draft is deleted upon sync. If not, I can often no longer access the draft text. This happens regardless of account, and only started after upgrading to the latest K9 version and adding my keys to OpenKeychain (I was using a much older version of K9 prior to this, not sure which).
### Steps to reproduce
1. Create a draft email with text in the body.
2. Select "don't encrypt"
3. Save draft by selecting either "save draft" or by pressing back and "save draft".
4. Text is gone after server sync.
OR
1. Create a draft email with text in the body.
2. Select "encrypt" or "encrypt if possible".
3. Save draft by selecting either "save draft" or by pressing back and "save draft".
4. Draft is gone after server sync.
### Environment
K-9 Mail version: 5.203
Android version: 5.1.1
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| 3009752cac4a0f7ea6341bbef01e41cf4ab27963 | f4147483e14bc42c7544a6336b2e40d34b43ebb4 | https://github.com/thundernest/k-9/compare/3009752cac4a0f7ea6341bbef01e41cf4ab27963...f4147483e14bc42c7544a6336b2e40d34b43ebb4 | 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 0f42badfa..718c6efe1 100644
--- a/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java
+++ b/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java
@@ -898,7 +898,7 @@ public class MessagingController {
if (account.syncRemoteDeletions()) {
List<String> destroyMessageUids = new ArrayList<>();
for (String localMessageUid : localUidMap.keySet()) {
- if (remoteUidMap.get(localMessageUid) == null) {
+ if (!localMessageUid.startsWith(K9.LOCAL_UID_PREFIX) && remoteUidMap.get(localMessageUid) == null) {
destroyMessageUids.add(localMessageUid);
}
}
@@ -1761,9 +1761,15 @@ public class MessagingController {
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(Collections.singletonList(localMessage));
- localFolder.changeUid(localMessage);
- for (MessagingListener l : getListeners()) {
- l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
+ if (localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) {
+ // We didn't get the server UID of the uploaded message. Remove the local message now. The uploaded
+ // version will be downloaded during the next sync.
+ localFolder.destroyMessages(Collections.singletonList(localMessage));
+ } else {
+ localFolder.changeUid(localMessage);
+ for (MessagingListener l : getListeners()) {
+ l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
+ }
}
} else {
/*
@@ -1796,10 +1802,17 @@ public class MessagingController {
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(Collections.singletonList(localMessage));
- localFolder.changeUid(localMessage);
- for (MessagingListener l : getListeners()) {
- l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
+ if (localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX)) {
+ // We didn't get the server UID of the uploaded message. Remove the local message now. The
+ // uploaded version will be downloaded during the next sync.
+ localFolder.destroyMessages(Collections.singletonList(localMessage));
+ } else {
+ localFolder.changeUid(localMessage);
+ for (MessagingListener l : getListeners()) {
+ l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
+ }
}
+
if (remoteDate != null) {
remoteMessage.setFlag(Flag.DELETED, true);
if (Expunge.EXPUNGE_IMMEDIATELY == account.getExpungePolicy()) {
@@ -3172,9 +3185,8 @@ public class MessagingController {
private void deleteMessagesSynchronous(final Account account, final String folder,
final List<? extends Message> messages,
MessagingListener listener) {
- Folder localFolder = null;
- Folder localTrashFolder = null;
- List<String> uids = getUidsFromMessages(messages);
+ LocalFolder localFolder = null;
+ LocalFolder localTrashFolder = null;
try {
//We need to make these callbacks before moving the messages to the trash
//as messages get a new UID after being moved
@@ -3183,13 +3195,32 @@ public class MessagingController {
l.messageDeleted(account, folder, message);
}
}
- Store localStore = account.getLocalStore();
+
+ List<Message> localOnlyMessages = new ArrayList<>();
+ List<Message> syncedMessages = new ArrayList<>();
+ List<String> syncedMessageUids = new ArrayList<>();
+ for (Message message : messages) {
+ String uid = message.getUid();
+ if (uid.startsWith(K9.LOCAL_UID_PREFIX)) {
+ localOnlyMessages.add(message);
+ } else {
+ syncedMessages.add(message);
+ syncedMessageUids.add(uid);
+ }
+ }
+
+ LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
Map<String, String> uidMap = null;
if (folder.equals(account.getTrashFolderName()) || !account.hasTrashFolder()) {
Timber.d("Deleting messages in trash folder or trash set to -None-, not copying");
- localFolder.setFlags(messages, Collections.singleton(Flag.DELETED), true);
+ if (!localOnlyMessages.isEmpty()) {
+ localFolder.destroyMessages(localOnlyMessages);
+ }
+ if (!syncedMessages.isEmpty()) {
+ localFolder.setFlags(syncedMessages, Collections.singleton(Flag.DELETED), true);
+ }
} else {
localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (!localTrashFolder.exists()) {
@@ -3221,18 +3252,21 @@ public class MessagingController {
queuePendingCommand(account, command);
}
processPendingCommands(account);
- } else if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) {
- if (folder.equals(account.getTrashFolderName())) {
- queueSetFlag(account, folder, true, Flag.DELETED, uids);
+ } else if (!syncedMessageUids.isEmpty()) {
+ if (account.getDeletePolicy() == DeletePolicy.ON_DELETE) {
+ if (folder.equals(account.getTrashFolderName())) {
+ queueSetFlag(account, folder, true, Flag.DELETED, syncedMessageUids);
+ } else {
+ queueMoveOrCopy(account, folder, account.getTrashFolderName(), false,
+ syncedMessageUids, uidMap);
+ }
+ processPendingCommands(account);
+ } else if (account.getDeletePolicy() == DeletePolicy.MARK_AS_READ) {
+ queueSetFlag(account, folder, true, Flag.SEEN, syncedMessageUids);
+ processPendingCommands(account);
} else {
- queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids, uidMap);
+ Timber.d("Delete policy %s prevents delete from server", account.getDeletePolicy());
}
- processPendingCommands(account);
- } else if (account.getDeletePolicy() == DeletePolicy.MARK_AS_READ) {
- queueSetFlag(account, folder, true, Flag.SEEN, uids);
- processPendingCommands(account);
- } else {
- Timber.d("Delete policy %s prevents delete from server", account.getDeletePolicy());
}
unsuppressMessages(account, messages);
diff --git a/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java b/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java
index c16869c47..ebfa32872 100644
--- a/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java
+++ b/k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java
@@ -227,7 +227,7 @@ class ImapSync {
if (account.syncRemoteDeletions()) {
List<String> destroyMessageUids = new ArrayList<>();
for (String localMessageUid : localUidMap.keySet()) {
- if (remoteUidMap.get(localMessageUid) == null) {
+ if (!localMessageUid.startsWith(K9.LOCAL_UID_PREFIX) && remoteUidMap.get(localMessageUid) == null) {
destroyMessageUids.add(localMessageUid);
}
} | ['k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java', 'k9mail/src/main/java/com/fsck/k9/controller/imap/ImapSync.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,643,983 | 713,898 | 99,791 | 492 | 5,025 | 882 | 80 | 2 | 1,696 | 276 | 400 | 29 | 1 | 0 | 2018-02-10T19:49:00 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,637 | thundernest/k-9/3146/3004 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3004 | https://github.com/thundernest/k-9/pull/3146 | https://github.com/thundernest/k-9/pull/3146 | 1 | fixes | Body in decrypted mails empty by reply or forwarding | ### Expected behavior
If I click reply or forward, the body of the original mail should be filled with the whole original text and maybe attachments by forwarding .
### Actual behavior
There is only the header (Mailadress and so on) and the subject line of the original mail
### Steps to reproduce
1. Receive a encrypted mail
2. Decrypt this mail
3. Click reply or forward
4. See there is no quote and no attachment (by forwarding)
### Environment
K-9 Mail version: 5.400
Android version: 7.0
Account type (IMAP, POP3, WebDAV/Exchange): IMAP
| 6767f41505e6e784af03befd1a122a99f771ead1 | 8b11a7284ee2e4c2dd1c9b43d05859bcd3468187 | https://github.com/thundernest/k-9/compare/6767f41505e6e784af03befd1a122a99f771ead1...8b11a7284ee2e4c2dd1c9b43d05859bcd3468187 | 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 6d6daccf7..bda32a1fc 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java
@@ -37,10 +37,10 @@ public class MessageViewInfo {
this.extraAttachments = extraAttachments;
}
- static MessageViewInfo createWithExtractedContent(Message message, boolean isMessageIncomplete,
+ static MessageViewInfo createWithExtractedContent(Message message, Part rootPart, boolean isMessageIncomplete,
String text, List<AttachmentViewInfo> attachments, AttachmentResolver attachmentResolver) {
return new MessageViewInfo(
- message, isMessageIncomplete, message, text, attachments, null, attachmentResolver, null,
+ message, isMessageIncomplete, rootPart, text, attachments, null, attachmentResolver, null,
Collections.<AttachmentViewInfo>emptyList());
}
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 975b56686..9956c2b9b 100644
--- a/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java
+++ b/k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java
@@ -124,7 +124,7 @@ public class MessageViewInfoExtractor {
!message.isSet(Flag.X_DOWNLOADED_FULL) || MessageExtractor.hasMissingParts(message);
return MessageViewInfo.createWithExtractedContent(
- message, isMessageIncomplete, viewable.html, attachmentInfos, attachmentResolver);
+ message, contentPart, isMessageIncomplete, viewable.html, attachmentInfos, attachmentResolver);
}
private ViewableExtractedText extractViewableAndAttachments(List<Part> parts,
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 a74910994..eae6f7aca 100644
--- a/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java
@@ -406,6 +406,8 @@ public class MessageViewInfoExtractorTest {
assertEquals("<pre class=\\"k9mail\\">text</pre>", messageViewInfo.text);
assertSame(annotation, messageViewInfo.cryptoResultAnnotation);
+ assertSame(message, messageViewInfo.message);
+ assertSame(message, messageViewInfo.rootPart);
assertTrue(messageViewInfo.attachments.isEmpty());
assertTrue(messageViewInfo.extraAttachments.isEmpty());
}
@@ -427,6 +429,8 @@ public class MessageViewInfoExtractorTest {
assertEquals("<pre class=\\"k9mail\\">replacement text</pre>", messageViewInfo.text);
assertSame(annotation, messageViewInfo.cryptoResultAnnotation);
+ assertSame(message, messageViewInfo.message);
+ assertSame(replacementPart, messageViewInfo.rootPart);
assertTrue(messageViewInfo.attachments.isEmpty());
assertTrue(messageViewInfo.extraAttachments.isEmpty());
} | ['k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfoExtractor.java', 'k9mail/src/main/java/com/fsck/k9/mailstore/MessageViewInfo.java', 'k9mail/src/test/java/com/fsck/k9/mailstore/MessageViewInfoExtractorTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,656,715 | 717,769 | 100,395 | 492 | 643 | 118 | 6 | 2 | 566 | 93 | 137 | 19 | 0 | 0 | 2018-01-28T12:07:26 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,638 | thundernest/k-9/3130/3129 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3129 | https://github.com/thundernest/k-9/pull/3130 | https://github.com/thundernest/k-9/pull/3130 | 1 | fixes | App crashes when I click on contact logo | Hi,
I've not found a recent issue related to my issue.
Thanks for your answer
### Expected behavior
It should be create a new message with the clicked contact, as recipient.
### Actual behavior
Since the update, the app crashes when I click on contact logo square.
### Steps to reproduce
1. Open the app
2. Click on the logo square of any email
3. The app will crash
### Environment
K-9 Mail version: 5.403
Android version: 5.1 with Flyme 6.2.0.0A
Account type (IMAP, POP3, WebDAV/Exchange): IMAP with Gmail
| 7c3b90b356ffe045c27b2ab5ceb0a4db3381a7b9 | 2ec1b3fe29aa8ce745acd03169f70cf0978c5b20 | https://github.com/thundernest/k-9/compare/7c3b90b356ffe045c27b2ab5ceb0a4db3381a7b9...2ec1b3fe29aa8ce745acd03169f70cf0978c5b20 | diff --git a/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java b/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java
index fbea32426..6a09fedca 100644
--- a/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java
+++ b/k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java
@@ -1,6 +1,7 @@
package com.fsck.k9.ui;
+import android.content.ActivityNotFoundException;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
@@ -20,6 +21,9 @@ import android.view.View.OnClickListener;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ImageView;
+import android.widget.Toast;
+
+import com.fsck.k9.R;
/**
@@ -207,10 +211,14 @@ public class ContactBadge extends ImageView implements OnClickListener {
getContext(), ContactBadge.this, lookupUri, QuickContact.MODE_LARGE, null);
} else if (createUri != null) {
// Prompt user to add this person to contacts
- final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, createUri);
- extras.remove(EXTRA_URI_CONTENT);
- intent.putExtras(extras);
- getContext().startActivity(intent);
+ try {
+ final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, createUri);
+ extras.remove(EXTRA_URI_CONTENT);
+ intent.putExtras(extras);
+ getContext().startActivity(intent);
+ } catch (ActivityNotFoundException e) {
+ Toast.makeText(getContext(), R.string.error_activity_not_found, Toast.LENGTH_LONG).show();
+ }
}
}
} | ['k9mail/src/main/java/com/fsck/k9/ui/ContactBadge.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,656,975 | 718,237 | 100,405 | 492 | 814 | 131 | 16 | 1 | 537 | 89 | 140 | 23 | 0 | 0 | 2018-01-25T02:02:55 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,639 | thundernest/k-9/3073/3065 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3065 | https://github.com/thundernest/k-9/pull/3073 | https://github.com/thundernest/k-9/pull/3073 | 1 | fixes | tel URI links are stripped by HtmlSanitizer | 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
Tell us what should happen
Click to call link does not work since a few weeks. A click to call link is a hyperlink which is opened by a dialer-application. For Exampel: `<a href="tel:004955555">55555</a>`
### Actual behavior
Tell us what happens instead
Link is shown as plain text
### Steps to reproduce
1. Create a new mail with html code` <a href="tel:004955555">55555</a>` in it
2. Check for new mails in an old version of k9, or in thunderbird and look for the link
3. Check with current k9 mail, link is shown as plain-text.
### Environment
K-9 Mail version: current 5.403
Android version:
7.0 (motorola) and 7.1.2 (lineage) verified
Account type (IMAP, POP3, WebDAV/Exchange):
does not matter
| e4467ef959d5dc13d84afb9e49029cc6676fe6f5 | 11f6614a3b63371e2ce8b7d41623692990de2930 | https://github.com/thundernest/k-9/compare/e4467ef959d5dc13d84afb9e49029cc6676fe6f5...11f6614a3b63371e2ce8b7d41623692990de2930 | diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
index 63e9eaedb..2b197857a 100644
--- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
+++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java
@@ -25,7 +25,8 @@ public class HtmlSanitizer {
"align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign",
"width")
.addAttributes(":all", "class", "style", "id")
- .addProtocols("img", "src", "http", "https", "cid", "data");
+ .addProtocols("img", "src", "http", "https", "cid", "data")
+ .addProtocols("a", "href", "tel", "sip", "bitcoin", "ethereum", "rtsp");
cleaner = new Cleaner(whitelist);
headCleaner = new HeadCleaner();
diff --git a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java
index 38d8d6e4f..3e9f6bf9c 100644
--- a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java
@@ -213,4 +213,31 @@ public class HtmlSanitizerTest {
"<center><font face=\\"Arial\\" color=\\"red\\" size=\\"12\\">A</font></center>" +
"</body></html>", toCompactString(result));
}
+
+ @Test
+ public void shouldKeepUris() {
+ String html = "<html><body>" +
+ "<a href=\\"http://example.com/index.html\\">HTTP</a>" +
+ "<a href=\\"https://example.com/default.html\\">HTTPS</a>" +
+ "<a href=\\"mailto:[email protected]\\">Mailto</a>" +
+ "<a href=\\"tel:00442079460111\\">Telephone</a>" +
+ "<a href=\\"sip:[email protected]\\">SIP</a>" +
+ "<a href=\\"bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu\\">Bitcoin</a>" +
+ "<a href=\\"ethereum:0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7\\">Ethereum</a>" +
+ "<a href=\\"rtsp://example.com/media.mp4\\">RTSP</a>" +
+ "</body></html>";
+
+ Document result = htmlSanitizer.sanitize(html);
+
+ assertEquals("<html><head></head><body>" +
+ "<a href=\\"http://example.com/index.html\\">HTTP</a>" +
+ "<a href=\\"https://example.com/default.html\\">HTTPS</a>" +
+ "<a href=\\"mailto:[email protected]\\">Mailto</a>" +
+ "<a href=\\"tel:00442079460111\\">Telephone</a>" +
+ "<a href=\\"sip:[email protected]\\">SIP</a>" +
+ "<a href=\\"bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu\\">Bitcoin</a>" +
+ "<a href=\\"ethereum:0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7\\">Ethereum</a>" +
+ "<a href=\\"rtsp://example.com/media.mp4\\">RTSP</a>" +
+ "</body></html>", toCompactString(result));
+ }
} | ['k9mail/src/main/java/com/fsck/k9/message/html/HtmlSanitizer.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlSanitizerTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,654,448 | 717,970 | 100,340 | 492 | 244 | 73 | 3 | 1 | 952 | 147 | 256 | 24 | 1 | 0 | 2018-01-10T00:25:35 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,647 | thundernest/k-9/2215/1500 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/1500 | https://github.com/thundernest/k-9/pull/2215 | https://github.com/thundernest/k-9/pull/2215 | 1 | fix | Webdav (Exchange) sending email is broken since v5.109 (alpha) | Android version: 6.01
Using K-9 Mail v5.010 (stable) i could send emails using my old WEBDAV account.
But never delete emails on the server.
Then Updated to K-9 Mail v5.109 (alpha) / and also to K-9 Mail v5.110 (alpha).
Now I can delete emails on the server, but I can not send emails any more.
They end up on the outgoing folder.
Sorry I can't tell you the error message. The message text is too long so it's truncated...
Then Downgraded (titanium Backup / also the database) and sending emails is working again.
| c150bafac3aa1137376af532bba1b13dfac85fd2 | 2cec47491d963b0e7493469aba1bf9497ccf2678 | https://github.com/thundernest/k-9/compare/c150bafac3aa1137376af532bba1b13dfac85fd2...2cec47491d963b0e7493469aba1bf9497ccf2678 | diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java
index 7eda5d5b3..0f7d8da1b 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java
@@ -27,6 +27,7 @@ import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -678,28 +679,8 @@ class WebDavFolder extends Folder<WebDavMessage> {
Log.i(LOG_TAG, "Uploading message as " + messageURL);
- httpmethod = new HttpGeneric(messageURL);
- httpmethod.setMethod("PUT");
- httpmethod.setEntity(bodyEntity);
+ store.sendRequest(messageURL, "PUT", bodyEntity, null, true);
- String mAuthString = store.getAuthString();
-
- if (mAuthString != null) {
- httpmethod.setHeader("Authorization", mAuthString);
- }
-
- response = httpclient.executeOverride(httpmethod, store.getContext());
- statusCode = response.getStatusLine().getStatusCode();
-
- if (statusCode < 200 ||
- statusCode > 300) {
-
- //TODO: Could we handle a login timeout here?
-
- throw new IOException("Error with status code " + statusCode
- + " while sending/appending message. Response = "
- + response.getStatusLine().toString() + " for message " + messageURL);
- }
WebDavMessage retMessage = new WebDavMessage(message.getUid(), this);
retMessage.setUrl(messageURL);
diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java
index 3132904b3..44ed5fa04 100644
--- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java
+++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java
@@ -830,7 +830,7 @@ public class WebDavStore extends RemoteStore {
return mHttpClient;
}
- private InputStream sendRequest(String url, String method, StringEntity messageBody,
+ protected InputStream sendRequest(String url, String method, StringEntity messageBody,
Map<String, String> headers, boolean tryAuth)
throws MessagingException {
if (url == null || method == null) {
diff --git a/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java b/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java
index 69b18552a..e9a6d1a25 100644
--- a/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java
+++ b/k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java
@@ -12,6 +12,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.BasicHttpEntity;
+import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.junit.Before;
import org.junit.Test;
@@ -37,6 +38,7 @@ import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyMapOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -75,10 +77,16 @@ public class WebDavFolderTest {
private StatusLine mockStatusLine;
@Captor
private ArgumentCaptor<Map<String, String>> headerCaptor;
+ @Captor
+ private ArgumentCaptor<String> urlCaptor;
+ @Captor
+ private ArgumentCaptor<StringEntity> entityCaptor;
private WebDavFolder folder;
private WebDavFolder destinationFolder;
+ private String storeUrl = "https://localhost/webDavStoreUrl";
+ private String folderName = "testFolder";
private String moveOrCopyXml = "<xml>MoveOrCopyXml</xml>";
private HashMap<String, String> moveOrCopyHeaders;
private List<WebDavMessage> messages;
@@ -86,10 +94,10 @@ public class WebDavFolderTest {
@Before
public void before() throws MessagingException, IOException {
MockitoAnnotations.initMocks(this);
- when(mockStore.getUrl()).thenReturn("https://localhost/webDavStoreUrl");
+ when(mockStore.getUrl()).thenReturn(storeUrl);
when(mockStore.getHttpClient()).thenReturn(mockHttpClient);
when(mockStore.getStoreConfig()).thenReturn(mockStoreConfig);
- folder = new WebDavFolder(mockStore, "testFolder");
+ folder = new WebDavFolder(mockStore, folderName);
setupTempDirectory();
}
@@ -514,9 +522,6 @@ public class WebDavFolderTest {
@Test
public void appendWebDavMessages_replaces_messages_with_WebDAV_versions() throws MessagingException, IOException {
- when(mockHttpClient.executeOverride(any(HttpUriRequest.class), any(HttpContext.class))).thenReturn(mockHttpResponse);
- when(mockHttpResponse.getStatusLine()).thenReturn(mockStatusLine);
- when(mockStatusLine.getStatusCode()).thenReturn(200);
List<Message> existingMessages = new ArrayList<>();
Message existingMessage = mock(Message.class);
existingMessages.add(existingMessage);
@@ -529,4 +534,20 @@ public class WebDavFolderTest {
assertEquals(WebDavMessage.class, response.get(0).getClass());
assertEquals(messageUid, response.get(0).getUid());
}
+
+ @Test
+ public void appendWebDavMessages_sendsRequestUsingStore() throws MessagingException, IOException {
+ List<Message> existingMessages = new ArrayList<>();
+ Message existingMessage = mock(Message.class);
+ existingMessages.add(existingMessage);
+ String messageUid = "testMessageUid";
+ when(existingMessage.getUid()).thenReturn(messageUid);
+
+ folder.appendWebDavMessages(existingMessages);
+
+ verify(mockStore).sendRequest(urlCaptor.capture(), eq("PUT"), entityCaptor.capture(),
+ Matchers.<Map<String, String>>eq(null), eq(true));
+ assertTrue(urlCaptor.getValue().startsWith(storeUrl + "/" + folderName + "/" + messageUid));
+ assertTrue(urlCaptor.getValue().endsWith(".eml"));
+ }
} | ['k9mail-library/src/test/java/com/fsck/k9/mail/store/webdav/WebDavFolderTest.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavStore.java', 'k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavFolder.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,476,576 | 690,051 | 95,154 | 439 | 1,247 | 207 | 25 | 2 | 516 | 93 | 136 | 11 | 0 | 0 | 2017-02-08T23:49:29 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,646 | thundernest/k-9/2380/2282 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2282 | https://github.com/thundernest/k-9/pull/2380 | https://github.com/thundernest/k-9/pull/2380 | 1 | fixes | Crash in 5.205: Bug in ParcelableUtil.unmarshall()? | Crash reported via Google Play.
User messages:
* crash when opening from 1x1 widget
* using inbox icon to start k9 results in crash
* force closes on start from widget
```
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fsck.k9/com.fsck.k9.activity.MessageList}: java.lang.NullPointerException: Attempt to get length of null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.fsck.k9.helper.ParcelableUtil.unmarshall(ParcelableUtil.java:27)
at com.fsck.k9.helper.ParcelableUtil.unmarshall(ParcelableUtil.java:19)
at com.fsck.k9.activity.MessageList.decodeExtras(MessageList.java:437)
at com.fsck.k9.activity.MessageList.onCreate(MessageList.java:225)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
... 9 more
``` | 7880e8396e9f4674a3728543742eec64ad389242 | 5485f7a1bb8c5d816706e58b35a176cfd79c7de9 | https://github.com/thundernest/k-9/compare/7880e8396e9f4674a3728543742eec64ad389242...5485f7a1bb8c5d816706e58b35a176cfd79c7de9 | 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 f1addf57f..28f4c0df3 100644
--- a/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java
+++ b/k9mail/src/main/java/com/fsck/k9/activity/MessageList.java
@@ -72,8 +72,11 @@ public class MessageList extends K9Activity implements MessageListFragmentListen
MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener,
OnSwitchCompleteListener {
- // for this activity
- private static final String EXTRA_SEARCH = "search";
+ @Deprecated
+ //TODO: Remove after 2017-09-11
+ private static final String EXTRA_SEARCH_OLD = "search";
+
+ private static final String EXTRA_SEARCH = "search_bytes";
private static final String EXTRA_NO_THREADING = "no_threading";
private static final String ACTION_SHORTCUT = "shortcut";
@@ -431,6 +434,9 @@ public class MessageList extends K9Activity implements MessageListFragmentListen
mSearch.addAccountUuid(LocalSearch.ALL_ACCOUNTS);
}
}
+ } else if (intent.hasExtra(EXTRA_SEARCH_OLD)) {
+ mSearch = intent.getParcelableExtra(EXTRA_SEARCH_OLD);
+ mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false);
} else {
// regular LocalSearch object was passed
mSearch = intent.hasExtra(EXTRA_SEARCH) ? | ['k9mail/src/main/java/com/fsck/k9/activity/MessageList.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,498,297 | 692,380 | 95,953 | 446 | 469 | 104 | 10 | 1 | 1,647 | 95 | 371 | 30 | 0 | 1 | 2017-03-11T20:31:25 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,645 | thundernest/k-9/2521/2503 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2503 | https://github.com/thundernest/k-9/pull/2521 | https://github.com/thundernest/k-9/pull/2521 | 1 | fixes | Export settings does not export 'Support signing of unecrypted mail' setting | If I set 'Support signing of unecrypted mail' option, then export the settings, then clear K9 mail app. data, then import the settings, the 'Support signing of unecrypted mail' option does not get set. | 231b46f27839f599d95ef3f62cd66f4a20e0e62e | 35a29ec4560a031c6ada2849be987aee08108e60 | https://github.com/thundernest/k-9/compare/231b46f27839f599d95ef3f62cd66f4a20e0e62e...35a29ec4560a031c6ada2849be987aee08108e60 | diff --git a/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java b/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java
index 14c77e63e..f1a799ed9 100644
--- a/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java
+++ b/k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java
@@ -285,10 +285,10 @@ public class GlobalSettings {
s.put("pgpSignOnlyDialogCounter", Settings.versions(
new V(45, new IntegerRangeSetting(0, Integer.MAX_VALUE, 0))
));
- s.put("openpgpProvider", Settings.versions(
+ s.put("openPgpProvider", Settings.versions(
new V(46, new StringSetting(K9.NO_OPENPGP_PROVIDER))
));
- s.put("openpgpSupportSignOnly", Settings.versions(
+ s.put("openPgpSupportSignOnly", Settings.versions(
new V(47, new BooleanSetting(false))
));
| ['k9mail/src/main/java/com/fsck/k9/preferences/GlobalSettings.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,519,596 | 691,880 | 96,815 | 464 | 225 | 56 | 4 | 1 | 201 | 34 | 49 | 1 | 0 | 0 | 2017-05-01T16:01:23 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,640 | thundernest/k-9/3025/3018 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/3018 | https://github.com/thundernest/k-9/pull/3025 | https://github.com/thundernest/k-9/pull/3025 | 1 | fixes | Bad <hr> detection causes emails to appear empty | Some emails displayed empty, despite there is text in the email body.
Note: Email preview in notification window shows (part) of body; but email body seems empty in K9.
This behavior has been introduced with the latest K9 update a few days ago.
### Expected behavior
Email displayed correctly.
### Actual behavior
Email shown empty. When using "Reply" on the mail, no email body is shown, the wait cursor is shown indefinitely.
### Steps to reproduce
Not sure why some emails get not displayed. I could provide the emails not correctly shown if needed.
### Environment
K-9 Mail version: 5.400
Android version:
7.1.1 and also 4.4.4
Account type (IMAP, POP3, WebDAV/Exchange): POP3
| 1506c6d4c028586da0cac60d0688f6a2493ed1e5 | b49af84dc803c361244ece7e0333787d2e321573 | https://github.com/thundernest/k-9/compare/1506c6d4c028586da0cac60d0688f6a2493ed1e5...b49af84dc803c361244ece7e0333787d2e321573 | diff --git a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java
index 9d5d27aa4..fb618e80d 100644
--- a/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java
+++ b/k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java
@@ -5,7 +5,6 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
-import java.util.regex.Pattern;
import android.text.Annotation;
import android.text.Editable;
@@ -179,11 +178,6 @@ public class HtmlConverter {
"style=\\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid $$COLOR$$; padding-left: 1ex;\\">";
private static final String HTML_BLOCKQUOTE_END = "</blockquote>";
private static final String HTML_NEWLINE = "<br />";
- private static final Pattern ASCII_PATTERN_FOR_HR = Pattern.compile(
- "(^|\\\\Q" + HTML_NEWLINE + "\\\\E)\\\\s*((\\\\Q" + HTML_NEWLINE + "\\\\E)*" +
- "((((\\\\Q" + HTML_NEWLINE + "\\\\E){0,2}([-=_]{3,})(\\\\Q" + HTML_NEWLINE +
- "\\\\E){0,2})|(([-=_]{2,} ?)(8<|<gt>8|%<|<gt>%)" +
- "( ?[-=_]{2,})))+(\\\\Q" + HTML_NEWLINE + "\\\\E|$)))");
/**
* Convert a text string into an HTML document.
@@ -276,7 +270,7 @@ public class HtmlConverter {
HTML_BLOCKQUOTE_END + "$1"
);
- text = ASCII_PATTERN_FOR_HR.matcher(text).replaceAll("<hr>");
+ text = text.replaceAll("\\\\s*([-=_]{30,}+)\\\\s*", "<hr>");
StringBuffer sb = new StringBuffer(text.length() + TEXT_TO_HTML_EXTRA_BUFFER_LENGTH);
diff --git a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java
index 9cd79b53d..b2dca89a9 100644
--- a/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java
+++ b/k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java
@@ -8,6 +8,7 @@ import java.io.IOException;
import com.fsck.k9.K9RobolectricTestRunner;
import org.apache.commons.io.IOUtils;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@@ -194,6 +195,7 @@ public class HtmlConverterTest {
}
@Test
+ @Ignore("Disabled due to temporary fix for issue #3018")
public void issue2259Spec() {
String text = "text\\n" +
"---------------------------\\n" +
@@ -225,6 +227,7 @@ public class HtmlConverterTest {
}
@Test
+ @Ignore("Disabled due to temporary fix for issue #3018")
public void mergeConsecutiveBreaksIntoOne() {
String text = "hello\\n------------\\n---------------\\nfoo bar";
String result = HtmlConverter.textToHtml(text);
@@ -260,6 +263,7 @@ public class HtmlConverterTest {
}
@Test
+ @Ignore("Disabled due to temporary fix for issue #3018")
public void anyTripletIsHRuledOut() {
String text = "--=\\n-=-\\n===\\n___\\n\\n";
String result = HtmlConverter.textToHtml(text);
@@ -267,6 +271,7 @@ public class HtmlConverterTest {
}
@Test
+ @Ignore("Disabled due to temporary fix for issue #3018")
public void replaceSpaceSeparatedDashesWithHR() {
String text = "hello\\n---------------------------\\nfoo bar";
String result = HtmlConverter.textToHtml(text);
@@ -274,6 +279,7 @@ public class HtmlConverterTest {
}
@Test
+ @Ignore("Disabled due to temporary fix for issue #3018")
public void replacementWithHRAtBeginning() {
String text = "---------------------------\\nfoo bar";
String result = HtmlConverter.textToHtml(text);
@@ -281,6 +287,7 @@ public class HtmlConverterTest {
}
@Test
+ @Ignore("Disabled due to temporary fix for issue #3018")
public void replacementWithHRAtEnd() {
String text = "hello\\n__________________________________";
String result = HtmlConverter.textToHtml(text);
@@ -288,6 +295,7 @@ public class HtmlConverterTest {
}
@Test
+ @Ignore("Disabled due to temporary fix for issue #3018")
public void replacementOfScissorsByHR() {
String text = "hello\\n-- %< -------------- >8 --\\nworld\\n";
String result = HtmlConverter.textToHtml(text); | ['k9mail/src/main/java/com/fsck/k9/message/html/HtmlConverter.java', 'k9mail/src/test/java/com/fsck/k9/message/html/HtmlConverterTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,599,243 | 707,505 | 98,930 | 484 | 543 | 178 | 8 | 1 | 711 | 112 | 166 | 23 | 0 | 0 | 2018-01-02T14:19:29 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
9,641 | thundernest/k-9/2885/2846 | thundernest | k-9 | https://github.com/thundernest/k-9/issues/2846 | https://github.com/thundernest/k-9/pull/2885 | https://github.com/thundernest/k-9/pull/2885 | 1 | fixes | Parsing email address list with invalid base64 encoded word crashes the app | Test case:
```java
Address.parse("=?utf-8?b?invalid#?= <[email protected]>");
```
Exception:
```
java.lang.Error: java.io.IOException: Unexpected base64 byte
at org.apache.james.mime4j.codec.DecoderUtil.decodeBase64(DecoderUtil.java:89)
at org.apache.james.mime4j.codec.DecoderUtil.decodeB(DecoderUtil.java:106)
at org.apache.james.mime4j.codec.DecoderUtil.tryDecodeEncodedWord(DecoderUtil.java:233)
at org.apache.james.mime4j.codec.DecoderUtil.decodeEncodedWords(DecoderUtil.java:187)
at org.apache.james.mime4j.codec.DecoderUtil.decodeEncodedWords(DecoderUtil.java:143)
at org.apache.james.mime4j.field.address.Builder.buildAddress(Builder.java:71)
at org.apache.james.mime4j.field.address.Builder.buildAddressList(Builder.java:51)
at org.apache.james.mime4j.field.address.DefaultAddressParser.parseAddressList(DefaultAddressParser.java:69)
at org.apache.james.mime4j.field.address.DefaultAddressParser.parseAddressList(DefaultAddressParser.java:73)
at com.fsck.k9.mail.Address.parse(Address.java:145)
[...]
Caused by: java.io.IOException: Unexpected base64 byte
at org.apache.james.mime4j.codec.Base64InputStream.read0(Base64InputStream.java:193)
at org.apache.james.mime4j.codec.Base64InputStream.read(Base64InputStream.java:87)
at org.apache.james.mime4j.codec.DecoderUtil.decodeBase64(DecoderUtil.java:80)
... 39 more
```
I'm not sure what the best way to handle this is. Probably using the personal part as is. However, the options in MIME4J are somewhat limited. It's either crashing with an `Error` or ignoring invalid characters when decoding the base64 payload. Since we don't like crashes we should probably start out with the latter option. | d696723023d8eb2c5dde223fdbcef1d67bd49bb9 | ddcf1e257e43a9e08bb4bdcd237f93651c3651d5 | https://github.com/thundernest/k-9/compare/d696723023d8eb2c5dde223fdbcef1d67bd49bb9...ddcf1e257e43a9e08bb4bdcd237f93651c3651d5 | 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 042fbbf44..eb8183768 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
@@ -2,12 +2,14 @@
package com.fsck.k9.mail;
import android.support.annotation.VisibleForTesting;
+
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.james.mime4j.MimeException;
+import org.apache.james.mime4j.codec.DecodeMonitor;
import org.apache.james.mime4j.codec.EncoderUtil;
import org.apache.james.mime4j.dom.address.Mailbox;
import org.apache.james.mime4j.dom.address.MailboxList;
@@ -30,7 +32,6 @@ public class Address implements Serializable {
private String mPersonal;
-
public Address(Address address) {
mAddress = address.mAddress;
mPersonal = address.mPersonal;
@@ -142,7 +143,7 @@ public class Address implements Serializable {
}
List<Address> addresses = new ArrayList<>();
try {
- MailboxList parsedList = DefaultAddressParser.DEFAULT.parseAddressList(addressList).flatten();
+ MailboxList parsedList = DefaultAddressParser.DEFAULT.parseAddressList(addressList, DecodeMonitor.SILENT).flatten();
for (int i = 0, count = parsedList.size(); i < count; i++) {
Mailbox mailbox = parsedList.get(i);
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 82a48be51..1fa329163 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
@@ -180,4 +180,10 @@ public class AddressTest {
assertNull(result);
}
+
+ @Test
+ public void handlesInvalidBase64Encoding() throws Exception {
+ Address address = Address.parse("=?utf-8?b?invalid#?= <[email protected]>")[0];
+ assertEquals("[email protected]", address.getAddress());
+ }
} | ['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,600,355 | 707,916 | 98,987 | 484 | 296 | 59 | 5 | 1 | 1,711 | 105 | 408 | 28 | 0 | 2 | 2017-10-30T18:54:48 | 8,156 | Kotlin | {'Kotlin': 4058553, 'Java': 2375292, 'Shell': 7553, 'AIDL': 1946} | Apache License 2.0 |
670 | apache/shardingsphere-elasticjob/368/367 | apache | shardingsphere-elasticjob | https://github.com/apache/shardingsphere-elasticjob/issues/367 | https://github.com/apache/shardingsphere-elasticjob/pull/368 | https://github.com/apache/shardingsphere-elasticjob/pull/368 | 1 | fixed | Resuming Transient Job is abnormal | ### Which version of Elastic-Job do you using?
2.1.4
### Expected behavior
Disable the job and then resume the job, then triggered by cron expression.
### Actual behavior
Disable the job and then resume the job, immediately triggered several times.
### Steps to reproduce the behavior
Disable the transient job(cron 0/30 * * * * ?) with "misfire" parameter, wait several minutes, then resume it.
| a3db7607ea9d33beb7b94c95ac0f56b7589d2b11 | 064eca0ab1804af654599bb06eae2ad6a1e59ea5 | https://github.com/apache/shardingsphere-elasticjob/compare/a3db7607ea9d33beb7b94c95ac0f56b7589d2b11...064eca0ab1804af654599bb06eae2ad6a1e59ea5 | diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java
index 0f9e58ae7..bccbb183a 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java
@@ -70,7 +70,7 @@ public final class CloudJobConfigurationListener implements TreeCacheListener {
if (!jobConfig.getTypeConfig().getCoreConfig().isMisfire()) {
readyService.setMisfireDisabled(jobConfig.getJobName());
}
- producerManager.reschedule(jobConfig);
+ producerManager.reschedule(jobConfig.getJobName());
} else if (isJobConfigNode(event, path, Type.NODE_REMOVED)) {
String jobName = path.substring(CloudJobConfigurationNode.ROOT.length() + 1, path.length());
producerManager.unschedule(jobName);
diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java
index 527c58e1a..d27c36c53 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java
@@ -172,12 +172,19 @@ public final class FacadeService {
if (!jobConfigOptional.isPresent()) {
return;
}
+ if (isDisable(jobConfigOptional.get())) {
+ return;
+ }
CloudJobConfiguration jobConfig = jobConfigOptional.get();
if (jobConfig.getTypeConfig().getCoreConfig().isFailover() || CloudJobExecutionType.DAEMON == jobConfig.getJobExecutionType()) {
failoverService.add(taskContext);
}
}
+ private boolean isDisable(final CloudJobConfiguration jobConfiguration) {
+ return disableAppService.isDisabled(jobConfiguration.getAppName()) || disableJobService.isDisabled(jobConfiguration.getJobName());
+ }
+
/**
* 将瞬时作业放入待执行队列.
*
@@ -223,6 +230,13 @@ public final class FacadeService {
* @param jobName 作业名称
*/
public void addDaemonJobToReadyQueue(final String jobName) {
+ Optional<CloudJobConfiguration> jobConfigOptional = jobConfigService.load(jobName);
+ if (!jobConfigOptional.isPresent()) {
+ return;
+ }
+ if (isDisable(jobConfigOptional.get())) {
+ return;
+ }
readyService.addDaemon(jobName);
}
diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java
index 71d4c6d37..e681e656e 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java
@@ -117,7 +117,7 @@ public final class ProducerManager {
throw new JobConfigurationException("Cannot found job '%s', please register first.", jobConfig.getJobName());
}
configService.update(jobConfig);
- reschedule(jobConfig);
+ reschedule(jobConfig.getJobName());
}
/**
@@ -130,7 +130,6 @@ public final class ProducerManager {
if (jobConfig.isPresent()) {
disableJobService.remove(jobName);
configService.remove(jobName);
- transientProducerScheduler.deregister(jobConfig.get());
}
unschedule(jobName);
}
@@ -162,16 +161,23 @@ public final class ProducerManager {
}
runningService.remove(jobName);
readyService.remove(Lists.newArrayList(jobName));
+ Optional<CloudJobConfiguration> jobConfig = configService.load(jobName);
+ if (jobConfig.isPresent()) {
+ transientProducerScheduler.deregister(jobConfig.get());
+ }
}
/**
* 重新调度作业.
*
- * @param jobConfig 作业配置
+ * @param jobName 作业名称
*/
- public void reschedule(final CloudJobConfiguration jobConfig) {
- unschedule(jobConfig.getJobName());
- schedule(jobConfig);
+ public void reschedule(final String jobName) {
+ unschedule(jobName);
+ Optional<CloudJobConfiguration> jobConfig = configService.load(jobName);
+ if (jobConfig.isPresent()) {
+ schedule(jobConfig.get());
+ }
}
/**
diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java
index bfb793cc0..93d379f9d 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java
@@ -112,7 +112,7 @@ final class TransientProducerScheduler {
return TriggerBuilder.newTrigger().withIdentity(cron).withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing()).build();
}
- void deregister(final CloudJobConfiguration jobConfig) {
+ synchronized void deregister(final CloudJobConfiguration jobConfig) {
repository.remove(jobConfig.getJobName());
String cron = jobConfig.getTypeConfig().getCoreConfig().getCron();
if (!repository.containsKey(buildJobKey(cron))) {
diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java
index 5c2c7f6a2..9d849510e 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java
@@ -186,6 +186,11 @@ public final class CloudAppRestfulApi {
public void enable(@PathParam("appName") final String appName) throws JSONException {
if (appConfigService.load(appName).isPresent()) {
disableAppService.remove(appName);
+ for (CloudJobConfiguration each : jobConfigService.loadAll()) {
+ if (appName.equals(each.getAppName())) {
+ producerManager.reschedule(each.getJobName());
+ }
+ }
}
}
diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java
index 2ad20f6db..2505b0435 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java
@@ -184,8 +184,10 @@ public final class CloudJobRestfulApi {
@DELETE
@Path("/{jobName}/disable")
public void enable(@PathParam("jobName") final String jobName) throws JSONException {
- if (configService.load(jobName).isPresent()) {
+ Optional<CloudJobConfiguration> configOptional = configService.load(jobName);
+ if (configOptional.isPresent()) {
facadeService.enableJob(jobName);
+ producerManager.reschedule(jobName);
}
}
diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java
index 99f7ae93e..e8dc9213b 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java
@@ -58,7 +58,7 @@ public final class CloudJobConfigurationListenerTest {
public void assertChildEventWhenDataIsNull() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, null));
verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
- verify(producerManager, times(0)).reschedule(ArgumentMatchers.<CloudJobConfiguration>any());
+ verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any());
verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any());
}
@@ -66,7 +66,7 @@ public final class CloudJobConfigurationListenerTest {
public void assertChildEventWhenIsNotConfigPath() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData("/other/test_job", null, "".getBytes())));
verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
- verify(producerManager, times(0)).reschedule(ArgumentMatchers.<CloudJobConfiguration>any());
+ verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any());
verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any());
}
@@ -74,7 +74,7 @@ public final class CloudJobConfigurationListenerTest {
public void assertChildEventWhenIsRootConfigPath() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_REMOVED, new ChildData("/config/job", null, "".getBytes())));
verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
- verify(producerManager, times(0)).reschedule(ArgumentMatchers.<CloudJobConfiguration>any());
+ verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any());
verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any());
}
@@ -82,7 +82,7 @@ public final class CloudJobConfigurationListenerTest {
public void assertChildEventWhenStateIsAddAndIsConfigPathAndInvalidData() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_ADDED, new ChildData("/config/job/test_job", null, "".getBytes())));
verify(producerManager, times(0)).schedule(ArgumentMatchers.<CloudJobConfiguration>any());
- verify(producerManager, times(0)).reschedule(ArgumentMatchers.<CloudJobConfiguration>any());
+ verify(producerManager, times(0)).reschedule(ArgumentMatchers.<String>any());
verify(producerManager, times(0)).unschedule(ArgumentMatchers.<String>any());
}
@@ -96,7 +96,7 @@ public final class CloudJobConfigurationListenerTest {
public void assertChildEventWhenStateIsUpdateAndIsConfigPathAndTransientJob() throws Exception {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED, new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson().getBytes())));
verify(readyService, times(0)).remove(Collections.singletonList("test_job"));
- verify(producerManager).reschedule(ArgumentMatchers.<CloudJobConfiguration>any());
+ verify(producerManager).reschedule(ArgumentMatchers.<String>any());
}
@Test
@@ -104,7 +104,7 @@ public final class CloudJobConfigurationListenerTest {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED,
new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson(CloudJobExecutionType.DAEMON).getBytes())));
verify(readyService).remove(Collections.singletonList("test_job"));
- verify(producerManager).reschedule(ArgumentMatchers.<CloudJobConfiguration>any());
+ verify(producerManager).reschedule(ArgumentMatchers.<String>any());
}
@Test
@@ -112,7 +112,7 @@ public final class CloudJobConfigurationListenerTest {
cloudJobConfigurationListener.childEvent(null, new TreeCacheEvent(TreeCacheEvent.Type.NODE_UPDATED,
new ChildData("/config/job/test_job", null, CloudJsonConstants.getJobJson(false).getBytes())));
verify(readyService).setMisfireDisabled("test_job");
- verify(producerManager).reschedule(ArgumentMatchers.<CloudJobConfiguration>any());
+ verify(producerManager).reschedule(ArgumentMatchers.<String>any());
}
@Test
diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java
index 35e44ccde..50cc09c4f 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java
@@ -222,6 +222,7 @@ public final class FacadeServiceTest {
@Test
public void assertAddDaemonJobToReadyQueue() {
+ when(jobConfigService.load("test_job")).thenReturn(Optional.of(CloudJobConfigurationBuilder.createCloudJobConfiguration("test_job")));
facadeService.addDaemonJobToReadyQueue("test_job");
verify(readyService).addDaemon("test_job");
}
diff --git a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java
index e1c902886..1956a5da2 100644
--- a/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java
+++ b/elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java
@@ -106,7 +106,7 @@ public final class CloudJobRestfulApiTest extends AbstractCloudRestfulApiTest {
public void assertDeregister() throws Exception {
when(getRegCenter().isExisted("/config/job/test_job")).thenReturn(false);
assertThat(sentRequest("http://127.0.0.1:19000/api/job/deregister", "DELETE", "test_job"), is(204));
- verify(getRegCenter(), times(2)).get("/config/job/test_job");
+ verify(getRegCenter(), times(3)).get("/config/job/test_job");
}
@Test | ['elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApi.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeServiceTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListener.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/mesos/FacadeService.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudAppRestfulApi.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/config/job/CloudJobConfigurationListenerTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/test/java/com/dangdang/ddframe/job/cloud/scheduler/restful/CloudJobRestfulApiTest.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/TransientProducerScheduler.java', 'elastic-job-cloud/elastic-job-cloud-scheduler/src/main/java/com/dangdang/ddframe/job/cloud/scheduler/producer/ProducerManager.java'] | {'.java': 9} | 9 | 9 | 0 | 0 | 9 | 841,618 | 188,763 | 24,229 | 277 | 2,092 | 393 | 45 | 6 | 411 | 65 | 93 | 12 | 0 | 0 | 2017-06-29T03:05:16 | 7,920 | Java | {'Java': 2266368, 'Shell': 3428, 'Dockerfile': 1094, 'Batchfile': 861} | Apache License 2.0 |
115 | spring-projects/spring-security/13276/13243 | spring-projects | spring-security | https://github.com/spring-projects/spring-security/issues/13243 | https://github.com/spring-projects/spring-security/pull/13276 | https://github.com/spring-projects/spring-security/pull/13276 | 1 | fixes | CasAuthenticationFilter.successfulAuthentication missing call to securityContextRepository.saveContext | **Describe the bug**
`org.springframework.security.cas.web.CasAuthenticationFilter.successfulAuthentication` seems to be missing a call to `securityContextRepository.saveContext` as per [the Spring 6 migration document](https://docs.spring.io/spring-security/reference/migration/servlet/session-management.html). I think this makes the filter completely unusable on Spring6/Boot3 and begs to question if the `CasAuthenticationFilter` code is production ready for Spring 6 otherwise.
**To Reproduce**
Use the filter
**Expected behavior**
SecurityContext is saved between requests :)
| 537e10cf9c7feaf8c00d5523052823f3c469410d | 52b87f339c36eaa95d835f456aadd37425bbad02 | https://github.com/spring-projects/spring-security/compare/537e10cf9c7feaf8c00d5523052823f3c469410d...52b87f339c36eaa95d835f456aadd37425bbad02 | diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java
index a951168f66..6f2920b3d0 100644
--- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java
+++ b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java
@@ -42,6 +42,7 @@ import org.springframework.security.web.authentication.AbstractAuthenticationPro
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
+import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
@@ -192,10 +193,12 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
private AuthenticationFailureHandler proxyFailureHandler = new SimpleUrlAuthenticationFailureHandler();
+ private SecurityContextRepository securityContextRepository= new HttpSessionSecurityContextRepository();
+
public CasAuthenticationFilter() {
super("/login/cas");
setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler());
- setSecurityContextRepository(new HttpSessionSecurityContextRepository());
+ setSecurityContextRepository(this.securityContextRepository);
}
@Override
@@ -211,6 +214,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authResult);
SecurityContextHolder.setContext(context);
+ this.securityContextRepository.saveContext(context,request,response);
if (this.eventPublisher != null) {
this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
} | ['cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 7,476,540 | 1,614,247 | 200,846 | 1,671 | 399 | 56 | 6 | 1 | 592 | 57 | 118 | 9 | 1 | 0 | 2023-06-05T09:36:46 | 7,860 | Java | {'Java': 16395664, 'Kotlin': 860788, 'Groovy': 47907, 'AspectJ': 16776, 'Ruby': 7008, 'PLSQL': 3180, 'XSLT': 2369, 'Shell': 811, 'Python': 129, 'HTML': 80, 'JavaScript': 10} | Apache License 2.0 |
51 | dropwizard/metrics/505/444 | dropwizard | metrics | https://github.com/dropwizard/metrics/issues/444 | https://github.com/dropwizard/metrics/pull/505 | https://github.com/dropwizard/metrics/pull/505 | 1 | fix | Another ClassCastException in metrics-jetty9's InstrumentedHandler | I found another ClassCastException in metrics-jetty9. Commit 622ef9b which is included in 3.0.1 doesn't seem to completly fix issue #435 that I reported earlier.
```
java.lang.ClassCastException: org.atmosphere.cpr.AtmosphereRequest cannot be cast to org.eclipse.jetty.server.Request
at com.codahale.metrics.jetty9.InstrumentedHandler$1.onComplete(InstrumentedHandler.java:140) ~[metrics-jetty9-3.0.1.jar:3.0.1]
at org.eclipse.jetty.server.HttpChannelState.completed(HttpChannelState.java:470) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:315) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]
at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:228) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]
at org.eclipse.jetty.server.handler.ContextHandler.handle(ContextHandler.java:1143) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]
at org.eclipse.jetty.server.HttpChannelState.complete(HttpChannelState.java:432) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]
at org.eclipse.jetty.server.AsyncContextState.complete(AsyncContextState.java:90) ~[jetty-server-9.0.4.v20130625.jar:9.0.4.v20130625]
at org.atmosphere.container.Servlet30CometSupport.action(Servlet30CometSupport.java:157) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]
at org.atmosphere.container.Servlet30CometSupport.action(Servlet30CometSupport.java:79) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]
at org.atmosphere.cpr.AtmosphereResourceImpl.resume(AtmosphereResourceImpl.java:326) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]
at org.atmosphere.jersey.util.JerseyBroadcasterUtil.broadcast(JerseyBroadcasterUtil.java:161) ~[atmosphere-jersey-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]
at org.atmosphere.jersey.JerseyBroadcaster.invokeOnStateChange(JerseyBroadcaster.java:77) ~[atmosphere-jersey-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]
at org.atmosphere.cpr.DefaultBroadcaster.prepareInvokeOnStateChange(DefaultBroadcaster.java:1047) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]
at org.atmosphere.cpr.DefaultBroadcaster.executeAsyncWrite(DefaultBroadcaster.java:921) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]
at org.atmosphere.cpr.DefaultBroadcaster$3.run(DefaultBroadcaster.java:580) ~[atmosphere-runtime-2.0.0-SNAPSHOT.jar:2.0.0-SNAPSHOT]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) ~[na:1.7.0_25]
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) ~[na:1.7.0_25]
at java.util.concurrent.FutureTask.run(FutureTask.java:166) ~[na:1.7.0_25]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) ~[na:1.7.0_25]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ~[na:1.7.0_25]
at java.lang.Thread.run(Thread.java:724) ~[na:1.7.0_25]
```
| 32f19d565b2883d91a9a9dbc52684891d58a8cd0 | 92f7d920deac3c0065ae504784a3b271d6b46fe7 | https://github.com/dropwizard/metrics/compare/32f19d565b2883d91a9a9dbc52684891d58a8cd0...92f7d920deac3c0065ae504784a3b271d6b46fe7 | diff --git a/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java b/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java
index 56805cdc9..503e7867f 100644
--- a/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java
+++ b/metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java
@@ -133,6 +133,8 @@ public class InstrumentedHandler extends HandlerWrapper {
this.otherRequests = metricRegistry.timer(name(prefix, "other-requests"));
this.listener = new AsyncListener() {
+ private long startTime;
+
@Override
public void onTimeout(AsyncEvent event) throws IOException {
asyncTimeouts.mark();
@@ -140,6 +142,7 @@ public class InstrumentedHandler extends HandlerWrapper {
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
+ startTime = System.currentTimeMillis();
event.getAsyncContext().addListener(this);
}
@@ -150,8 +153,9 @@ public class InstrumentedHandler extends HandlerWrapper {
@Override
public void onComplete(AsyncEvent event) throws IOException {
final AsyncContextState state = (AsyncContextState) event.getAsyncContext();
- final Request request = (Request) state.getRequest();
- updateResponses(request);
+ final HttpServletRequest request = (HttpServletRequest) state.getRequest();
+ final HttpServletResponse response = (HttpServletResponse) state.getResponse();
+ updateResponses(request, response, startTime);
if (!state.getHttpChannelState().isDispatched()) {
activeSuspended.dec();
}
@@ -197,7 +201,7 @@ public class InstrumentedHandler extends HandlerWrapper {
}
activeSuspended.inc();
} else if (state.isInitial()) {
- updateResponses(request);
+ updateResponses(httpRequest, httpResponse, start);
}
// else onCompletion will handle it.
}
@@ -233,13 +237,13 @@ public class InstrumentedHandler extends HandlerWrapper {
}
}
- private void updateResponses(Request request) {
- final int response = request.getResponse().getStatus() / 100;
- if (response >= 1 && response <= 5) {
- responses[response - 1].mark();
+ private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start) {
+ final int responseStatus = response.getStatus() / 100;
+ if (responseStatus >= 1 && responseStatus <= 5) {
+ responses[responseStatus - 1].mark();
}
activeRequests.dec();
- final long elapsedTime = System.currentTimeMillis() - request.getTimeStamp();
+ final long elapsedTime = System.currentTimeMillis() - start;
requests.update(elapsedTime, TimeUnit.MILLISECONDS);
requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS);
}
diff --git a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java
index 3c31cb66f..27b03900a 100644
--- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java
+++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java
@@ -133,6 +133,8 @@ public class InstrumentedHandler extends HandlerWrapper {
this.otherRequests = metricRegistry.timer(name(prefix, "other-requests"));
this.listener = new AsyncListener() {
+ private long startTime;
+
@Override
public void onTimeout(AsyncEvent event) throws IOException {
asyncTimeouts.mark();
@@ -140,6 +142,7 @@ public class InstrumentedHandler extends HandlerWrapper {
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
+ startTime = System.currentTimeMillis();
event.getAsyncContext().addListener(this);
}
@@ -150,8 +153,9 @@ public class InstrumentedHandler extends HandlerWrapper {
@Override
public void onComplete(AsyncEvent event) throws IOException {
final AsyncContextState state = (AsyncContextState) event.getAsyncContext();
- final Request request = (Request) state.getRequest();
- updateResponses(request);
+ final HttpServletRequest request = (HttpServletRequest) state.getRequest();
+ final HttpServletResponse response = (HttpServletResponse) state.getResponse();
+ updateResponses(request, response, startTime);
if (state.getHttpChannelState().getState() != HttpChannelState.State.DISPATCHED) {
activeSuspended.dec();
}
@@ -197,7 +201,7 @@ public class InstrumentedHandler extends HandlerWrapper {
}
activeSuspended.inc();
} else if (state.isInitial()) {
- updateResponses(request);
+ updateResponses(httpRequest, httpResponse, start);
}
// else onCompletion will handle it.
}
@@ -233,13 +237,13 @@ public class InstrumentedHandler extends HandlerWrapper {
}
}
- private void updateResponses(Request request) {
- final int response = request.getResponse().getStatus() / 100;
- if (response >= 1 && response <= 5) {
- responses[response - 1].mark();
+ private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start) {
+ final int responseStatus = response.getStatus() / 100;
+ if (responseStatus >= 1 && responseStatus <= 5) {
+ responses[responseStatus - 1].mark();
}
activeRequests.dec();
- final long elapsedTime = System.currentTimeMillis() - request.getTimeStamp();
+ final long elapsedTime = System.currentTimeMillis() - start;
requests.update(elapsedTime, TimeUnit.MILLISECONDS);
requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS);
} | ['metrics-jetty9-legacy/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java', 'metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 394,935 | 77,392 | 11,434 | 109 | 2,454 | 400 | 40 | 2 | 2,933 | 96 | 957 | 27 | 0 | 1 | 2013-12-27T14:26:23 | 7,744 | Java | {'Java': 1542841, 'Shell': 1659, 'Python': 351} | Apache License 2.0 |
102 | swagger-api/swagger-core/1579/1578 | swagger-api | swagger-core | https://github.com/swagger-api/swagger-core/issues/1578 | https://github.com/swagger-api/swagger-core/pull/1579 | https://github.com/swagger-api/swagger-core/pull/1579 | 1 | fixes | byte and binary properties are wrong | It looks like these two commits are backwards:
Addition of `binary` property:
https://github.com/swagger-api/swagger-core/commit/a18409eb69d9c69435bb2f0bbec7b2540b46616d
Addition of `byte` property:
https://github.com/swagger-api/swagger-core/commit/4e7a8014d14a8d0dd54f31f825858ae072be1061
| 05475b8552b8ac18864de841468f8665f8c3de10 | deda3feafc61377ccf55883cca0e396a07615bc5 | https://github.com/swagger-api/swagger-core/compare/05475b8552b8ac18864de841468f8665f8c3de10...deda3feafc61377ccf55883cca0e396a07615bc5 | diff --git a/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java b/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java
index 8c4980987..237c592c2 100644
--- a/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java
+++ b/modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java
@@ -1,19 +1,7 @@
package io.swagger.util;
import com.fasterxml.jackson.databind.type.TypeFactory;
-import io.swagger.models.properties.BaseIntegerProperty;
-import io.swagger.models.properties.BooleanProperty;
-import io.swagger.models.properties.DateProperty;
-import io.swagger.models.properties.DateTimeProperty;
-import io.swagger.models.properties.DecimalProperty;
-import io.swagger.models.properties.DoubleProperty;
-import io.swagger.models.properties.FloatProperty;
-import io.swagger.models.properties.IntegerProperty;
-import io.swagger.models.properties.LongProperty;
-import io.swagger.models.properties.ObjectProperty;
-import io.swagger.models.properties.Property;
-import io.swagger.models.properties.StringProperty;
-import io.swagger.models.properties.UUIDProperty;
+import io.swagger.models.properties.*;
import java.lang.reflect.Type;
import java.util.Collections;
@@ -49,8 +37,17 @@ public enum PrimitiveType {
*/
BYTE(Byte.class, "byte") {
@Override
- public StringProperty createProperty() {
- return new StringProperty(StringProperty.Format.BYTE);
+ public ByteArrayProperty createProperty() {
+ return new ByteArrayProperty();
+ }
+ },
+ /**
+ * Binary
+ */
+ BINARY(Byte.class, "binary") {
+ @Override
+ public BinaryProperty createProperty() {
+ return new BinaryProperty();
}
},
/**
diff --git a/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java b/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java
index b043684b1..ef27bd4cf 100644
--- a/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java
+++ b/modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java
@@ -4,10 +4,17 @@ import io.swagger.converter.ModelConverters;
import io.swagger.matchers.SerializationMatchers;
import io.swagger.models.Model;
+import io.swagger.models.ModelImpl;
+import io.swagger.models.properties.ArrayProperty;
+import io.swagger.models.properties.BinaryProperty;
+import io.swagger.models.properties.ByteArrayProperty;
+import io.swagger.util.Json;
import org.testng.annotations.Test;
import java.util.Map;
+import static org.testng.Assert.assertEquals;
+
public class ByteConverterTest {
@Test
@@ -30,6 +37,54 @@ public class ByteConverterTest {
SerializationMatchers.assertEqualsToJson(models, json);
}
+ @Test
+ public void testByteProperty() {
+ Model model = new ModelImpl()
+ .property("byteProperty", new ByteArrayProperty());
+
+ assertEquals(Json.pretty(model), "{\\n" +
+ " \\"properties\\" : {\\n" +
+ " \\"byteProperty\\" : {\\n" +
+ " \\"type\\" : \\"string\\",\\n" +
+ " \\"format\\" : \\"byte\\"\\n" +
+ " }\\n" +
+ " }\\n" +
+ "}");
+ }
+
+ @Test
+ public void testDeserializeByteProperty() throws Exception {
+ String json = "{\\n" +
+ " \\"properties\\" : {\\n" +
+ " \\"byteProperty\\" : {\\n" +
+ " \\"type\\" : \\"string\\",\\n" +
+ " \\"format\\" : \\"byte\\"\\n" +
+ " }\\n" +
+ " }\\n" +
+ "}";
+
+ Model model = Json.mapper().readValue(json, Model.class);
+ Json.prettyPrint(model);
+ }
+
+ @Test
+ public void testByteArray() {
+ Model model = new ModelImpl()
+ .property("byteArray", new ArrayProperty(new BinaryProperty()));
+
+ assertEquals(Json.pretty(model), "{\\n" +
+ " \\"properties\\" : {\\n" +
+ " \\"byteArray\\" : {\\n" +
+ " \\"type\\" : \\"array\\",\\n" +
+ " \\"items\\" : {\\n" +
+ " \\"type\\" : \\"string\\",\\n" +
+ " \\"format\\" : \\"binary\\"\\n" +
+ " }\\n" +
+ " }\\n" +
+ " }\\n" +
+ "}");
+ }
+
class ByteConverterModel {
public Byte[] myBytes = new Byte[0];
}
diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java
similarity index 74%
rename from modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java
rename to modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java
index c80d984b9..c1e20c5ac 100644
--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java
+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/BinaryProperty.java
@@ -2,73 +2,52 @@ package io.swagger.models.properties;
import io.swagger.models.Xml;
-import java.util.ArrayList;
import java.util.List;
-public class ByteProperty extends AbstractProperty implements Property {
+public class BinaryProperty extends AbstractProperty implements Property {
private static final String TYPE = "string";
-
- private static final String FORMAT = "byte";
-
protected List<String> _enum;
protected Integer minLength = null, maxLength = null;
protected String pattern = null;
protected String _default;
- public ByteProperty() {
- super.type = TYPE;
- super.format = FORMAT;
- }
-
- public ByteProperty _enum(String value) {
- if (this._enum == null) {
- this._enum = new ArrayList<String>();
- }
- if (!_enum.contains(value)) {
- _enum.add(value);
- }
- return this;
- }
-
- public ByteProperty _enum(List<String> value) {
- this._enum = value;
- return this;
+ public BinaryProperty() {
+ super.type = "string";
+ super.format = "binary";
}
public static boolean isType(String type, String format) {
- if (TYPE.equals(type) && FORMAT.equals(format)) {
+ if ("string".equals(type) && "binary".equals(format))
return true;
- } else {
- return false;
- }
+ else return false;
}
- public ByteProperty xml(Xml xml) {
+ public BinaryProperty xml(Xml xml) {
this.setXml(xml);
return this;
}
- public ByteProperty minLength(Integer minLength) {
+ public BinaryProperty minLength(Integer minLength) {
this.setMinLength(minLength);
return this;
}
- public ByteProperty maxLength(Integer maxLength) {
+ public BinaryProperty maxLength(Integer maxLength) {
this.setMaxLength(maxLength);
return this;
}
- public ByteProperty pattern(String pattern) {
+ public BinaryProperty pattern(String pattern) {
this.setPattern(pattern);
return this;
}
- public ByteProperty _default(String _default) {
+ public BinaryProperty _default(String _default) {
this._default = _default;
return this;
}
- public ByteProperty vendorExtension(String key, Object obj) {
+ public BinaryProperty vendorExtension(String key, Object obj) {
this.setVendorExtension(key, obj);
return this;
}
@@ -130,10 +109,10 @@ public class ByteProperty extends AbstractProperty implements Property {
if (!super.equals(obj)) {
return false;
}
- if (!(obj instanceof ByteProperty)) {
+ if (!(obj instanceof BinaryProperty)) {
return false;
}
- ByteProperty other = (ByteProperty) obj;
+ BinaryProperty other = (BinaryProperty) obj;
if (_default == null) {
if (other._default != null) {
return false;
diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java
index 496a7ed05..c6ba49a34 100644
--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java
+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java
@@ -2,18 +2,16 @@ package io.swagger.models.properties;
import io.swagger.models.Xml;
-import java.util.*;
-
public class ByteArrayProperty extends AbstractProperty implements Property {
public ByteArrayProperty() {
super.type = "string";
- super.format = "binary";
+ super.format = "byte";
}
public static boolean isType(String type, String format) {
- if ("string".equals(type) && "binary".equals(format))
+ if ("string".equals(type) && "byte".equals(format))
return true;
else return false;
}
diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java
index 750f788d2..8fb677dca 100644
--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java
+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java
@@ -156,6 +156,17 @@ public class PropertyBuilder {
return new ByteArrayProperty();
}
},
+ BINARY(BinaryProperty.class) {
+ @Override
+ protected boolean isType(String type, String format) {
+ return BinaryProperty.isType(type, format);
+ }
+
+ @Override
+ protected BinaryProperty create() {
+ return new BinaryProperty();
+ }
+ },
DATE(DateProperty.class) {
@Override
protected boolean isType(String type, String format) {
diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java
index 0dbb65ced..920ab1b3e 100644
--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java
+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java
@@ -17,7 +17,6 @@ public class StringProperty extends AbstractProperty implements Property {
protected String _default;
public enum Format {
- BYTE("byte"),
URI("uri"),
URL("url");
diff --git a/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java b/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java
index 19bf1ae6e..45be6930d 100644
--- a/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java
+++ b/modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java
@@ -1,21 +1,17 @@
package io.swagger;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotEquals;
-
import io.swagger.models.properties.StringProperty;
-
import org.testng.annotations.Test;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotEquals;
+
public class StringPropertyTest {
private static final String PROP_1 = "prop1";
private static final String PROP_2 = "prop2";
@Test
public void testEquals() {
- assertNotEquals(new StringProperty(StringProperty.Format.BYTE), new StringProperty(StringProperty.Format.URL));
- assertEquals(new StringProperty(StringProperty.Format.BYTE), new StringProperty(StringProperty.Format.BYTE));
-
final StringProperty prop1 = new StringProperty();
prop1.setName(PROP_1);
prop1.setRequired(true);
diff --git a/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java b/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java
index d32f3dc27..3c0ff8b69 100644
--- a/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java
+++ b/modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java
@@ -1,17 +1,15 @@
package io.swagger.models.properties;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.Iterator;
-import java.util.List;
-
+import io.swagger.models.properties.PropertyBuilder.PropertyId;
+import io.swagger.models.properties.StringProperty.Format;
import org.testng.Assert;
-
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
-import io.swagger.models.properties.PropertyBuilder.PropertyId;
-import io.swagger.models.properties.StringProperty.Format;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.Iterator;
+import java.util.List;
public class PropertyBuilderTest {
@@ -57,8 +55,8 @@ public class PropertyBuilderTest {
{"number", "float", FloatProperty.class},
{"number", "double", DoubleProperty.class},
{"string", null, StringProperty.class},
- {"string", "byte", StringProperty.class}, // are this and the next one correct?
- {"string", "binary", ByteArrayProperty.class},
+ {"string", "byte", ByteArrayProperty.class},
+ {"string", "binary", BinaryProperty.class},
{"boolean", null, BooleanProperty.class},
{"string", "date", DateProperty.class},
{"string", "date-time", DateTimeProperty.class}, | ['modules/swagger-core/src/main/java/io/swagger/util/PrimitiveType.java', 'modules/swagger-models/src/test/java/io/swagger/StringPropertyTest.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/ByteArrayProperty.java', 'modules/swagger-models/src/test/java/io/swagger/models/properties/PropertyBuilderTest.java', 'modules/swagger-core/src/test/java/io/swagger/ByteConverterTest.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/ByteProperty.java', 'modules/swagger-models/src/main/java/io/swagger/models/properties/StringProperty.java'] | {'.java': 8} | 8 | 8 | 0 | 0 | 8 | 578,968 | 111,634 | 18,293 | 165 | 1,727 | 295 | 45 | 5 | 293 | 18 | 96 | 8 | 2 | 0 | 2015-12-23T13:07:48 | 7,244 | Java | {'Java': 2870337, 'Shell': 9095, 'Python': 4538} | Apache License 2.0 |
101 | swagger-api/swagger-core/1678/1512 | swagger-api | swagger-core | https://github.com/swagger-api/swagger-core/issues/1512 | https://github.com/swagger-api/swagger-core/pull/1678 | https://github.com/swagger-api/swagger-core/pull/1678 | 1 | fix | swagger-servlet generating non-unique operationIds | using swagger-servlet-1.5.4.
first of all, @iushankin huuuge thanks for swagger-servlet migration with 1.5.4! works almost flawlessly.
i noticed that swagger-servlet will use `@ApiOperation`s `nickname` attribute for path generation as well as for `operationId`.
however, it may be necessary to have multiple operations with the same path (but different http methods).
in this case, the `nickname` is correctly used multiple times as path for different operations but also as `operationId` which means the `operationId` is no longer unique.
as a result, swagger editor - for example - shows errors:
> Cannot have multiple operations with the same operationId: /myPath
thanks, zyro
| 9e93afaf1ee7a9a0130b262fd2112b3c20bbb825 | b2ae3198f993ac3d20446e4da7725153c19185b3 | https://github.com/swagger-api/swagger-core/compare/9e93afaf1ee7a9a0130b262fd2112b3c20bbb825...b2ae3198f993ac3d20446e4da7725153c19185b3 | diff --git a/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java b/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java
index 5345b1a9f..5eaae4195 100644
--- a/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java
+++ b/modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java
@@ -222,7 +222,7 @@ public class ServletReaderExtension implements ReaderExtension {
final String operationPath = apiOperation == null ? null : apiOperation.nickname();
return PathUtils.collectPath(context.getParentPath(),
apiAnnotation == null ? null : apiAnnotation.value(),
- StringUtils.defaultIfBlank(operationPath, method.getName()));
+ method.getName());
}
@Override
diff --git a/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java b/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java
index a48d65190..a36bacfe1 100644
--- a/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java
+++ b/modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java
@@ -43,12 +43,12 @@ public class ReaderTest {
Assert.assertEquals(swagger.getHost(), "host");
Assert.assertEquals(swagger.getBasePath(), "/api");
- Assert.assertNotNull(swagger.getPath("/resources/users"));
+ Assert.assertNotNull(swagger.getPath("/resources/testMethod3"));
Assert.assertNotNull(swagger.getDefinitions().get("SampleData"));
Assert.assertEquals(swagger.getExternalDocs().getDescription(), "docs");
Assert.assertEquals(swagger.getExternalDocs().getUrl(), "url_to_docs");
- Path path = swagger.getPath("/resources/users");
+ Path path = swagger.getPath("/resources/testMethod3");
Assert.assertNotNull(path);
Operation get = path.getGet();
Assert.assertNotNull( get );
diff --git a/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java b/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java
index 4b643b073..3c1092335 100644
--- a/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java
+++ b/modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java
@@ -13,7 +13,7 @@ public class PathGetterTest extends BaseServletReaderExtensionTest {
return new Object[][]{
{"testMethod1", "/tests/resources/testMethod1"},
{"testMethod2", "/tests/resources/testMethod2"},
- {"testMethod3", "/tests/resources/users"},
+ {"testMethod3", "/tests/resources/testMethod3"},
{"testMethod4", "/tests/resources/testMethod4"},
};
}
@@ -23,7 +23,7 @@ public class PathGetterTest extends BaseServletReaderExtensionTest {
return new Object[][]{
{"testMethod1", "/tests/testMethod1"},
{"testMethod2", "/tests/testMethod2"},
- {"testMethod3", "/tests/users"},
+ {"testMethod3", "/tests/testMethod3"},
{"testMethod4", "/tests/testMethod4"},
};
} | ['modules/swagger-servlet/src/main/java/io/swagger/servlet/extensions/ServletReaderExtension.java', 'modules/swagger-servlet/src/test/java/io/swagger/servlet/extensions/PathGetterTest.java', 'modules/swagger-servlet/src/test/java/io/swagger/servlet/ReaderTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 601,624 | 116,159 | 18,969 | 167 | 114 | 15 | 2 | 1 | 686 | 100 | 159 | 14 | 0 | 0 | 2016-02-24T15:06:56 | 7,244 | Java | {'Java': 2870337, 'Shell': 9095, 'Python': 4538} | Apache License 2.0 |
103 | swagger-api/swagger-core/1556/1526 | swagger-api | swagger-core | https://github.com/swagger-api/swagger-core/issues/1526 | https://github.com/swagger-api/swagger-core/pull/1556 | https://github.com/swagger-api/swagger-core/pull/1556 | 1 | fixes | Example Value overwrites Parameter's DataType | Hi,
I encountered the following unexpected behavior. When specifying an example value in a `@ApiImplicitParam` annotation the parameter's dataType will be set to the example value.
For instance annotation
``` java
@ApiImplicitParam(name="id", paramType="path", dataType="string", example="123456")
```
will lead to JSON
``` json
"parameters":
[{"name":"id",
"in":"path",
"type":"123456",
"x-example":"123456"}]
```
This behavior was observed on swagger 1.5.4.
Cause is the `ParameterProcessor.applyAnnotations()` method. The following code found in the method overwrites the parameter's dataType:
``` java
if (StringUtils.isNotEmpty(param.getExample())) {
p.setType(param.getExample());
}
```
I am not really sure about the original intention of the code but it does not look right to me. The code was introduced by commit 62c100f33a54d7688e859cd011abb89a907e02ef "added example support for non-body params, implicits".
Best regards,
phosn
| 436a9cb792be23fc835cf2dcbe1bdb087590f483 | edeca227123e85ab03666f3d5e131d6e2c457663 | https://github.com/swagger-api/swagger-core/compare/436a9cb792be23fc835cf2dcbe1bdb087590f483...edeca227123e85ab03666f3d5e131d6e2c457663 | diff --git a/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java b/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java
index b75656013..adb4106f0 100644
--- a/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java
+++ b/modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java
@@ -67,9 +67,6 @@ public class ParameterProcessor {
p.setType(param.getDataType());
}
}
- if (StringUtils.isNotEmpty(param.getExample())) {
- p.setType(param.getExample());
- }
if (helper.getMinItems() != null) {
p.setMinItems(helper.getMinItems());
}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java b/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java
index 63f6d5da6..fbf438d74 100644
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java
+++ b/modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java
@@ -13,7 +13,7 @@ public class ResourceWithImplicitFileParam {
@POST
@Path("/testString")
@ApiImplicitParams({
- @ApiImplicitParam(name = "sort", paramType = "form", dataType = "java.io.File", required = false, value = "file to upload")
+ @ApiImplicitParam(name = "sort", paramType = "form", dataType = "java.io.File", required = false, value = "file to upload")
})
@ApiOperation("Test operation with implicit parameters")
public void testImplicitFileParam() { | ['modules/swagger-core/src/main/java/io/swagger/util/ParameterProcessor.java', 'modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithImplicitFileParam.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 564,498 | 108,724 | 17,783 | 163 | 125 | 19 | 3 | 1 | 969 | 116 | 236 | 36 | 0 | 3 | 2015-11-28T17:33:13 | 7,244 | Java | {'Java': 2870337, 'Shell': 9095, 'Python': 4538} | Apache License 2.0 |
104 | swagger-api/swagger-core/1453/1440 | swagger-api | swagger-core | https://github.com/swagger-api/swagger-core/issues/1440 | https://github.com/swagger-api/swagger-core/pull/1453 | https://github.com/swagger-api/swagger-core/pull/1453 | 1 | fixes | The ApiOperation.nickname property does not work | The reason: please check this class: io.swagger.jaxrs.Reader, line 711
I think there should be: operationId = apiOperation.nickname();
instead of: operationId = method.getName();
Sincerely yours
Nazar
| 4e6793564819457e5724464b27a782afad145e10 | 91a4dbef7c3756ecc69f334bd5d7a89ecf4b5737 | https://github.com/swagger-api/swagger-core/compare/4e6793564819457e5724464b27a782afad145e10...91a4dbef7c3756ecc69f334bd5d7a89ecf4b5737 | diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java
index 937ec0a52..464d77c2a 100644
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java
+++ b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java
@@ -714,7 +714,7 @@ public class Reader {
return null;
}
if (!"".equals(apiOperation.nickname())) {
- operationId = method.getName();
+ operationId = apiOperation.nickname();
}
defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); | ['modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 532,171 | 102,641 | 16,824 | 160 | 104 | 15 | 2 | 1 | 203 | 25 | 49 | 7 | 0 | 0 | 2015-09-22T14:55:56 | 7,244 | Java | {'Java': 2870337, 'Shell': 9095, 'Python': 4538} | Apache License 2.0 |
105 | swagger-api/swagger-core/1262/1175 | swagger-api | swagger-core | https://github.com/swagger-api/swagger-core/issues/1175 | https://github.com/swagger-api/swagger-core/pull/1262 | https://github.com/swagger-api/swagger-core/pull/1262 | 1 | fixes | Change logging level to DEBUG for some messages in PropertyBuilder | Change logging level for [this](https://github.com/swagger-api/swagger-core/blob/400662d7253c0c2efb14316f8948ddc61a60069e/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java#L569) message to DEBUG as these messages look confusing for [codegen](https://github.com/swagger-api/swagger-codegen) users (https://github.com/swagger-api/swagger-parser/issues/60).
| 42056f20c52407e4c13283794a65d6d71b3a7e41 | 183a6fccd65bc0cd6de129aa2c7b35b13bfd2797 | https://github.com/swagger-api/swagger-core/compare/42056f20c52407e4c13283794a65d6d71b3a7e41...183a6fccd65bc0cd6de129aa2c7b35b13bfd2797 | diff --git a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java
index 41fbdf96a..660d11c86 100644
--- a/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java
+++ b/modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java
@@ -566,7 +566,7 @@ public class PropertyBuilder {
return item;
}
}
- LOGGER.error("no property for " + type + ", " + format);
+ LOGGER.debug("no property for " + type + ", " + format);
return null;
}
| ['modules/swagger-models/src/main/java/io/swagger/models/properties/PropertyBuilder.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 438,099 | 84,995 | 14,008 | 142 | 139 | 32 | 2 | 1 | 392 | 17 | 96 | 2 | 3 | 0 | 2015-07-14T10:15:32 | 7,244 | Java | {'Java': 2870337, 'Shell': 9095, 'Python': 4538} | Apache License 2.0 |
107 | swagger-api/swagger-core/1190/1185 | swagger-api | swagger-core | https://github.com/swagger-api/swagger-core/issues/1185 | https://github.com/swagger-api/swagger-core/pull/1190 | https://github.com/swagger-api/swagger-core/pull/1190 | 1 | fixes | 'hidden' variable is not used | 'hidden' variable is declared, but isn't used https://github.com/swagger-api/swagger-core/blob/9c67549cc4e30db916dac0165f0549485a6eb4c7/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java#L834-L837
| 8999c5b5a862cc4b9f533d1692ba9db7858b1d5f | a671881ac26a1df940012f2b2ff370d393f2dfee | https://github.com/swagger-api/swagger-core/compare/8999c5b5a862cc4b9f533d1692ba9db7858b1d5f...a671881ac26a1df940012f2b2ff370d393f2dfee | diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java
index 1657326ca..145416564 100644
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java
+++ b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java
@@ -829,11 +829,6 @@ public class Reader {
operation.setDeprecated(true);
}
- boolean hidden = false;
- if (apiOperation != null) {
- hidden = apiOperation.hidden();
- }
-
// process parameters
for (Parameter globalParameter : globalParameters) {
operation.parameter(globalParameter); | ['modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 431,150 | 83,484 | 13,753 | 140 | 127 | 24 | 5 | 1 | 211 | 8 | 66 | 2 | 1 | 0 | 2015-06-22T14:55:41 | 7,244 | Java | {'Java': 2870337, 'Shell': 9095, 'Python': 4538} | Apache License 2.0 |
109 | swagger-api/swagger-core/1033/1000 | swagger-api | swagger-core | https://github.com/swagger-api/swagger-core/issues/1000 | https://github.com/swagger-api/swagger-core/pull/1033 | https://github.com/swagger-api/swagger-core/pull/1033 | 1 | fixes | NPE without any class with @Api annotation | If there is no class with `@Api` annotation trying to get `swagger.json` causes NPE. This may be very confusing at the beginning, when we are implementing Swagger step-by-step and get exception.
Stack:
```
java.lang.NullPointerException
at com.wordnik.swagger.jaxrs.config.BeanConfig.configure(BeanConfig.java:196)
at com.wordnik.swagger.jaxrs.listing.ApiListingResource.scan(ApiListingResource.java:52)
at com.wordnik.swagger.jaxrs.listing.ApiListingResource.getListingJson(ApiListingResource.java:79)
...
```
So we have to check for nulls somewhere in this area: https://github.com/swagger-api/swagger-core/blob/c4260bea041027f9887c67d5d6c6eb408c238969/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/config/BeanConfig.java#L197
| e9cad60100c883f171b6d2a989ee6eb398fd3a25 | e2e459b0a134e4310b91f60e2fb31625a40f57f0 | https://github.com/swagger-api/swagger-core/compare/e9cad60100c883f171b6d2a989ee6eb398fd3a25...e2e459b0a134e4310b91f60e2fb31625a40f57f0 | diff --git a/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java
index 0574c9891..23aea9a17 100644
--- a/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java
+++ b/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java
@@ -58,7 +58,7 @@ public class Reader {
static ObjectMapper m = Json.mapper();
public Reader(Swagger swagger) {
- this.swagger = swagger;
+ this.swagger = swagger == null ? new Swagger() : swagger;
}
public Swagger read(Set<Class<?>> classes) {
@@ -76,8 +76,6 @@ public class Reader {
}
protected Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean readHidden, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters) {
- if(swagger == null)
- swagger = new Swagger();
Api api = (Api) cls.getAnnotation(Api.class);
Map<String, SecurityScope> globalScopes = new HashMap<String, SecurityScope>();
| ['modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/Reader.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 887,167 | 204,437 | 29,102 | 399 | 148 | 33 | 4 | 1 | 764 | 54 | 192 | 14 | 1 | 1 | 2015-05-05T11:23:24 | 7,244 | Java | {'Java': 2870337, 'Shell': 9095, 'Python': 4538} | Apache License 2.0 |
100 | swagger-api/swagger-core/1718/1714 | swagger-api | swagger-core | https://github.com/swagger-api/swagger-core/issues/1714 | https://github.com/swagger-api/swagger-core/pull/1718 | https://github.com/swagger-api/swagger-core/pull/1718 | 1 | fix | jersey2 listing resource broken | 1.5.8 seems to have broken the listing resource for jersey2. Now this class:
``` java
package io.swagger.jersey.listing;
/* */
@Path("/")
public class ApiListingResourceJSON
extends ApiListingResource {
}
```
causes the swagger definition to appear only on `"/"` instead of `"/swagger.{type:json|yaml}"` as defined in the `io.swagger.jaxrs.listing.ApiListingResource` class
The solution is to use `io.swagger.jaxrs.listing.ApiListingResource`, but for previous uses (like swagger-generator), the 1.5.8 changes break the resource.
We should either fix the ApiListingResourceJSON, remove it, or make it clear how to update when going to 1.5.8.
| 3e5a7e613daaa95028f3aeb45cd8545c14deaa8c | 2425b7f3aa36d7661777ca8819445180af792431 | https://github.com/swagger-api/swagger-core/compare/3e5a7e613daaa95028f3aeb45cd8545c14deaa8c...2425b7f3aa36d7661777ca8819445180af792431 | diff --git a/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java b/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java
index 05a54d0cf..dbe40f642 100644
--- a/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java
+++ b/modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java
@@ -2,9 +2,7 @@ package io.swagger.jersey.listing;
import io.swagger.jaxrs.listing.ApiListingResource;
-import javax.ws.rs.Path;
-
-@Path("/")
+@Deprecated
public class ApiListingResourceJSON
extends ApiListingResource {
}
\\ No newline at end of file | ['modules/swagger-jersey2-jaxrs/src/main/java/io/swagger/jersey/listing/ApiListingResourceJSON.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 618,360 | 119,346 | 19,394 | 169 | 52 | 12 | 4 | 1 | 656 | 83 | 164 | 18 | 0 | 1 | 2016-03-18T11:21:07 | 7,244 | Java | {'Java': 2870337, 'Shell': 9095, 'Python': 4538} | Apache License 2.0 |
8,978 | karatelabs/karate/1556/1555 | karatelabs | karate | https://github.com/karatelabs/karate/issues/1555 | https://github.com/karatelabs/karate/pull/1556 | https://github.com/karatelabs/karate/pull/1556 | 1 | fixes | `logPrettyResponse` configuration parameter is not considered | `logPrettyResponse` is not considered when configured, either in `karate-config.js` or in the feature itself.
Looking at the code I found the issue and will submit a PR to fix it.
| e2b4f3a875805da0a6f2531952af26540eb7c7c1 | d5abda97bfcd507f7bd1fcd5b31a876f564b5bc5 | https://github.com/karatelabs/karate/compare/e2b4f3a875805da0a6f2531952af26540eb7c7c1...d5abda97bfcd507f7bd1fcd5b31a876f564b5bc5 | diff --git a/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java b/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java
index f6d7466cd..bc5464d12 100644
--- a/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java
+++ b/karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java
@@ -69,7 +69,7 @@ public class HttpLogger {
}
Variable v = new Variable(body);
String text;
- if (config != null && config.isLogPrettyRequest()) {
+ if (config != null && needsPrettyLogging(config, request)) {
text = v.getAsPrettyString();
} else {
text = v.getAsString();
@@ -80,6 +80,18 @@ public class HttpLogger {
sb.append(text);
}
+ private static boolean needsPrettyLogging(Config config, boolean request) {
+ return logPrettyRequest(config, request) || logPrettyResponse(config, request);
+ }
+
+ private static boolean logPrettyResponse(Config config, boolean request) {
+ return !request && config.isLogPrettyResponse();
+ }
+
+ private static boolean logPrettyRequest(Config config, boolean request) {
+ return request && config.isLogPrettyRequest();
+ }
+
private static HttpLogModifier logModifier(Config config, String uri) {
HttpLogModifier logModifier = config.getLogModifier();
return logModifier == null ? null : logModifier.enableForUri(uri) ? logModifier : null; | ['karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,614,061 | 334,168 | 47,449 | 310 | 601 | 115 | 14 | 1 | 182 | 30 | 42 | 3 | 0 | 0 | 2021-04-13T13:52:49 | 7,226 | Java | {'Java': 2164729, 'Gherkin': 262656, 'JavaScript': 70334, 'HTML': 44272, 'Scala': 13901, 'CSS': 7856, 'ANTLR': 4088, 'Shell': 3629, 'Dockerfile': 2919} | MIT License |
8,977 | karatelabs/karate/2376/2259 | karatelabs | karate | https://github.com/karatelabs/karate/issues/2259 | https://github.com/karatelabs/karate/pull/2376 | https://github.com/karatelabs/karate/pull/2376 | 1 | resolves | Double Click and Right Click in Karate Robot framework for windows app | Double click doesnt work in Karate Robot framework for windows app
```
locate('abc').doubleClick(0,0)
```
It clicks twice but does it slowly such that the double click does not really work. I found doubleClick() method in RobotBase.Java which has a 40ms delay between the clicks and i'm not sure if that is the reason behind the lag in clicks.
Right Click also doesnt work as there is no method in Element.java but there is a rightClick() method in RobotBase.Java which calls Click(3) internally | 7e1f3b3bb0405847722f814d4ab8fed08e7f8832 | 7ee8b8bd272a7e12a7e2318a193ab84b4c45da6a | https://github.com/karatelabs/karate/compare/7e1f3b3bb0405847722f814d4ab8fed08e7f8832...7ee8b8bd272a7e12a7e2318a193ab84b4c45da6a | diff --git a/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java b/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java
index af420922a..0ee7dfbfc 100644
--- a/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java
+++ b/karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java
@@ -277,7 +277,7 @@ public abstract class RobotBase implements Robot, Plugin {
@Override
public Robot rightClick() {
- return click(3);
+ return click(2);
}
@Override
@@ -299,9 +299,20 @@ public abstract class RobotBase implements Robot, Plugin {
@Override
public Robot doubleClick() {
- click();
- delay(40);
- click();
+ if (highlight) {
+ getLocation().highlight(highlightDuration);
+ int toDelay = highlightDuration;
+ if (toDelay > 0) {
+ RobotUtils.delay(toDelay);
+ }
+ }
+ int clickType = mask(1);
+ robot.mousePress(clickType);
+ robot.mouseRelease(clickType);
+ RobotUtils.delay(100);
+ robot.mousePress(clickType);
+ robot.mouseRelease(clickType);
+
return this;
}
| ['karate-robot/src/main/java/com/intuit/karate/robot/RobotBase.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,727,793 | 357,449 | 50,168 | 307 | 562 | 110 | 19 | 1 | 504 | 82 | 115 | 7 | 0 | 1 | 2023-08-04T21:47:12 | 7,226 | Java | {'Java': 2164729, 'Gherkin': 262656, 'JavaScript': 70334, 'HTML': 44272, 'Scala': 13901, 'CSS': 7856, 'ANTLR': 4088, 'Shell': 3629, 'Dockerfile': 2919} | MIT License |
3,321 | apache/beam/27699/27670 | apache | beam | https://github.com/apache/beam/issues/27670 | https://github.com/apache/beam/pull/27699 | https://github.com/apache/beam/pull/27699 | 1 | fixes | [Bug]: Storage Write API fails on Batch Pipelines on 2.49 | ### What happened?
When writing to a BigQuery sink in a Batch pipeline using Storage Write API the pipeline fails due to the following error,
```
java.lang.RuntimeException: org.apache.beam.sdk.util.UserCodeException: java.lang.RuntimeException: Schema field not found: eventid
at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowsParDoFn.java:187 )
at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner$1.outputWindowedValue ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:108 )
at org.apache.beam.runners.dataflow.worker.util.BatchGroupAlsoByWindowReshuffleFn.processElement ( org/apache.beam.runners.dataflow.worker.util/BatchGroupAlsoByWindowReshuffleFn.java:56 )
at org.apache.beam.runners.dataflow.worker.util.BatchGroupAlsoByWindowReshuffleFn.processElement ( org/apache.beam.runners.dataflow.worker.util/BatchGroupAlsoByWindowReshuffleFn.java:39 )
at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.invokeProcessElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:121 )
at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.processElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowFnRunner.java:73 )
at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn.processElement ( org/apache.beam.runners.dataflow.worker/GroupAlsoByWindowsParDoFn.java:117 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( org/apache.beam.runners.dataflow.worker.util.common.worker/ParDoOperation.java:44 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( org/apache.beam.runners.dataflow.worker.util.common.worker/OutputReceiver.java:54 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop ( org/apache.beam.runners.dataflow.worker.util.common.worker/ReadOperation.java:218 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start ( org/apache.beam.runners.dataflow.worker.util.common.worker/ReadOperation.java:169 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute ( org/apache.beam.runners.dataflow.worker.util.common.worker/MapTaskExecutor.java:83 )
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.executeWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:319 )
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.doWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:291 )
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.getAndPerformWork ( org/apache.beam.runners.dataflow.worker/BatchDataflowWorker.java:221 )
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.doWork ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:147 )
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:127 )
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call ( org/apache.beam.runners.dataflow.worker/DataflowBatchWorkerHarness.java:114 )
at java.util.concurrent.FutureTask.run ( java/util.concurrent/FutureTask.java:264 )
at org.apache.beam.sdk.util.UnboundedScheduledExecutorService$ScheduledFutureTask.run ( org/apache.beam.sdk.util/UnboundedScheduledExecutorService.java:163 )
at java.util.concurrent.ThreadPoolExecutor.runWorker ( java/util.concurrent/ThreadPoolExecutor.java:1128 )
at java.util.concurrent.ThreadPoolExecutor$Worker.run ( java/util.concurrent/ThreadPoolExecutor.java:628 )
at java.lang.Thread.run ( java/lang/Thread.java:834 )
Caused by: org.apache.beam.sdk.util.UserCodeException
at org.apache.beam.sdk.util.UserCodeException.wrap ( UserCodeException.java:39 )
at org.apache.beam.sdk.io.gcp.bigquery.StorageApiConvertMessages$ConvertMessagesDoFn$DoFnInvoker.invokeProcessElement
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )
at org.apache.beam.runners.dataflow.worker.AssignWindowsParDoFnFactory$AssignWindowsParDoFn.processElement ( AssignWindowsParDoFnFactory.java:115 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 )
at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement ( PrepareWrite.java:84 )
at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1$DoFnInvoker.invokeProcessElement
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:185 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 )
at org.apache.beam.sdk.io.jdbc.JdbcIO$ReadFn.processElement ( JdbcIO.java:1528 )
at org.apache.beam.sdk.io.jdbc.JdbcIO$ReadFn$DoFnInvoker.invokeProcessElement
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 )
at org.apache.beam.sdk.transforms.DoFnOutputReceivers$WindowedContextOutputReceiver.output ( DoFnOutputReceivers.java:76 )
at org.apache.beam.sdk.transforms.MapElements$2.processElement ( MapElements.java:151 )
at org.apache.beam.sdk.transforms.MapElements$2$DoFnInvoker.invokeProcessElement
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn$1.output ( SimpleParDoFn.java:285 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.outputWindowedValue ( SimpleDoFnRunner.java:275 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.access$900 ( SimpleDoFnRunner.java:85 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:423 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner$DoFnProcessContext.output ( SimpleDoFnRunner.java:411 )
at org.apache.beam.runners.dataflow.ReshuffleOverrideFactory$ReshuffleWithOnlyTrigger$1.processElement ( ReshuffleOverrideFactory.java:86 )
at org.apache.beam.runners.dataflow.ReshuffleOverrideFactory$ReshuffleWithOnlyTrigger$1$DoFnInvoker.invokeProcessElement
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement ( SimpleDoFnRunner.java:211 )
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement ( SimpleDoFnRunner.java:188 )
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement ( SimpleParDoFn.java:340 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process ( ParDoOperation.java:44 )
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process ( OutputReceiver.java:54 )
at org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output ( GroupAlsoByWindowsParDoFn.java:185 )
Caused by: java.lang.RuntimeException
at org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto$SchemaInformation.getSchemaForField ( TableRowToStorageApiProto.java:371 )
at org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto.messageFromMap ( TableRowToStorageApiProto.java:472 )
at org.apache.beam.sdk.io.gcp.bigquery.TableRowToStorageApiProto.messageFromTableRow ( TableRowToStorageApiProto.java:625 )
at org.apache.beam.sdk.io.gcp.bigquery.StorageApiDynamicDestinationsTableRow$TableRowConverter.toMessage ( StorageApiDynamicDestinationsTableRow.java:170 )
at org.apache.beam.sdk.io.gcp.bigquery.StorageApiConvertMessages$ConvertMessagesDoFn.processElement ( StorageApiConvertMessages.java:159 )
```
The field `eventId` exists but for some reason the case of the field changes.
This does not occur in when using File Loads method.
### Issue Priority
Priority: 1 (data loss / total loss of function)
### Issue Components
- [ ] Component: Python SDK
- [X] Component: Java SDK
- [ ] Component: Go SDK
- [ ] Component: Typescript SDK
- [x] Component: IO connector
- [ ] Component: Beam examples
- [ ] Component: Beam playground
- [ ] Component: Beam katas
- [ ] Component: Website
- [ ] Component: Spark Runner
- [ ] Component: Flink Runner
- [ ] Component: Samza Runner
- [ ] Component: Twister2 Runner
- [ ] Component: Hazelcast Jet Runner
- [ ] Component: Google Cloud Dataflow Runner | f35a6365e8a6a67e74e933f29789f5bbf5f59315 | 2e958499e5d9060706d54b2fd99a347e48f3f1db | https://github.com/apache/beam/compare/f35a6365e8a6a67e74e933f29789f5bbf5f59315...2e958499e5d9060706d54b2fd99a347e48f3f1db | diff --git a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java
index d231d84aea..d98f9115cb 100644
--- a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java
+++ b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java
@@ -344,7 +344,7 @@ public class TableRowToStorageApiProto {
new SchemaInformation(
field, Iterables.concat(this.parentSchemas, ImmutableList.of(this)));
subFields.add(schemaInformation);
- subFieldsByName.put(field.getName(), schemaInformation);
+ subFieldsByName.put(field.getName().toLowerCase(), schemaInformation);
}
}
@@ -365,9 +365,9 @@ public class TableRowToStorageApiProto {
}
public SchemaInformation getSchemaForField(String name) {
- SchemaInformation schemaInformation = subFieldsByName.get(name);
+ SchemaInformation schemaInformation = subFieldsByName.get(name.toLowerCase());
if (schemaInformation == null) {
- throw new RuntimeException("Schema field not found: " + name);
+ throw new RuntimeException("Schema field not found: " + name.toLowerCase());
}
return schemaInformation;
}
diff --git a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java
index 534c1b0c36..6405c0599e 100644
--- a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java
+++ b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java
@@ -1824,7 +1824,7 @@ public class BigQueryIOWriteTest implements Serializable {
new SimpleFunction<Long, TableRow>() {
@Override
public TableRow apply(Long input) {
- return new TableRow().set("name", "name " + input).set("number", input);
+ return new TableRow().set("NaMe", "name " + input).set("numBEr", input);
}
}))
.setCoder(TableRowJsonCoder.of()); | ['sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java', 'sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 26,087,797 | 5,616,266 | 667,143 | 3,970 | 461 | 78 | 6 | 1 | 12,687 | 590 | 2,911 | 125 | 0 | 1 | 2023-07-26T21:22:07 | 7,039 | Java | {'Java': 44997581, 'Python': 11684345, 'Go': 6460783, 'TypeScript': 2009450, 'Dart': 1436710, 'Groovy': 981282, 'Shell': 411640, 'SCSS': 319433, 'Kotlin': 251827, 'HCL': 233427, 'HTML': 200724, 'JavaScript': 122178, 'Cython': 75277, 'Dockerfile': 73608, 'Jupyter Notebook': 61209, 'Sass': 27577, 'FreeMarker': 7933, 'CSS': 7584, 'Rust': 5168, 'C': 3869, 'Lua': 3620, 'Thrift': 3260, 'Smarty': 2618, 'ANTLR': 1598, 'Scala': 1429} | Apache License 2.0 |
516 | google/closure-compiler/1409/1407 | google | closure-compiler | https://github.com/google/closure-compiler/issues/1407 | https://github.com/google/closure-compiler/pull/1409 | https://github.com/google/closure-compiler/pull/1409 | 1 | fixes | Cannot use globs when running the compiler. | Since 62ca536... I am no longer able to use globs for files when running the compiler:
Running this command used to work before that change:
```
java -jar ../../compiler/compiler.jar \\
--flagfile=options/compile.ini \\
--define "goog.json.USE_NATIVE_JSON=true" --define "goog.ui.Component.ALLOW_DETACHED_DECORATION=true" --define "goog.NATIVE_ARRAY_PROTOTYPES=true" --define "goog.array.ASSUME_NATIVE_FUNCTIONS=true" --define "goog.Promise.UNHANDLED_REJECTION_DELAY=-1" --define "app.settings.RUN_AS_USER=false" --externs=../externs/material.js --generate_exports --export_local_property_definitions --language_in=ECMASCRIPT6 --language_out=ES3 --use_types_for_optimization --output_wrapper="(function(){%output%})();" \\
--only_closure_dependencies \\
--closure_entry_point=app \\
--manage_closure_dependencies true \\
--output_manifest build/app.filelist.txt \\
--js_output_file /tmp/closure_compiler_build \\
--js="js/**.js" --js="tpl/en/**.js" --js="../../templates/soyutils_usegoog.js" --js="../../library/closure/goog/**.js" --js="../../library/third_party/closure/goog/mochikit/async/deferred.js" --js="../../library/third_party/closure/goog/mochikit/async/deferredlist.js" --js="../pstj/animation/**.js" --js="../pstj/app/**.js" --js="../pstj/autogenerated/**.js" --js="../pstj/cast/**.js" --js="../pstj/color/**.js" --js="../pstj/config/**.js" --js="../pstj/control/**.js" --js="../pstj/date/**.js" --js="../pstj/debug/**.js" --js="../pstj/ds/**.js" --js="../pstj/element/**.js" --js="../pstj/error/**.js" --js="../pstj/fx/**.js" --js="../pstj/graphics/**.js" --js="../pstj/material/**.js" --js="../pstj/math/**.js" --js="../pstj/mvc/**.js" --js="../pstj/ng/**.js" --js="../pstj/object/**.js" --js="../pstj/options/**.js" --js="../pstj/resource/**.js" --js="../pstj/sourcegen/**.js" --js="../pstj/storage/**.js" --js="../pstj/style/**.js" --js="../pstj/themes/**.js" --js="../pstj/ui/**.js" --js="../smjs/ds/**.js" --js="../smjs/element/**.js" --js="../smjs/persistence/**.js" --js="../smjs/player/**.js" --js="../smjs/remotecontrol/**.js" --js="../smjs/transport/**.js" --js="../smjs/tv/**.js" --js="../smjs/widgets/**.js" --js="!**_test.js"
```
Now (after the mentioned change) it gives this:
```
ERROR - Cannot read: !**_test.js
ERROR - Cannot read: ../../library/closure/goog/**.js
ERROR - Cannot read: ../pstj/animation/**.js
ERROR - Cannot read: ../pstj/app/**.js
ERROR - Cannot read: ../pstj/autogenerated/**.js
ERROR - Cannot read: ../pstj/cast/**.js
ERROR - Cannot read: ../pstj/color/**.js
ERROR - Cannot read: ../pstj/config/**.js
ERROR - Cannot read: ../pstj/control/**.js
ERROR - Cannot read: ../pstj/date/**.js
ERROR - Cannot read: ../pstj/debug/**.js
ERROR - Cannot read: ../pstj/ds/**.js
ERROR - Cannot read: ../pstj/element/**.js
ERROR - Cannot read: ../pstj/error/**.js
ERROR - Cannot read: ../pstj/fx/**.js
ERROR - Cannot read: ../pstj/graphics/**.js
ERROR - Cannot read: ../pstj/material/**.js
ERROR - Cannot read: ../pstj/math/**.js
ERROR - Cannot read: ../pstj/mvc/**.js
ERROR - Cannot read: ../pstj/ng/**.js
ERROR - Cannot read: ../pstj/object/**.js
ERROR - Cannot read: ../pstj/options/**.js
ERROR - Cannot read: ../pstj/resource/**.js
ERROR - Cannot read: ../pstj/sourcegen/**.js
ERROR - Cannot read: ../pstj/storage/**.js
ERROR - Cannot read: ../pstj/style/**.js
ERROR - Cannot read: ../pstj/themes/**.js
ERROR - Cannot read: ../pstj/ui/**.js
ERROR - Cannot read: ../smjs/ds/**.js
ERROR - Cannot read: ../smjs/element/**.js
ERROR - Cannot read: ../smjs/persistence/**.js
ERROR - Cannot read: ../smjs/player/**.js
ERROR - Cannot read: ../smjs/remotecontrol/**.js
ERROR - Cannot read: ../smjs/transport/**.js
ERROR - Cannot read: ../smjs/tv/**.js
ERROR - Cannot read: ../smjs/widgets/**.js
ERROR - Cannot read: js/**.js
ERROR - Cannot read: tpl/en/**.js
ERROR - required entry point "app" never provided
39 error(s), 0 warning(s)
```
| 00adf761809e997aadadcf07050310d5d1dbad68 | dfd1853feeb252fd57cf245816cef4305d3e1fe8 | https://github.com/google/closure-compiler/compare/00adf761809e997aadadcf07050310d5d1dbad68...dfd1853feeb252fd57cf245816cef4305d3e1fe8 | diff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java
index 34c79d686..019b4d62e 100644
--- a/src/com/google/javascript/jscomp/CommandLineRunner.java
+++ b/src/com/google/javascript/jscomp/CommandLineRunner.java
@@ -26,8 +26,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
-import com.google.javascript.jscomp.AbstractCommandLineRunner.FlagEntry;
-import com.google.javascript.jscomp.AbstractCommandLineRunner.JsSourceType;
import com.google.javascript.jscomp.SourceMap.LocationMapping;
import com.google.javascript.rhino.TokenStream;
import com.google.protobuf.TextFormat;
@@ -47,8 +45,8 @@ import org.kohsuke.args4j.spi.StringOptionHandler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
-import java.io.InputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.lang.reflect.AnnotatedElement;
@@ -64,10 +62,10 @@ import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.TreeSet;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -732,6 +730,28 @@ public class CommandLineRunner extends
return allJsInputs;
}
+ protected List<FlagEntry<JsSourceType>> getMixedJsSources()
+ throws CmdLineException, IOException {
+ List<FlagEntry<JsSourceType>> mixedSources = new ArrayList<>();
+ for (FlagEntry<JsSourceType> source : Flags.mixedJsSources) {
+ if (source.value.endsWith(".zip")) {
+ mixedSources.add(source);
+ } else {
+ for (String filename : findJsFiles(Collections.singletonList(source.value))) {
+ mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));
+ }
+ }
+ }
+ List<String> fromArguments = findJsFiles(arguments);
+ for (String filename : fromArguments) {
+ mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));
+ }
+ if (!Flags.mixedJsSources.isEmpty() && !arguments.isEmpty() && mixedSources.isEmpty()) {
+ throw new CmdLineException(parser, "No inputs matched");
+ }
+ return mixedSources;
+ }
+
List<SourceMap.LocationMapping> getSourceMapLocationMappings() throws CmdLineException {
ImmutableList.Builder<LocationMapping> locationMappings = ImmutableList.builder();
@@ -1078,6 +1098,7 @@ public class CommandLineRunner extends
Flags.mixedJsSources.clear();
List<String> jsFiles = null;
+ List<FlagEntry<JsSourceType>> mixedSources = null;
List<LocationMapping> mappings = null;
ImmutableMap<String, String> sourceMapInputs = null;
try {
@@ -1089,6 +1110,7 @@ public class CommandLineRunner extends
}
jsFiles = flags.getJsFiles();
+ mixedSources = flags.getMixedJsSources();
mappings = flags.getSourceMapLocationMappings();
sourceMapInputs = flags.getSourceMapInputs();
} catch (CmdLineException e) {
@@ -1207,7 +1229,7 @@ public class CommandLineRunner extends
.setExterns(flags.externs)
.setJs(jsFiles)
.setJsZip(flags.jszip)
- .setMixedJsSources(Flags.mixedJsSources)
+ .setMixedJsSources(mixedSources)
.setJsOutputFile(flags.jsOutputFile)
.setModule(flags.module)
.setVariableMapOutputFile(flags.variableMapOutputFile)
@@ -1437,7 +1459,7 @@ public class CommandLineRunner extends
* within the directory and sub-directories.
*/
public static List<String> findJsFiles(Collection<String> patterns) throws IOException {
- Set<String> allJsInputs = new LinkedHashSet<>();
+ Set<String> allJsInputs = new TreeSet<>();
for (String pattern : patterns) {
if (!pattern.contains("*") && !pattern.startsWith("!")) {
File matchedFile = new File(pattern);
@@ -1458,7 +1480,9 @@ public class CommandLineRunner extends
throws IOException {
FileSystem fs = FileSystems.getDefault();
final boolean remove = pattern.indexOf('!') == 0;
- if (remove) pattern = pattern.substring(1);
+ if (remove) {
+ pattern = pattern.substring(1);
+ }
if (File.separator.equals("\\\\")) {
pattern = pattern.replace('\\\\', '/');
@@ -1473,18 +1497,20 @@ public class CommandLineRunner extends
if (i == 0) {
break;
} else {
- prefix = Joiner.on("/").join(patternParts.subList(0, i));
- pattern = Joiner.on("/").join(patternParts.subList(i, patternParts.size()));
+ prefix = Joiner.on(File.separator).join(patternParts.subList(0, i));
+ pattern = Joiner.on(File.separator).join(patternParts.subList(i, patternParts.size()));
}
}
}
- final PathMatcher matcher = fs.getPathMatcher("glob:" + pattern);
+ final PathMatcher matcher = fs.getPathMatcher("glob:" + (prefix.equals(".")
+ ? pattern
+ : prefix + File.separator + pattern));
java.nio.file.Files.walkFileTree(
fs.getPath(prefix), new SimpleFileVisitor<Path>() {
@Override public FileVisitResult visitFile(
Path p, BasicFileAttributes attrs) {
- if (matcher.matches(p)) {
+ if (matcher.matches(p.normalize())) {
if (remove) {
allJsInputs.remove(p.toString());
} else {
diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
index fbee0ec4e..09463a96c 100644
--- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
+++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
@@ -42,6 +42,7 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
+import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -1113,6 +1114,36 @@ public final class CommandLineRunnerTest extends TestCase {
}
}
+ public void testGlobJs1() throws IOException {
+ try {
+ FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;");
+ FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;");
+ // Move test2 to the same directory as test1, also make the filename of test2
+ // lexicographically larger than test1
+ new File(jsFile2.value).renameTo(new File(
+ new File(jsFile1.value).getParentFile() + File.separator + "utest2.js"));
+ String glob = new File(jsFile1.value).getParent() + File.separator + "**.js";
+ compileFiles(
+ "var a;var b;", new FlagEntry<>(JsSourceType.JS, glob));
+ } catch (FlagUsageException e) {
+ fail("Unexpected exception" + e);
+ }
+ }
+
+ public void testGlobJs2() throws IOException {
+ try {
+ FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;");
+ FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;");
+ new File(jsFile2.value).renameTo(new File(
+ new File(jsFile1.value).getParentFile() + File.separator + "utest2.js"));
+ String glob = new File(jsFile1.value).getParent() + File.separator + "*test*.js";
+ compileFiles(
+ "var a;var b;", new FlagEntry<>(JsSourceType.JS, glob));
+ } catch (FlagUsageException e) {
+ fail("Unexpected exception" + e);
+ }
+ }
+
public void testSourceMapInputs() throws Exception {
args.add("--js_output_file");
args.add("/path/to/out.js");
@@ -1875,7 +1906,8 @@ public final class CommandLineRunnerTest extends TestCase {
private static FlagEntry<JsSourceType> createZipFile(Map<String, String> entryContentsByName)
throws IOException {
- File tempZipFile = File.createTempFile("testdata", ".js.zip");
+ File tempZipFile = File.createTempFile("testdata", ".js.zip",
+ Files.createTempDirectory("jscomp").toFile());
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(tempZipFile))) {
for (Entry<String, String> entry : entryContentsByName.entrySet()) {
@@ -1889,9 +1921,11 @@ public final class CommandLineRunnerTest extends TestCase {
private FlagEntry<JsSourceType> createJsFile(String filename, String fileContent)
throws IOException {
- File tempJsFile = File.createTempFile(filename, ".js");
- FileOutputStream fileOutputStream = new FileOutputStream(tempJsFile);
- fileOutputStream.write(fileContent.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ File tempJsFile = File.createTempFile(filename, ".js",
+ Files.createTempDirectory("jscomp").toFile());
+ try (FileOutputStream fileOutputStream = new FileOutputStream(tempJsFile)) {
+ fileOutputStream.write(fileContent.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ }
return new FlagEntry<>(JsSourceType.JS, tempJsFile.getAbsolutePath());
} | ['src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 7,125,544 | 1,615,261 | 217,124 | 706 | 2,277 | 480 | 48 | 1 | 3,904 | 319 | 1,206 | 100 | 0 | 2 | 2016-01-20T08:57:19 | 7,031 | Java | {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078} | Apache License 2.0 |
515 | google/closure-compiler/1469/1407 | google | closure-compiler | https://github.com/google/closure-compiler/issues/1407 | https://github.com/google/closure-compiler/pull/1469 | https://github.com/google/closure-compiler/pull/1469 | 1 | fixes | Cannot use globs when running the compiler. | Since 62ca536... I am no longer able to use globs for files when running the compiler:
Running this command used to work before that change:
```
java -jar ../../compiler/compiler.jar \\
--flagfile=options/compile.ini \\
--define "goog.json.USE_NATIVE_JSON=true" --define "goog.ui.Component.ALLOW_DETACHED_DECORATION=true" --define "goog.NATIVE_ARRAY_PROTOTYPES=true" --define "goog.array.ASSUME_NATIVE_FUNCTIONS=true" --define "goog.Promise.UNHANDLED_REJECTION_DELAY=-1" --define "app.settings.RUN_AS_USER=false" --externs=../externs/material.js --generate_exports --export_local_property_definitions --language_in=ECMASCRIPT6 --language_out=ES3 --use_types_for_optimization --output_wrapper="(function(){%output%})();" \\
--only_closure_dependencies \\
--closure_entry_point=app \\
--manage_closure_dependencies true \\
--output_manifest build/app.filelist.txt \\
--js_output_file /tmp/closure_compiler_build \\
--js="js/**.js" --js="tpl/en/**.js" --js="../../templates/soyutils_usegoog.js" --js="../../library/closure/goog/**.js" --js="../../library/third_party/closure/goog/mochikit/async/deferred.js" --js="../../library/third_party/closure/goog/mochikit/async/deferredlist.js" --js="../pstj/animation/**.js" --js="../pstj/app/**.js" --js="../pstj/autogenerated/**.js" --js="../pstj/cast/**.js" --js="../pstj/color/**.js" --js="../pstj/config/**.js" --js="../pstj/control/**.js" --js="../pstj/date/**.js" --js="../pstj/debug/**.js" --js="../pstj/ds/**.js" --js="../pstj/element/**.js" --js="../pstj/error/**.js" --js="../pstj/fx/**.js" --js="../pstj/graphics/**.js" --js="../pstj/material/**.js" --js="../pstj/math/**.js" --js="../pstj/mvc/**.js" --js="../pstj/ng/**.js" --js="../pstj/object/**.js" --js="../pstj/options/**.js" --js="../pstj/resource/**.js" --js="../pstj/sourcegen/**.js" --js="../pstj/storage/**.js" --js="../pstj/style/**.js" --js="../pstj/themes/**.js" --js="../pstj/ui/**.js" --js="../smjs/ds/**.js" --js="../smjs/element/**.js" --js="../smjs/persistence/**.js" --js="../smjs/player/**.js" --js="../smjs/remotecontrol/**.js" --js="../smjs/transport/**.js" --js="../smjs/tv/**.js" --js="../smjs/widgets/**.js" --js="!**_test.js"
```
Now (after the mentioned change) it gives this:
```
ERROR - Cannot read: !**_test.js
ERROR - Cannot read: ../../library/closure/goog/**.js
ERROR - Cannot read: ../pstj/animation/**.js
ERROR - Cannot read: ../pstj/app/**.js
ERROR - Cannot read: ../pstj/autogenerated/**.js
ERROR - Cannot read: ../pstj/cast/**.js
ERROR - Cannot read: ../pstj/color/**.js
ERROR - Cannot read: ../pstj/config/**.js
ERROR - Cannot read: ../pstj/control/**.js
ERROR - Cannot read: ../pstj/date/**.js
ERROR - Cannot read: ../pstj/debug/**.js
ERROR - Cannot read: ../pstj/ds/**.js
ERROR - Cannot read: ../pstj/element/**.js
ERROR - Cannot read: ../pstj/error/**.js
ERROR - Cannot read: ../pstj/fx/**.js
ERROR - Cannot read: ../pstj/graphics/**.js
ERROR - Cannot read: ../pstj/material/**.js
ERROR - Cannot read: ../pstj/math/**.js
ERROR - Cannot read: ../pstj/mvc/**.js
ERROR - Cannot read: ../pstj/ng/**.js
ERROR - Cannot read: ../pstj/object/**.js
ERROR - Cannot read: ../pstj/options/**.js
ERROR - Cannot read: ../pstj/resource/**.js
ERROR - Cannot read: ../pstj/sourcegen/**.js
ERROR - Cannot read: ../pstj/storage/**.js
ERROR - Cannot read: ../pstj/style/**.js
ERROR - Cannot read: ../pstj/themes/**.js
ERROR - Cannot read: ../pstj/ui/**.js
ERROR - Cannot read: ../smjs/ds/**.js
ERROR - Cannot read: ../smjs/element/**.js
ERROR - Cannot read: ../smjs/persistence/**.js
ERROR - Cannot read: ../smjs/player/**.js
ERROR - Cannot read: ../smjs/remotecontrol/**.js
ERROR - Cannot read: ../smjs/transport/**.js
ERROR - Cannot read: ../smjs/tv/**.js
ERROR - Cannot read: ../smjs/widgets/**.js
ERROR - Cannot read: js/**.js
ERROR - Cannot read: tpl/en/**.js
ERROR - required entry point "app" never provided
39 error(s), 0 warning(s)
```
| f98608a07dc43fb3e950a730ca59906179386ffb | 16d143d67f4c27aa1435d3561a64acbe039dc972 | https://github.com/google/closure-compiler/compare/f98608a07dc43fb3e950a730ca59906179386ffb...16d143d67f4c27aa1435d3561a64acbe039dc972 | diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
index fbdc565a5..87f9c2037 100644
--- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
+++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
@@ -2542,6 +2542,16 @@ public abstract class AbstractCommandLineRunner<A extends Compiler,
this.flag = flag;
this.value = value;
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof FlagEntry) {
+ FlagEntry<?> that = (FlagEntry<?>) o;
+ return that.flag.equals(this.flag)
+ && that.value.equals(this.value);
+ }
+ return false;
+ }
}
/**
diff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java
index 47c87615d..1f83037d4 100644
--- a/src/com/google/javascript/jscomp/CommandLineRunner.java
+++ b/src/com/google/javascript/jscomp/CommandLineRunner.java
@@ -61,6 +61,7 @@ import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -745,12 +746,21 @@ public class CommandLineRunner extends
protected List<FlagEntry<JsSourceType>> getMixedJsSources()
throws CmdLineException, IOException {
List<FlagEntry<JsSourceType>> mixedSources = new ArrayList<>();
+ Set<String> excludes = new HashSet<>();
for (FlagEntry<JsSourceType> source : Flags.mixedJsSources) {
if (source.value.endsWith(".zip")) {
mixedSources.add(source);
+ } else if (source.value.startsWith("!")) {
+ for (String filename : findJsFiles(
+ Collections.singletonList(source.value.substring(1)))) {
+ excludes.add(filename);
+ mixedSources.remove(new FlagEntry<>(JsSourceType.JS, filename));
+ }
} else {
for (String filename : findJsFiles(Collections.singletonList(source.value))) {
- mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));
+ if (!excludes.contains(filename)) {
+ mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));
+ }
}
}
}
@@ -1475,23 +1485,25 @@ public class CommandLineRunner extends
*/
public static List<String> findJsFiles(Collection<String> patterns) throws IOException {
Set<String> allJsInputs = new TreeSet<>();
+ Set<String> excludes = new HashSet<>();
for (String pattern : patterns) {
if (!pattern.contains("*") && !pattern.startsWith("!")) {
File matchedFile = new File(pattern);
if (matchedFile.isDirectory()) {
- matchPaths(new File(matchedFile, "**.js").toString(), allJsInputs);
- } else {
+ matchPaths(new File(matchedFile, "**.js").toString(), allJsInputs, excludes);
+ } else if (!excludes.contains(pattern)) {
allJsInputs.add(pattern);
}
} else {
- matchPaths(pattern, allJsInputs);
+ matchPaths(pattern, allJsInputs, excludes);
}
}
return new ArrayList<>(allJsInputs);
}
- private static void matchPaths(String pattern, final Set<String> allJsInputs)
+ private static void matchPaths(String pattern, final Set<String> allJsInputs,
+ final Set<String> excludes)
throws IOException {
FileSystem fs = FileSystems.getDefault();
final boolean remove = pattern.indexOf('!') == 0;
@@ -1526,10 +1538,12 @@ public class CommandLineRunner extends
@Override public FileVisitResult visitFile(
Path p, BasicFileAttributes attrs) {
if (matcher.matches(p.normalize())) {
+ String pathString = p.toString();
if (remove) {
- allJsInputs.remove(p.toString());
- } else {
- allJsInputs.add(p.toString());
+ excludes.add(pathString);
+ allJsInputs.remove(pathString);
+ } else if (!excludes.contains(pathString)) {
+ allJsInputs.add(pathString);
}
}
return FileVisitResult.CONTINUE;
diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
index 66b8ec811..0af52d6cb 100644
--- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
+++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
@@ -1139,6 +1139,34 @@ public final class CommandLineRunnerTest extends TestCase {
}
}
+ public void testGlobJs3() throws IOException, FlagUsageException {
+ FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;");
+ FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;");
+ new File(jsFile2.value).renameTo(new File(
+ new File(jsFile1.value).getParentFile() + File.separator + "test2.js"));
+ // Make sure test2.js is excluded from the inputs when the exclusion
+ // comes after the inclusion
+ String glob1 = new File(jsFile1.value).getParent() + File.separator + "**.js";
+ String glob2 = "!" + new File(jsFile1.value).getParent() + File.separator + "**test2.js";
+ compileFiles(
+ "var a;", new FlagEntry<>(JsSourceType.JS, glob1),
+ new FlagEntry<>(JsSourceType.JS, glob2));
+ }
+
+ public void testGlobJs4() throws IOException, FlagUsageException {
+ FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;");
+ FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;");
+ new File(jsFile2.value).renameTo(new File(
+ new File(jsFile1.value).getParentFile() + File.separator + "test2.js"));
+ // Make sure test2.js is excluded from the inputs when the exclusion
+ // comes before the inclusion
+ String glob1 = "!" + new File(jsFile1.value).getParent() + File.separator + "**test2.js";
+ String glob2 = new File(jsFile1.value).getParent() + File.separator + "**.js";
+ compileFiles(
+ "var a;", new FlagEntry<>(JsSourceType.JS, glob1),
+ new FlagEntry<>(JsSourceType.JS, glob2));
+ }
+
public void testSourceMapInputs() throws Exception {
args.add("--js_output_file");
args.add("/path/to/out.js"); | ['src/com/google/javascript/jscomp/AbstractCommandLineRunner.java', 'src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 7,155,232 | 1,622,150 | 217,888 | 708 | 1,800 | 354 | 40 | 2 | 3,904 | 319 | 1,206 | 100 | 0 | 2 | 2016-01-30T04:36:50 | 7,031 | Java | {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078} | Apache License 2.0 |
514 | google/closure-compiler/1549/1548 | google | closure-compiler | https://github.com/google/closure-compiler/issues/1548 | https://github.com/google/closure-compiler/pull/1549 | https://github.com/google/closure-compiler/pull/1549 | 2 | fixes | File order not maintained | I call the closure compiler like:
```
java.exe -jar dev\\jars\\closure\\compiler.jar --compilation_level WHITESPACE_ONLY --formatting PRETTY_PRINT --formatting PRINT_INPUT_DELIMITER --formatting SINGLE_QUOTES --js_output_file jQuery_a52d83c3.min.js --js jquery.js ui\\core.js ui\\widget.js ui\\mouse.js ui\\draggable.js ui\\droppable.js ui\\resizable.js ui\\selectable.js ui\\sortable.js ui\\button.js ui\\position.js
```
When I use the `compiler.jar` from github binary downloads `compiler-20151216.tar.gz` everything is fine. When I use `compiler-20160208.tar.gz` the file originial order is not maintained in the compressed file which breaks the code, as the js files have to be included in a specific order.
I tried the new parameter `--dependency_mode NONE` but it changed nothing. According to the docs should NONE be the default.
I'm on Windows 10, 64 bit JAVA 8 as provided by Oracle.
| 4544359bba2cac67e0ff13fda514b6e52d9d29cb | b193c1b5b10c1246877c384526fc01d9f0db448b | https://github.com/google/closure-compiler/compare/4544359bba2cac67e0ff13fda514b6e52d9d29cb...b193c1b5b10c1246877c384526fc01d9f0db448b | diff --git a/src/com/google/javascript/jscomp/CommandLineRunner.java b/src/com/google/javascript/jscomp/CommandLineRunner.java
index 65e615bdd..cd1896c4a 100644
--- a/src/com/google/javascript/jscomp/CommandLineRunner.java
+++ b/src/com/google/javascript/jscomp/CommandLineRunner.java
@@ -62,6 +62,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -757,7 +758,7 @@ public class CommandLineRunner extends
mixedSources.remove(new FlagEntry<>(JsSourceType.JS, filename));
}
} else {
- for (String filename : findJsFiles(Collections.singletonList(source.value))) {
+ for (String filename : findJsFiles(Collections.singletonList(source.value), true)) {
if (!excludes.contains(filename)) {
mixedSources.add(new FlagEntry<>(JsSourceType.JS, filename));
}
@@ -1503,7 +1504,20 @@ public class CommandLineRunner extends
* within the directory and sub-directories.
*/
public static List<String> findJsFiles(Collection<String> patterns) throws IOException {
- Set<String> allJsInputs = new TreeSet<>();
+ return findJsFiles(patterns, false);
+ }
+
+ /**
+ * Returns all the JavaScript files from the set of patterns.
+ *
+ * @param patterns A collection of filename patterns.
+ * @param sortAlphabetically Whether the output filenames should be in alphabetical order.
+ * @return The list of JS filenames found by expanding the patterns.
+ */
+ private static List<String> findJsFiles(Collection<String> patterns, boolean sortAlphabetically)
+ throws IOException {
+ Set<String> allJsInputs = sortAlphabetically
+ ? new TreeSet<String>() : new LinkedHashSet<String>();
Set<String> excludes = new HashSet<>();
for (String pattern : patterns) {
if (!pattern.contains("*") && !pattern.startsWith("!")) {
diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
index 114df7d5e..e270af668 100644
--- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
+++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
@@ -1094,9 +1094,11 @@ public final class CommandLineRunnerTest extends TestCase {
}
public void testInputMultipleJsFilesWithOneJsFlag() throws IOException, FlagUsageException {
+ // Test that file order is preserved with --js test3.js test2.js test1.js
FlagEntry<JsSourceType> jsFile1 = createJsFile("test1", "var a;");
FlagEntry<JsSourceType> jsFile2 = createJsFile("test2", "var b;");
- compileJsFiles("var a;var b;", jsFile1, jsFile2);
+ FlagEntry<JsSourceType> jsFile3 = createJsFile("test3", "var c;");
+ compileJsFiles("var c;var b;var a;", jsFile3, jsFile2, jsFile1);
}
public void testGlobJs1() throws IOException, FlagUsageException { | ['src/com/google/javascript/jscomp/CommandLineRunner.java', 'test/com/google/javascript/jscomp/CommandLineRunnerTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 7,185,495 | 1,629,249 | 218,744 | 712 | 865 | 174 | 18 | 1 | 883 | 109 | 223 | 11 | 0 | 1 | 2016-02-15T14:27:38 | 7,031 | Java | {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078} | Apache License 2.0 |
517 | google/closure-compiler/1322/1314 | google | closure-compiler | https://github.com/google/closure-compiler/issues/1314 | https://github.com/google/closure-compiler/pull/1322 | https://github.com/google/closure-compiler/pull/1322 | 1 | fixes | Unlike var statements, const statements do not support multiple types | Code -
```
// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// @language ECMASCRIPT6_STRICT
// ==/ClosureCompiler==
"use strict";
const
/** @const {string} */ foo = "1",
/** @const {number} */ bar = 1;
const
/** @type {string} */ baz = "1",
/** @type {number} */ taz = 1;
```
Warnings -
```
JSC_MULTIPLE_VAR_DEF: declaration of multiple variables with shared type information at line 2 character 0
const
^
JSC_MULTIPLE_VAR_DEF: declaration of multiple variables with shared type information at line 6 character 0
const
^
```
Note - changing them to `var` avoids the warnings, of course.
| 0767ef6c3863cd188d1f5fe61b73967ea9e3c912 | 7de586e22e0663c275f2320ad4ddac4e23abb145 | https://github.com/google/closure-compiler/compare/0767ef6c3863cd188d1f5fe61b73967ea9e3c912...7de586e22e0663c275f2320ad4ddac4e23abb145 | diff --git a/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java b/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java
index 291ff9a2e..bf678d067 100644
--- a/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java
+++ b/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java
@@ -132,17 +132,26 @@ public final class Es6RewriteBlockScopedDeclaration extends AbstractPostOrderCal
if (!letConsts.isEmpty()) {
for (Node n : letConsts) {
if (n.isConst()) {
- JSDocInfo existingInfo = n.getJSDocInfo();
- if (existingInfo == null) {
- existingInfo = n.getFirstChild().getJSDocInfo();
- n.getFirstChild().setJSDocInfo(null);
+ // Normalize declarations like "const x = 1, y = 2;" so that inline
+ // type annotations are preserved.
+ for (Node child : n.children()) {
+ Node declaration = IR.var(child.detachFromParent());
+ declaration.useSourceInfoFrom(n);
+ JSDocInfo existingInfo = n.getJSDocInfo();
+ if (existingInfo == null) {
+ existingInfo = child.getJSDocInfo();
+ child.setJSDocInfo(null);
+ }
+ JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(existingInfo);
+ builder.recordConstancy();
+ JSDocInfo info = builder.build();
+ declaration.setJSDocInfo(info);
+ n.getParent().addChildAfter(declaration, n);
}
- JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(existingInfo);
- builder.recordConstancy();
- JSDocInfo info = builder.build();
- n.setJSDocInfo(info);
+ n.detachFromParent();
+ } else {
+ n.setType(Token.VAR);
}
- n.setType(Token.VAR);
}
compiler.reportCodeChange();
}
diff --git a/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java b/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java
index fcc8c663c..270c277b4 100644
--- a/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java
+++ b/test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java
@@ -778,6 +778,10 @@ public final class Es6RewriteBlockScopedDeclarationTest extends CompilerTestCase
testWarning("/** @type {number} */ const x = 'str';", TypeValidator.TYPE_MISMATCH_WARNING);
testWarning("const /** number */ x = 'str';", TypeValidator.TYPE_MISMATCH_WARNING);
testWarning("const /** @type {number} */ x = 'str';", TypeValidator.TYPE_MISMATCH_WARNING);
+ testWarning("const /** @type {string} */ x = 3, /** @type {number} */ y = 3;",
+ TypeValidator.TYPE_MISMATCH_WARNING);
+ testWarning("const /** @type {string} */ x = 'str', /** @type {string} */ y = 3;",
+ TypeValidator.TYPE_MISMATCH_WARNING);
}
public void testDoWhileForOfCapturedLetAnnotated() { | ['test/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclarationTest.java', 'src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 7,100,552 | 1,609,557 | 216,424 | 705 | 1,284 | 278 | 27 | 1 | 651 | 96 | 182 | 31 | 0 | 2 | 2015-12-21T15:01:34 | 7,031 | Java | {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078} | Apache License 2.0 |
513 | google/closure-compiler/3988/3840 | google | closure-compiler | https://github.com/google/closure-compiler/issues/3840 | https://github.com/google/closure-compiler/pull/3988 | https://github.com/google/closure-compiler/pull/3988 | 1 | fixes | --create_source_map throws exception on windows when using input source maps and chunks | Closure throws an exception when I try to build source maps for chunks:
java.io.FileNotFoundException: .\\dist\\closure\\common.js.map (The system cannot find the path specified)
It seems like there's a race condition issue if the source map of a depending module is built before the dependency. It seems to work properly if I run the build without `--create_source_map`, and then run it again _with_ `--create_source_map`.
Reproducer is available here: https://github.com/DerGernTod/ts-esbuild-closure-reproducer/blob/main/index.js
The used flags:
--chunk common:2
--chunk_wrapper common:(function(){%s})()
--source_map_input dist/esbuild/chunk-7THFJKJQ.js|dist/esbuild/chunk-7THFJKJQ.js.map
--js dist/esbuild/chunk-7THFJKJQ.js
--source_map_input dist/esbuild/filecommon.js|dist/esbuild/filecommon.js.map
--js dist/esbuild/filecommon.js
--chunk filea:1:common
--chunk_wrapper filea:(function(){%s})()
--source_map_input dist/esbuild/filea.js|dist/esbuild/filea.js.map
--js dist/esbuild/filea.js
--chunk fileb:1:common
--chunk_wrapper fileb:(function(){%s})()
--source_map_input dist/esbuild/fileb.js|dist/esbuild/fileb.js.map
--js dist/esbuild/fileb.js
--language_in ECMASCRIPT_2017
--language_out ECMASCRIPT_2017
--chunk_output_path_prefix ./dist/closure/
--rename_prefix_namespace myNamespace
--compilation_level ADVANCED_OPTIMIZATIONS
--create_source_map %outname%.map
I also tried `--source_map_include_content`, but that doesn't seem to work either (even if you build it once without source maps to prevent the error mentioned above, and then build it with source maps). The source is not embedded at all.
| 3784fba4f48519472ca66792d0ed318ee443d44a | 55e3c557a2d9aae7cffefdad42140911130c8551 | https://github.com/google/closure-compiler/compare/3784fba4f48519472ca66792d0ed318ee443d44a...55e3c557a2d9aae7cffefdad42140911130c8551 | diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
index e27089744..ad4fdaff2 100644
--- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
+++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
@@ -1139,12 +1139,9 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
@GwtIncompatible("Unnecessary")
private static void maybeCreateDirsForPath(String pathPrefix) {
if (!Strings.isNullOrEmpty(pathPrefix)) {
- String dirName =
- pathPrefix.charAt(pathPrefix.length() - 1) == File.separatorChar
- ? pathPrefix.substring(0, pathPrefix.length() - 1)
- : new File(pathPrefix).getParent();
- if (dirName != null) {
- new File(dirName).mkdirs();
+ File parent = new File(pathPrefix).getParentFile();
+ if (parent != null) {
+ parent.mkdirs();
}
}
}
@@ -1769,7 +1766,8 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
throws IOException {
parsedModuleWrappers = parseModuleWrappers(config.moduleWrapper, modules);
if (!isOutputInJson()) {
- maybeCreateDirsForPath(config.moduleOutputPathPrefix);
+ // make sure the method generates all dirs up to the latest /
+ maybeCreateDirsForPath(config.moduleOutputPathPrefix + "dummy");
}
// If the source map path is in fact a pattern for each | ['src/com/google/javascript/jscomp/AbstractCommandLineRunner.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,466,863 | 2,112,089 | 269,013 | 876 | 600 | 130 | 12 | 1 | 1,643 | 150 | 423 | 31 | 1 | 0 | 2022-08-24T13:13:44 | 7,031 | Java | {'Java': 20926778, 'JavaScript': 13942727, 'Starlark': 32989, 'Shell': 3465, 'HTML': 3018, 'Smarty': 2078} | Apache License 2.0 |
404 | gocd/gocd/9900/9890 | gocd | gocd | https://github.com/gocd/gocd/issues/9890 | https://github.com/gocd/gocd/pull/9900 | https://github.com/gocd/gocd/pull/9900 | 1 | fixes | Double-Checked Locking might be incorrect in PipelineGroups | https://github.com/gocd/gocd/blob/86b555e57daccec6b53b246f0dcdd4d0090566ef/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java#L183-L187
Double-Checked Locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment.
Unfortunately, it will not work reliably in a platform independent way when implemented in Java, without additional synchronization.
Modify the variable ‘packageToPipelineMap’ with volatile to tackle the problem. | 0c6b1a98742b3aaa1e019d52c670ad9a1be013a9 | 9d8ecf50f70adb4b80987d15a3f857bb257b5349 | https://github.com/gocd/gocd/compare/0c6b1a98742b3aaa1e019d52c670ad9a1be013a9...9d8ecf50f70adb4b80987d15a3f857bb257b5349 | diff --git a/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java b/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java
index 02747ee396..abaa4e98d8 100644
--- a/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java
+++ b/config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java
@@ -21,8 +21,6 @@ import com.thoughtworks.go.config.exceptions.RecordNotFoundException;
import com.thoughtworks.go.config.exceptions.UnprocessableEntityException;
import com.thoughtworks.go.config.materials.PackageMaterialConfig;
import com.thoughtworks.go.config.materials.PluggableSCMMaterialConfig;
-import com.thoughtworks.go.config.materials.ScmMaterialConfig;
-import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.domain.packagerepository.PackageDefinition;
import com.thoughtworks.go.domain.packagerepository.PackageRepository;
import com.thoughtworks.go.domain.scm.SCM;
@@ -33,8 +31,8 @@ import java.util.*;
@ConfigCollection(value = BasicPipelineConfigs.class)
public class PipelineGroups extends BaseCollection<PipelineConfigs> implements Validatable {
private final ConfigErrors configErrors = new ConfigErrors();
- private Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> packageToPipelineMap;
- private Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> pluggableSCMMaterialToPipelineMap;
+ private volatile Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> packageToPipelineMap;
+ private volatile Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> pluggableSCMMaterialToPipelineMap;
public PipelineGroups() {
}
@@ -235,10 +233,7 @@ public class PipelineGroups extends BaseCollection<PipelineConfigs> implements V
public boolean canDeletePluggableSCMMaterial(SCM scmConfig) {
Map<String, List<Pair<PipelineConfig, PipelineConfigs>>> packageUsageInPipelines = getPluggableSCMMaterialUsageInPipelines();
- if (packageUsageInPipelines.containsKey(scmConfig.getId())) {
- return false;
- }
- return true;
+ return !packageUsageInPipelines.containsKey(scmConfig.getId());
}
public PipelineGroups getLocal() {
diff --git a/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java b/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java
index 553ea6019b..93b5f1315f 100644
--- a/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java
+++ b/domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java
@@ -22,6 +22,7 @@ import com.thoughtworks.go.util.command.CommandArgument;
import com.thoughtworks.go.util.command.UrlArgument;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
+import org.jetbrains.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -30,7 +31,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
-import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.jar.JarEntry;
@@ -44,16 +44,13 @@ class TfsSDKCommandBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(TfsSDKCommandBuilder.class);
private final File tempFolder = new File("data/tfs-sdk");
private final ClassLoader sdkLoader;
- private static TfsSDKCommandBuilder ME;
+ private static volatile TfsSDKCommandBuilder ME;
- private TfsSDKCommandBuilder() throws IOException, URISyntaxException {
+ private TfsSDKCommandBuilder() throws IOException {
this.sdkLoader = initSdkLoader();
}
- /*
- * Used in tests
- */
- @Deprecated
+ @VisibleForTesting
TfsSDKCommandBuilder(ClassLoader sdkLoader) {
this.sdkLoader = sdkLoader;
}
@@ -61,7 +58,7 @@ class TfsSDKCommandBuilder {
TfsCommand buildTFSSDKCommand(String materialFingerPrint, UrlArgument url, String domain, String userName,
String password, final String computedWorkspaceName, String projectPath) {
try {
- return instantitateAdapter(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath);
+ return instantiateAdapter(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath);
} catch (Exception e) {
String message = "[TFS SDK] Could not create TFS SDK Command ";
LOGGER.error(message, e);
@@ -69,7 +66,7 @@ class TfsSDKCommandBuilder {
}
}
- private TfsCommand instantitateAdapter(String materialFingerPrint, UrlArgument url, String domain, String userName, String password, String computedWorkspaceName, String projectPath) throws ReflectiveOperationException {
+ private TfsCommand instantiateAdapter(String materialFingerPrint, UrlArgument url, String domain, String userName, String password, String computedWorkspaceName, String projectPath) throws ReflectiveOperationException {
Class<?> adapterClass = Class.forName(tfsSdkCommandTCLAdapterClassName(), true, sdkLoader);
Constructor<?> constructor = adapterClass.getConstructor(String.class, CommandArgument.class, String.class, String.class, String.class, String.class, String.class);
return (TfsCommand) constructor.newInstance(materialFingerPrint, url, domain, userName, password, computedWorkspaceName, projectPath);
@@ -79,7 +76,7 @@ class TfsSDKCommandBuilder {
return "com.thoughtworks.go.tfssdk.TfsSDKCommandTCLAdapter";
}
- static TfsSDKCommandBuilder getBuilder() throws IOException, URISyntaxException {
+ static TfsSDKCommandBuilder getBuilder() throws IOException {
if (ME == null) {
synchronized (TfsSDKCommandBuilder.class) {
if (ME == null) { | ['domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsSDKCommandBuilder.java', 'config/config-api/src/main/java/com/thoughtworks/go/domain/PipelineGroups.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,875,936 | 3,177,194 | 374,335 | 3,354 | 2,008 | 393 | 28 | 2 | 523 | 48 | 119 | 6 | 1 | 0 | 2021-11-27T10:19:37 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
408 | gocd/gocd/1052/1045 | gocd | gocd | https://github.com/gocd/gocd/issues/1045 | https://github.com/gocd/gocd/pull/1052 | https://github.com/gocd/gocd/pull/1052 | 1 | fixed | Temporary console log issues | 1) ~~Even though console logs are available in 'Artifacts' tab, yet i see following message there which should not be happen~~
~~"Artifacts for this job instance are unavailable as they may have been purged by Go or deleted externally. Re-run the stage or job to generate them again."~~
This is not an issue [@arikagoyal]
2) a) When a job is cancelled, its o/p looks like this -
[go] Job Completed Console-testing/8/defaultStage/1/job213:30:25.194 [go] Start to execute cancel task: Kills child processes
13:30:25.383 [go] Task is cancelled
Expected : "[go] Job Completed Console-testing/8/defaultStage/1/job2" should show up in the end of console log
b) Also on specifying job timeout, the console o/p looks like this -
[go] Job Completed Simple-console-testing/3/defaultStage/1/defaultJobGo cancelled this job as it has not generated any console output for more than 2 minute(s)10:15:54.829 [go] Start to execute cancel task: Kills child processes
10:15:54.891 [go] Task is cancelled
Expected o/p :
Go cancelled this job as it has not generated any console output for more than 1 minute(s)
[go] Start to execute cancel task: Kills child processes
[go] Task is cancelled
[go] Job completed test/4/defaultStage/1/defaultJob on f9c423f70d26 [/var/lib/cruise-agent] at Wed Apr 15 20:43:26 UTC 2015
Also at times when a job is cancelled, sometimes logs do not get moved to the final artifact location.
3) ~~If temporary console logs fails to make to the final artifact location due to disk space issue or permissions issue, they continue to lie in the temporary location forever. There should be a way to get these temp logs moved over to the actual location once the issue is resolved with the actual artifact location. Some automatic retry mechanism or on demand retry mechanism should be in place ?? Maybe in later releases ?~~ Moved this to #1057
| dd9050b6c43282dfcb1d7684038ea9cd9934d819 | 81080bc7ced42ef543338721f9ca582e85ac8aef | https://github.com/gocd/gocd/compare/dd9050b6c43282dfcb1d7684038ea9cd9934d819...81080bc7ced42ef543338721f9ca582e85ac8aef | diff --git a/common/src/com/thoughtworks/go/remote/work/BuildWork.java b/common/src/com/thoughtworks/go/remote/work/BuildWork.java
index 2732b8543e..b6bc734e87 100644
--- a/common/src/com/thoughtworks/go/remote/work/BuildWork.java
+++ b/common/src/com/thoughtworks/go/remote/work/BuildWork.java
@@ -94,6 +94,8 @@ public class BuildWork implements Work {
LOGGER.error("Agent UUID changed in the middle of the build.", e);
} catch (Exception e) {
reportFailure(e);
+ } finally {
+ goPublisher.stop();
}
}
@@ -110,9 +112,9 @@ public class BuildWork implements Work {
private void reportCompletion(JobResult result) {
try {
builders.waitForCancelTasks();
- goPublisher.stop();
if (result == null) {
goPublisher.reportCurrentStatus(JobState.Completed);
+ goPublisher.reportCompletedAction();
} else {
goPublisher.reportCompleted(result);
}
diff --git a/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java b/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java
index 36aece3d2d..b7d3e8b71e 100644
--- a/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java
+++ b/common/src/com/thoughtworks/go/work/DefaultGoPublisher.java
@@ -16,11 +16,13 @@
package com.thoughtworks.go.work;
+import java.io.File;
+
+import com.thoughtworks.go.domain.builder.FetchArtifactBuilder;
import com.thoughtworks.go.domain.JobIdentifier;
import com.thoughtworks.go.domain.JobResult;
import com.thoughtworks.go.domain.JobState;
import com.thoughtworks.go.domain.Property;
-import com.thoughtworks.go.domain.builder.FetchArtifactBuilder;
import com.thoughtworks.go.publishers.GoArtifactsManipulator;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.BuildRepositoryRemote;
@@ -32,8 +34,6 @@ import com.thoughtworks.go.util.TimeProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import java.io.File;
-
import static java.lang.String.format;
public class DefaultGoPublisher implements GoPublisher {
@@ -107,6 +107,11 @@ public class DefaultGoPublisher implements GoPublisher {
LOG.info(String.format("%s is reporting build result [%s] to Go Server for %s", agentIdentifier, result,
jobIdentifier.toFullString()));
remoteBuildRepository.reportCompleted(agentRuntimeInfo, jobIdentifier, result);
+ reportCompletedAction();
+ }
+
+ public void reportCompletedAction() {
+ reportAction("Job completed");
}
public boolean isIgnored() {
diff --git a/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java b/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java
index 9a39151595..38643b1547 100644
--- a/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java
+++ b/server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java
@@ -22,12 +22,9 @@ import com.thoughtworks.go.domain.JobIdentifier;
import com.thoughtworks.go.domain.JobInstance;
import com.thoughtworks.go.server.domain.JobStatusListener;
import com.thoughtworks.go.server.service.ConsoleService;
-import com.thoughtworks.go.util.GoConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import static java.lang.String.format;
-
@Component
public class ConsoleLogArtifactHandler implements JobStatusListener {
private ConsoleService consoleService;
@@ -43,9 +40,6 @@ public class ConsoleLogArtifactHandler implements JobStatusListener {
try {
JobIdentifier identifier = job.getIdentifier();
consoleService.moveConsoleArtifacts(identifier);
- // TODO: Put correct timestamp of job completion the agent and the server maybe on different timezones.
- consoleService.appendToConsoleLog(identifier, format("[%s] %s %s", GoConstants.PRODUCT_NAME, "Job Completed"
- , identifier.buildLocatorForDisplay()));
} catch (Exception e) {
throw new RuntimeException(e);
}
diff --git a/server/src/com/thoughtworks/go/server/service/ConsoleService.java b/server/src/com/thoughtworks/go/server/service/ConsoleService.java
index 74609d7b3a..c55be1ec99 100644
--- a/server/src/com/thoughtworks/go/server/service/ConsoleService.java
+++ b/server/src/com/thoughtworks/go/server/service/ConsoleService.java
@@ -173,6 +173,7 @@ public class ConsoleService {
public void moveConsoleArtifacts(LocatableEntity locatableEntity) {
try {
File from = chooser.temporaryConsoleFile(locatableEntity);
+ from.createNewFile(); // Job cancellation skips temporary file creation. Force create one if it does not exist.
File to = chooser.findArtifact(locatableEntity, getConsoleOutputFolderAndFileName());
FileUtils.moveFile(from, to);
} catch (IOException e) {
diff --git a/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java b/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java
index a7e297e068..86ab26af52 100644
--- a/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java
+++ b/server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java
@@ -35,12 +35,6 @@ public class ConsoleLogArtifactHandlerTest {
verify(consoleService, never()).moveConsoleArtifacts(buildingJobInstance.getIdentifier());
}
- @Test
- public void shouldReportJobAsCompletedOnConsole() throws Exception {
- handler.jobStatusChanged(completedJobInstance);
- verify(consoleService).appendToConsoleLog(completedJobInstance.getIdentifier(), "[go] Job Completed pipeline/label-1/stage/1/job");
- }
-
@Test
public void shouldReportJobAsCompletedOnConsoleOnlyWhenStatusIsCompleted() throws Exception {
handler.jobStatusChanged(buildingJobInstance); | ['server/src/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandler.java', 'common/src/com/thoughtworks/go/work/DefaultGoPublisher.java', 'server/test/unit/com/thoughtworks/go/domain/activity/ConsoleLogArtifactHandlerTest.java', 'common/src/com/thoughtworks/go/remote/work/BuildWork.java', 'server/src/com/thoughtworks/go/server/service/ConsoleService.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 7,843,133 | 1,575,547 | 204,493 | 1,780 | 967 | 172 | 22 | 4 | 1,861 | 292 | 454 | 31 | 0 | 0 | 2015-04-22T10:53:18 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
409 | gocd/gocd/1003/1000 | gocd | gocd | https://github.com/gocd/gocd/issues/1000 | https://github.com/gocd/gocd/pull/1003 | https://github.com/gocd/gocd/pull/1003 | 1 | fixes | handle special characters in material name in pipeline label template | In XSD [here](https://github.com/gocd/gocd/blob/master/config/config-server/resources/cruise-config.xsd#L715) the label template allows special characters like `-` in material name inside `${ }`. But [here](https://github.com/gocd/gocd/blob/master/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java#L45) we don't match them in material name.
causes `${git-repo}` to not get resolved to revision.
| 0e31f680841b78cc06d851d731ff7da9ee1493ae | ee180c73421285ee93905caa7c0db27166df1219 | https://github.com/gocd/gocd/compare/0e31f680841b78cc06d851d731ff7da9ee1493ae...ee180c73421285ee93905caa7c0db27166df1219 | diff --git a/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java b/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java
index 36e2d48f34..7a834ee52a 100644
--- a/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java
+++ b/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java
@@ -19,6 +19,7 @@ package com.thoughtworks.go.domain;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.materials.ScmMaterial;
import com.thoughtworks.go.config.materials.mercurial.HgMaterial;
+import com.thoughtworks.go.config.materials.svn.SvnMaterial;
import com.thoughtworks.go.domain.label.PipelineLabel;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.helper.MaterialsMother;
@@ -221,7 +222,7 @@ public class PipelineLabelTest {
public void canMatchWithOneTruncationAsFirstRevision() throws Exception {
final String[][] expectedGroups = { {"git", "4"}, { "svn" } };
String res = assertLabelGroupsMatchingAndReplace("release-${git[:4]}-${svn}", expectedGroups);
- assertThat(res, is("release-" + GIT_REVISION.substring(0, 4) + "-" + SVN_REVISION));
+ assertThat(res, is("release-" + GIT_REVISION.substring(0, 4) + "-" + SVN_REVISION));
}
@Test
@@ -231,6 +232,36 @@ public class PipelineLabelTest {
assertThat(res, is("release-" + GIT_REVISION.substring(0, 5) + "-" + SVN_REVISION.substring(0, 3)));
}
+ @Test
+ public void canNotMatchWithTruncationWhenMaterialNameHasAColon() throws Exception {
+ final String[][] expectedGroups = { { "git:one", "7" } };
+ String res = assertLabelGroupsMatchingAndReplace("release-${git:one[:7]}", expectedGroups);
+ assertThat(res, is("release-${git:one[:7]}"));
+ }
+
+ @Test
+ public void shouldReplaceTheTemplateWithSpecialCharacters() throws Exception {
+ ensureLabelIsReplaced("SVNMaterial");
+ ensureLabelIsReplaced("SVN-Material");
+ ensureLabelIsReplaced("SVN_Material");
+ ensureLabelIsReplaced("SVN!Material");
+ ensureLabelIsReplaced("SVN__##Material_1023_WithNumbers");
+ ensureLabelIsReplaced("SVN_Material-_!!_");
+ ensureLabelIsReplaced("svn_Material'WithQuote");
+ ensureLabelIsReplaced("SVN_Material.With.Period");
+ ensureLabelIsReplaced("SVN_Material#With#Hash");
+ ensureLabelIsReplaced("SVN_Material:With:Colon");
+ ensureLabelIsReplaced("SVN_Material~With~Tilde");
+
+ ensureLabelIsNOTReplaced("SVN*MATERIAL");
+ ensureLabelIsNOTReplaced("SVN+Material");
+ ensureLabelIsNOTReplaced("SVN^Material");
+ ensureLabelIsNOTReplaced("SVN_Material(With)Parentheses");
+ ensureLabelIsNOTReplaced("SVN_Material{With}Braces");
+ ensureLabelIsNOTReplaced("SVN**Material");
+ ensureLabelIsNOTReplaced("SVN\\\\Material_With_Backslash");
+ }
+
@BeforeClass
public static void setup() {
MATERIAL_REVISIONS.put(new CaseInsensitiveString("svnRepo.verynice"), SVN_REVISION);
@@ -285,4 +316,23 @@ public class PipelineLabelTest {
}
return builder.toString();
}
+
+ private void ensureLabelIsReplaced(String name) {
+ PipelineLabel label = getReplacedLabelFor(name, String.format("release-${%s}", name));
+ assertThat(label.toString(), is("release-" + ModificationsMother.currentRevision()));
+ }
+
+ private void ensureLabelIsNOTReplaced(String name) {
+ String labelFormat = String.format("release-${%s}", name);
+ PipelineLabel label = getReplacedLabelFor(name, labelFormat);
+ assertThat(label.toString(), is(labelFormat));
+ }
+
+ private PipelineLabel getReplacedLabelFor(String name, String labelFormat) {
+ MaterialRevisions materialRevisions = ModificationsMother.oneUserOneFile();
+ PipelineLabel label = PipelineLabel.create(labelFormat);
+ ((SvnMaterial) materialRevisions.getRevisions().get(0).getMaterial()).setName(new CaseInsensitiveString(name));
+ label.updateLabel(materialRevisions.getNamedRevisions());
+ return label;
+ }
}
diff --git a/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java b/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java
index 0b77ba92da..132a09b249 100644
--- a/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java
+++ b/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java
@@ -42,7 +42,7 @@ public class PipelineLabel implements Serializable {
return label;
}
- public static final Pattern PATTERN = Pattern.compile("(?i)\\\\$\\\\{([\\\\w\\\\.]+)(\\\\[:(\\\\d+)\\\\])?\\\\}");
+ public static final Pattern PATTERN = Pattern.compile("(?i)\\\\$\\\\{([a-zA-Z0-9_\\\\-\\\\.!~'#:]+)(\\\\[:(\\\\d+)\\\\])?\\\\}");
private String replaceRevisionsInLabel(Map<CaseInsensitiveString, String> materialRevisions) {
final Matcher matcher = PATTERN.matcher(this.label); | ['config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java', 'common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 7,829,565 | 1,572,877 | 204,139 | 1,777 | 222 | 81 | 2 | 1 | 420 | 34 | 106 | 4 | 2 | 0 | 2015-04-06T12:17:11 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
405 | gocd/gocd/9899/9889 | gocd | gocd | https://github.com/gocd/gocd/issues/9889 | https://github.com/gocd/gocd/pull/9899 | https://github.com/gocd/gocd/pull/9899 | 1 | fixes | Unreleased Resource: Streams in business continuity ViewResolver | https://github.com/gocd/gocd/blob/86b555e57daccec6b53b246f0dcdd4d0090566ef/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java#L40
The program can potentially fail to release a system resource. | c83d03b8ff7b4dd04915476f409c7625ce0c7602 | 750effbf9f204a1c9203f4caefa7a9f5a768e483 | https://github.com/gocd/gocd/compare/c83d03b8ff7b4dd04915476f409c7625ce0c7602...750effbf9f204a1c9203f4caefa7a9f5a768e483 | diff --git a/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java b/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java
index d45bf86971..edd169b2c2 100644
--- a/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java
+++ b/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java
@@ -21,6 +21,7 @@ import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
+import java.util.Objects;
import static java.text.MessageFormat.format;
@@ -68,33 +69,20 @@ public class FileValidator implements Validator {
String message = format("File {0} is not readable or writeable.", file.getAbsolutePath());
return validation.addError(new RuntimeException(message));
}
- } else {
- // Pull out the file from the class path
- InputStream input = this.getClass().getResourceAsStream(srcDir + "/" + fileName);
+ }
+ // Pull out the file from the class path
+ try (InputStream input = this.getClass().getResourceAsStream(srcDir + "/" + fileName)) {
if (input == null) {
String message = format("Resource {0}/{1} does not exist in the classpath", srcDir, fileName);
return validation.addError(new RuntimeException(message));
- } else {
- FileOutputStream output = null;
- try {
- // Make sure the dir exists
- file.getParentFile().mkdirs();
- output = new FileOutputStream(file);
- IOUtils.copy(input, output);
- } catch (Exception e) {
- return handleExceptionDuringFileHandling(validation, e);
- } finally {
- try {
- input.close();
- if (output != null) {
- output.flush();
- output.close();
- }
- } catch (Exception e) {
- return handleExceptionDuringFileHandling(validation, e);
- }
- }
}
+ // Make sure the dir exists
+ file.getParentFile().mkdirs();
+ try (FileOutputStream output = new FileOutputStream(file)) {
+ IOUtils.copy(input, output);
+ }
+ } catch (Exception e) {
+ return handleExceptionDuringFileHandling(validation, e);
}
return Validation.SUCCESS;
}
@@ -112,9 +100,9 @@ public class FileValidator implements Validator {
FileValidator that = (FileValidator) o;
if (shouldReplace != that.shouldReplace) return false;
- if (fileName != null ? !fileName.equals(that.fileName) : that.fileName != null) return false;
- if (srcDir != null ? !srcDir.equals(that.srcDir) : that.srcDir != null) return false;
- return destDir != null ? destDir.equals(that.destDir) : that.destDir == null;
+ if (!Objects.equals(fileName, that.fileName)) return false;
+ if (!Objects.equals(srcDir, that.srcDir)) return false;
+ return Objects.equals(destDir, that.destDir);
}
@Override
diff --git a/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java b/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java
index f49ae008d3..63b4aed02d 100644
--- a/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java
+++ b/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java
@@ -23,7 +23,6 @@ import org.jdom2.input.SAXBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
-import java.io.InputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
@@ -69,10 +68,7 @@ public class SvnLogXmlParserTest {
@Test
public void shouldParseSvnLogContainingNullComments() throws IOException {
- String xml;
- try (InputStream stream = getClass().getResourceAsStream("jemstep_svn_log.xml")) {
- xml = IOUtils.toString(stream, UTF_8);
- }
+ String xml = IOUtils.toString(getClass().getResource("jemstep_svn_log.xml"), UTF_8);
SvnLogXmlParser parser = new SvnLogXmlParser();
List<Modification> revisions = parser.parse(xml, "", new SAXBuilder());
diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java
index 807a0edd83..f504b22c22 100644
--- a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java
+++ b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java
@@ -35,7 +35,10 @@ import com.thoughtworks.go.config.remote.PartialConfig;
import com.thoughtworks.go.config.rules.Allow;
import com.thoughtworks.go.config.rules.Deny;
import com.thoughtworks.go.config.rules.Rules;
-import com.thoughtworks.go.config.validation.*;
+import com.thoughtworks.go.config.validation.ArtifactDirValidator;
+import com.thoughtworks.go.config.validation.GoConfigValidator;
+import com.thoughtworks.go.config.validation.ServerIdImmutabilityValidator;
+import com.thoughtworks.go.config.validation.TokenGenerationKeyImmutabilityValidator;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.config.*;
import com.thoughtworks.go.domain.label.PipelineLabel;
@@ -1690,15 +1693,6 @@ public class MagicalGoConfigXmlLoaderTest {
ConfigMigrator.loadWithMigration(content); // should not fail with a validation exception
}
- @Test
- void shouldLoadLargeConfigFileInReasonableTime() throws Exception {
- String content = IOUtils.toString(getClass().getResourceAsStream("/data/big-cruise-config.xml"), UTF_8);
-// long start = System.currentTimeMillis();
- GoConfigHolder configHolder = ConfigMigrator.loadWithMigration(content);
-// assertThat(System.currentTimeMillis() - start, lessThan(new Long(2000)));
- assertThat(configHolder.config.schemaVersion()).isEqualTo(CONFIG_SCHEMA_VERSION);
- }
-
@Test
void shouldLoadConfigWithPipelinesMatchingUpWithPipelineDefinitionCaseInsensitively() {
String content = configWithEnvironments(
@@ -3884,7 +3878,7 @@ public class MagicalGoConfigXmlLoaderTest {
final CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(configXml).configForEdit;
final ArtifactTypeConfigs artifactTypeConfigs = cruiseConfig.pipelineConfigByName(
- new CaseInsensitiveString("up42")).getStage("up42_stage")
+ new CaseInsensitiveString("up42")).getStage("up42_stage")
.getJobs().getJob(new CaseInsensitiveString("up42_job")).artifactTypeConfigs();
assertThat(artifactTypeConfigs).hasSize(1);
@@ -4224,7 +4218,7 @@ public class MagicalGoConfigXmlLoaderTest {
ArtifactPluginInfo artifactPluginInfo = new ArtifactPluginInfo(pluginDescriptor, storeConfigSettings, publishArtifactSettings, fetchArtifactSettings, null, new Capabilities());
ArtifactMetadataStore.instance().setPluginInfo(artifactPluginInfo);
- String content = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8));
+ String content = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8));
CruiseConfig config = xmlLoader.loadConfigHolder(content).configForEdit;
PipelineConfig ancestor = config.pipelineConfigByName(new CaseInsensitiveString("ancestor"));
@@ -4484,7 +4478,7 @@ public class MagicalGoConfigXmlLoaderTest {
MaterialConfig materialConfig = config
.getPipelineConfigByName(new CaseInsensitiveString("pipeline"))
.materialConfigs().get(0);
-
+
assertThat(materialConfig).isInstanceOf(PluggableSCMMaterialConfig.class);
assertThat(materialConfig.isInvertFilter()).isTrue();
}
diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java
index de03835525..94a55028ba 100644
--- a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java
+++ b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java
@@ -55,14 +55,15 @@ import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
import static com.thoughtworks.go.helper.MaterialConfigsMother.git;
import static com.thoughtworks.go.helper.MaterialConfigsMother.tfs;
import static com.thoughtworks.go.util.DataStructureUtils.m;
import static com.thoughtworks.go.util.GoConstants.CONFIG_SCHEMA_VERSION;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail;
@ExtendWith(ResetCipher.class)
@@ -321,7 +322,9 @@ public class MagicalGoConfigXmlWriterTest {
@Test
public void shouldBeAValidXSD() throws Exception {
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
- factory.newSchema(new StreamSource(getClass().getResourceAsStream("/cruise-config.xsd")));
+ try (InputStream xsdStream = getClass().getResourceAsStream("/cruise-config.xsd")) {
+ factory.newSchema(new StreamSource(xsdStream));
+ }
}
@Test
diff --git a/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java b/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java
index 6c96c73262..2ab651bece 100644
--- a/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java
+++ b/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java
@@ -40,9 +40,9 @@ public class ConfigRepoMigrator {
}
private Chainr getTransformerFor(int targetVersion) {
+ String targetVersionFile = String.format("/config-repo/migrations/%s.json", targetVersion);
try {
- String targetVersionFile = String.format("/config-repo/migrations/%s.json", targetVersion);
- String transformJSON = IOUtils.toString(this.getClass().getResourceAsStream(targetVersionFile), StandardCharsets.UTF_8);
+ String transformJSON = IOUtils.toString(this.getClass().getResource(targetVersionFile), StandardCharsets.UTF_8);
return Chainr.fromSpec(JsonUtils.jsonToList(transformJSON));
} catch (Exception e) {
throw new RuntimeException("Failed to migrate to version " + targetVersion, e);
@@ -50,9 +50,9 @@ public class ConfigRepoMigrator {
}
private Map<String, Object> getContextMap(int targetVersion) {
+ String contextFile = String.format("/config-repo/contexts/%s.json", targetVersion);
try {
- String contextFile = String.format("/config-repo/contexts/%s.json", targetVersion);
- String contextJSON = IOUtils.toString(this.getClass().getResourceAsStream(contextFile), StandardCharsets.UTF_8);
+ String contextJSON = IOUtils.toString(this.getClass().getResource(contextFile), StandardCharsets.UTF_8);
return JsonUtils.jsonToMap(contextJSON);
} catch (Exception e) {
LOGGER.debug(String.format("No context file present for target version '%s'.", targetVersion));
diff --git a/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java b/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java
index 90885bd189..2cf16d1836 100644
--- a/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java
+++ b/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java
@@ -18,6 +18,7 @@ package com.thoughtworks.go.plugin.access.configrepo;
import com.bazaarvoice.jolt.JsonUtils;
import org.apache.commons.io.IOUtils;
+import java.nio.charset.StandardCharsets;
import java.util.Map;
import static com.bazaarvoice.jolt.utils.JoltUtils.remove;
@@ -41,7 +42,7 @@ class ConfigRepoDocumentMother {
private Map<String, Object> getJSONFor(String fileName) {
try {
- String transformJSON = IOUtils.toString(this.getClass().getResourceAsStream(fileName), "UTF-8");
+ String transformJSON = IOUtils.toString(this.getClass().getResource(fileName), StandardCharsets.UTF_8);
return JsonUtils.jsonToMap(transformJSON);
} catch (Exception e) {
throw new RuntimeException(e);
diff --git a/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java b/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java
index 44c809ffd6..d16eaadece 100644
--- a/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java
+++ b/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java
@@ -22,6 +22,7 @@ import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
import java.util.Map;
import static java.lang.String.format;
@@ -36,9 +37,8 @@ public class ViewResolver {
}
public String resolveView(String viewName, Map<String, String> modelMap) {
- try {
- InputStream resourceAsStream = getResourceAsStream(viewName);
- String template = IOUtils.toString(resourceAsStream, "UTF-8");
+ try (InputStream resourceAsStream = getResourceAsStream(viewName)) {
+ String template = IOUtils.toString(resourceAsStream, StandardCharsets.UTF_8);
for (String modelKey : modelMap.keySet()) {
template = template.replaceAll(format("<<<%s>>>", modelKey), modelMap.get(modelKey));
}
diff --git a/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java b/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java
index b2ae2982cb..0a66781184 100644
--- a/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java
+++ b/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java
@@ -118,7 +118,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin
try {
byte[] payload = Base64.getDecoder().decode(data.getBytes());
- byte[] pluginEndpointJsContent = IOUtils.toByteArray(getClass().getResourceAsStream("/" + PLUGIN_ENDPOINT_JS));
+ byte[] pluginEndpointJsContent = IOUtils.toByteArray(getClass().getResource("/" + PLUGIN_ENDPOINT_JS));
try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(payload))) {
String assetsHash = calculateHash(payload, pluginEndpointJsContent);
@@ -139,7 +139,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin
private void safeCopyExternalAssetsToPluginAssetRoot(final String pluginAssetsRoot) {
Path externalAssetsPath = Paths.get(systemEnvironment.get(SystemEnvironment.GO_ANALYTICS_PLUGIN_EXTERNAL_ASSETS));
- if (externalAssetsPath == null || !Files.exists(externalAssetsPath) || !Files.isDirectory(externalAssetsPath)) {
+ if (!Files.exists(externalAssetsPath) || !Files.isDirectory(externalAssetsPath)) {
LOGGER.debug("Analytics plugin external assets path ({}) does not exist or is not a directory. Not loading any assets.", externalAssetsPath);
return;
}
@@ -184,9 +184,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin
LOGGER.info("Deleting cached static assets for plugin: {}", pluginId);
try {
FileUtils.deleteDirectory(new File(pluginStaticAssetsRootDir(pluginId)));
- if (pluginAssetPaths.containsKey(pluginId)) {
- pluginAssetPaths.remove(pluginId);
- }
+ pluginAssetPaths.remove(pluginId);
} catch (Exception e) {
LOGGER.error("Failed to delete cached static assets for plugin: {}", pluginId, e);
ExceptionUtils.bomb(e);
diff --git a/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java b/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java
index 4e750c430a..c71e9091a0 100644
--- a/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java
+++ b/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java
@@ -3,6 +3,7 @@ package com.thoughtworks.go.addon.businesscontinuity;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -20,7 +21,7 @@ class ViewResolverTest {
modelMap.put("key2", "value2");
ViewResolver viewResolverSpy = spy(new ViewResolver());
- doReturn(IOUtils.toInputStream(template)).when(viewResolverSpy).getResourceAsStream("sample");
+ doReturn(IOUtils.toInputStream(template, StandardCharsets.UTF_8)).when(viewResolverSpy).getResourceAsStream("sample");
String resolvedView = viewResolverSpy.resolveView("sample", modelMap);
assertThat(resolvedView, is("<html><head><link href=\\"value1\\\\value2\\"/></head></html>"));
diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java
index 283cdda954..52e4ce6b62 100644
--- a/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java
+++ b/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java
@@ -24,7 +24,6 @@ import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
-import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -35,7 +34,6 @@ import org.mockito.junit.jupiter.MockitoExtension;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -76,7 +74,7 @@ public class AnalyticsPluginAssetsServiceTest {
}
@Test
- public void shouldBeAPluginMetadataChangeListener() throws Exception {
+ public void shouldBeAPluginMetadataChangeListener() {
verify(analyticsMetadataLoader).registerListeners(assetsService);
}
@@ -165,7 +163,7 @@ public class AnalyticsPluginAssetsServiceTest {
assertTrue(pluginDirPath.toFile().exists());
assertTrue(actualPath.toFile().exists());
- byte[] expected = IOUtils.toByteArray(getClass().getResourceAsStream("/plugin-endpoint.js"));
+ byte[] expected = IOUtils.toByteArray(getClass().getResource("/plugin-endpoint.js"));
assertArrayEquals(expected, Files.readAllBytes(actualPath), "Content of plugin-endpoint.js should be preserved");
}
@@ -178,8 +176,8 @@ public class AnalyticsPluginAssetsServiceTest {
when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());
when(systemEnvironment.get(SystemEnvironment.GO_ANALYTICS_PLUGIN_EXTERNAL_ASSETS)).thenReturn(externalAssetsDir.getAbsolutePath());
- Files.write(Paths.get(externalAssetsDir.getAbsolutePath(), "a.js"), "a".getBytes(StandardCharsets.UTF_8));
- Files.write(Paths.get(externalAssetsDir.getAbsolutePath(), "b.js"), "b".getBytes(StandardCharsets.UTF_8));
+ Files.writeString(Paths.get(externalAssetsDir.getAbsolutePath(), "a.js"), "a");
+ Files.writeString(Paths.get(externalAssetsDir.getAbsolutePath(), "b.js"), "b");
assetsService.onPluginMetadataCreate(PLUGIN_ID);
@@ -241,7 +239,7 @@ public class AnalyticsPluginAssetsServiceTest {
}
private String testDataZipArchive() throws IOException {
- return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResourceAsStream("/plugin_cache_test.zip"))));
+ return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResource("/plugin_cache_test.zip"))));
}
private void addAnalyticsPluginInfoToStore(String pluginId) {
diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java
index 6c83d9839b..ed7c1caab2 100644
--- a/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java
+++ b/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java
@@ -32,7 +32,6 @@ import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
-import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Optional;
@@ -48,7 +47,6 @@ public class BackupFilterTest {
private FilterChain chain;
private BackupService backupService;
private PrintWriter writer;
- private InputStream inputStream;
@BeforeEach
public void setUp() throws ServletException, IOException {
@@ -57,7 +55,6 @@ public class BackupFilterTest {
res = mock(HttpServletResponse.class);
backupService = mock(BackupService.class);
chain = mock(FilterChain.class);
- inputStream = BackupFilter.class.getClassLoader().getResourceAsStream("backup_in_progress.html");
writer = mock(PrintWriter.class);
when(res.getWriter()).thenReturn(writer);
this.backupFilter = new BackupFilter(backupService);
@@ -99,7 +96,7 @@ public class BackupFilterTest {
when(backupService.backupRunningSinceISO8601()).thenReturn(BACKUP_STARTED_AT);
when(backupService.backupStartedBy()).thenReturn(BACKUP_STARTED_BY);
- String content = IOUtils.toString(inputStream, UTF_8);
+ String content = IOUtils.toString(BackupFilter.class.getClassLoader().getResource("backup_in_progress.html"), UTF_8);
content = backupFilter.replaceStringLiterals(content);
Request request = request(HttpMethod.GET, "", "/go/agents");
diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java
index e0a00b18b0..7417d7b1d6 100644
--- a/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java
+++ b/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java
@@ -54,7 +54,10 @@ import com.thoughtworks.go.serverhealth.HealthStateType;
import com.thoughtworks.go.serverhealth.ServerHealthService;
import com.thoughtworks.go.serverhealth.ServerHealthState;
import com.thoughtworks.go.service.ConfigRepository;
-import com.thoughtworks.go.util.*;
+import com.thoughtworks.go.util.GoConstants;
+import com.thoughtworks.go.util.ReflectionUtil;
+import com.thoughtworks.go.util.SystemEnvironment;
+import com.thoughtworks.go.util.TempDirUtils;
import com.thoughtworks.go.util.command.CommandLine;
import com.thoughtworks.go.util.command.ConsoleResult;
import org.apache.commons.io.FileUtils;
@@ -1200,7 +1203,7 @@ public class CachedGoConfigIntegrationTest {
ArtifactStore artifactStore = new ArtifactStore("dockerhub", "cd.go.artifact.docker.registry");
artifactStoreService.create(Username.ANONYMOUS, artifactStore, new HttpLocalizedOperationResult());
File configFile = new File(new SystemEnvironment().getCruiseConfigFile());
- String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8));
+ String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8));
FileUtils.writeStringToFile(configFile, config, UTF_8);
cachedGoConfig.forceReload();
@@ -1221,7 +1224,7 @@ public class CachedGoConfigIntegrationTest {
ArtifactStore artifactStore = new ArtifactStore("dockerhub", "cd.go.artifact.docker.registry");
artifactStoreService.create(Username.ANONYMOUS, artifactStore, new HttpLocalizedOperationResult());
File configFile = new File(new SystemEnvironment().getCruiseConfigFile());
- String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8));
+ String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8));
FileUtils.writeStringToFile(configFile, config, UTF_8);
cachedGoConfig.forceReload();
diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java b/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java
index 2668a2a71e..32236b8585 100644
--- a/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java
+++ b/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java
@@ -41,8 +41,8 @@ import java.util.ArrayList;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
-import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = {
@@ -70,7 +70,7 @@ public abstract class FullConfigSaveFlowTestBase {
public void setUp() throws Exception {
configHelper = new GoConfigFileHelper(goConfigDao);
configHelper.onSetUp();
- xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8));
+ xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8));
loader = new MagicalGoConfigXmlLoader(configCache, registry);
setupMetadataForPlugin();
}
diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java
index 6910f8d923..f9d8272ca5 100644
--- a/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java
+++ b/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java
@@ -27,7 +27,9 @@ import com.thoughtworks.go.security.ResetCipher;
import com.thoughtworks.go.server.service.GoConfigService;
import com.thoughtworks.go.serverhealth.ServerHealthService;
import com.thoughtworks.go.service.ConfigRepository;
-import com.thoughtworks.go.util.*;
+import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother;
+import com.thoughtworks.go.util.SystemEnvironment;
+import com.thoughtworks.go.util.TimeProvider;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Document;
@@ -112,7 +114,7 @@ public class GoConfigMigrationIntegrationTest {
@Test
public void shouldMigrateToRevision22() throws Exception {
- final String content = IOUtils.toString(getClass().getResourceAsStream("cruise-config-escaping-migration-test-fixture.xml"), UTF_8);
+ final String content = IOUtils.toString(getClass().getResource("cruise-config-escaping-migration-test-fixture.xml"), UTF_8);
String migratedContent = ConfigMigrator.migrate(content, 21, 22);
@@ -122,7 +124,7 @@ public class GoConfigMigrationIntegrationTest {
@Test
public void shouldMigrateToRevision28() throws Exception {
- final String content = IOUtils.toString(getClass().getResourceAsStream("no-tracking-tool-group-holder-config.xml"), UTF_8);
+ final String content = IOUtils.toString(getClass().getResource("no-tracking-tool-group-holder-config.xml"), UTF_8);
String migratedContent = migrateXmlString(content, 27);
@@ -132,7 +134,7 @@ public class GoConfigMigrationIntegrationTest {
@Test
public void shouldMigrateToRevision34() throws Exception {
- final String content = IOUtils.toString(getClass().getResourceAsStream("svn-p4-with-parameterized-passwords.xml"), UTF_8);
+ final String content = IOUtils.toString(getClass().getResource("svn-p4-with-parameterized-passwords.xml"), UTF_8);
String migratedContent = ConfigMigrator.migrate(content, 22, 34);
@@ -144,7 +146,7 @@ public class GoConfigMigrationIntegrationTest {
@Test
public void shouldMigrateToRevision35_escapeHash() throws Exception {
- final String content = IOUtils.toString(getClass().getResourceAsStream("escape_param_for_nant_p4.xml"), UTF_8).trim();
+ final String content = IOUtils.toString(getClass().getResource("escape_param_for_nant_p4.xml"), UTF_8).trim();
String migratedContent = ConfigMigrator.migrate(content, 22, 35);
diff --git a/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java
index d8aba694df..d215589cb0 100644
--- a/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java
+++ b/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java
@@ -71,7 +71,7 @@ public class PipelineConfigsServiceIntegrationTest {
@BeforeEach
public void setUp() throws Exception {
configHelper = new GoConfigFileHelper();
- xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/config_with_pluggable_artifacts_store.xml"), UTF_8));
+ xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/config_with_pluggable_artifacts_store.xml"), UTF_8));
setupMetadataForPlugin();
configHelper.usingCruiseConfigDao(goConfigDao);
@@ -201,7 +201,7 @@ public class PipelineConfigsServiceIntegrationTest {
}
private String groupSnippetWithSecurePropertiesBeforeEncryption() throws IOException {
- return IOUtils.toString(getClass().getResourceAsStream("/data/pipeline_group_snippet_with_pluggable_artifacts.xml"), UTF_8);
+ return IOUtils.toString(getClass().getResource("/data/pipeline_group_snippet_with_pluggable_artifacts.xml"), UTF_8);
}
} | ['server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java', 'plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java', 'server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java', 'base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java', 'server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java', 'server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java', 'server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java', 'plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java', 'config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java', 'common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java', 'config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java', 'server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java', 'server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java'] | {'.java': 15} | 15 | 15 | 0 | 0 | 15 | 15,876,612 | 3,177,279 | 374,348 | 3,354 | 8,706 | 1,665 | 111 | 11 | 228 | 11 | 67 | 3 | 1 | 0 | 2021-11-27T10:07:34 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
403 | gocd/gocd/10087/10086 | gocd | gocd | https://github.com/gocd/gocd/issues/10086 | https://github.com/gocd/gocd/pull/10087 | https://github.com/gocd/gocd/pull/10087 | 1 | fixes | Test Drive/standalone GoCD fails to start when commit GPG signing is enabled at system/user level | ##### Issue Type
- Bug Report
##### Summary
When I run Test Drive 21.4.0 (`gocd-21.4.0-13469-1477-osx`) which is current stable version, GoCD server couldn't be started.
##### Environment
On my macbook
###### Basic environment details
* Go Version: `21.4.0`
* JAVA Version: `openjdk 15.0.4`
* OS: `macOS 11.6`
##### Steps to Reproduce
1. Run `curl -fsSL 'https://www.gocd.org/test-drive-gocd/try.sh' | bash -s 'https://download.gocd.org/test-drive/installers/21.4.0/13469/gocd-21.4.0-13469-1477-osx.zip'`
2. Server hung with `Wating for the GoCD server to finish initializing.....`
##### Expected Results
GoCD Server launched
##### Actual Results
Starting server failed.
##### Log snippets
```
org.eclipse.jgit.api.errors.ServiceUnavailableException: Signing service is not available
at org.eclipse.jgit.api.CommitCommand.sign(CommitCommand.java:290)
at org.eclipse.jgit.api.CommitCommand.call(CommitCommand.java:247)
at com.thoughtworks.go.service.ConfigRepository$1.run(ConfigRepository.java:125)
at com.thoughtworks.go.util.VoidThrowingFn.call(VoidThrowingFn.java:25)
at com.thoughtworks.go.service.ConfigRepository.doLocked(ConfigRepository.java:136)
at com.thoughtworks.go.service.ConfigRepository.checkin(ConfigRepository.java:121)
at com.thoughtworks.go.config.FullConfigSaveFlow.checkinToConfigRepo(FullConfigSaveFlow.java:79)
at com.thoughtworks.go.config.FullConfigSaveNormalFlow.execute(FullConfigSaveNormalFlow.java:67)
at com.thoughtworks.go.config.GoConfigMigrator.upgradeConfigFile(GoConfigMigrator.java:110)
at com.thoughtworks.go.config.GoConfigMigrator.upgrade(GoConfigMigrator.java:96)
at com.thoughtworks.go.config.GoConfigMigrator.migrate(GoConfigMigrator.java:87)
at com.thoughtworks.go.config.CachedGoConfig.upgradeConfig(CachedGoConfig.java:149)
at com.thoughtworks.go.server.initializers.ApplicationInitializer.onApplicationEvent(ApplicationInitializer.java:112)
at com.thoughtworks.go.server.initializers.ApplicationInitializer.onApplicationEvent(ApplicationInitializer.java:49)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:883)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:1067)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:572)
at org.eclipse.jetty.server.handler.ContextHandler.contextInitialized(ContextHandler.java:996)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:746)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:379)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:910)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73)
at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:46)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:517)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:157)
at com.thoughtworks.go.server.Jetty9Server.startHandlers(Jetty9Server.java:179)
at com.thoughtworks.go.server.Jetty9Server.start(Jetty9Server.java:129)
at com.thoughtworks.go.server.GoServer.startServer(GoServer.java:62)
at com.thoughtworks.go.server.GoServer.go(GoServer.java:54)
at com.thoughtworks.go.server.util.GoLauncher.main(GoLauncher.java:42)
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:567)
at com.thoughtworks.gocd.Boot.run(Boot.java:90)
at com.thoughtworks.gocd.Boot.main(Boot.java:56)
2022-01-14 20:54:16,934 WARN [main] GoConfigMigrator:98 - Error upgrading config file, trying to upgrade using the versioned config file.
2022-01-14 20:54:16,935 WARN [main] ConfigRepository:196 - [CONFIG REPOSITORY] No head exists in the config repository.
2022-01-14 20:54:16,935 WARN [main] GoConfigMigrator:116 - There is no versioned configuration to fallback for migration.
2022-01-14 20:54:16,944 ERROR [main] GoConfigMigrator:64 - There are errors in the Cruise config file. Please read the error message and correct the errors.
Once fixed, please restart GoCD.
Error: Signing service is not available
```
| fb73c589ce0052f30d576f115a8bafe101d1c1c3 | 2db3a23f2bd8f4836e3db34bf7d80b7b242221e9 | https://github.com/gocd/gocd/compare/fb73c589ce0052f30d576f115a8bafe101d1c1c3...2db3a23f2bd8f4836e3db34bf7d80b7b242221e9 | diff --git a/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java b/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java
index 8eb6f587f3..9f2520ca6b 100644
--- a/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java
+++ b/config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java
@@ -78,10 +78,14 @@ public class ConfigRepository {
workingDir = this.systemEnvironment.getConfigRepoDir();
File configRepoDir = new File(workingDir, ".git");
gitRepo = new FileRepositoryBuilder().setGitDir(configRepoDir).build();
- gitRepo.getConfig().setInt("gc", null, "auto", 0);
+ updateWithDefaults(gitRepo.getConfig());
git = new Git(gitRepo);
}
+ private void updateWithDefaults(StoredConfig config) {
+ config.setInt(ConfigConstants.CONFIG_GC_SECTION, null, ConfigConstants.CONFIG_KEY_AUTO, 0);
+ config.setBoolean(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_GPGSIGN, false);
+ }
public Repository getGitRepo() {
return gitRepo;
diff --git a/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java b/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java
index 25fbac99ae..b40abe1b64 100644
--- a/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java
+++ b/config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java
@@ -24,8 +24,11 @@ import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.TimeProvider;
import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
+import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.util.SystemReader;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -35,6 +38,7 @@ import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
+import java.util.function.Consumer;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
@@ -70,6 +74,33 @@ public class ConfigRepositoryTest {
assertThat(configRepo.getRevision("md5-v2").getContent(), is("v1 v2"));
}
+ @Test
+ public void shouldBeAbleToCheckInWithGlobalGpgSigningEnabled() throws Exception {
+ try (UndoableUserGitConfig ignored = new UndoableUserGitConfig(c -> c.setBoolean(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_GPGSIGN, true))) {
+ configRepo = new ConfigRepository(systemEnvironment);
+ configRepo.initialize();
+ configRepo.checkin(new GoConfigRevision("v1", "md5-v1", "user-name", "100.3.9", new TimeProvider()));
+ assertThat(configRepo.getRevision("md5-v1").getContent(), is("v1"));
+ assertThat(configRepo.getCurrentRevCommit().getRawGpgSignature(), nullValue());
+ }
+ }
+
+ private static class UndoableUserGitConfig implements AutoCloseable {
+ private final String originalConfig;
+
+ public UndoableUserGitConfig(Consumer<StoredConfig> configConsumer) throws Exception {
+ StoredConfig config = SystemReader.getInstance().getUserConfig();
+ originalConfig = config.toText();
+ configConsumer.accept(config);
+ }
+
+ @Override
+ public void close() throws Exception {
+ StoredConfig config = SystemReader.getInstance().getUserConfig();
+ config.fromText(originalConfig);
+ }
+ }
+
@Test
public void shouldGetCommitsCorrectly() throws Exception {
configRepo.checkin(new GoConfigRevision("v1", "md5-v1", "user-name", "100.3.9", new TimeProvider()));
@@ -110,7 +141,7 @@ public class ConfigRepositoryTest {
}
@Test
- public void shouldReturnNullWhenThereAreNoCheckIns() throws GitAPIException, IOException {
+ public void shouldReturnNullWhenThereAreNoCheckIns() throws Exception {
assertThat(configRepo.getRevision("current"), is(nullValue()));
}
@@ -317,7 +348,7 @@ public class ConfigRepositoryTest {
}
@Test
- public void shouldSwitchToMasterAndDeleteTempBranches() throws Exception, GitAPIException {
+ public void shouldSwitchToMasterAndDeleteTempBranches() throws Exception {
configRepo.checkin(goConfigRevision("v1", "md5-1"));
configRepo.createBranch(ConfigRepository.BRANCH_AT_HEAD, configRepo.getCurrentRevCommit());
configRepo.createBranch(ConfigRepository.BRANCH_AT_REVISION, configRepo.getCurrentRevCommit());
@@ -376,10 +407,10 @@ public class ConfigRepositoryTest {
public void shouldPerformGC() throws Exception {
configRepo.checkin(goConfigRevision("v1", "md5-1"));
Long numberOfLooseObjects = (Long) configRepo.git().gc().getStatistics().get("sizeOfLooseObjects");
- assertThat(numberOfLooseObjects > 0l, is(true));
+ assertThat(numberOfLooseObjects > 0L, is(true));
configRepo.garbageCollect();
numberOfLooseObjects = (Long) configRepo.git().gc().getStatistics().get("sizeOfLooseObjects");
- assertThat(numberOfLooseObjects, is(0l));
+ assertThat(numberOfLooseObjects, is(0L));
}
@Test
@@ -411,7 +442,7 @@ public class ConfigRepositoryTest {
return new GoConfigRevision(fileContent, md5, "user-1", "13.2", new TimeProvider());
}
- private String getLatestConfigAt(String branchName) throws GitAPIException, IOException {
+ private String getLatestConfigAt(String branchName) throws GitAPIException {
configRepo.git().checkout().setName(branchName).call();
String content = configRepo.getCurrentRevision().getContent(); | ['config/config-server/src/main/java/com/thoughtworks/go/service/ConfigRepository.java', 'config/config-server/src/test/java/com/thoughtworks/go/service/ConfigRepositoryTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,850,828 | 3,172,153 | 373,812 | 3,347 | 393 | 83 | 6 | 1 | 6,058 | 278 | 1,380 | 89 | 2 | 1 | 2022-01-15T02:51:37 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
402 | gocd/gocd/10649/10648 | gocd | gocd | https://github.com/gocd/gocd/issues/10648 | https://github.com/gocd/gocd/pull/10649 | https://github.com/gocd/gocd/pull/10649 | 1 | fixes | Plugin admin page can display stale plugin information after plugin upgrades | ##### Issue Type
- Bug Report
##### Summary
<!--- Provide a brief summary of the issue -->
When plugins are updated to new versions without changing which plugins are installed, `/go/admin/plugins` will display stale data in the browser until browser cache expiry.
###### Basic environment details
<!--- We recommend providing the for us to reproduce the issue quicker -->
* Go Version: `22.1.0`
##### Steps to Reproduce
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
<!--- reproduce this bug include code to reproduce, if relevant -->
1. Load the plugins admin page
2. Update a plugin to a new version while changing nothing else
3. Bounce the server
4. Re-load the plugins admin page, not the old version.
5. Clear cache and/or force refresh and notice it changing.
##### Expected Results
<!--- Tell us what should happen -->
The page should be updated reliably when plugins are updated.
##### Actual Results
<!--- Tell us what happens instead -->
Stale data displayed for some indeterminate amount of time.
##### Possible Fix
<!--- Not obligatory, but suggest a fix or reason for the bug -->
It looks like the below defines a custom hash algorithm for `PluginInfo` which excludes `version`, `name` and other aspects of the plugin descriptor so if they are updated it won't cause a refresh. At the very least the `version` should be included so when a new version is released (which may have new values for other fields) the hash changes, and thus the entity `ETag`.
https://github.com/gocd/gocd/blob/5c7c6c226dc2caa1fe729f5142536634912e795a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java#L107-L113 | c2293bcb6397761bc052789ae59facf315afbfe2 | 85d5ba31393959d8328f5d0dec8e33b27afce6ce | https://github.com/gocd/gocd/compare/c2293bcb6397761bc052789ae59facf315afbfe2...85d5ba31393959d8328f5d0dec8e33b27afce6ce | diff --git a/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java b/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java
index a75120a5a9..1568613acb 100644
--- a/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java
+++ b/api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java
@@ -18,7 +18,6 @@ package com.thoughtworks.go.apiv7.plugininfos;
import com.thoughtworks.go.api.ApiController;
import com.thoughtworks.go.api.ApiVersion;
import com.thoughtworks.go.api.spring.ApiAuthenticationHelper;
-import com.thoughtworks.go.api.spring.ToggleRegisterLatest;
import com.thoughtworks.go.apiv7.plugininfos.representers.PluginInfoRepresenter;
import com.thoughtworks.go.apiv7.plugininfos.representers.PluginInfosRepresenter;
import com.thoughtworks.go.config.exceptions.RecordNotFoundException;
diff --git a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java b/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java
index ebdffb96bd..870f071742 100644
--- a/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java
+++ b/server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java
@@ -107,6 +107,7 @@ public class EntityHashes implements DigestMixin {
JsonSerializer<PluginInfo> PLUGIN_INFO = (src, typeOfSrc, context) -> {
final JsonObject result = new JsonObject();
result.addProperty("id", src.getDescriptor().id());
+ result.addProperty("version", src.getDescriptor().version());
result.addProperty("extension", src.getExtensionName());
result.add("settings", context.serialize(src.getPluginSettings()));
return result;
diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java
index 3459ec986a..ff9b142ec9 100644
--- a/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java
+++ b/server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java
@@ -41,6 +41,7 @@ import java.util.List;
import static com.thoughtworks.go.server.service.EntityHashingService.ETAG_CACHE_KEY;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@@ -72,29 +73,35 @@ public class EntityHashingServiceTest {
@Test
void digestsCombinedPluginInfoAndCollection() {
- final CombinedPluginInfo info1 = new CombinedPluginInfo(new NotificationPluginInfo(
- GoPluginDescriptor.builder().id("foo").build(),
- new PluggableInstanceSettings(List.of(new PluginConfiguration("user", null)))
- ));
- final CombinedPluginInfo info2 = new CombinedPluginInfo(new NotificationPluginInfo(
- GoPluginDescriptor.builder().id("bar").build(),
- new PluggableInstanceSettings(List.of(new PluginConfiguration("user", null)))
- ));
+ PluggableInstanceSettings testSettings = new PluggableInstanceSettings(List.of(new PluginConfiguration("user", null)));
+ final CombinedPluginInfo info1 = new CombinedPluginInfo(
+ new NotificationPluginInfo(GoPluginDescriptor.builder().id("foo").build(), testSettings)
+ );
+ final CombinedPluginInfo info2 = new CombinedPluginInfo(
+ new NotificationPluginInfo(GoPluginDescriptor.builder().id("bar").build(), testSettings)
+ );
final Collection<CombinedPluginInfo> many = List.of(info1, info2);
final String actual = service.hashForEntity(many);
assertTrue(actual.matches("[a-f0-9]{64}"));
assertEquals(digests.digest(
- service.hashForEntity(info1),
- service.hashForEntity(info2)
+ service.hashForEntity(info1),
+ service.hashForEntity(info2)
), actual);
+
+ final CombinedPluginInfo info2v2 = new CombinedPluginInfo(
+ new NotificationPluginInfo(GoPluginDescriptor.builder().id("bar").version("2").build(), testSettings)
+ );
+
+ assertThat(service.hashForEntity(info2v2)).isNotEqualTo(service.hashForEntity(info2));
+
}
@Test
@DisplayName("when plugin settings contain secret properties, the digest used for" +
- "ETags should not change as long as the decrypted values remain the same, " +
- "even if the crypto salt changes between requests")
+ "ETags should not change as long as the decrypted values remain the same, " +
+ "even if the crypto salt changes between requests")
void digestIsConsistentForPluginSettingsWithSecretPropertiesEvenWhenCryptoSaltChanges() {
TestIVProvider.with(new ProductionIVProvider(), () -> {
final String id = "com.foo.plugin";
@@ -106,9 +113,9 @@ public class EntityHashingServiceTest {
final PluginSettings p2 = pluginSettings(id, key, secret);
assertNotEquals(
- p1.getPluginSettingsProperties().get(0).getEncryptedValue(),
- p2.getPluginSettingsProperties().get(0).getEncryptedValue(),
- "both entities should have different cipherTexts even though the input values are equal"
+ p1.getPluginSettingsProperties().get(0).getEncryptedValue(),
+ p2.getPluginSettingsProperties().get(0).getEncryptedValue(),
+ "both entities should have different cipherTexts even though the input values are equal"
);
final String expected = service.hashForEntity(p1);
@@ -162,7 +169,7 @@ public class EntityHashingServiceTest {
@Test
@DisplayName("hashForEntity() can determine the proper overloaded method for implementations of " +
- "EnvironmentConfig and List<EnvironmentConfig> without ambiguity")
+ "EnvironmentConfig and List<EnvironmentConfig> without ambiguity")
void hashesEnvironmentConfigsWithoutClassAmbiguityIssues() {
// important to test these when typed as the non-specific parent interface
final EnvironmentConfig basic = new BasicEnvironmentConfig(new CaseInsensitiveString("hello"));
@@ -175,11 +182,11 @@ public class EntityHashingServiceTest {
// resolving the wrong overload might result in an exception indicating that the object "does not
// have a ConfigTag"
assertDoesNotThrow(() -> {
- assertTrue(isNotBlank(service.hashForEntity(basic)));
- assertTrue(isNotBlank(service.hashForEntity(merged)));
- assertTrue(isNotBlank(service.hashForEntity(mult)));
- assertTrue(isNotBlank(service.hashForEntity(nested)));
- }
+ assertTrue(isNotBlank(service.hashForEntity(basic)));
+ assertTrue(isNotBlank(service.hashForEntity(merged)));
+ assertTrue(isNotBlank(service.hashForEntity(mult)));
+ assertTrue(isNotBlank(service.hashForEntity(nested)));
+ }
);
}
@@ -190,8 +197,8 @@ public class EntityHashingServiceTest {
MergeEnvironmentConfig merged = new MergeEnvironmentConfig(env1, env2);
when(goCache.get(ETAG_CACHE_KEY, "com.thoughtworks.go.config.BasicEnvironmentConfig.env")).
- thenReturn("foo").
- thenReturn("bar");
+ thenReturn("foo").
+ thenReturn("bar");
final String type = MergeEnvironmentConfig.class.getSimpleName();
assertEquals(digests.digest(type, "foo", "bar"), service.hashForEntity(merged)); | ['server/src/main/java/com/thoughtworks/go/server/service/EntityHashes.java', 'api/api-plugin-infos-v7/src/main/java/com/thoughtworks/go/apiv7/plugininfos/PluginInfosControllerV7.java', 'server/src/test-fast/java/com/thoughtworks/go/server/service/EntityHashingServiceTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 15,791,732 | 3,160,232 | 372,429 | 3,334 | 3,440 | 626 | 55 | 3 | 1,709 | 257 | 382 | 39 | 1 | 0 | 2022-08-01T13:24:35 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
401 | gocd/gocd/10676/10036 | gocd | gocd | https://github.com/gocd/gocd/issues/10036 | https://github.com/gocd/gocd/pull/10676 | https://github.com/gocd/gocd/pull/10676 | 1 | fixes | HTTP 500 when using external authorization plugins and GoCD site urls are blank | ##### Issue Type
- Bug Report
##### Summary
When using GoCD GitLab or GitHub authentication plugins, the server site URLs must be set properly in the server configuration, otherwise the GoCD will fail with HTTP 500.
##### Environment
Discovered on 21.2.0, Java 15.
I suppose it is not related to the GoCD or Java version.
###### Basic environment details
* Go Version: 21.2.0
* JAVA Version: 15.0.2
* OS: Linux 4.19.0-17-amd64
##### Steps to Reproduce
1. Put a GitLab or GitHub plugin JAR into the appropriate folder and restart the server
2. Create a new authorization configuration with the desired plugin
3. Make sure that both server site urls are not set OR at least the second one (Secure site URL) is not set
4. Try to login via plugin
##### Expected Results
Should be redirected to the external IDP properly
##### Actual Results
GoCD throws an HTTP500
##### Possible Fix
Use at least the site url which is set or something default, like http://localhost:8153
##### Log snippets
In the go-server.log you can see following:
```
2022-01-03 10:25:48,470 WARN [qtp679525351-29] HttpChannel:673 - handleException /go/plugin/cd.go.authorization.gitlab/login java.net.MalformedURLException: no protocol:
```
| 4fae75d5c7e6e6dcfcacaea0577eafb193e6f29b | 5b7c362731eae1fd8deec665bc025c2e99cba3be | https://github.com/gocd/gocd/compare/4fae75d5c7e6e6dcfcacaea0577eafb193e6f29b...5b7c362731eae1fd8deec665bc025c2e99cba3be | diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java
index 0fef04a87e..51f01b601b 100644
--- a/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java
+++ b/config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java
@@ -294,15 +294,12 @@ public class ServerConfig implements Validatable {
public ServerSiteUrlConfig getSiteUrlPreferablySecured() {
- SiteUrl siteUrl = getSiteUrl();
- SecureSiteUrl secureSiteUrlConfig = getSecureSiteUrl();
- if (secureSiteUrlConfig.hasNonNullUrl()) {
- return secureSiteUrlConfig;
- }
- if (!secureSiteUrlConfig.hasNonNullUrl()) {
- return siteUrl;
+ SecureSiteUrl secureSiteUrl = getSecureSiteUrl();
+ if (!secureSiteUrl.isBlank()) {
+ return secureSiteUrl;
+ } else {
+ return getSiteUrl();
}
- return new SiteUrl();
}
public ServerSiteUrlConfig getHttpsUrl() {
@@ -311,7 +308,7 @@ public class ServerConfig implements Validatable {
}
public boolean hasAnyUrlConfigured() {
- return getSiteUrl().hasNonNullUrl() || getSecureSiteUrl().hasNonNullUrl();
+ return !getSiteUrl().isBlank() || !getSecureSiteUrl().isBlank();
}
public Double getPurgeStart() {
diff --git a/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java
index b350abcc9b..c978d4c873 100644
--- a/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java
+++ b/config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java
@@ -16,6 +16,7 @@
package com.thoughtworks.go.domain;
import com.thoughtworks.go.config.ConfigValue;
+import org.apache.commons.lang3.StringUtils;
import java.net.URI;
import java.net.URISyntaxException;
@@ -32,8 +33,8 @@ public abstract class ServerSiteUrlConfig {
this.url = url;
}
- public boolean hasNonNullUrl() {
- return getUrl() != null;
+ public boolean isBlank() {
+ return StringUtils.isBlank(url);
}
public String getUrl() {
@@ -68,14 +69,22 @@ public abstract class ServerSiteUrlConfig {
}
public String siteUrlFor(String givenUrl, boolean honorGivenHostName) throws URISyntaxException {
- if (url == null || isPath(givenUrl)) {
+ if (isBlank() || isPath(givenUrl)) {
return givenUrl; //it is a path
}
URI baseUri = new URI(url);
URI givenUri = new URI(givenUrl);
- return new URI(baseUri.getScheme(), getOrDefault(givenUri, baseUri, URI::getUserInfo), honorGivenHostName ? givenUri.getHost() : baseUri.getHost(), baseUri.getPort(), getOrDefault(givenUri, baseUri, URI::getPath), getOrDefault(givenUri, baseUri, URI::getQuery), getOrDefault(givenUri, baseUri, URI::getFragment)).toString();
+ return new URI(
+ baseUri.getScheme(),
+ getOrDefault(givenUri, baseUri, URI::getUserInfo),
+ honorGivenHostName ? givenUri.getHost() : baseUri.getHost(),
+ baseUri.getPort(),
+ getOrDefault(givenUri, baseUri, URI::getPath),
+ getOrDefault(givenUri, baseUri, URI::getQuery),
+ getOrDefault(givenUri, baseUri, URI::getFragment)
+ ).toString();
}
private boolean isPath(String givenUrl) {
@@ -88,7 +97,7 @@ public abstract class ServerSiteUrlConfig {
}
public boolean isAHttpsUrl() {
- return url != null && url.matches(HTTPS_URL_REGEX);
+ return !isBlank() && url.matches(HTTPS_URL_REGEX);
}
interface Getter {
@@ -97,7 +106,7 @@ public abstract class ServerSiteUrlConfig {
@Override
public String toString() {
- return hasNonNullUrl() ? url : "";
+ return isBlank() ? "" : url;
}
}
diff --git a/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java b/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java
index ccc451b193..14968fde88 100644
--- a/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java
+++ b/config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java
@@ -61,11 +61,11 @@ public class ServerConfigTest {
public void shouldReturnBlankUrlBothSiteUrlAndSecureSiteUrlIsNotDefined() {
defaultServerConfig.setSiteUrl(null);
defaultServerConfig.setSecureSiteUrl(null);
- assertThat(defaultServerConfig.getSiteUrlPreferablySecured().hasNonNullUrl(), is(false));
+ assertThat(defaultServerConfig.getSiteUrlPreferablySecured().isBlank(), is(true));
}
@Test
- public void shouldReturnAnEmptyForSecureSiteUrlIfOnlySiteUrlIsConfigured() throws Exception {
+ public void shouldReturnAnEmptyForSecureSiteUrlIfOnlySiteUrlIsConfigured() {
ServerConfig serverConfig = new ServerConfig(null, null, new SiteUrl("http://foo.bar:813"), new SecureSiteUrl());
assertThat(serverConfig.getHttpsUrl(), is(new SecureSiteUrl()));
}
diff --git a/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java b/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java
index 46826f047d..dfb2286558 100644
--- a/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java
+++ b/config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java
@@ -16,11 +16,14 @@
package com.thoughtworks.go.domain;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
import java.net.URISyntaxException;
-import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
public class ServerSiteUrlConfigTest {
@Test
@@ -77,9 +80,14 @@ public class ServerSiteUrlConfigTest {
assertThat(url.toString(), is("http://someurl.com"));
}
- @Test
- public void shouldReturnEmptyStringForToStringWhenTheUrlIsNotSet() throws Exception {
- ServerSiteUrlConfig url = new SiteUrl();
+ @ParameterizedTest
+ @NullSource
+ @ValueSource(strings = {"", " "})
+ public void shouldHandleBlankUrlsConsistently(String input) throws Exception {
+ ServerSiteUrlConfig url = new SiteUrl(input);
assertThat(url.toString(), is(""));
+ assertThat(url.isBlank(), is(true));
+ assertThat(url.isAHttpsUrl(), is(false));
+ assertThat(url.siteUrlFor("http://test.host/foo/bar?foo=bar#quux"), is("http://test.host/foo/bar?foo=bar#quux"));
}
}
diff --git a/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java b/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java
index daf9d31e81..ef23185c10 100644
--- a/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java
+++ b/server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java
@@ -88,12 +88,12 @@ public class WebBasedPluginAuthenticationProvider extends AbstractPluginAuthenti
return new AuthenticationToken<>(userPrinciple, credentials, pluginId, clock.currentTimeMillis(), authConfigId);
}
- private String getRootUrl(String string) {
+ private String rootUrlFrom(String urlString) {
try {
- final URL url = new URL(string);
+ final URL url = new URL(urlString);
return new URL(url.getProtocol(), url.getHost(), url.getPort(), "").toString();
} catch (MalformedURLException e) {
- throw new RuntimeException(e);
+ throw new RuntimeException(String.format("Configured siteUrl [%s] does not appear to be a valid URL", urlString), e);
}
}
@@ -107,11 +107,12 @@ public class WebBasedPluginAuthenticationProvider extends AbstractPluginAuthenti
return goConfigService.security().securityAuthConfigs().findByPluginId(pluginId);
}
- public String getAuthorizationServerUrl(String pluginId, String rootURL) {
- if (goConfigService.serverConfig().hasAnyUrlConfigured()) {
- rootURL = getRootUrl(goConfigService.serverConfig().getSiteUrlPreferablySecured().getUrl());
- }
- return authorizationExtension.getAuthorizationServerUrl(pluginId, getAuthConfigs(pluginId), rootURL);
+ public String getAuthorizationServerUrl(String pluginId, String alternateRootUrl) {
+ String chosenRootUrl =
+ goConfigService.serverConfig().hasAnyUrlConfigured()
+ ? rootUrlFrom(goConfigService.serverConfig().getSiteUrlPreferablySecured().getUrl())
+ : alternateRootUrl;
+ return authorizationExtension.getAuthorizationServerUrl(pluginId, getAuthConfigs(pluginId), chosenRootUrl);
}
}
diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java
index 03988934a9..3c63a1d1b5 100644
--- a/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java
+++ b/server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java
@@ -41,6 +41,8 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
+import java.net.MalformedURLException;
+
import static com.thoughtworks.go.server.security.GoAuthority.ROLE_USER;
import static java.util.Arrays.asList;
import static java.util.Collections.*;
@@ -322,6 +324,19 @@ class WebBasedPluginAuthenticationProviderTest {
verify(authorizationExtension).getAuthorizationServerUrl(PLUGIN_ID, singletonList(githubSecurityAuthconfig), "https://example.com");
}
+ @Test
+ void shouldThrowUsefulErrorIfAuthorizationServerUrlIsBad() {
+ final ServerConfig serverConfig = mock(ServerConfig.class);
+ when(goConfigService.serverConfig()).thenReturn(serverConfig);
+ when(serverConfig.hasAnyUrlConfigured()).thenReturn(true);
+ when(serverConfig.getSiteUrlPreferablySecured()).thenReturn(new SecureSiteUrl("https://badurl:3434:"));
+
+ assertThatThrownBy(() -> authenticationProvider.getAuthorizationServerUrl(PLUGIN_ID, "https://example.com"))
+ .isInstanceOf(RuntimeException.class)
+ .hasMessageContaining("does not appear to be a valid URL")
+ .hasCauseInstanceOf(MalformedURLException.class);
+ }
+
@Test
void shouldFetchAccessTokenFromPlugin() {
when(authorizationExtension.fetchAccessToken(PLUGIN_ID, emptyMap(), singletonMap("code", "some-code"), singletonList(githubSecurityAuthconfig))).thenReturn(singletonMap("access_token", "some-access-token")); | ['config/config-api/src/main/java/com/thoughtworks/go/domain/ServerSiteUrlConfig.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/ServerConfig.java', 'server/src/main/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProvider.java', 'config/config-api/src/test/java/com/thoughtworks/go/config/ServerConfigTest.java', 'server/src/test-fast/java/com/thoughtworks/go/server/newsecurity/providers/WebBasedPluginAuthenticationProviderTest.java', 'config/config-api/src/test/java/com/thoughtworks/go/domain/ServerSiteUrlConfigTest.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 15,770,573 | 3,155,800 | 372,021 | 3,332 | 3,869 | 815 | 68 | 4 | 1,275 | 188 | 312 | 47 | 1 | 1 | 2022-08-07T15:32:32 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
400 | gocd/gocd/11262/11260 | gocd | gocd | https://github.com/gocd/gocd/issues/11260 | https://github.com/gocd/gocd/pull/11262 | https://github.com/gocd/gocd/pull/11262 | 1 | fixes | Loading materials admin page creates syntax error on MySQL 8.0 | ### Issue Type
- Bug Report
### Summary
the error occurs after start go-server:
```
2023-01-31 11:17:15,621 ERROR [qtp338329632-38] JDBCExceptionReporter:234 - You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near '* FROM modifications
) mods JOIN materials m ON mods.materialid=m.id WHERE mo' at line 1
```
### Environment
my system env:
```
Centos 7 - kernel-3.10.0-693
go-server-22.3.0-15301
MySQL 8.0.23
```
db.properties:
```
# /etc/go/db.properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3301/gocd?useUnicode=true&characterEncoding=utf8&useSSL=false
db.user=user_gocd
db.password=xxxxxxxx
db.maxActive=32
db.maxIdle=32
```
### Steps to Reproduce
1. start go-server
2. click the `AGENTS` OR `MATERIALS` button on the gocd web
3. check the error file /var/log/go-server/go-server.log
### mysql query
```
2023-01-31 11:17:15| cli -> ser |【Query】 SELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid)
as max_id, * FROM modifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id;
2023-01-31 11:17:15| ser -> cli |【Err】 Err code:1064,Err msg:42000You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to use near '* FROM modifications )
mods JOIN materials m ON mods.materialid=m.id WHERE mo' at line 1
```
### Possible Fix
read more from [mysql8-select](https://dev.mysql.com/doc/refman/8.0/en/select.html).
Use of an unqualified * with other items in the select list may produce a parse error. For example:
```
SELECT id, * FROM t1
```
to avoid this problem, use a qualified tbl_name.* reference:
```
SELECT id, t1.* FROM t1
```
So we should change the sql:
```
SELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, * FROM modifications )
mods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id;
==>
SELECT mods.* FROM ( SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, modifications.* FROM
modifications ) mods JOIN materials m ON mods.materialid=m.id WHERE mods.id=mods.max_id;
``` | b3a6bad328f3e0e7e6739e6913f13499725c605c | c173255552af0656a9adbbd7c725d93ba8f62ab3 | https://github.com/gocd/gocd/compare/b3a6bad328f3e0e7e6739e6913f13499725c605c...c173255552af0656a9adbbd7c725d93ba8f62ab3 | diff --git a/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java b/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java
index 8fe5c7ba3d..162fc4e57c 100644
--- a/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java
+++ b/server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java
@@ -1031,7 +1031,7 @@ public class MaterialRepository extends HibernateDaoSupport {
public List<Modification> getLatestModificationForEachMaterial() {
String queryString = "SELECT mods.* " +
"FROM (" +
- " SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, * " +
+ " SELECT MAX(id) OVER (PARTITION BY materialid) as max_id, modifications.* " +
" FROM modifications " +
") mods " +
"JOIN materials m ON mods.materialid=m.id " + | ['server/src/main/java/com/thoughtworks/go/server/persistence/MaterialRepository.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,411,055 | 3,088,725 | 363,908 | 3,249 | 181 | 45 | 2 | 1 | 2,265 | 300 | 632 | 72 | 1 | 7 | 2023-01-31T15:50:05 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
397 | gocd/gocd/11874/11868 | gocd | gocd | https://github.com/gocd/gocd/issues/11868 | https://github.com/gocd/gocd/pull/11874 | https://github.com/gocd/gocd/pull/11874 | 1 | fixes | `runOnAllAgents="true"` added to jobs at GoCD startup | ##### Issue Type
<!--- Please specify the issue type to help us categorize the issue, mention any one of the below types -->
- Bug Report
##### Summary
<!--- Provide a brief summary of the issue -->
GoCD surprisingly adds `runOnAllAgents="true"` to jobs.
##### Environment
<!---
Describe the environment in which you encountered this issue.
Details of the environment GoCD is running in can be fetched from the GoCD support api - http://<go-server-host>/go/api/support.
If you are pasting plain text, please surround it with 3 backticks on each side
```plain
paste any text output
to prevent formatting
```
-->
👋 Let me know if you need this and I can share this individually, as it might contain sensitive information.
###### Basic environment details
<!--- We recommend providing the for us to reproduce the issue quicker -->
* Go Version: `23.1.0 (16080-54a6971915ff8d402c9fea8cd2ceeb6e31c8cdc8)`
* JAVA Version: `17.0.6`
* OS: `Linux 5.10.176+`
###### Additional Environment Details
<!-- More environment details captured from the support API or other sources can be shared here -->
##### Steps to Reproduce
1. Restarting GoCD
##### Expected Results
1. GoCD config behaving like before.
##### Actual Results
1. GoCD surprisingly adds `runOnAllAgents="true"` to jobs.
##### Possible Fix
<!--- Not obligatory, but suggest a fix or reason for the bug -->
🤷
##### Log snippets
<!---
If you could find any information/exceptions from the logs do provide it here.
Do mask any confidential information which you don't want to be shared.
Remember to surround them in 3 backticks like this —
```
long log lines go here
```
-->
##### Code snippets/Screenshots
Here is an example of a commit GoCD makes:
```diff
commit a29ab7eddd8a8d864f33a656f96ad1291abe53b7
Author: Upgrade <[email protected]>
Date: Fri Aug 11 05:11:37 2023 +0000
user:Upgrade|timestamp:1691730697644|schema_version:139|go_edition:OpenSource|go_version:23.1.0 (16080-54a6971915ff8d402c9fea8cd2ceeb6e31c8cdc8)|md5:536dedf85183254cabe2192eb1f7c5e2
diff --git a/cruise-config.xml b/cruise-config.xml
index 5234ae934..65a8023b5 100644
--- a/cruise-config.xml
+++ b/cruise-config.xml
@@ -34838,7 +34838,7 @@ fi</arg>
<artifact type="test" src="some-tests/target/logs/docker" dest="logs" />
</artifacts>
</job>
- <job name="some-tests">
+ <job name="some-tests" runOnAllAgents="true">
<tasks>
<fetchartifact artifactOrigin="gocd" srcfile="tag" stage="build" job="defaultJob" />
<exec command="/bin/bash">
```
##### Any other info
<!--- Provide any other information you would like to share to explain this issue more better -->
| 9a9a12047df94036b92106d4296555278eb7bce6 | 04e6ccb02476a095b12ff09f909a93bee210d2dd | https://github.com/gocd/gocd/compare/9a9a12047df94036b92106d4296555278eb7bce6...04e6ccb02476a095b12ff09f909a93bee210d2dd | diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java b/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java
index 3087dc0b1f..de6c0c0a5f 100644
--- a/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java
+++ b/config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java
@@ -19,7 +19,6 @@ import com.thoughtworks.go.config.parser.GoConfigFieldTypeConverter;
import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry;
import com.thoughtworks.go.util.ConfigUtil;
import org.jdom2.Element;
-import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.TypeMismatchException;
import java.lang.reflect.Field;
@@ -33,23 +32,17 @@ public class GoConfigFieldWriter {
private final ConfigUtil configUtil = new ConfigUtil("magic");
private final Field configField;
private final Object value;
- private final SimpleTypeConverter typeConverter;
private final ConfigCache configCache;
private final ConfigElementImplementationRegistry registry;
- public GoConfigFieldWriter(Field declaredField, Object value, SimpleTypeConverter converter, ConfigCache configCache, final ConfigElementImplementationRegistry registry) {
+ public GoConfigFieldWriter(Field declaredField, Object value, ConfigCache configCache, final ConfigElementImplementationRegistry registry) {
this.configField = declaredField;
this.value = value;
this.configField.setAccessible(true);
- this.typeConverter = converter;
this.configCache = configCache;
this.registry = registry;
}
- public GoConfigFieldWriter(Field declaredField, Object value, ConfigCache configCache, final ConfigElementImplementationRegistry registry) {
- this(declaredField, value, new GoConfigFieldTypeConverter(), configCache, registry);
- }
-
public Field getConfigField() {
return configField;
}
@@ -78,7 +71,7 @@ public class GoConfigFieldWriter {
try {
setFieldIfNotNull(configField, o, val);
} catch (TypeMismatchException e1) {
- final String message = format("Could not set value [{0}] on Field [{1}] of type [{2}] ", val,
+ final String message = format("Could not set value [{0}] on field [{1}] of type [{2}] ", val,
configField.getName(), configField.getType());
throw new RuntimeException(message, e1);
}
@@ -87,9 +80,7 @@ public class GoConfigFieldWriter {
private void bombIfNullAndNotAllowed(Field field, Object instance, ConfigAttribute attribute) {
try {
if (!attribute.allowNull()) {
- bombIfNull(field.get(instance),
- () -> "Field '" + field.getName() + "' is still set to null. "
- + "Must give a default value.");
+ bombIfNull(field.get(instance), () -> "Field '" + field.getName() + "' is still set to null. Must give a default value.");
}
} catch (IllegalAccessException e) {
throw bomb("Error getting configField: " + field.getName(), e);
@@ -99,7 +90,7 @@ public class GoConfigFieldWriter {
private void setFieldIfNotNull(Field field, Object instance, Object val) {
try {
if (val != null) {
- Object convertedValue = typeConverter.convertIfNecessary(val, configField.getType());
+ Object convertedValue = GoConfigFieldTypeConverter.forThread().convertIfNecessary(val, configField.getType());
field.set(instance, convertedValue);
}
} catch (IllegalAccessException e) {
@@ -107,15 +98,15 @@ public class GoConfigFieldWriter {
}
}
-@SuppressWarnings({"DataFlowIssue", "unchecked"})
-private Collection<?> parseCollection(Element e, Class<?> collectionType) {
+ @SuppressWarnings({"DataFlowIssue", "unchecked"})
+ private Collection<?> parseCollection(Element e, Class<?> collectionType) {
ConfigCollection collection = collectionType.getAnnotation(ConfigCollection.class);
Class<?> type = collection.value();
Object o = newInstance(collectionType);
bombUnless(o instanceof Collection,
- () -> "Must be some sort of list. Was: " + collectionType.getName());
+ () -> "Must be some sort of list. Was: " + collectionType.getName());
Collection<Object> baseCollection = (Collection<Object>) o;
for (Element childElement : e.getChildren()) {
@@ -124,7 +115,7 @@ private Collection<?> parseCollection(Element e, Class<?> collectionType) {
}
}
bombIf(baseCollection.size() < collection.minimum(),
- () -> "Required at least " + collection.minimum() + " subelements to '" + e.getName() + "'. "
+ () -> "Required at least " + collection.minimum() + " subelements to '" + e.getName() + "'. "
+ "Found " + baseCollection.size() + ".");
return baseCollection;
}
@@ -192,7 +183,7 @@ private Collection<?> parseCollection(Element e, Class<?> collectionType) {
ConfigTag tag = configTag(field.getType());
boolean optional = field.getAnnotation(ConfigSubtag.class).optional();
boolean isMissingElement = !configUtil.hasChild(e, tag);
- if(!optional && isMissingElement) {
+ if (!optional && isMissingElement) {
throw bomb("Non optional tag '" + tag + "' is not in config file. Found: " + configUtil.elementOutput(e));
}
return optional && isMissingElement;
@@ -201,7 +192,7 @@ private Collection<?> parseCollection(Element e, Class<?> collectionType) {
private boolean optionalAndMissingAttribute(Element e, ConfigAttribute attribute) {
boolean optional = attribute.optional();
boolean isMissingAttribute = !configUtil.hasAttribute(e, attribute.value());
- if(!optional && isMissingAttribute) {
+ if (!optional && isMissingAttribute) {
throw bomb("Non optional attribute '" + attribute.value() + "' is not in element: " + configUtil.elementOutput(e));
}
return optional && isMissingAttribute;
diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java b/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java
index d7c9ff96b2..40b88dd33a 100644
--- a/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java
+++ b/config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java
@@ -15,16 +15,25 @@
*/
package com.thoughtworks.go.config.parser;
-import java.io.File;
-
+import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.SimpleTypeConverter;
+import org.springframework.beans.TypeConverter;
import org.springframework.beans.propertyeditors.FileEditor;
-import org.apache.commons.lang3.StringUtils;
+
+import java.io.File;
public class GoConfigFieldTypeConverter extends SimpleTypeConverter {
+ public static TypeConverter forThread() {
+ return typeConverter.get();
+ }
+
private static final CustomizedFileEditor propertyEditor = new CustomizedFileEditor();
+ // Type converters are NOT thread safe. Should be OK to cache them per thread as not too large and don't think
+ // we have too many threads that will be doing so?
+ private static final ThreadLocal<TypeConverter> typeConverter = ThreadLocal.withInitial(GoConfigFieldTypeConverter::new);
+
public GoConfigFieldTypeConverter() {
super();
this.registerCustomEditor(File.class, propertyEditor);
diff --git a/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java b/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java
deleted file mode 100644
index 6a70e36071..0000000000
--- a/config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright 2023 Thoughtworks, Inc.
- *
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * 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.thoughtworks.go.config.parser;
-
-import java.beans.PropertyEditor;
-import java.io.File;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-
-import com.thoughtworks.go.util.ReflectionUtil;
-import org.junit.jupiter.api.Test;
-
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class GoConfigFieldTypeConverterTest {
- @Test
- public void shouldOnlyCreateOneInstanceOfCustomizedFileEditorAndUseIt() throws Exception {
- GoConfigFieldTypeConverter converter = new GoConfigFieldTypeConverter();
- Field expectedField = converter.getClass().getDeclaredField("propertyEditor");
- int modifier = expectedField.getModifiers();
- assertThat(Modifier.isStatic(modifier), is(true));
- assertThat(Modifier.isFinal(modifier), is(true));
- PropertyEditor actual = converter.findCustomEditor(File.class, null);
- assertThat(actual, is(ReflectionUtil.getStaticField(converter.getClass(), "propertyEditor")));
- }
-}
diff --git a/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java b/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java
index 8891250284..e90d5fb7ba 100644
--- a/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java
+++ b/config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java
@@ -20,14 +20,13 @@ import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry;
import com.thoughtworks.go.security.GoCipher;
import org.jdom2.Attribute;
import org.jdom2.Element;
-import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.TypeMismatchException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
-import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
import static com.thoughtworks.go.config.ConfigCache.isAnnotationPresent;
import static com.thoughtworks.go.config.parser.GoConfigAttributeLoader.attributeParser;
@@ -38,8 +37,7 @@ import static com.thoughtworks.go.util.ExceptionUtils.bomb;
import static java.text.MessageFormat.format;
public class GoConfigFieldLoader<T> {
- private static final Map<Field, Boolean> implicits = new HashMap<>();
- private static final SimpleTypeConverter typeConverter = new GoConfigFieldTypeConverter();
+ private static final Map<Field, Boolean> implicits = new ConcurrentHashMap<>();
private final Element e;
private final T instance;
@@ -49,7 +47,7 @@ public class GoConfigFieldLoader<T> {
private final ConfigElementImplementationRegistry registry;
public static <T> GoConfigFieldLoader<T> fieldParser(Element e, T instance, Field field, ConfigCache configCache, final ConfigElementImplementationRegistry registry,
- ConfigReferenceElements configReferenceElements) {
+ ConfigReferenceElements configReferenceElements) {
return new GoConfigFieldLoader<>(e, instance, field, configCache, registry, configReferenceElements);
}
@@ -93,11 +91,8 @@ public class GoConfigFieldLoader<T> {
}
private boolean isImplicitCollection() {
- if (!implicits.containsKey(field)) {
- implicits.put(field, ConfigCache.isAnnotationPresent(field, ConfigSubtag.class)
- && GoConfigClassLoader.isImplicitCollection(field.getType()));
- }
- return implicits.get(field);
+ return implicits.computeIfAbsent(field,
+ f -> ConfigCache.isAnnotationPresent(f, ConfigSubtag.class) && GoConfigClassLoader.isImplicitCollection(f.getType()));
}
private void setValue(Object val) {
@@ -109,13 +104,12 @@ public class GoConfigFieldLoader<T> {
field.set(instance, constructor.newInstance(val));
}
} else if (val != null) {
- Object convertedValue = typeConverter.convertIfNecessary(val, field.getType());
- field.set(instance, convertedValue);
+ field.set(instance, GoConfigFieldTypeConverter.forThread().convertIfNecessary(val, field.getType()));
}
} catch (IllegalAccessException e) {
throw bomb("Error setting configField: " + field.getName(), e);
} catch (TypeMismatchException e) {
- final String message = format("Could not set value [{0}] on Field [{1}] of type [{2}] ",
+ final String message = format("Could not set value [{0}] on field [{1}] of type [{2}] ",
val, field.getName(), field.getType());
throw bomb(message, e);
} catch (NoSuchMethodException e) {
diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java
deleted file mode 100644
index 7d221b5f32..0000000000
--- a/config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2023 Thoughtworks, Inc.
- *
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * 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.thoughtworks.go.config.parser;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-
-import org.junit.jupiter.api.Test;
-
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class GoConfigFieldLoaderTest {
-
- @Test
- public void shouldOnlyCreateOneInstanceOfSimpleTypeConverterAndUseIt() throws Exception {
- Integer dummyValue = 0;
- Field randomField = dummyValue.getClass().getDeclaredFields()[0]; // Random field because I can't mock java.lang.reflect.Field (Sachin)
- GoConfigFieldLoader loader = GoConfigFieldLoader.fieldParser(null, null, randomField, null, null, new ConfigReferenceElements());
- Field expectedField = loader.getClass().getDeclaredField("typeConverter");
- int modifier = expectedField.getModifiers();
- assertThat(Modifier.isStatic(modifier), is(true));
- assertThat(Modifier.isFinal(modifier), is(true));
- }
-}
- | ['config/config-server/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldLoaderTest.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverter.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/GoConfigFieldWriter.java', 'config/config-api/src/test/java/com/thoughtworks/go/config/parser/GoConfigFieldTypeConverterTest.java', 'config/config-server/src/main/java/com/thoughtworks/go/config/parser/GoConfigFieldLoader.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 15,198,620 | 3,045,503 | 359,172 | 3,182 | 4,463 | 843 | 64 | 3 | 2,831 | 347 | 748 | 97 | 1 | 3 | 2023-08-17T15:44:19 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
395 | gocd/gocd/631/548 | gocd | gocd | https://github.com/gocd/gocd/issues/548 | https://github.com/gocd/gocd/pull/631 | https://github.com/gocd/gocd/issues/548#issuecomment-58576865 | 2 | fixes | Polling and builds fail when a git submodule URL changes | This causes `git submodule update --init` to fail which means material updates fail and builds running on the agent fail if they have the stale submodule url:
```
git submodule update --init
--- Environment ---
{}
--- INPUT ----
--OUTPUT ---
<cut>
ERROR: fatal: reference is not a tree: 176026c856dd4cecd80fcdd5fe904fbc9f4c1385
ERROR: Unable to checkout '176026c856dd4cecd80fcdd5fe904fbc9f4c1385' in submodule path 'src/gnatsd'
```
`git submodule sync` is needed to refresh the submodule url.
This is time consuming to recover from because the fix involves running git submodule sync on the flyweights on the server and all copies on the agents which have stale urls.
| c08ce3bedd2bccb769537e6d811283a57782a842 | 89442cfbb75236c00391d846bf2364ef4beef4cd | https://github.com/gocd/gocd/compare/c08ce3bedd2bccb769537e6d811283a57782a842...89442cfbb75236c00391d846bf2364ef4beef4cd | diff --git a/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java b/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java
index 65d377c49a..849470b65d 100644
--- a/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java
+++ b/common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java
@@ -149,7 +149,7 @@ public class GitCommand extends SCMCommand {
run(gitCmd, outputStreamConsumer);
}
- private void resetHard(ProcessOutputStreamConsumer outputStreamConsumer, Revision revision) {
+ public void resetHard(ProcessOutputStreamConsumer outputStreamConsumer, Revision revision) {
outputStreamConsumer.stdOutput("[GIT] Updating working copy to revision " + revision.getRevision());
String[] args = new String[]{"reset", "--hard", revision.getRevision()};
CommandLine gitCmd = git().withArgs(args).withWorkingDir(workingDir);
@@ -172,9 +172,17 @@ public class GitCommand extends SCMCommand {
return;
}
outputStreamConsumer.stdOutput("[GIT] Updating git sub-modules");
- String[] args = new String[]{"submodule", "update", "--init"};
- CommandLine gitCmd = git().withArgs(args).withWorkingDir(workingDir);
- runOrBomb(gitCmd);
+
+ String[] initArgs = new String[]{"submodule", "init"};
+ CommandLine initCmd = git().withArgs(initArgs).withWorkingDir(workingDir);
+ runOrBomb(initCmd);
+
+ submoduleSync();
+
+ String[] updateArgs = new String[]{"submodule", "update"};
+ CommandLine updateCmd = git().withArgs(updateArgs).withWorkingDir(workingDir);
+ runOrBomb(updateCmd);
+
outputStreamConsumer.stdOutput("[GIT] Cleaning unversioned files and sub-modules");
printSubmoduleStatus(outputStreamConsumer);
}
@@ -259,7 +267,7 @@ public class GitCommand extends SCMCommand {
runOrBomb(gitCmd);
}
- private void fetch(ProcessOutputStreamConsumer outputStreamConsumer) {
+ public void fetch(ProcessOutputStreamConsumer outputStreamConsumer) {
outputStreamConsumer.stdOutput("[GIT] Fetching changes");
CommandLine gitFetch = git().withArgs("fetch", "origin").withWorkingDir(workingDir);
@@ -357,4 +365,20 @@ public class GitCommand extends SCMCommand {
ConsoleResult consoleResult = runOrBomb(getCurrentBranchCommand);
return consoleResult.outputAsString();
}
+
+ public void changeSubmoduleUrl(String submoduleName, String newUrl) {
+ String[] args = new String[]{"config", "--file", ".gitmodules", "submodule." + submoduleName + ".url", newUrl};
+ CommandLine gitConfig = git().withArgs(args).withWorkingDir(workingDir);
+ runOrBomb(gitConfig);
+ }
+
+ public void submoduleSync() {
+ String[] syncArgs = new String[]{"submodule", "sync"};
+ CommandLine syncCmd = git().withArgs(syncArgs).withWorkingDir(workingDir);
+ runOrBomb(syncCmd);
+
+ String[] foreachArgs = new String[]{"submodule", "foreach", "--recursive", "git", "submodule", "sync"};
+ CommandLine foreachCmd = git().withArgs(foreachArgs).withWorkingDir(workingDir);
+ runOrBomb(foreachCmd);
+ }
}
diff --git a/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java b/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java
index 7094807e96..36a7804cc2 100644
--- a/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java
+++ b/common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java
@@ -445,6 +445,24 @@ public class GitCommandTest {
clonedCopy.fetchAndReset(outputStreamConsumer, new StringRevision("HEAD"));
}
+ @Test
+ public void shouldAllowSubmoduleUrlstoChange() throws Exception {
+ InMemoryStreamConsumer outputStreamConsumer = inMemoryConsumer();
+ GitSubmoduleRepos submoduleRepos = new GitSubmoduleRepos();
+ String submoduleDirectoryName = "local-submodule";
+ File cloneDirectory = createTempWorkingDirectory();
+
+ File remoteSubmoduleLocation = submoduleRepos.addSubmodule(SUBMODULE, submoduleDirectoryName);
+
+ GitCommand clonedCopy = new GitCommand(null, cloneDirectory, GitMaterialConfig.DEFAULT_BRANCH, false);
+ clonedCopy.cloneFrom(outputStreamConsumer, submoduleRepos.mainRepo().getUrl());
+ clonedCopy.fetchAndResetToHead(outputStreamConsumer);
+
+ submoduleRepos.changeSubmoduleUrl(submoduleDirectoryName);
+
+ clonedCopy.fetchAndResetToHead(outputStreamConsumer);
+ }
+
private List<File> allFilesIn(File directory, String prefixOfFiles) {
return new ArrayList<File>(FileUtils.listFiles(directory, andFileFilter(fileFileFilter(), prefixFileFilter(prefixOfFiles)), null));
}
diff --git a/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java b/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java
index 6f4787a81b..423ad2fa4f 100644
--- a/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java
+++ b/common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java
@@ -21,6 +21,7 @@ import com.thoughtworks.go.config.materials.git.GitMaterialConfig;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext;
import com.thoughtworks.go.domain.materials.git.GitCommand;
+import com.thoughtworks.go.domain.materials.mercurial.StringRevision;
import com.thoughtworks.go.util.TestFileUtil;
import org.apache.commons.io.FileUtils;
@@ -137,4 +138,18 @@ public class GitSubmoduleRepos extends TestRepo {
@Override public GitMaterial material() {
return new GitMaterial(remoteRepoDir.getAbsolutePath());
}
+
+ public void changeSubmoduleUrl(String submoduleName) throws Exception {
+ File newSubmodule = createRepo("new-submodule");
+ addAndCommitNewFile(newSubmodule, "new", "make a commit");
+
+ git(remoteRepoDir).changeSubmoduleUrl(submoduleName, newSubmodule.getAbsolutePath());
+ git(remoteRepoDir).submoduleSync();
+
+ git(new File(remoteRepoDir, "local-submodule")).fetch(inMemoryConsumer());
+ git(new File(remoteRepoDir, "local-submodule")).resetHard(inMemoryConsumer(), new StringRevision("origin/master"));
+ git(remoteRepoDir).add(new File(".gitmodules"));
+ git(remoteRepoDir).add(new File("local-submodule"));
+ git(remoteRepoDir).commit("change submodule url");
+ }
} | ['common/test/com/thoughtworks/go/helper/GitSubmoduleRepos.java', 'common/test/com/thoughtworks/go/domain/materials/git/GitCommandTest.java', 'common/src/com/thoughtworks/go/domain/materials/git/GitCommand.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 7,018,116 | 1,409,995 | 184,079 | 1,644 | 1,700 | 362 | 34 | 1 | 673 | 101 | 174 | 19 | 0 | 1 | 2014-10-08T08:52:05 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
407 | gocd/gocd/7738/7737 | gocd | gocd | https://github.com/gocd/gocd/issues/7737 | https://github.com/gocd/gocd/pull/7738 | https://github.com/gocd/gocd/pull/7738 | 1 | fixes | Issues with moving pipelines between groups | ##### Issue Type
- Bug Report
##### Summary
Moving pipelines between groups on the pipelines page fails if the given pipeline has a dependency material defined and uses parameters to define the upstream pipeline.
If a dependency material is defined without a name, the name defaults to the pipeline name. If the name of the upstream pipeline is a parameter then on update(in this pipeline group move) to the pipeline would fail for material name validation, as the material can only be alphanumeric.
| fbe640c871dfe4bff5b3e3ddead658e6ca9694a0 | 504b1403e2f25ab90650f9590fd6f0562ce55c4b | https://github.com/gocd/gocd/compare/fbe640c871dfe4bff5b3e3ddead658e6ca9694a0...504b1403e2f25ab90650f9590fd6f0562ce55c4b | diff --git a/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java b/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java
index b1e9b4bf15..d86ea9bef4 100644
--- a/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java
+++ b/config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java
@@ -80,11 +80,6 @@ public class DependencyMaterialConfig extends AbstractMaterialConfig implements
this.ignoreForScheduling = ignoreForScheduling;
}
- @Override
- public CaseInsensitiveString getName() {
- return super.getName() == null ? pipelineName : super.getName();
- }
-
public String getUserName() {
return "cruise";
}
@@ -207,7 +202,8 @@ public class DependencyMaterialConfig extends AbstractMaterialConfig implements
@Override
public String getDisplayName() {
- return CaseInsensitiveString.str(getName());
+ CaseInsensitiveString name = getName() == null ? pipelineName : getName();
+ return name.toString();
}
@Override
diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java
index 7d23231b7b..d8f4d38e79 100644
--- a/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java
+++ b/config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java
@@ -26,8 +26,9 @@ import com.thoughtworks.go.domain.materials.dependency.NewGoConfigMother;
import com.thoughtworks.go.helper.GoConfigMother;
import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother;
import org.apache.commons.io.IOUtils;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -36,18 +37,17 @@ import java.util.Map;
import static com.thoughtworks.go.helper.MaterialConfigsMother.p4;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
-public class DependencyMaterialConfigTest {
+class DependencyMaterialConfigTest {
private MagicalGoConfigXmlWriter writer;
private MagicalGoConfigXmlLoader loader;
private CruiseConfig config;
private PipelineConfig pipelineConfig;
- @Before
- public void setUp() throws Exception {
+ @BeforeEach
+ void setUp() {
writer = new MagicalGoConfigXmlWriter(new ConfigCache(), ConfigElementImplementationRegistryMother.withNoPlugins());
loader = new MagicalGoConfigXmlLoader(new ConfigCache(), ConfigElementImplementationRegistryMother.withNoPlugins());
config = GoConfigMother.configWithPipelines("pipeline1", "pipeline2", "pipeline3", "go");
@@ -55,16 +55,16 @@ public class DependencyMaterialConfigTest {
}
@Test
- public void shouldBeAbleToLoadADependencyMaterialFromConfig() throws Exception {
+ void shouldBeAbleToLoadADependencyMaterialFromConfig() throws Exception {
String xml = "<pipeline pipelineName=\\"pipeline-name\\" stageName=\\"stage-name\\" />";
DependencyMaterialConfig material = loader.fromXmlPartial(xml, DependencyMaterialConfig.class);
- assertThat(material.getPipelineName(), is(new CaseInsensitiveString("pipeline-name")));
- assertThat(material.getStageName(), is(new CaseInsensitiveString("stage-name")));
- assertThat(writer.toXmlPartial(material), is(xml));
+ assertThat(material.getPipelineName()).isEqualTo(new CaseInsensitiveString("pipeline-name"));
+ assertThat(material.getStageName()).isEqualTo(new CaseInsensitiveString("stage-name"));
+ assertThat(writer.toXmlPartial(material)).isEqualTo(xml);
}
@Test
- public void shouldBeAbleToSaveADependencyMaterialToConfig() throws Exception {
+ void shouldBeAbleToSaveADependencyMaterialToConfig() throws Exception {
DependencyMaterialConfig originalMaterial = new DependencyMaterialConfig(new CaseInsensitiveString("pipeline-name"), new CaseInsensitiveString("stage-name"));
NewGoConfigMother mother = new NewGoConfigMother();
@@ -79,13 +79,13 @@ public class DependencyMaterialConfigTest {
CruiseConfig config = loader.loadConfigHolder(IOUtils.toString(inputStream, UTF_8)).config;
DependencyMaterialConfig material = (DependencyMaterialConfig) config.pipelineConfigByName(new CaseInsensitiveString("dependent")).materialConfigs().get(1);
- assertThat(material, is(originalMaterial));
- assertThat(material.getPipelineName(), is(new CaseInsensitiveString("pipeline-name")));
- assertThat(material.getStageName(), is(new CaseInsensitiveString("stage-name")));
+ assertThat(material).isEqualTo(originalMaterial);
+ assertThat(material.getPipelineName()).isEqualTo(new CaseInsensitiveString("pipeline-name"));
+ assertThat(material.getStageName()).isEqualTo(new CaseInsensitiveString("stage-name"));
}
@Test
- public void shouldBeAbleToHaveADependencyAndOneOtherMaterial() throws Exception {
+ void shouldBeAbleToHaveADependencyAndOneOtherMaterial() throws Exception {
NewGoConfigMother mother = new NewGoConfigMother();
mother.addPipeline("pipeline-name", "stage-name", "job-name");
PipelineConfig pipelineConfig = mother.addPipeline("dependent", "stage-name", "job-name",
@@ -102,62 +102,62 @@ public class DependencyMaterialConfigTest {
CruiseConfig config = loader.loadConfigHolder(IOUtils.toString(inputStream, UTF_8)).config;
MaterialConfigs materialConfigs = config.pipelineConfigByName(new CaseInsensitiveString("dependent")).materialConfigs();
- assertThat(materialConfigs.get(0), is(instanceOf(DependencyMaterialConfig.class)));
- assertThat(materialConfigs.get(1), is(instanceOf(P4MaterialConfig.class)));
+ assertThat(materialConfigs.get(0)).isInstanceOf(DependencyMaterialConfig.class);
+ assertThat(materialConfigs.get(1)).isInstanceOf(P4MaterialConfig.class);
}
@Test
- public void shouldAddErrorForInvalidMaterialName() {
+ void shouldAddErrorForInvalidMaterialName() {
DependencyMaterialConfig materialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("wrong name"), new CaseInsensitiveString("pipeline-foo"), new CaseInsensitiveString("stage-bar"));
materialConfig.validate(ConfigSaveValidationContext.forChain(new BasicCruiseConfig(), pipelineConfig));
- assertThat(materialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME), is("Invalid material name 'wrong name'. This must be alphanumeric and can contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."));
+ assertThat(materialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME)).isEqualTo("Invalid material name 'wrong name'. This must be alphanumeric and can contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.");
}
@Test
- public void shouldAddErrorWhenInvalidPipelineNameStage() {
+ void shouldAddErrorWhenInvalidPipelineNameStage() {
DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig();
Map<String, String> configMap = new HashMap<>();
configMap.put(DependencyMaterialConfig.PIPELINE_STAGE_NAME, "invalid pipeline stage");
dependencyMaterialConfig.setConfigAttributes(configMap);
- assertThat(dependencyMaterialConfig.getPipelineStageName(), is("invalid pipeline stage"));
- assertThat(dependencyMaterialConfig.errors().isEmpty(), is(false));
- assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), is("'invalid pipeline stage' should conform to the pattern 'pipeline [stage]'"));
+ assertThat(dependencyMaterialConfig.getPipelineStageName()).isEqualTo("invalid pipeline stage");
+ assertThat(dependencyMaterialConfig.errors().isEmpty()).isFalse();
+ assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).isEqualTo("'invalid pipeline stage' should conform to the pattern 'pipeline [stage]'");
}
@Test
- public void shouldNotBombValidationWhenMaterialNameIsNotSet() {
+ void shouldNotBombValidationWhenMaterialNameIsNotSet() {
DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("pipeline-foo"), new CaseInsensitiveString("stage-bar"));
dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(new BasicCruiseConfig(), pipelineConfig));
- assertThat(dependencyMaterialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME), is(nullValue()));
+ assertThat(dependencyMaterialConfig.errors().on(AbstractMaterialConfig.MATERIAL_NAME)).isNull();
}
@Test
- public void shouldNOTBeValidIfThePipelineExistsButTheStageDoesNot() throws Exception {
+ void shouldNOTBeValidIfThePipelineExistsButTheStageDoesNot() throws Exception {
DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("pipeline2"), new CaseInsensitiveString("stage-not-existing does not exist!"));
dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(config, pipelineConfig));
ConfigErrors configErrors = dependencyMaterialConfig.errors();
- assertThat(configErrors.isEmpty(), is(false));
- assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), containsString("Stage with name 'stage-not-existing does not exist!' does not exist on pipeline 'pipeline2'"));
+ assertThat(configErrors.isEmpty()).isFalse();
+ assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).contains("Stage with name 'stage-not-existing does not exist!' does not exist on pipeline 'pipeline2'");
}
@Test
- public void shouldNOTBeValidIfTheReferencedPipelineDoesNotExist() throws Exception {
+ void shouldNOTBeValidIfTheReferencedPipelineDoesNotExist() throws Exception {
CruiseConfig config = GoConfigMother.configWithPipelines("pipeline1", "pipeline2", "pipeline3", "go");
DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("pipeline-not-exist"), new CaseInsensitiveString("stage"));
dependencyMaterialConfig.validate(ConfigSaveValidationContext.forChain(config, pipelineConfig));
ConfigErrors configErrors = dependencyMaterialConfig.errors();
- assertThat(configErrors.isEmpty(), is(false));
- assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), containsString("Pipeline with name 'pipeline-not-exist' does not exist"));
+ assertThat(configErrors.isEmpty()).isFalse();
+ assertThat(configErrors.on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).contains("Pipeline with name 'pipeline-not-exist' does not exist");
}
@Test
- public void setConfigAttributes_shouldPopulateFromConfigAttributes() {
+ void setConfigAttributes_shouldPopulateFromConfigAttributes() {
DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString(""), new CaseInsensitiveString(""));
- assertThat(dependencyMaterialConfig.getPipelineStageName(), is(nullValue()));
- assertThat(dependencyMaterialConfig.ignoreForScheduling(), is(false));
+ assertThat(dependencyMaterialConfig.getPipelineStageName()).isNull();
+ assertThat(dependencyMaterialConfig.ignoreForScheduling()).isFalse();
HashMap<String, String> configMap = new HashMap<>();
configMap.put(AbstractMaterialConfig.MATERIAL_NAME, "name1");
configMap.put(DependencyMaterialConfig.PIPELINE_STAGE_NAME, "pipeline-1 [stage-1]");
@@ -165,30 +165,64 @@ public class DependencyMaterialConfigTest {
dependencyMaterialConfig.setConfigAttributes(configMap);
- assertThat(dependencyMaterialConfig.getMaterialName(), is(new CaseInsensitiveString("name1")));
- assertThat(dependencyMaterialConfig.getPipelineName(), is(new CaseInsensitiveString("pipeline-1")));
- assertThat(dependencyMaterialConfig.getStageName(), is(new CaseInsensitiveString("stage-1")));
- assertThat(dependencyMaterialConfig.getPipelineStageName(), is("pipeline-1 [stage-1]"));
- assertThat(dependencyMaterialConfig.ignoreForScheduling(), is(true));
+ assertThat(dependencyMaterialConfig.getMaterialName()).isEqualTo(new CaseInsensitiveString("name1"));
+ assertThat(dependencyMaterialConfig.getPipelineName()).isEqualTo(new CaseInsensitiveString("pipeline-1"));
+ assertThat(dependencyMaterialConfig.getStageName()).isEqualTo(new CaseInsensitiveString("stage-1"));
+ assertThat(dependencyMaterialConfig.getPipelineStageName()).isEqualTo("pipeline-1 [stage-1]");
+ assertThat(dependencyMaterialConfig.ignoreForScheduling()).isTrue();
}
@Test
- public void setConfigAttributes_shouldNotPopulateNameFromConfigAttributesIfNameIsEmptyOrNull() {
+ void setConfigAttributes_shouldNotPopulateNameFromConfigAttributesIfNameIsEmptyOrNull() {
DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("name2"), new CaseInsensitiveString("pipeline"), new CaseInsensitiveString("stage"));
HashMap<String, String> configMap = new HashMap<>();
configMap.put(AbstractMaterialConfig.MATERIAL_NAME, "");
dependencyMaterialConfig.setConfigAttributes(configMap);
- assertThat(dependencyMaterialConfig.getMaterialName(), is(nullValue()));
+ assertThat(dependencyMaterialConfig.getMaterialName()).isNull();
}
@Test
- public void shouldValidateTree() {
+ void shouldValidateTree() {
DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("upstream_stage"), new CaseInsensitiveString("upstream_pipeline"), new CaseInsensitiveString("stage"));
PipelineConfig pipeline = new PipelineConfig(new CaseInsensitiveString("p"), new MaterialConfigs());
pipeline.setOrigin(new FileConfigOrigin());
dependencyMaterialConfig.validateTree(PipelineConfigSaveValidationContext.forChain(true, "group", config, pipeline));
- assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME), is("Pipeline with name 'upstream_pipeline' does not exist, it is defined as a dependency for pipeline 'p' (cruise-config.xml)"));
+ assertThat(dependencyMaterialConfig.errors().on(DependencyMaterialConfig.PIPELINE_STAGE_NAME)).isEqualTo("Pipeline with name 'upstream_pipeline' does not exist, it is defined as a dependency for pipeline 'p' (cruise-config.xml)");
+ }
+
+ @Nested
+ class getName {
+ @Test
+ void shouldBeSameAsConfiguredName() {
+ DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("material name"), new CaseInsensitiveString("#{upstream_pipeline}"), new CaseInsensitiveString("stage"));
+
+ assertThat(dependencyMaterialConfig.getName()).isEqualTo(new CaseInsensitiveString("material name"));
+ }
+
+ @Test
+ void shouldBeEmptyIfNotSet() {
+ DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("#{upstream_pipeline}"), new CaseInsensitiveString("stage"));
+
+ assertThat(dependencyMaterialConfig.getName()).isNull();
+ }
+ }
+
+ @Nested
+ class displayName {
+ @Test
+ void shouldBeSameSameAsNameIfConfigured() {
+ DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("material name"), new CaseInsensitiveString("#{upstream_pipeline}"), new CaseInsensitiveString("stage"));
+
+ assertThat(dependencyMaterialConfig.getDisplayName()).isEqualTo("material name");
+ }
+
+ @Test
+ void shouldBePipelineNameIfNameNotSet() {
+ DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("#{upstream_pipeline}"), new CaseInsensitiveString("stage"));
+
+ assertThat(dependencyMaterialConfig.getDisplayName()).isEqualTo("#{upstream_pipeline}");
+ }
}
} | ['config/config-server/src/test/java/com/thoughtworks/go/config/serialization/DependencyMaterialConfigTest.java', 'config/config-api/src/main/java/com/thoughtworks/go/config/materials/dependency/DependencyMaterialConfig.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,603,778 | 3,124,659 | 370,187 | 3,319 | 314 | 58 | 8 | 1 | 513 | 83 | 94 | 9 | 0 | 0 | 2020-02-14T00:37:36 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
396 | gocd/gocd/1869/1799 | gocd | gocd | https://github.com/gocd/gocd/issues/1799 | https://github.com/gocd/gocd/pull/1869 | https://github.com/gocd/gocd/pull/1869#issuecomment-194664589 | 2 | close | pipeline config API: cannot create pipeline with dependency on an upstream with a template | Pipeline "upstream" uses some template that has a stage called "run".
Using the pipeline config API, try to create a pipeline "downstream" with a material that points to the upstream pipeline.
```
"materials": [ some_git_repo, {"attributes": {"auto_update": true, "name": "upstream", "pipeline": "upstream", "stage": "run"}, "type": "dependency"}],
```
I get the following error:
```
Validations failed for pipeline 'downstream'.... errors: pipeline: "Stage with name 'run' does not exist on pipeline 'upstream'"
```
| 68e97393b25c016f55f58e9ba37d808c5577b429 | e075da259f523da22a32fe0f663c9ef516abc1aa | https://github.com/gocd/gocd/compare/68e97393b25c016f55f58e9ba37d808c5577b429...e075da259f523da22a32fe0f663c9ef516abc1aa | diff --git a/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java b/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java
index a9821da177..d3e1e95df0 100644
--- a/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java
+++ b/server/src/com/thoughtworks/go/server/service/PipelineConfigService.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2015 ThoughtWorks, Inc.
+ * Copyright 2016 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -184,7 +184,7 @@ public class PipelineConfigService implements PipelineConfigChangedListener, Ini
@Override
public void onConfigChange(CruiseConfig newCruiseConfig) {
- PipelineConfigurationCache.getInstance().onConfigChange(goConfigService.getConfigForEditing());
+ PipelineConfigurationCache.getInstance().onConfigChange(goConfigService.cruiseConfig());
if (goCache.get(GO_PIPELINE_CONFIGS_ETAGS_CACHE) != null) {
goCache.remove(GO_PIPELINE_CONFIGS_ETAGS_CACHE);
}
diff --git a/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java b/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java
index ad9f249ddd..6d5423aa56 100644
--- a/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java
+++ b/server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java
@@ -51,6 +51,7 @@ import java.util.Arrays;
import java.util.UUID;
import static com.thoughtworks.go.util.TestUtils.contains;
+import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertFalse;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
@@ -148,6 +149,49 @@ public class PipelineConfigServiceIntegrationTest {
assertThat(configRepository.getCurrentRevision().getUsername(), is(user.getDisplayName()));
}
+ @Test
+ public void shouldUpdatePipelineConfigWhenDependencyMaterialHasTemplateDefined() throws Exception {
+ CaseInsensitiveString templateName = new CaseInsensitiveString("template_with_param");
+ saveTemplateWithParamToConfig(templateName);
+
+ pipelineConfig.clear();
+ pipelineConfig.setTemplateName(templateName);
+ pipelineConfig.addParam(new ParamConfig("SOME_PARAM", "SOME_VALUE"));
+
+ CruiseConfig cruiseConfig = goConfigDao.loadConfigHolder().configForEdit;
+ cruiseConfig.update(groupName, pipelineConfig.name().toString(), pipelineConfig);
+ saveConfig(cruiseConfig);
+
+ PipelineConfig downstream = GoConfigMother.createPipelineConfigWithMaterialConfig("downstream", new DependencyMaterialConfig(pipelineConfig.name(), new CaseInsensitiveString("stage")));
+ pipelineConfigService.createPipelineConfig(user, downstream, result, groupName);
+
+ assertThat(result.toString(), result.isSuccessful(), is(true));
+ assertTrue(downstream.materialConfigs().first().errors().isEmpty());
+ }
+
+ @Test
+ public void shouldUpdatePipelineConfigWhenFetchTaskFromUpstreamHasPipelineWithTemplateDefined() throws Exception {
+ CaseInsensitiveString templateName = new CaseInsensitiveString("template_with_param");
+ saveTemplateWithParamToConfig(templateName);
+
+ pipelineConfig.clear();
+ pipelineConfig.setTemplateName(templateName);
+ pipelineConfig.addParam(new ParamConfig("SOME_PARAM", "SOME_VALUE"));
+
+ CaseInsensitiveString stage = new CaseInsensitiveString("stage");
+ CaseInsensitiveString job = new CaseInsensitiveString("job");
+ CruiseConfig cruiseConfig = goConfigDao.loadConfigHolder().configForEdit;
+ cruiseConfig.update(groupName, pipelineConfig.name().toString(), pipelineConfig);
+ saveConfig(cruiseConfig);
+
+ PipelineConfig downstream = GoConfigMother.createPipelineConfigWithMaterialConfig("downstream", new DependencyMaterialConfig(pipelineConfig.name(), stage));
+ downstream.getStage(stage).getJobs().first().addTask(new FetchTask(pipelineConfig.name(), stage, job, "src", "dest"));
+ pipelineConfigService.createPipelineConfig(user, downstream, result, groupName);
+
+ assertThat(result.toString(), result.isSuccessful(), is(true));
+ assertTrue(downstream.materialConfigs().first().errors().isEmpty());
+ }
+
@Test
public void shouldNotCreatePipelineConfigWhenAPipelineBySameNameAlreadyExists() throws GitAPIException {
GoConfigHolder goConfigHolderBeforeUpdate = goConfigDao.loadConfigHolder(); | ['server/src/com/thoughtworks/go/server/service/PipelineConfigService.java', 'server/test/integration/com/thoughtworks/go/server/service/PipelineConfigServiceIntegrationTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 7,502,322 | 1,499,524 | 198,300 | 1,822 | 278 | 52 | 4 | 1 | 524 | 71 | 132 | 14 | 0 | 2 | 2016-02-02T05:11:17 | 6,872 | Java | {'Java': 20634641, 'TypeScript': 4429797, 'Groovy': 2083065, 'JavaScript': 777429, 'SCSS': 597726, 'Ruby': 404083, 'HTML': 257482, 'XSLT': 206746, 'NSIS': 24216, 'Sass': 21277, 'Shell': 15583, 'FreeMarker': 13166, 'EJS': 1626, 'CSS': 1580, 'PowerShell': 664, 'Batchfile': 474} | Apache License 2.0 |
428 | real-logic/aeron/145/29 | real-logic | aeron | https://github.com/real-logic/aeron/issues/29 | https://github.com/real-logic/aeron/pull/145 | https://github.com/real-logic/aeron/pull/145 | 1 | fixes | ReceiverTest setUp() method throws exception | OS (uname -a): Linux 3.5.0-51-generic #77~precise1-Ubuntu SMP Thu Jun 5 00:48:28 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
Thanks for open sourcing this library. I hope to learn a lot about high performance messaging from it.
I noticed that the ReceiverTest tearDown() method was throwing NPEs when closing the receiveChannelEndpoint so I wrapped the creation of the ReceiveChannelEndpoint in the ReceiverTest's setUp() method with a try/catch that printed the exception and I got this:
Exception: java.lang.IllegalStateException: Failed to set SO_RCVBUF: attempted=131072, actual=131071
Looks like UdpChannelTransport's constructor is throwing the exception.
% sysctl net | grep 131071
net.core.rmem_max = 131071
net.core.wmem_max = 131071
Looks like there's a hard limit we're hitting up against.
Thanks!
| fb68c69719010f56b9698572bbeb2dac0b597f2e | 308142d22d1afb0efdefce2867b5097ba0b2dbc4 | https://github.com/real-logic/aeron/compare/fb68c69719010f56b9698572bbeb2dac0b597f2e...308142d22d1afb0efdefce2867b5097ba0b2dbc4 | diff --git a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java
index e3430f374..dfd794552 100644
--- a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java
+++ b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java
@@ -35,6 +35,11 @@ import uk.co.real_logic.agrona.concurrent.ringbuffer.RingBuffer;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
+
+import java.nio.channels.DatagramChannel;
+import java.net.StandardSocketOptions;
+import java.io.IOException;
+
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -103,6 +108,8 @@ public final class MediaDriver implements AutoCloseable
ensureDirectoriesAreRecreated();
+ warnOnInsufficentSocketBuffers();
+
ctx.unicastSenderFlowControl(Configuration::unicastFlowControlStrategy)
.multicastSenderFlowControl(Configuration::multicastFlowControlStrategy)
.conductorTimerWheel(Configuration.newConductorTimerWheel())
@@ -247,6 +254,38 @@ public final class MediaDriver implements AutoCloseable
return this;
}
+ private void warnOnInsufficentSocketBuffers()
+ {
+ try (DatagramChannel probe = DatagramChannel.open())
+ {
+
+ probe.setOption(StandardSocketOptions.SO_SNDBUF, Integer.MAX_VALUE);
+ final int maxSoSndbuf = probe.getOption(StandardSocketOptions.SO_SNDBUF);
+
+ if (maxSoSndbuf < Configuration.SOCKET_SNDBUF_LENGTH)
+ {
+ System.err.println(
+ String.format("WARNING: Could not get desired SO_SNDBUF: attempted=%d, actual=%d",
+ Configuration.SOCKET_SNDBUF_LENGTH, maxSoSndbuf));
+ }
+
+ probe.setOption(StandardSocketOptions.SO_RCVBUF, Integer.MAX_VALUE);
+ final int maxSoRcvbuf = probe.getOption(StandardSocketOptions.SO_RCVBUF);
+
+ if (maxSoRcvbuf < Configuration.SOCKET_RCVBUF_LENGTH)
+ {
+ System.err.println(
+ String.format("WARNING: Could not get desired SO_RCVBUF: attempted=%d, actual=%d",
+ Configuration.SOCKET_RCVBUF_LENGTH, maxSoRcvbuf));
+ }
+ }
+ catch (final IOException ex)
+ {
+ throw new RuntimeException(
+ String.format("probe socket: %s", ex.toString()), ex);
+ }
+ }
+
private void ensureDirectoriesAreRecreated()
{
final BiConsumer<String, String> callback =
diff --git a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java
index 045ae88a8..0b8d56182 100644
--- a/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java
+++ b/aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java
@@ -78,25 +78,11 @@ public abstract class UdpChannelTransport implements AutoCloseable
if (0 != Configuration.SOCKET_SNDBUF_LENGTH)
{
datagramChannel.setOption(StandardSocketOptions.SO_SNDBUF, Configuration.SOCKET_SNDBUF_LENGTH);
- final int soSndbuf = datagramChannel.getOption(StandardSocketOptions.SO_SNDBUF);
-
- if (soSndbuf != Configuration.SOCKET_SNDBUF_LENGTH)
- {
- throw new IllegalStateException(String.format(
- "Failed to set SO_SNDBUF: attempted=%d, actual=%d", Configuration.SOCKET_SNDBUF_LENGTH, soSndbuf));
- }
}
if (0 != Configuration.SOCKET_RCVBUF_LENGTH)
{
datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, Configuration.SOCKET_RCVBUF_LENGTH);
- final int soRcvbuf = datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF);
-
- if (soRcvbuf != Configuration.SOCKET_RCVBUF_LENGTH)
- {
- throw new IllegalStateException(String.format(
- "Failed to set SO_RCVBUF: attempted=%d, actual=%d", Configuration.SOCKET_RCVBUF_LENGTH, soRcvbuf));
- }
}
datagramChannel.configureBlocking(false); | ['aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/MediaDriver.java', 'aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/media/UdpChannelTransport.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,023,943 | 209,160 | 30,104 | 188 | 2,273 | 459 | 53 | 2 | 813 | 112 | 212 | 18 | 0 | 0 | 2015-06-09T15:40:10 | 6,607 | Java | {'Java': 7808647, 'C++': 2885942, 'C': 2193186, 'CMake': 83950, 'Shell': 66446, 'Batchfile': 43311, 'Dockerfile': 3239} | Apache License 2.0 |
258 | alluxio/alluxio/14635/14620 | alluxio | alluxio | https://github.com/Alluxio/alluxio/issues/14620 | https://github.com/Alluxio/alluxio/pull/14635 | https://github.com/Alluxio/alluxio/pull/14635 | 1 | solve | workerFuse stressbench write Input/output error | **Alluxio Version:**
Current master branch
**Describe the bug**
Fuse stress bench with workerFuse writing data errors out.
Not tuning MaxDirectMemorySize, all threads fail. Logs from `worker.out`:
```
io.netty.util.internal.OutOfDirectMemoryError: failed to allocate 16777216 byte(s) of direct memory (used: 4278190359, max: 4294967296)
at io.netty.util.internal.PlatformDependent.incrementMemoryCounter(PlatformDependent.java:754)
at io.netty.util.internal.PlatformDependent.allocateDirectNoCleaner(PlatformDependent.java:709)
at io.netty.buffer.PoolArena$DirectArena.allocateDirect(PoolArena.java:645)
at io.netty.buffer.PoolArena$DirectArena.newChunk(PoolArena.java:621)
at io.netty.buffer.PoolArena.allocateNormal(PoolArena.java:204)
at io.netty.buffer.PoolArena.tcacheAllocateNormal(PoolArena.java:188)
at io.netty.buffer.PoolArena.allocate(PoolArena.java:138)
at io.netty.buffer.PoolArena.allocate(PoolArena.java:128)
at io.netty.buffer.PooledByteBufAllocator.newDirectBuffer(PooledByteBufAllocator.java:378)
at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:187)
at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:178)
at io.netty.buffer.AbstractByteBufAllocator.buffer(AbstractByteBufAllocator.java:115)
at alluxio.client.block.stream.BlockOutStream.allocateBuffer(BlockOutStream.java:294)
at alluxio.client.block.stream.BlockOutStream.updateCurrentChunk(BlockOutStream.java:252)
at alluxio.client.block.stream.BlockOutStream.write(BlockOutStream.java:141)
at alluxio.client.file.AlluxioFileOutStream.writeInternal(AlluxioFileOutStream.java:271)
at alluxio.client.file.AlluxioFileOutStream.write(AlluxioFileOutStream.java:229)
at alluxio.fuse.AlluxioJniFuseFileSystem.writeInternal(AlluxioJniFuseFileSystem.java:438)
at alluxio.fuse.AlluxioJniFuseFileSystem.lambda$write$6(AlluxioJniFuseFileSystem.java:413)
at alluxio.fuse.AlluxioFuseUtils.call(AlluxioFuseUtils.java:278)
at alluxio.fuse.AlluxioJniFuseFileSystem.write(AlluxioJniFuseFileSystem.java:413)
at alluxio.jnifuse.AbstractFuseFileSystem.writeCallback(AbstractFuseFileSystem.java:316)
```
With following java options in `alluxio-env.sh`: `ALLUXIO_WORKER_JAVA_OPTS+=" -Xmx24G -Xms24G -XX:MaxDirectMemorySize=18g" `, only some threads report failure, and no logs in `worker.out`.
**To Reproduce**
Using ec2 instance r5.2xlarge which has 64GB memory.
Using the following properties in `alluxio-site.properties`:
```
alluxio.master.hostname=localhost
alluxio.master.mount.table.root.ufs=s3://xxxxx
aws.accessKeyId=xxxxxxxxx
aws.secretKey=xxxxxxxxxxxxxxx
alluxio.worker.ramdisk.size=15GB
alluxio.worker.fuse.enabled=true
alluxio.worker.fuse.mount.alluxio.path=/fuseTest
alluxio.worker.fuse.mount.point=/home/centos/fuseTest
# User properties
alluxio.user.file.writetype.default=MUST_CACHE
alluxio.user.block.size.bytes.default=200k
alluxio.client.cache.async.write.enabled=false
alluxio.user.file.passive.cache.enabled=false
```
Run Fuse stress bench with:
```
bin/alluxio runClass alluxio.stress.cli.fuse.FuseIOBench --local-path /home/centos/fuseTest --operation Write --threads 32 --num-dirs 100 --num-files-per-dir 1000 --file-size 100k
```
**Additional information**
Standalone Fuse has no such issue. | 4325774f94b2acb2019adeaf3d53713529209e5d | eecfcd4358dfa2cac0ae6b0275d8e7eb09f85c90 | https://github.com/alluxio/alluxio/compare/4325774f94b2acb2019adeaf3d53713529209e5d...eecfcd4358dfa2cac0ae6b0275d8e7eb09f85c90 | diff --git a/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java b/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java
index 0076f9b427..ffe84c9b91 100644
--- a/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java
+++ b/core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java
@@ -92,18 +92,23 @@ public final class BlockWorkerDataWriter implements DataWriter {
@Override
public void writeChunk(final ByteBuf buf) throws IOException {
- if (mReservedBytes < pos() + buf.readableBytes()) {
- try {
- long bytesToReserve = Math.max(mBufferSize, pos() + buf.readableBytes() - mReservedBytes);
- // Allocate enough space in the existing temporary block for the write.
- mBlockWorker.requestSpace(mSessionId, mBlockId, bytesToReserve);
- } catch (Exception e) {
- throw new IOException(e);
+ try {
+ if (mReservedBytes < pos() + buf.readableBytes()) {
+ try {
+ long bytesToReserve = Math.max(mBufferSize, pos() + buf.readableBytes()
+ - mReservedBytes);
+ // Allocate enough space in the existing temporary block for the write.
+ mBlockWorker.requestSpace(mSessionId, mBlockId, bytesToReserve);
+ } catch (Exception e) {
+ throw new IOException(e);
+ }
}
+ long append = mBlockWriter.append(buf);
+ MetricsSystem.counter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT.getName()).inc(append);
+ MetricsSystem.meter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT_THROUGHPUT.getName()).mark(append);
+ } finally {
+ buf.release();
}
- long append = mBlockWriter.append(buf);
- MetricsSystem.counter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT.getName()).inc(append);
- MetricsSystem.meter(MetricKey.WORKER_BYTES_WRITTEN_DIRECT_THROUGHPUT.getName()).mark(append);
}
@Override | ['core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataWriter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,523,936 | 2,143,288 | 272,269 | 1,621 | 1,346 | 309 | 25 | 1 | 3,483 | 169 | 871 | 60 | 0 | 3 | 2021-12-07T20:49:25 | 6,326 | Java | {'Java': 15817407, 'TypeScript': 340217, 'Shell': 175186, 'Go': 79288, 'C++': 47930, 'Mustache': 15785, 'Ruby': 15044, 'SCSS': 12027, 'JavaScript': 9992, 'C': 7326, 'Roff': 5919, 'Python': 4554, 'Dockerfile': 3642, 'Handlebars': 3633, 'HTML': 3412, 'Makefile': 2362} | Apache License 2.0 |
1,432 | micronaut-projects/micronaut-core/1273/1272 | micronaut-projects | micronaut-core | https://github.com/micronaut-projects/micronaut-core/issues/1272 | https://github.com/micronaut-projects/micronaut-core/pull/1273 | https://github.com/micronaut-projects/micronaut-core/pull/1273 | 1 | fixes | Regression on bean with preDestroy | My project has a factory that replaces the `DefaultMongoClientFactory`:
```kotlin
@Requirements(Requires(beans = [DefaultMongoConfiguration::class]), Requires(classes = [MongoClient::class]))
@Replaces(factory = DefaultMongoClientFactory::class)
@Factory
class KMongoClientFactory {
companion object: KLogging()
@Bean(preDestroy = "close")
@Singleton
fun kmongoClient(configuration: DefaultMongoConfiguration): MongoClient {
logger.debug { "===== KMongo creating client for ${configuration.uri}" }
val client = KMongo.createClient(MongoClientURI(configuration.uri))
return client
}
}
```
This was working last week, but I am now seeing this error:
```
$ ./gradlew test
$ ./gradlew test
e: /Users/mmindenhall/projects/micronaut-examples/hello-world-kotlin/build/tmp/kapt3/stubs/main/example/KMongoClientFactory.java:19: error: @Bean method defines a preDestroy method that does not exist or is not public: close
public final com.mongodb.MongoClient kmongoClient(@org.jetbrains.annotations.NotNull()
^
```
It seems likely that this was caused by the recent fix for #1267.
### Task List
- [x] Steps to reproduce provided
- [x] Stacktrace (if present) provided
- [x] Example that reproduces the problem uploaded to Github
- [x] Full description of the issue provided (see below)
### Steps to Reproduce
1. Clone [my fork of micronaut-examples](https://github.com/mmindenhall/micronaut-examples)
1. `cd micronaut-examples`
1. `git checkout pre-destroy-regression`
1. `cd hello-world-kotlin`
1. `./gradlew test`
Note that if this is executed against micronaut 1.1.0.M1 instead of 1.1.0.BUILD-SNAPSHOT, the tests all pass:
1. Edit `gradle.properties`
1. Change micronaut version (comment out line 2, uncomment line 3), save changes
1. `./gradlew test`
### Expected Behaviour
Everything passes.
### Actual Behaviour
The factory returns an instance of `MongoClient`, which implements the `Closeable` interface (and therefore the public `close` method). Micronaut is erroneously reporting the error above.
### Environment Information
- **Operating System**: macOS 10.14.3
- **Micronaut Version:** 1.1.0.BUILD-SNAPSHOT
- **JDK Version:** 1.8.0_191
### Example Application
See steps to reproduce above.
| bb11cd1e6e5b1d1360f9c0f941df8bcbf57363a7 | 6985a5886137dbd18d8be09a0cc12dbd386b200a | https://github.com/micronaut-projects/micronaut-core/compare/bb11cd1e6e5b1d1360f9c0f941df8bcbf57363a7...6985a5886137dbd18d8be09a0cc12dbd386b200a | diff --git a/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java b/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java
index 0929252063..4696741dd0 100644
--- a/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java
+++ b/inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java
@@ -202,7 +202,7 @@ public class ModelUtils {
* @return The executable element
*/
Optional<ExecutableElement> findAccessibleNoArgumentInstanceMethod(TypeElement classElement, String methodName) {
- return ElementFilter.methodsIn(classElement.getEnclosedElements())
+ return ElementFilter.methodsIn(elementUtils.getAllMembers(classElement))
.stream().filter(m -> m.getSimpleName().toString().equals(methodName) && !isPrivate(m) && !isStatic(m))
.findFirst();
} | ['inject-java/src/main/java/io/micronaut/annotation/processing/ModelUtils.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 6,970,541 | 1,407,026 | 198,293 | 1,950 | 157 | 26 | 2 | 1 | 2,372 | 259 | 569 | 72 | 1 | 2 | 2019-02-20T06:11:39 | 5,790 | Java | {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14} | Apache License 2.0 |
1,426 | micronaut-projects/micronaut-core/2153/2152 | micronaut-projects | micronaut-core | https://github.com/micronaut-projects/micronaut-core/issues/2152 | https://github.com/micronaut-projects/micronaut-core/pull/2153 | https://github.com/micronaut-projects/micronaut-core/pull/2153 | 1 | fixes | HTTP client pool caches dns lookup forever | When the DefaultHttpClient creates it's poolMap instance a DNS lookup is made and stored in the bootstrap instance:
` Bootstrap newBootstrap = bootstrap.clone(group);
newBootstrap.remoteAddress(key.getRemoteAddress());
`
The remoteAddress is never updated, which means that if the ip is recycled (very common for AWS hosted services), the pool will continue to try to create connections to the original ip.
### Task List
- [x] Steps to reproduce provided
- [x] Stacktrace (if present) provided
- [x] Example that reproduces the problem uploaded to Github
- [x] Full description of the issue provided (see below)
### Steps to Reproduce
https://github.com/luckyswede/micronaut-dnstest
### Expected Behaviour
When new connections are created a new DNS lookup should take place
### Actual Behaviour
The original DNS lookup result is reused
### Environment Information
- **Operating System**: All
- **Micronaut Version:** 1.2.2
- **JDK Version:** 11
### Example Application
https://github.com/luckyswede/micronaut-dnstest
| 11e6988348ea8ae0c740d74e91b28c4f13937472 | 601d4e69dfd188ac8ae8ca376bee3407c858cb05 | https://github.com/micronaut-projects/micronaut-core/compare/11e6988348ea8ae0c740d74e91b28c4f13937472...601d4e69dfd188ac8ae8ca376bee3407c858cb05 | diff --git a/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java b/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java
index f46d23daad..760d142124 100644
--- a/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java
+++ b/http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java
@@ -260,7 +260,6 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr
Bootstrap newBootstrap = bootstrap.clone(group);
newBootstrap.remoteAddress(key.getRemoteAddress());
-
AbstractChannelPoolHandler channelPoolHandler = newPoolHandler(key);
final Long acquireTimeoutMillis = connectionPoolConfiguration.getAcquireTimeout().map(Duration::toMillis).orElse(-1L);
return new FixedChannelPool(
@@ -281,6 +280,7 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr
protected ChannelPool newPool(RequestKey key) {
Bootstrap newBootstrap = bootstrap.clone(group);
newBootstrap.remoteAddress(key.getRemoteAddress());
+
AbstractChannelPoolHandler channelPoolHandler = newPoolHandler(key);
return new SimpleChannelPool(
newBootstrap,
@@ -2303,7 +2303,7 @@ public class DefaultHttpClient implements RxWebSocketClient, RxHttpClient, RxStr
}
public InetSocketAddress getRemoteAddress() {
- return new InetSocketAddress(host, port);
+ return InetSocketAddress.createUnresolved(host, port);
}
public boolean isSecure() { | ['http-client/src/main/java/io/micronaut/http/client/DefaultHttpClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 7,131,028 | 1,428,690 | 200,862 | 1,797 | 126 | 21 | 4 | 1 | 1,100 | 141 | 240 | 30 | 2 | 0 | 2019-09-25T16:28:27 | 5,790 | Java | {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14} | Apache License 2.0 |
1,421 | micronaut-projects/micronaut-core/9427/9423 | micronaut-projects | micronaut-core | https://github.com/micronaut-projects/micronaut-core/issues/9423 | https://github.com/micronaut-projects/micronaut-core/pull/9427 | https://github.com/micronaut-projects/micronaut-core/pull/9427 | 1 | fixes | New allowed-origins-regex property not working..? | ### Expected Behavior
With 3.9.0 allowed-origins no longer supports a regex value for the cors configuration. Instead you now need to use a new property called allowed-origins-regex.
When replacing allowed-origins with allowed-origins-regex using the same regular expression and previously, it's expected that calls from an Origin matching the pattern are allowed through.
### Actual Behaviour
Calls with a matching Origin header are no longer accepted and a 403 forbidden is returned.
### Steps To Reproduce
Start a 3.8.9 micronaut server with a configuration set to
```
micronaut:
application:
name: testApp
server:
cors:
enabled: true
configurations:
web:
allowed-origins:
- ^http(|s):\\/\\/(\\w*\\.)*integration\\.mydomain\\.com$
```
Make a call to an endpoint on that server specifying an Origin value in the header of "https://www.integration.mydomain.com"
You should receive a 200 okay.
Now change the configuration to the below and the version of Micronaut to 3.9.x
```
micronaut:
application:
name: testApp
server:
cors:
enabled: true
configurations:
web:
allowed-origins-regex: ^http(|s):\\/\\/(\\w*\\.)*integration\\.mydomain\\.com$
```
Make the same call to an endpoint and you should receive a 403 Forbidden. (Expected that you receive a 200)
### Environment Information
macOS
JDK 17
Micronaut 3.8.9 and 3.9.2
### Example Application
_No response_
### Version
3.9.2 | 2c1bee6be0af723c66e8ce790590f4f7d22a84d3 | 5d60708289271499c5435b7558880f01b6941656 | https://github.com/micronaut-projects/micronaut-core/compare/2c1bee6be0af723c66e8ce790590f4f7d22a84d3...5d60708289271499c5435b7558880f01b6941656 | diff --git a/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java b/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java
index 6dc7342aad..33278f69cc 100644
--- a/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java
+++ b/http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2017-2022 original authors
+ * Copyright 2017-2023 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -184,22 +184,42 @@ public class CorsSimpleRequestTest {
"micronaut.server.cors.configurations.foo.allowed-origins", Collections.singletonList("https://foo.com")
),
createRequest("https://foo.com"),
- (server, request) -> {
+ CorsSimpleRequestTest::isSuccessfulCorsAssertion
+ );
+ }
- RefreshCounter refreshCounter = server.getApplicationContext().getBean(RefreshCounter.class);
- assertEquals(0, refreshCounter.getRefreshCount());
+ /**
+ * CORS Simple request for localhost can be allowed via configuration of a regex.
+ * @throws IOException may throw the try for resources
+ */
+ @Test
+ // "https://github.com/micronaut-projects/micronaut-core/issues/9423")
+ void corsSimpleRequestForLocalhostCanBeAllowedViaRegexConfiguration() throws IOException {
+ asserts(SPECNAME,
+ CollectionUtils.mapOf(
+ PROPERTY_MICRONAUT_SERVER_CORS_ENABLED, StringUtils.TRUE,
+ "micronaut.server.cors.configurations.foo.allowed-origins-regex", Collections.singletonList("^http(|s):\\\\/\\\\/foo\\\\.com$")
+ ),
+ createRequest("https://foo.com"),
+ CorsSimpleRequestTest::isSuccessfulCorsAssertion
+ );
+ }
- AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
- .status(HttpStatus.OK)
- .assertResponse(response -> CorsAssertion.builder()
- .vary("Origin")
- .allowCredentials()
- .allowOrigin("https://foo.com")
- .build()
- .validate(response))
- .build());
- assertEquals(1, refreshCounter.getRefreshCount());
- });
+ /**
+ * CORS Simple request for localhost can be forbidden via configuration of a regex.
+ * @throws IOException may throw the try for resources
+ */
+ @Test
+ // "https://github.com/micronaut-projects/micronaut-core/issues/9423")
+ void corsSimpleRequestForLocalhostForbiddenViaRegexConfiguration() throws IOException {
+ asserts(SPECNAME,
+ CollectionUtils.mapOf(
+ PROPERTY_MICRONAUT_SERVER_CORS_ENABLED, StringUtils.TRUE,
+ "micronaut.server.cors.configurations.foo.allowed-origins-regex", Collections.singletonList("^http(|s):\\\\/\\\\/foo\\\\.com$")
+ ),
+ createRequest("https://bar.com"),
+ CorsSimpleRequestTest::isForbidden
+ );
}
private RequestSupplier createRequestFor(String host, String origin) {
@@ -225,6 +245,21 @@ public class CorsSimpleRequestTest {
assertEquals(1, refreshCounter.getRefreshCount());
}
+ static void isSuccessfulCorsAssertion(ServerUnderTest server, HttpRequest<?> request) {
+ RefreshCounter refreshCounter = server.getApplicationContext().getBean(RefreshCounter.class);
+ assertEquals(0, refreshCounter.getRefreshCount());
+ AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
+ .status(HttpStatus.OK)
+ .assertResponse(response -> CorsAssertion.builder()
+ .vary("Origin")
+ .allowCredentials()
+ .allowOrigin("https://foo.com")
+ .build()
+ .validate(response))
+ .build());
+ assertEquals(1, refreshCounter.getRefreshCount());
+ }
+
static HttpRequest<?> createRequest(String origin) {
return createRequest("/refresh", origin);
}
diff --git a/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java b/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java
index 7bf75191a3..52601235db 100644
--- a/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java
+++ b/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2017-2020 original authors
+ * Copyright 2017-2023 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,6 +62,7 @@ import static io.micronaut.http.annotation.Filter.MATCH_ALL_PATTERN;
*/
@Filter(MATCH_ALL_PATTERN)
public class CorsFilter implements HttpServerFilter {
+
private static final Logger LOG = LoggerFactory.getLogger(CorsFilter.class);
private static final ArgumentConversionContext<HttpMethod> CONVERSION_CONTEXT_HTTP_METHOD = ImmutableArgumentConversionContext.of(HttpMethod.class);
@@ -140,7 +141,7 @@ public class CorsFilter implements HttpServerFilter {
return false;
}
String host = httpHostResolver.resolve(request);
- return isAny(corsOriginConfiguration.getAllowedOrigins()) && isHostLocal(host);
+ return isAnyOrigin(corsOriginConfiguration.getAllowedOriginsRegex().isPresent(), corsOriginConfiguration.getAllowedOrigins()) && isHostLocal(host);
}
/**
@@ -351,6 +352,11 @@ public class CorsFilter implements HttpServerFilter {
return m.matches();
}
+ private static boolean isAnyOrigin(boolean isAllowedOriginsRegexConfigured, List<String> values) {
+ // True if a regular expression has not been set for origin, and the allowed hosts are still ANY
+ return !isAllowedOriginsRegexConfigured && isAny(values);
+ }
+
private static boolean isAny(List<String> values) {
return values == CorsOriginConfiguration.ANY;
} | ['http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/cors/CorsSimpleRequestTest.java', 'http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,143,135 | 1,805,359 | 250,070 | 1,907 | 615 | 132 | 10 | 1 | 1,611 | 190 | 369 | 59 | 1 | 2 | 2023-06-09T16:22:58 | 5,790 | Java | {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14} | Apache License 2.0 |
1,434 | micronaut-projects/micronaut-core/623/618 | micronaut-projects | micronaut-core | https://github.com/micronaut-projects/micronaut-core/issues/618 | https://github.com/micronaut-projects/micronaut-core/pull/623 | https://github.com/micronaut-projects/micronaut-core/pull/623 | 1 | fixes | Inconsistent @Body handling in browser | Body is occasionally lost when uploaded from browser
### Steps to Reproduce
See sample
### Expected Behaviour
Body handling should work
### Actual Behaviour
Occasional:
```
i.m.h.s.netty.RoutingInBoundHandler - Encoding emitted response object [ /command - Required argument [LoginCommand command] not specified] using codec: io.micronaut.jackson.codec.JsonMediaTypeCodec@3ee39da0
```
### Example Application
https://github.com/liwujun0513/micronaut_demo
| 2c286aba5a06c3b684ba3475d39ca6be48ed2d2f | 454e9d34b5d7968931b92b59600029da5fac911f | https://github.com/micronaut-projects/micronaut-core/compare/2c286aba5a06c3b684ba3475d39ca6be48ed2d2f...454e9d34b5d7968931b92b59600029da5fac911f | diff --git a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java
index cffc0be9cf..6c91f26c8e 100644
--- a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java
+++ b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java
@@ -173,7 +173,7 @@ abstract class HttpStreamsHandler<In extends HttpMessage, Out extends HttpMessag
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
- if (inClass.isInstance(msg)) {
+ if (isValidInMessage(msg)) {
receivedInMessage(ctx);
final In inMsg = inClass.cast(msg);
@@ -279,7 +279,7 @@ abstract class HttpStreamsHandler<In extends HttpMessage, Out extends HttpMessag
@Override
public void write(final ChannelHandlerContext ctx, Object msg, final ChannelPromise promise) throws Exception {
- if (outClass.isInstance(msg)) {
+ if (isValidOutMessage(msg)) {
Outgoing out = new Outgoing(outClass.cast(msg), promise);
receivedOutMessage(ctx);
@@ -404,6 +404,22 @@ abstract class HttpStreamsHandler<In extends HttpMessage, Out extends HttpMessag
}
}
+ /**
+ * @param msg The message
+ * @return True if the handler should write the message
+ */
+ protected boolean isValidOutMessage(Object msg) {
+ return outClass.isInstance(msg);
+ }
+
+ /**
+ * @param msg The message
+ * @return True if the handler should read the message
+ */
+ protected boolean isValidInMessage(Object msg) {
+ return inClass.isInstance(msg);
+ }
+
/**
* The outgoing class.
*/
@@ -420,4 +436,5 @@ abstract class HttpStreamsHandler<In extends HttpMessage, Out extends HttpMessag
this.promise = promise;
}
}
+
}
diff --git a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java
index 69b1e028a0..6b464abd05 100644
--- a/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java
+++ b/http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java
@@ -22,15 +22,7 @@ import io.micronaut.http.netty.reactive.HandlerSubscriber;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
-import io.netty.handler.codec.http.DefaultFullHttpResponse;
-import io.netty.handler.codec.http.FullHttpRequest;
-import io.netty.handler.codec.http.HttpContent;
-import io.netty.handler.codec.http.HttpHeaderNames;
-import io.netty.handler.codec.http.HttpRequest;
-import io.netty.handler.codec.http.HttpResponse;
-import io.netty.handler.codec.http.HttpResponseStatus;
-import io.netty.handler.codec.http.HttpUtil;
-import io.netty.handler.codec.http.HttpVersion;
+import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
@@ -185,6 +177,11 @@ public class HttpStreamsServerHandler extends HttpStreamsHandler<HttpRequest, Ht
}
}
+ @Override
+ protected boolean isValidOutMessage(Object msg) {
+ return msg instanceof FullHttpResponse || msg instanceof StreamedHttpResponse || msg instanceof WebSocketHttpResponse;
+ }
+
private boolean canHaveBody(HttpResponse message) {
HttpResponseStatus status = message.status();
// All 1xx (Informational), 204 (No Content), and 304 (Not Modified)
diff --git a/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java b/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java
index 31319e04c2..884125f275 100644
--- a/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java
+++ b/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java
@@ -69,6 +69,7 @@ import io.netty.handler.codec.http.multipart.DiskFileUpload;
import io.netty.handler.flow.FlowControlHandler;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
+import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GlobalEventExecutor;
@@ -104,6 +105,7 @@ import java.util.function.BiConsumer;
@Singleton
public class NettyHttpServer implements EmbeddedServer, WebSocketSessionRepository {
public static final String HTTP_STREAMS_CODEC = "http-streams-codec";
+ public static final String HTTP_CHUNKED_HANDLER = "http-chunked-handler";
@SuppressWarnings("WeakerAccess")
public static final String HTTP_CODEC = "http-codec";
@SuppressWarnings("WeakerAccess")
@@ -260,6 +262,7 @@ public class NettyHttpServer implements EmbeddedServer, WebSocketSessionReposito
pipeline.addLast(HTTP_KEEP_ALIVE_HANDLER, new HttpServerKeepAliveHandler());
pipeline.addLast(HTTP_COMPRESSOR, new SmartHttpContentCompressor());
pipeline.addLast(HTTP_STREAMS_CODEC, new HttpStreamsServerHandler());
+ pipeline.addLast(HTTP_CHUNKED_HANDLER, new ChunkedWriteHandler());
pipeline.addLast(HttpRequestDecoder.ID, new HttpRequestDecoder(
NettyHttpServer.this,
environment,
diff --git a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java
index de30bb8f82..ffadc22f02 100644
--- a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java
+++ b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java
@@ -19,7 +19,6 @@ package io.micronaut.http.server.netty.types.files;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.netty.NettyMutableHttpResponse;
-import io.micronaut.http.server.netty.NettyHttpServer;
import io.micronaut.http.server.netty.types.NettyFileCustomizableResponseType;
import io.micronaut.http.server.types.files.StreamedFile;
import io.netty.channel.ChannelHandlerContext;
@@ -27,11 +26,9 @@ import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpChunkedInput;
import io.netty.handler.stream.ChunkedStream;
-import io.netty.handler.stream.ChunkedWriteHandler;
import java.io.InputStream;
import java.net.URL;
-import java.util.Optional;
/**
* Writes an {@link InputStream} to the Netty context.
@@ -76,11 +73,6 @@ public class NettyStreamedFileCustomizableResponseType extends StreamedFile impl
if (response instanceof NettyMutableHttpResponse) {
FullHttpResponse nettyResponse = ((NettyMutableHttpResponse) response).getNativeResponse();
- //The streams codec prevents non full responses from being written
- Optional
- .ofNullable(context.pipeline().get(NettyHttpServer.HTTP_STREAMS_CODEC))
- .ifPresent(handler -> context.pipeline().replace(handler, "chunked-handler", new ChunkedWriteHandler()));
-
// Write the request data
context.write(new DefaultHttpResponse(nettyResponse.protocolVersion(), nettyResponse.status(), nettyResponse.headers()), context.voidPromise());
context.writeAndFlush(new HttpChunkedInput(new ChunkedStream(getInputStream())));
diff --git a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java
index b120b6e0f4..7c3bd17646 100644
--- a/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java
+++ b/http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java
@@ -19,7 +19,6 @@ package io.micronaut.http.server.netty.types.files;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.netty.NettyMutableHttpResponse;
-import io.micronaut.http.server.netty.NettyHttpServer;
import io.micronaut.http.server.netty.SmartHttpContentCompressor;
import io.micronaut.http.server.netty.types.NettyFileCustomizableResponseType;
import io.micronaut.http.server.types.CustomizableResponseTypeException;
@@ -29,12 +28,10 @@ import io.netty.channel.DefaultFileRegion;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpChunkedInput;
-import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedFile;
-import io.netty.handler.stream.ChunkedWriteHandler;
import java.io.File;
import java.io.FileNotFoundException;
@@ -112,11 +109,6 @@ public class NettySystemFileCustomizableResponseType extends SystemFileCustomiza
FullHttpResponse nettyResponse = ((NettyMutableHttpResponse) response).getNativeResponse();
- //The streams codec prevents non full responses from being written
- Optional
- .ofNullable(context.pipeline().get(NettyHttpServer.HTTP_STREAMS_CODEC))
- .ifPresent(handler -> context.pipeline().replace(handler, "chunked-handler", new ChunkedWriteHandler()));
-
// Write the request data
HttpHeaders headers = nettyResponse.headers();
context.write(new DefaultHttpResponse(nettyResponse.protocolVersion(), nettyResponse.status(), headers), context.voidPromise());
@@ -124,12 +116,6 @@ public class NettySystemFileCustomizableResponseType extends SystemFileCustomiza
// Write the content.
if (context.pipeline().get(SslHandler.class) == null && SmartHttpContentCompressor.shouldSkip(headers)) {
// SSL not enabled - can use zero-copy file transfer.
- // Remove the content compressor to prevent incorrect behavior with zero-copy
- HttpContentCompressor compressor = context.pipeline().get(HttpContentCompressor.class);
- if (compressor != null) {
- context.pipeline().remove(HttpContentCompressor.class);
- }
-
context.write(new DefaultFileRegion(raf.getChannel(), 0, getLength()), context.newProgressivePromise());
context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
} else { | ['http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpServer.java', 'http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettySystemFileCustomizableResponseType.java', 'http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsHandler.java', 'http-server-netty/src/main/java/io/micronaut/http/server/netty/types/files/NettyStreamedFileCustomizableResponseType.java', 'http-netty/src/main/java/io/micronaut/http/netty/stream/HttpStreamsServerHandler.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 6,796,725 | 1,368,789 | 195,312 | 2,007 | 2,798 | 532 | 61 | 5 | 487 | 49 | 108 | 23 | 1 | 1 | 2018-09-25T19:46:59 | 5,790 | Java | {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14} | Apache License 2.0 |
1,423 | micronaut-projects/micronaut-core/2984/2934 | micronaut-projects | micronaut-core | https://github.com/micronaut-projects/micronaut-core/issues/2934 | https://github.com/micronaut-projects/micronaut-core/pull/2984 | https://github.com/micronaut-projects/micronaut-core/pull/2984 | 1 | fixes | AmazonComputeInstanceMetadataResolver has an invalid path | While connecting the application to a consul running in a different ec2 instance (same VPC) the following error occurs in the logs
`[35mi.m.d.c.a.AmazonComputeInstanceMetadataResolver[0;39m - error getting public host name from:http://169.254.169.254//latest/meta-data/publicHostname
java.io.FileNotFoundException: http://169.254.169.254//latest/meta-data/public-hostname`
double // is included in path.
| bd51d3353b629abddfbc3ad9f909c135ab47c150 | 4876cc6f12e22b0e99acd59105550a8d546db82a | https://github.com/micronaut-projects/micronaut-core/compare/bd51d3353b629abddfbc3ad9f909c135ab47c150...4876cc6f12e22b0e99acd59105550a8d546db82a | diff --git a/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java b/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java
index 8fb8db8f8d..779a3499e3 100644
--- a/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java
+++ b/runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java
@@ -46,7 +46,7 @@ public class AmazonMetadataConfiguration implements Toggleable {
* The default url value.
*/
@SuppressWarnings("WeakerAccess")
- public static final String DEFAULT_URL = "http://169.254.169.254/";
+ public static final String DEFAULT_URL = "http://169.254.169.254";
private String url = DEFAULT_URL;
private String metadataUrl; | ['runtime/src/main/java/io/micronaut/discovery/cloud/aws/AmazonMetadataConfiguration.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 7,542,554 | 1,507,719 | 211,614 | 1,858 | 144 | 38 | 2 | 1 | 414 | 38 | 99 | 7 | 2 | 0 | 2020-03-27T16:12:03 | 5,790 | Java | {'Java': 11816931, 'Groovy': 6321305, 'Kotlin': 1605995, 'HTML': 143, 'Shell': 14} | Apache License 2.0 |
386 | raphw/byte-buddy/528/527 | raphw | byte-buddy | https://github.com/raphw/byte-buddy/issues/527 | https://github.com/raphw/byte-buddy/pull/528 | https://github.com/raphw/byte-buddy/pull/528 | 1 | fixes | Using MethodCall onField with field locator pointing to different class fails | ```java
DynamicType.Loaded<Object> loaded = new ByteBuddy()
.subclass(Object.class)
.invokable(isTypeInitializer())
.intercept(MethodCall.invoke(named("println").and(takesArguments(Object.class)))
.onField("out", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with(""))
.make()
.load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
loaded.getLoaded().getDeclaredConstructor().newInstance();
```
The code above fails with the error below:
```
java.lang.VerifyError: Local variable table overflow
Exception Details:
Location:
net/bytebuddy/renamed/java/lang/Object$ByteBuddy$XtBtrrHJ.<clinit>()V @0: aload_0
Reason:
Local index 0 is invalid
Bytecode:
0x0000000: 2ab2 000f 1211 b600 17b1
```
Relevant bytecode:
```
static <clinit>()V
ALOAD 0
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
LDC ""
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
RETURN
MAXSTACK = 3
MAXLOCALS = 0
}
```
| 0f9f5d84a878b3f04cd52475c48215dbd53e5053 | 7abdaf36e9ba49e5aae30e421344d30728e68cf8 | https://github.com/raphw/byte-buddy/compare/0f9f5d84a878b3f04cd52475c48215dbd53e5053...7abdaf36e9ba49e5aae30e421344d30728e68cf8 | diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java
index 9b06dc57a6..6c241dc565 100644
--- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java
+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java
@@ -1770,9 +1770,10 @@ public class MethodCall implements Implementation.Composable {
if (!stackManipulation.isValid()) {
throw new IllegalStateException("Cannot invoke " + invokedMethod + " on " + resolution.getField());
}
- return new StackManipulation.Compound(invokedMethod.isStatic()
+ return new StackManipulation.Compound(invokedMethod.isStatic() || resolution.getField().isStatic()
? StackManipulation.Trivial.INSTANCE
- : MethodVariableAccess.loadThis(), FieldAccess.forField(resolution.getField()).read(), stackManipulation);
+ : MethodVariableAccess.loadThis(),
+ FieldAccess.forField(resolution.getField()).read(), stackManipulation);
}
@Override
diff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java
index a92ee06c90..eec5b5a728 100644
--- a/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java
+++ b/byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java
@@ -7,6 +7,7 @@ import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
+import net.bytebuddy.dynamic.scaffold.FieldLocator;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.constant.TextConstant;
@@ -276,6 +277,38 @@ public class MethodCallTest {
.make();
}
+ @Test
+ public void testStaticOnStaticFieldFromAnotherClass() throws Exception {
+ DynamicType.Loaded<Object> loaded = new ByteBuddy()
+ .subclass(Object.class)
+ .invokable(isTypeInitializer())
+ .intercept(MethodCall.invoke(named("println").and(takesArguments(Object.class)))
+ .onField("out", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with(""))
+ .make()
+ .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
+ assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
+ assertThat(loaded.getLoaded().getDeclaredMethods().length, is(0));
+ assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
+ Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
+ assertThat(instance, instanceOf(Object.class));
+ }
+
+ @Test
+ public void testOnStaticFieldFromAnotherClass() throws Exception {
+ DynamicType.Loaded<Object> loaded = new ByteBuddy()
+ .subclass(Object.class)
+ .defineMethod("foo", void.class)
+ .intercept(MethodCall.invoke(named("println").and(takesArguments(Object.class)))
+ .onField("out", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))).with("fooCall"))
+ .make()
+ .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
+ assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
+ assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
+ assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
+ Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
+ assertThat(instance, instanceOf(Object.class));
+ }
+
@Test
public void testOnFieldUsingMatcher() throws Exception {
DynamicType.Loaded<MethodCallOnField> loaded = new ByteBuddy() | ['byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodCallTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodCall.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 5,630,943 | 947,133 | 125,923 | 304 | 484 | 80 | 5 | 1 | 1,111 | 76 | 287 | 37 | 0 | 3 | 2018-08-28T16:44:25 | 5,668 | Java | {'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742} | Apache License 2.0 |
385 | raphw/byte-buddy/951/948 | raphw | byte-buddy | https://github.com/raphw/byte-buddy/issues/948 | https://github.com/raphw/byte-buddy/pull/951 | https://github.com/raphw/byte-buddy/pull/951 | 2 | fix | JavaConstant.MethodHandle.getDescriptor() returns wrong value for PUT_FIELD and PUT_FIELD_STATIC cases | As always, thanks for this project. I am nervous filing this bug because there are so few bugs in ByteBuddy that I feel like this can't actually be one! But I think it is.
For background, see https://stackoverflow.com/questions/64296731/how-do-i-install-and-use-a-constant-methodhandle-in-bytebuddy.
In the case of `PUT_FIELD` and `PUT_FIELD_STATIC` `HandleType`s, I think that the wrong value is being returned from the default implementation of `getDescriptor()`. Specifically, this will return `V` in "field setter" cases, because of this code:
https://github.com/raphw/byte-buddy/blob/291a512c609b647edccfdead540764ee402abd00/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L695-L696
For a "field setter" method handle, this will always return `V`, and that will cause a `ClassFormatError` that resembles the following:
```
java.lang.ClassFormatError: Field "fortyTwo" in class com/foo/bar/GeneratedSubclassOf$com$foo$bar$Baz$26753A95 has illegal signature "V"
```
This is because the return type of a "field setter" method handle as acquired via `JavaConstant.MethodHandle.ofSetter(FieldDescription.InDefinedShape)` will always be `void`, which is correct (see line 626 below):
https://github.com/raphw/byte-buddy/blob/291a512c609b647edccfdead540764ee402abd00/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L623-L627
But [section 5.4.3.5 of the JVM specification](https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.5-240) indicates that if your method handle is of types 1 through 4 inclusive (which `PUT_FIELD` and `PUT_STATIC_FIELD` are), then resolution of the constant must follow the rules of field resolution. [Those rules](https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.2) indicate that the descriptor of the field reference needs to be used. ByteBuddy is instead using the method handle's return type descriptor, which, in the case of field setter method handles, anyway, is `V`.
The workaround that seems to get around this problem is to create a subclass of `JavaConstant.MethodHandle` that overrides the `getDescriptor()` method to do the right thing:
```java
@Override
public final String getDescriptor() {
// See https://stackoverflow.com/questions/64296731/how-do-i-install-and-use-a-constant-methodhandle-in-bytebuddy.
switch (this.getHandleType()) {
case PUT_FIELD:
case PUT_STATIC_FIELD:
// In the case of "field setter" method handles use the sole parameter type's descriptor
// to follow the rules prescribed by
// https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-5.html#jvms-5.4.3.5-240
return this.getParameterTypes().getOnly().getDescriptor();
default:
return super.getDescriptor();
}
}
```
With this override, I can avoid the `ClassFormatError`. (I don't know if it is best to solve the problem here or in `asConstantPoolValue()`.)
I'll attempt to put together a PR shortly.
Thanks again for a great project. | 291a512c609b647edccfdead540764ee402abd00 | 3795ee8733b2f8d0904fe28121a550c5e2b95997 | https://github.com/raphw/byte-buddy/compare/291a512c609b647edccfdead540764ee402abd00...3795ee8733b2f8d0904fe28121a550c5e2b95997 | diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
index 51ad4443c8..5e0e4e2bb6 100644
--- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
@@ -692,9 +692,11 @@ public interface JavaConstant {
* @return The method descriptor of this method handle representation.
*/
public String getDescriptor() {
- if (handleType.isField()) {
- return returnType.getDescriptor();
- } else {
+ switch (handleType) {
+ case PUT_FIELD:
+ case PUT_STATIC_FIELD:
+ return parameterTypes.get(0).getDescriptor();
+ default:
StringBuilder stringBuilder = new StringBuilder().append('(');
for (TypeDescription parameterType : parameterTypes) {
stringBuilder.append(parameterType.getDescriptor());
diff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java
index b0b482f049..71b8ed1c47 100644
--- a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java
+++ b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java
@@ -20,7 +20,7 @@ import static org.mockito.Mockito.when;
public class JavaConstantMethodHandleTest {
- private static final String BAR = "bar", QUX = "qux";
+ private static final String BAR = "bar", FROB = "frob", QUX = "qux";
@Rule
public MethodRule javaVersionRule = new JavaVersionRule();
@@ -106,12 +106,13 @@ public class JavaConstantMethodHandleTest {
@Test
@SuppressWarnings("unchecked")
public void testMethodHandleOfSetter() throws Exception {
- JavaConstant.MethodHandle methodHandle = JavaConstant.MethodHandle.ofSetter(Foo.class.getDeclaredField(BAR));
+ JavaConstant.MethodHandle methodHandle = JavaConstant.MethodHandle.ofSetter(Foo.class.getDeclaredField(FROB));
assertThat(methodHandle.getHandleType(), is(JavaConstant.MethodHandle.HandleType.PUT_FIELD));
- assertThat(methodHandle.getName(), is(BAR));
+ assertThat(methodHandle.getName(), is(FROB));
assertThat(methodHandle.getOwnerType(), is((TypeDescription) TypeDescription.ForLoadedType.of(Foo.class)));
assertThat(methodHandle.getReturnType(), is(TypeDescription.VOID));
- assertThat(methodHandle.getParameterTypes(), is((List<TypeDescription>) new TypeList.ForLoadedTypes(Void.class)));
+ assertThat(methodHandle.getParameterTypes(), is((List<TypeDescription>) new TypeList.ForLoadedTypes(Integer.class)));
+ assertThat(methodHandle.getDescriptor(), is(methodHandle.getParameterTypes().getOnly().getDescriptor()));
}
@Test
@@ -123,6 +124,7 @@ public class JavaConstantMethodHandleTest {
assertThat(methodHandle.getOwnerType(), is((TypeDescription) TypeDescription.ForLoadedType.of(Foo.class)));
assertThat(methodHandle.getReturnType(), is(TypeDescription.VOID));
assertThat(methodHandle.getParameterTypes(), is((List<TypeDescription>) new TypeList.ForLoadedTypes(Void.class)));
+ assertThat(methodHandle.getDescriptor(), is(methodHandle.getParameterTypes().getOnly().getDescriptor()));
}
@Test
@@ -195,6 +197,8 @@ public class JavaConstantMethodHandleTest {
public Void bar;
+ public Integer frob;
+
public Foo(Void value) {
/* empty*/
} | ['byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantMethodHandleTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 7,028,418 | 1,179,473 | 163,217 | 353 | 299 | 51 | 8 | 1 | 3,029 | 321 | 786 | 42 | 7 | 2 | 2020-10-12T17:06:15 | 5,668 | Java | {'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742} | Apache License 2.0 |
384 | raphw/byte-buddy/955/954 | raphw | byte-buddy | https://github.com/raphw/byte-buddy/issues/954 | https://github.com/raphw/byte-buddy/pull/955 | https://github.com/raphw/byte-buddy/pull/955 | 1 | fixes | The type assignability check in JavaConstant.Dynamic.ofInvocation() is too strict | Hi; it's me again; sorry!
For background: https://stackoverflow.com/questions/64360249/is-type-assignability-too-strict-in-javaconstant-dynamic-ofinvocation
In very concrete terms, I think that this assignability check:
https://github.com/raphw/byte-buddy/blob/e4ce4af1bab578a7ac3497d07449e50628d050e7/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L1636-L1638
…is too strict given that it prevents a method from being invoked that uses varargs. Specifically, `iterator.next()` will, in such a case, return something like `Glorp[]`, and (let's say) `Glorp` is not assignable to `Glorp[]`.
Suppose I have:
```
static final JavaConstant toJavaConstant(final Glorp[] glorps) {
final JavaConstant[] javaConstants = new JavaConstant[glorps.length];
for (int i = 0; i < javaConstants.length; i++) {
javaConstants[i] = toJavaConstant(glorps[i]); // another version of this method that works on scalars
}
return JavaConstant.Dynamic.ofInvocation(SOME_METHOD_THAT_ACCEPTS_A_VARARGS_OF_THINGS, javaConstants);
}
```
…and `SOME_METHOD_THAT_ACCEPTS_A_VARARGS_OF_THINGS` is a `MethodDescription.InDefinedShape` that resolves to something like this:
```
public static final Glorp[] toGlorps(final Glorp... glorps) {
return glorps;
}
```
Currently, ByteBuddy will not allow this because of that type assignability check.
If I comment out lines 1636 through 1638, i.e. if I disable the type assignability check, this construction works just fine (probably thanks to all the `MethodHandle` argument conversion machinery happening at constant resolution time).
I'll file a PR shortly. | e4ce4af1bab578a7ac3497d07449e50628d050e7 | 9c7ce054a3607820241310f85a2fe44ed45e6473 | https://github.com/raphw/byte-buddy/compare/e4ce4af1bab578a7ac3497d07449e50628d050e7...9c7ce054a3607820241310f85a2fe44ed45e6473 | diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
index 51ad4443c8..b4b1b108ca 100644
--- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
@@ -1602,7 +1602,7 @@ public interface JavaConstant {
public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, List<?> constants) {
if (!methodDescription.isConstructor() && methodDescription.getReturnType().represents(void.class)) {
throw new IllegalArgumentException("Bootstrap method is no constructor or non-void static factory: " + methodDescription);
- } else if (methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) {
+ } else if (!methodDescription.isVarArgs() && methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) {
throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
}
List<Object> arguments = new ArrayList<Object>(constants.size());
@@ -1633,8 +1633,13 @@ public interface JavaConstant {
throw new IllegalArgumentException("Not a compile-time constant: " + constant);
}
}
- if (!typeDescription.isAssignableTo(iterator.next())) {
- throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
+ if (iterator.hasNext()) {
+ TypeDescription next = iterator.next();
+ if (!typeDescription.isAssignableTo(next)) {
+ if (!methodDescription.isVarArgs() || iterator.hasNext() || !next.isArray() || !typeDescription.isAssignableTo(next.getComponentType())) {
+ throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
+ }
+ }
}
}
return new Dynamic(new ConstantDynamic("invoke",
diff --git a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java
index f95547b3e1..faaa07f74a 100644
--- a/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java
+++ b/byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java
@@ -1,5 +1,7 @@
package net.bytebuddy.utility;
+import java.lang.reflect.Method;
+
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
@@ -478,6 +480,24 @@ public class JavaConstantDynamicTest {
assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo)));
}
+ @Test
+ @JavaVersionRule.Enforce(11)
+ public void testInvocationOfVarargsMethod() throws Exception {
+ final Integer[] sourceIntegers = new Integer[] { Integer.valueOf(1), Integer.valueOf(2) };
+ Class<? extends Foo> baz = new ByteBuddy()
+ .subclass(Foo.class)
+ .method(isDeclaredBy(Foo.class))
+ .intercept(FixedValue.value(toJavaConstant(sourceIntegers)))
+ .make()
+ .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
+ .getLoaded();
+ assertThat(baz.getDeclaredFields().length, is(0));
+ assertThat(baz.getDeclaredMethods().length, is(1));
+ Foo foo = baz.getDeclaredConstructor().newInstance();
+ assertThat((Integer[])baz.getDeclaredMethod(FOO).invoke(foo), equalTo(sourceIntegers));
+ assertThat(baz.getDeclaredMethod(FOO).invoke(foo), sameInstance(baz.getDeclaredMethod(FOO).invoke(foo)));
+ }
+
@Test
@JavaVersionRule.Enforce(11)
public void testStaticFieldVarHandle() throws Exception {
@@ -649,6 +669,7 @@ public class JavaConstantDynamicTest {
public Object bar() {
return null;
}
+
}
private static Object methodHandle() throws Exception {
@@ -660,4 +681,24 @@ public class JavaConstantDynamicTest {
private static Object methodType() throws Exception {
return Class.forName("java.lang.invoke.MethodType").getMethod("methodType", Class.class).invoke(null, void.class);
}
+
+ private static JavaConstant toJavaConstant(Integer[] integers) throws Exception {
+ // This is convoluted and exists only to test issue #954.
+ JavaConstant[] constants = new JavaConstant[integers.length];
+ for (int i = 0; i < integers.length; i++) {
+ constants[i] = toJavaConstant(integers[i]);
+ }
+ return JavaConstant.Dynamic.ofInvocation(JavaConstantDynamicTest.class.getDeclaredMethod("toIntegers", Integer[].class), constants);
+ }
+
+ private static JavaConstant toJavaConstant(Integer i) throws Exception {
+ // This is convoluted and exists only to test issue #954.
+ return JavaConstant.Dynamic.ofInvocation(Integer.class.getMethod("valueOf", String.class), i.toString());
+ }
+
+ public static Integer[] toIntegers(final Integer... varargs) {
+ // This is convoluted and exists only to test issue #954.
+ return varargs;
+ }
+
} | ['byte-buddy-dep/src/test/java/net/bytebuddy/utility/JavaConstantDynamicTest.java', 'byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 7,028,418 | 1,179,473 | 163,217 | 353 | 1,062 | 189 | 11 | 1 | 1,640 | 176 | 421 | 31 | 2 | 2 | 2020-10-14T21:15:09 | 5,668 | Java | {'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742} | Apache License 2.0 |
383 | raphw/byte-buddy/958/957 | raphw | byte-buddy | https://github.com/raphw/byte-buddy/issues/957 | https://github.com/raphw/byte-buddy/pull/958 | https://github.com/raphw/byte-buddy/pull/958 | 2 | fixes | JavaConstant.Dynamic.ofInvocation() doesn't seem to permit interface default methods as bootstrap methods | Using JDK 15, if I try to use `List#of(E[])` (a `static` interface method declared on `List` itself) as a bootstrap method, I get:
```
java.lang.IncompatibleClassChangeError: Inconsistent constant pool data in classfile for class java/util/List. Method 'java.util.List of(java.lang.Object[])' at index 19 is CONSTANT_MethodRef and should be CONSTANT_InterfaceMethodRef
at java.base/java.lang.invoke.MethodHandleNatives.copyOutBootstrapArguments(Native Method)
at java.base/java.lang.invoke.BootstrapMethodInvoker$VM_BSCI.copyConstants(BootstrapMethodInvoker.java:402)
at java.base/java.lang.invoke.BootstrapMethodInvoker$VM_BSCI.fillCache(BootstrapMethodInvoker.java:377)
at java.base/java.lang.invoke.AbstractConstantGroup$WithCache.get(AbstractConstantGroup.java:278)
at java.base/java.lang.invoke.BootstrapMethodInvoker$PullAdapter.pullFromBootstrapMethod(BootstrapMethodInvoker.java:509)
at java.base/java.lang.invoke.BootstrapMethodInvoker.invoke(BootstrapMethodInvoker.java:117)
at java.base/java.lang.invoke.ConstantBootstraps.makeConstant(ConstantBootstraps.java:72)
at java.base/java.lang.invoke.MethodHandleNatives.linkDynamicConstantImpl(MethodHandleNatives.java:327)
at java.base/java.lang.invoke.MethodHandleNatives.linkDynamicConstant(MethodHandleNatives.java:319)
```
I've edited this bug description to remove what I thought was the problem. Now I just don't know what the problem is at all. 😄 | e4ce4af1bab578a7ac3497d07449e50628d050e7 | 265b0c623ffe1c323d524f0ffdbdf104adba1071 | https://github.com/raphw/byte-buddy/compare/e4ce4af1bab578a7ac3497d07449e50628d050e7...265b0c623ffe1c323d524f0ffdbdf104adba1071 | diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
index 51ad4443c8..85769d7735 100644
--- a/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
@@ -1610,7 +1610,7 @@ public interface JavaConstant {
methodDescription.getDeclaringType().getInternalName(),
methodDescription.getInternalName(),
methodDescription.getDescriptor(),
- false));
+ methodDescription.getDeclaringType().isInterface()));
Iterator<TypeDescription> iterator = (methodDescription.isStatic() || methodDescription.isConstructor()
? methodDescription.getParameters().asTypeList().asErasures()
: CompoundList.of(methodDescription.getDeclaringType(), methodDescription.getParameters().asTypeList().asErasures())).iterator(); | ['byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 7,028,418 | 1,179,473 | 163,217 | 353 | 104 | 14 | 2 | 1 | 1,434 | 91 | 318 | 14 | 0 | 1 | 2020-10-16T00:40:16 | 5,668 | Java | {'Java': 13588158, 'C': 5763, 'Batchfile': 4028, 'Shell': 3742} | Apache License 2.0 |
8,968 | wiremock/wiremock/2277/2085 | wiremock | wiremock | https://github.com/wiremock/wiremock/issues/2085 | https://github.com/wiremock/wiremock/pull/2277 | https://github.com/wiremock/wiremock/pull/2277 | 1 | closes | Result (emptyJson) returned immediately without being stored in a variable, if any | https://github.com/wiremock/wiremock/blob/25b82f9f97f3cc09136097b249cfd37aef924c36/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java#L60
Result (emptyJson) returned immediately without being stored in a variable, if any | 7b8a7d351255342d8d22cb5217b6847cc8ddaa29 | 831fc3090d83148420aee214bb0bb892163d87f5 | https://github.com/wiremock/wiremock/compare/7b8a7d351255342d8d22cb5217b6847cc8ddaa29...831fc3090d83148420aee214bb0bb892163d87f5 | diff --git a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java
index 6260fa064..e7f42f687 100644
--- a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java
+++ b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2021 Thomas Akehurst
+ * Copyright (C) 2021-2023 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -57,13 +57,13 @@ public class ParseJsonHelper extends HandlebarsHelper<Object> {
// Edge case if JSON object is empty {}
String jsonAsStringWithoutSpace = jsonAsString.replaceAll("\\\\s", "");
if (jsonAsStringWithoutSpace.equals("{}") || jsonAsStringWithoutSpace.equals("")) {
- return result;
- }
-
- if (jsonAsString.startsWith("[") && jsonAsString.endsWith("]")) {
- result = Json.read(jsonAsString, new TypeReference<List<Object>>() {});
+ result = new HashMap<String, Object>();
} else {
- result = Json.read(jsonAsString, new TypeReference<Map<String, Object>>() {});
+ if (jsonAsString.startsWith("[") && jsonAsString.endsWith("]")) {
+ result = Json.read(jsonAsString, new TypeReference<List<Object>>() {});
+ } else {
+ result = Json.read(jsonAsString, new TypeReference<Map<String, Object>>() {});
+ }
}
}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java b/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java
index ad973c9da..2f3195651 100644
--- a/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java
+++ b/src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java
@@ -33,9 +33,7 @@ import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
-/**
- * @deprecated this is the legacy recorder and will be removed before 3.x is out of beta
- */
+/** @deprecated this is the legacy recorder and will be removed before 3.x is out of beta */
@Deprecated
public class StubMappingJsonRecorder implements RequestListener {
diff --git a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java
index 2ac9bd44d..fadedf8c6 100644
--- a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java
+++ b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java
@@ -914,6 +914,26 @@ public class ResponseTemplateTransformerTest {
assertThat(transform("{{parseJson}}"), is("[ERROR: Missing required JSON string parameter]"));
}
+ @Test
+ public void parsesEmptyJsonLiteralToAnEmptyMap() {
+ String result = transform("{{#parseJson 'parsedObj'}}\\n" + "{\\n" + "}\\n" + "{{/parseJson}}\\n");
+
+ assertThat(result, equalToCompressingWhiteSpace(""));
+ }
+
+ @Test
+ public void parsesEmptyJsonVariableToAnEmptyMap() {
+ String result =
+ transform(
+ "{{#assign 'json'}}\\n"
+ + "{\\n"
+ + "}\\n"
+ + "{{/assign}}\\n"
+ + "{{parseJson json 'parsedObj'}}\\n");
+
+ assertThat(result, equalToCompressingWhiteSpace(""));
+ }
+
@Test
public void conditionalBranchingOnStringMatchesRegexInline() {
assertThat(transform("{{#if (matches '123' '[0-9]+')}}YES{{/if}}"), is("YES"));
diff --git a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java
index b5caba622..0bf38da67 100644
--- a/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java
+++ b/src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2021 Thomas Akehurst
+ * Copyright (C) 2021-2023 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,16 @@
package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.*;
-
+import static org.hamcrest.Matchers.aMapWithSize;
+import static org.hamcrest.Matchers.hasEntry;
+import static org.hamcrest.Matchers.hasKey;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.isA;
+import static org.hamcrest.Matchers.nullValue;
+
+import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Options;
import com.github.jknack.handlebars.TagType;
import com.github.jknack.handlebars.Template;
@@ -116,10 +124,54 @@ public class ParseJsonHelperTest extends HandlebarsHelperTestBase {
@Test
public void parsesEmptyJsonIfSection() throws Exception {
+ String inputJson = "";
+ String variableName = "parsedObject";
+ Template template = new Handlebars().compileInline(inputJson);
+ Options options =
+ new Options.Builder(null, null, TagType.SECTION, createContext(), template)
+ .setParams(new Object[] {})
+ .build();
+ Object output = render(variableName, options);
+
+ // Check that it returns null
+ assertThat(output, is(nullValue()));
+
+ /* Check that it stores parsed json (an empty map in this case because json is empty)
+ * in given variable name */
+ Object storedData = options.data(variableName);
+ assertThat(storedData, isA(Map.class));
+ Map<String, Object> castedData = (Map<String, Object>) storedData;
+ assertThat(castedData, is(aMapWithSize(0)));
+ }
+
+ @Test
+ public void parsesEmptyJsonWithBracesIfSection() throws Exception {
String inputJson = "{}";
- Object output = render(inputJson, new Object[] {}, TagType.SECTION);
+ String variableName = "parsedObject";
+ Template template = new Handlebars().compileInline(inputJson);
+ Options options =
+ new Options.Builder(null, null, TagType.SECTION, createContext(), template)
+ .setParams(new Object[] {})
+ .build();
+ Object output = render(variableName, options);
+
+ // Check that it returns null
+ assertThat(output, is(nullValue()));
+
+ /* Check that it stores parsed json (an empty map in this case because json is empty)
+ * in given variable name */
+ Object storedData = options.data(variableName);
+ assertThat(storedData, isA(Map.class));
+ Map<String, Object> castedData = (Map<String, Object>) storedData;
+ assertThat(castedData, is(aMapWithSize(0)));
+ }
- // Check that it returns empty object
+ @Test
+ public void parsesEmptyJsonIfSectionIfVariableNameNull() throws Exception {
+ String variableName = null;
+ Object output = render(variableName, new Object[] {}, TagType.SECTION);
+
+ // Check that it returns empty object because variable name is null
assertThat(output, instanceOf(Map.class));
Map<String, Object> result = (Map<String, Object>) output;
assertThat(result, aMapWithSize(0));
@@ -127,20 +179,68 @@ public class ParseJsonHelperTest extends HandlebarsHelperTestBase {
@Test
public void parsesEmptyJsonIfNotSection() throws Exception {
+ String inputJson = "";
+ String variableName = "parsedObject";
+ Object[] params = {variableName};
+ Options options =
+ new Options.Builder(null, null, TagType.VAR, createContext(), Template.EMPTY)
+ .setParams(params)
+ .build();
+ Object output = render(inputJson, options);
+
+ // Check that it returns empty object
+ assertThat(output, is(nullValue()));
+
+ /* Check that it stores parsed json (an empty map in this case because json is empty)
+ * in given variable name */
+ Object storedData = options.data(variableName);
+ assertThat(storedData, isA(Map.class));
+ Map<String, Object> castedData = (Map<String, Object>) storedData;
+ assertThat(castedData, is(aMapWithSize(0)));
+ }
+
+ @Test
+ public void parsesEmptyJsonWithBracesIfNotSection() throws Exception {
String inputJson = "{}";
- Object output = render(inputJson, new Object[] {}, TagType.VAR);
+ String variableName = "parsedObject";
+ Object[] params = {variableName};
+ Options options =
+ new Options.Builder(null, null, TagType.VAR, createContext(), Template.EMPTY)
+ .setParams(params)
+ .build();
+ Object output = render(inputJson, options);
// Check that it returns empty object
+ assertThat(output, is(nullValue()));
+
+ /* Check that it stores parsed json (an empty map in this case because json is empty)
+ * in given variable name */
+ Object storedData = options.data(variableName);
+ assertThat(storedData, isA(Map.class));
+ Map<String, Object> castedData = (Map<String, Object>) storedData;
+ assertThat(castedData, is(aMapWithSize(0)));
+ }
+
+ @Test
+ public void parsesEmptyJsonIfNotSectionIfVariableNameAbsent() throws Exception {
+ String inputJson = "{}";
+ Object output = render(inputJson, new Object[] {}, TagType.VAR);
+
+ // Check that it returns empty object because variable name is null
assertThat(output, instanceOf(Map.class));
Map<String, Object> result = (Map<String, Object>) output;
assertThat(result, aMapWithSize(0));
}
private Object render(Object context, Object[] params, TagType tagType) throws IOException {
- return helper.apply(
+ return render(
context,
new Options.Builder(null, null, tagType, createContext(), Template.EMPTY)
.setParams(params)
.build());
}
+
+ private Object render(Object context, Options options) throws IOException {
+ return helper.apply(context, options);
+ }
} | ['src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java', 'src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelperTest.java', 'src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/ParseJsonHelper.java', 'src/main/java/com/github/tomakehurst/wiremock/stubbing/StubMappingJsonRecorder.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 1,437,077 | 305,440 | 43,967 | 518 | 878 | 190 | 18 | 2 | 276 | 13 | 80 | 3 | 1 | 0 | 2023-07-17T22:00:43 | 5,664 | Java | {'Java': 3153326, 'SCSS': 65082, 'XSLT': 14502, 'HTML': 11389, 'Scala': 6556, 'JavaScript': 1343, 'Shell': 1066, 'Ruby': 117} | Apache License 2.0 |
9,220 | shopify/react-native-skia/814/813 | shopify | react-native-skia | https://github.com/Shopify/react-native-skia/issues/813 | https://github.com/Shopify/react-native-skia/pull/814 | https://github.com/Shopify/react-native-skia/pull/814 | 1 | fixes | Android: Multitouch not working as expected | ### Description
Multitouch example (API/Touch) is not working on Android.
### Version
0.1.139
### Steps to reproduce
Run the API/Touch Handling on Android in the Example app and perform one or more touches on the screen with multiple fingers.
Expected: Each finger should have a colored ring that follows your finger
Observed: Only the first finger has a correct ring, all other moves and touches looks very wrong
### Snack, code example, screenshot, or link to a repository
https://github.com/Shopify/react-native-skia | 1612227e4dcfc5662a40ef887b2d93409657e8a1 | f81d6327163661096155788f502322ce762e9008 | https://github.com/shopify/react-native-skia/compare/1612227e4dcfc5662a40ef887b2d93409657e8a1...f81d6327163661096155788f502322ce762e9008 | diff --git a/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java b/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java
index 4df19305..540b77e1 100644
--- a/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java
+++ b/package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java
@@ -2,7 +2,6 @@ package com.shopify.reactnative.skia;
import android.content.Context;
import android.graphics.SurfaceTexture;
-import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.view.MotionEvent;
@@ -56,37 +55,74 @@ public class SkiaDrawView extends TextureView implements TextureView.SurfaceText
@Override
public boolean onTouchEvent(MotionEvent ev) {
- int action = ev.getAction();
- int count = ev.getPointerCount();
+ // https://developer.android.com/training/gestures/multi
+ int action = ev.getActionMasked();
+
MotionEvent.PointerCoords r = new MotionEvent.PointerCoords();
- double[] points = new double[count*5];
- for (int i = 0; i < count; i++) {
- ev.getPointerCoords(i, r);
- points[i] = r.x;
- points[i+1] = r.y;
- points[i+2] = ev.getPressure(i);
- switch (action) {
- case MotionEvent.ACTION_DOWN:
- case MotionEvent.ACTION_POINTER_DOWN:
- points[i+3] = 0;
- break;
- case MotionEvent.ACTION_MOVE:
- points[i+3] = 1;
- break;
- case MotionEvent.ACTION_UP:
- case MotionEvent.ACTION_POINTER_UP:
- points[i+3] = 2;
- break;
- case MotionEvent.ACTION_CANCEL:
- points[i+3] = 3;
- break;
+
+ double[] points;
+
+ // If this is a pointer_up/down event we need to handle it a bit specialized
+ switch (action) {
+ case MotionEvent.ACTION_POINTER_DOWN:
+ case MotionEvent.ACTION_POINTER_UP: {
+ points = new double[5];
+ int pointerIndex = ev.getActionIndex();
+ ev.getPointerCoords(pointerIndex, r);
+ points[0] = r.x;
+ points[1] = r.y;
+ points[2] = ev.getPressure(pointerIndex);
+ points[3] = motionActionToType(action);
+ points[4] = ev.getPointerId(pointerIndex);
+
+ updateTouchPoints(points);
+
+ break;
+ }
+ default: {
+ // For the rest we can just handle it like expected
+ int count = ev.getPointerCount();
+ int pointerIndex = 0;
+ points = new double[5 * count];
+ for (int i = 0; i < count; i++) {
+ ev.getPointerCoords(i, r);
+ points[pointerIndex++] = r.x;
+ points[pointerIndex++] = r.y;
+ points[pointerIndex++] = ev.getPressure(i);
+ points[pointerIndex++] = motionActionToType(action);
+ points[pointerIndex++] = ev.getPointerId(i);
+ }
+
+ updateTouchPoints(points);
+
+ break;
}
- points[i+4] = ev.getPointerId(i);
}
- updateTouchPoints(points);
+
return true;
}
+ private static int motionActionToType(int action) {
+ int actionType = 3;
+ switch (action) {
+ case MotionEvent.ACTION_DOWN:
+ case MotionEvent.ACTION_POINTER_DOWN:
+ actionType = 0;
+ break;
+ case MotionEvent.ACTION_MOVE:
+ actionType = 1;
+ break;
+ case MotionEvent.ACTION_UP:
+ case MotionEvent.ACTION_POINTER_UP:
+ actionType = 2;
+ break;
+ case MotionEvent.ACTION_CANCEL:
+ actionType = 3;
+ break;
+ }
+ return actionType;
+ }
+
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mSurface = new Surface(surface); | ['package/android/src/main/java/com/shopify/reactnative/skia/SkiaDrawView.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 32,586 | 6,587 | 992 | 12 | 3,252 | 615 | 88 | 1 | 531 | 79 | 119 | 18 | 1 | 0 | 2022-08-15T18:35:14 | 5,300 | TypeScript | {'TypeScript': 1013030, 'C++': 584955, 'Java': 36511, 'Objective-C++': 26443, 'JavaScript': 16557, 'Objective-C': 9224, 'CMake': 6620, 'Ruby': 3879, 'Starlark': 602, 'HTML': 428, 'C': 104} | MIT License |
10,190 | StarRocks/starrocks/23320/2527 | StarRocks | starrocks | https://github.com/StarRocks/starrocks/issues/2527 | https://github.com/StarRocks/starrocks/pull/23320 | https://github.com/StarRocks/starrocks/pull/23320 | 1 | fixes | Wrong result return while date type of column is `datetime`. | <!-- (At least include the following, feel free to add if you have more content) -->
insert and delete error.
1. Precision problem of `datetime` when insert into table values.
2. Delete error('ERROR 1064 (HY000): Invalid column value[null] for column k2')
### Steps to reproduce the behavior (Required)
```
mysql> CREATE TABLE test_string2 (`k1` string not null,k2 datetime) ENGINE=OLAP duplicate key(k1) DISTRIBUTED BY HASH(`k1`) BUCKETS 3 PROPERTIES ("replication_num" = "1");
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test_string2 values('2021-12-29 16:58:56.032000','2021-12-29 16:58:56.032000');
Query OK, 1 row affected (0.03 sec)
{'label':'insert_5e9563d2-689f-11ec-8fab-00163e10c9d6', 'status':'VISIBLE', 'txnId':'33055'}
mysql> select * from test_string2;
+----------------------------+----------------------------+
| k1 | k2 |
+----------------------------+----------------------------+
| 2021-12-29 16:58:56.032000 | 2021-12-29 16:58:56.032000 |
+----------------------------+----------------------------+
1 row in set (0.01 sec)
mysql> delete from test_string2 where k2='2021-12-29 16:58:56.032000';
ERROR 1064 (HY000): Invalid column value[null] for column k2
mysql> delete from test_string2 where k1='2021-12-29 16:58:56.032000';
Query OK, 0 rows affected (0.02 sec)
{'label':'delete_a088fb14-0748-44ce-b354-18e3b66fc20d', 'status':'VISIBLE', 'txnId':'33056'}
mysql> select * from test_string2;
Empty set (0.00 sec)
```
-mysql
```
mysql> CREATE TABLE test_string2 (`k1` datetime not null,k2 datetime);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into test_string2 values('2021-12-29 16:58:56.032000','2021-12-29 16:58:56.032000');
Query OK, 1 row affected (0.00 sec)
mysql> select * from test_string2;
+---------------------+---------------------+
| k1 | k2 |
+---------------------+---------------------+
| 2021-12-29 16:58:56 | 2021-12-29 16:58:56 |
+---------------------+---------------------+
1 row in set (0.00 sec)
```
### Expected behavior (Required)
```
mysql> select * from test_string2;
+---------------------+---------------------+
| k1 | k2 |
+---------------------+---------------------+
| 2021-12-29 16:58:56 | 2021-12-29 16:58:56 |
+---------------------+---------------------+
1 row in set (0.00 sec)
```
### Real behavior (Required)
```
mysql> select * from test_string2;
+----------------------------+----------------------------+
| k1 | k2 |
+----------------------------+----------------------------+
| 2021-12-29 16:58:56.032000 | 2021-12-29 16:58:56.032000 |
+----------------------------+----------------------------+
1 row in set (0.01 sec)
```
### StarRocks version (Required)
- You can get the StarRocks version by executing SQL `select current_version()`
- 2.1 | 3585258b549767bff6c4638d379c8e67a697e923 | 1836a3a138a9ea19ff8795e0315bf04e1373a2d1 | https://github.com/StarRocks/starrocks/compare/3585258b549767bff6c4638d379c8e67a697e923...1836a3a138a9ea19ff8795e0315bf04e1373a2d1 | diff --git a/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java b/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java
index 42f8a622dd..406ea029fc 100644
--- a/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java
+++ b/fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java
@@ -64,6 +64,13 @@ public class MarkedCountDownLatch<K, V> extends CountDownLatch {
return false;
}
+ public synchronized boolean markedCountDown(K key, V value, Status status) {
+ if (st.ok()) {
+ st = status;
+ }
+ return markedCountDown(key, value);
+ }
+
public synchronized List<Entry<K, V>> getLeftMarks() {
return Lists.newArrayList(marks.entries());
}
diff --git a/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java b/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java
index 146cf68054..16921c61da 100644
--- a/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java
+++ b/fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java
@@ -224,12 +224,26 @@ public class LeaderImpl {
String errMsg = "task type: " + taskType + ", status_code: " + taskStatus.getStatus_code().toString() +
", backendId: " + backendId + ", signature: " + signature;
task.setErrorMsg(errMsg);
+ LOG.warn(errMsg);
// We start to let FE perceive the task's error msg
if (taskType != TTaskType.MAKE_SNAPSHOT && taskType != TTaskType.UPLOAD
&& taskType != TTaskType.DOWNLOAD && taskType != TTaskType.MOVE
&& taskType != TTaskType.CLONE && taskType != TTaskType.PUBLISH_VERSION
&& taskType != TTaskType.CREATE && taskType != TTaskType.UPDATE_TABLET_META_INFO
&& taskType != TTaskType.DROP_AUTO_INCREMENT_MAP) {
+ if (taskType == TTaskType.REALTIME_PUSH) {
+ PushTask pushTask = (PushTask) task;
+ if (pushTask.getPushType() == TPushType.DELETE) {
+ LOG.info("remove push replica. tabletId: {}, backendId: {}", task.getSignature(),
+ pushTask.getBackendId());
+
+ String failMsg = "Backend: " + task.getBackendId() + "Tablet: " + pushTask.getTabletId() +
+ " error msg: " + taskStatus.getError_msgs().toString();
+ pushTask.countDownLatch(pushTask.getBackendId(), pushTask.getTabletId(), failMsg);
+ AgentTaskQueue.removeTask(pushTask.getBackendId(), TTaskType.REALTIME_PUSH,
+ task.getSignature());
+ }
+ }
return result;
}
}
diff --git a/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java b/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java
index 4c8b8f32df..11c9cc3836 100644
--- a/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java
+++ b/fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java
@@ -54,6 +54,7 @@ import com.starrocks.common.DdlException;
import com.starrocks.common.FeConstants;
import com.starrocks.common.MarkedCountDownLatch;
import com.starrocks.common.MetaNotFoundException;
+import com.starrocks.common.Status;
import com.starrocks.common.UserException;
import com.starrocks.qe.QueryStateException;
import com.starrocks.server.GlobalStateMgr;
@@ -183,6 +184,7 @@ public class OlapDeleteJob extends DeleteJob {
} finally {
db.readUnlock();
}
+ LOG.info("countDownLatch count: {}", countDownLatch.getCount());
long timeoutMs = getTimeoutMs();
LOG.info("waiting delete Job finish, signature: {}, timeout: {}", getTransactionId(), timeoutMs);
@@ -208,59 +210,65 @@ public class OlapDeleteJob extends DeleteJob {
} catch (InterruptedException e) {
LOG.warn("InterruptedException: ", e);
}
+ LOG.info("delete job finish, countDownLatch count: {}", countDownLatch.getCount());
+
+ String errMsg = "";
+ List<Map.Entry<Long, Long>> unfinishedMarks = countDownLatch.getLeftMarks();
+ Status st = countDownLatch.getStatus();
+ // only show at most 5 results
+ List<Map.Entry<Long, Long>> subList = unfinishedMarks.subList(0, Math.min(unfinishedMarks.size(), 5));
+ if (!subList.isEmpty()) {
+ errMsg = "unfinished replicas: " + Joiner.on(", ").join(subList);
+ } else if (!st.ok()) {
+ errMsg = st.toString();
+ }
+ LOG.warn(errMsg);
- if (!ok) {
- String errMsg = "";
- List<Map.Entry<Long, Long>> unfinishedMarks = countDownLatch.getLeftMarks();
- // only show at most 5 results
- List<Map.Entry<Long, Long>> subList = unfinishedMarks.subList(0, Math.min(unfinishedMarks.size(), 5));
- if (!subList.isEmpty()) {
- errMsg = "unfinished replicas: " + Joiner.on(", ").join(subList);
- }
- LOG.warn(errMsg);
-
- try {
- checkAndUpdateQuorum();
- } catch (MetaNotFoundException e) {
- cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage());
- throw new DdlException(e.getMessage(), e);
- }
- DeleteState state = getState();
- switch (state) {
- case DELETING:
- LOG.warn("delete job timeout: transactionId {}, timeout {}, {}", getTransactionId(), timeoutMs,
- errMsg);
+ try {
+ checkAndUpdateQuorum();
+ } catch (MetaNotFoundException e) {
+ cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage());
+ throw new DdlException(e.getMessage(), e);
+ }
+ DeleteState state = getState();
+ switch (state) {
+ case DELETING:
+ LOG.warn("delete job failed: transactionId {}, timeout {}, {}", getTransactionId(), timeoutMs,
+ errMsg);
+ if (countDownLatch.getCount() > 0) {
cancel(DeleteHandler.CancelType.TIMEOUT, "delete job timeout");
- throw new DdlException("failed to execute delete. transaction id " + getTransactionId() +
- ", timeout(ms) " + timeoutMs + ", " + errMsg);
- case QUORUM_FINISHED:
- case FINISHED:
- try {
- long nowQuorumTimeMs = System.currentTimeMillis();
- long endQuorumTimeoutMs = nowQuorumTimeMs + timeoutMs / 2;
- // if job's state is quorum_finished then wait for a period of time and commit it.
- while (getState() == DeleteState.QUORUM_FINISHED && endQuorumTimeoutMs > nowQuorumTimeMs) {
- checkAndUpdateQuorum();
- Thread.sleep(1000);
- nowQuorumTimeMs = System.currentTimeMillis();
- LOG.debug("wait for quorum finished delete job: {}, txn_id: {}", getId(),
- getTransactionId());
- }
- } catch (MetaNotFoundException e) {
- cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage());
- throw new DdlException(e.getMessage(), e);
- } catch (InterruptedException e) {
- cancel(DeleteHandler.CancelType.UNKNOWN, e.getMessage());
- throw new DdlException(e.getMessage(), e);
+ } else {
+ cancel(DeleteHandler.CancelType.UNKNOWN, "delete job failed");
+ }
+ throw new DdlException("failed to execute delete. transaction id " + getTransactionId() +
+ ", timeout(ms) " + timeoutMs + ", " + errMsg);
+ case QUORUM_FINISHED:
+ case FINISHED:
+ try {
+ long nowQuorumTimeMs = System.currentTimeMillis();
+ long endQuorumTimeoutMs = nowQuorumTimeMs + timeoutMs / 2;
+ // if job's state is quorum_finished then wait for a period of time and commit it.
+ while (getState() == DeleteState.QUORUM_FINISHED && endQuorumTimeoutMs > nowQuorumTimeMs
+ && countDownLatch.getCount() > 0) {
+ checkAndUpdateQuorum();
+ Thread.sleep(1000);
+ nowQuorumTimeMs = System.currentTimeMillis();
+ LOG.debug("wait for quorum finished delete job: {}, txn_id: {}", getId(),
+ getTransactionId());
}
- commit(db, timeoutMs);
- break;
- default:
- throw new IllegalStateException("wrong delete job state: " + state.name());
- }
- } else {
- commit(db, timeoutMs);
+ } catch (MetaNotFoundException e) {
+ cancel(DeleteHandler.CancelType.METADATA_MISSING, e.getMessage());
+ throw new DdlException(e.getMessage(), e);
+ } catch (InterruptedException e) {
+ cancel(DeleteHandler.CancelType.UNKNOWN, e.getMessage());
+ throw new DdlException(e.getMessage(), e);
+ }
+ commit(db, timeoutMs);
+ break;
+ default:
+ throw new IllegalStateException("wrong delete job state: " + state.name());
}
+
}
/**
diff --git a/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java b/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java
index bc5b8884a5..12a862afb6 100644
--- a/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java
+++ b/fe/fe-core/src/main/java/com/starrocks/task/PushTask.java
@@ -43,6 +43,7 @@ import com.starrocks.analysis.LiteralExpr;
import com.starrocks.analysis.Predicate;
import com.starrocks.analysis.SlotRef;
import com.starrocks.common.MarkedCountDownLatch;
+import com.starrocks.common.Status;
import com.starrocks.thrift.TBrokerScanRange;
import com.starrocks.thrift.TCondition;
import com.starrocks.thrift.TDescriptorTable;
@@ -50,6 +51,7 @@ import com.starrocks.thrift.TPriority;
import com.starrocks.thrift.TPushReq;
import com.starrocks.thrift.TPushType;
import com.starrocks.thrift.TResourceInfo;
+import com.starrocks.thrift.TStatusCode;
import com.starrocks.thrift.TTabletType;
import com.starrocks.thrift.TTaskType;
import org.apache.logging.log4j.LogManager;
@@ -219,6 +221,15 @@ public class PushTask extends AgentTask {
}
}
+ public void countDownLatch(long backendId, long tabletId, String errMsg) {
+ if (this.latch != null) {
+ if (latch.markedCountDown(backendId, tabletId, new Status(TStatusCode.INTERNAL_ERROR, errMsg))) {
+ LOG.info("pushTask current latch count: {}. backend: {}, tablet:{}",
+ latch.getCount(), backendId, tabletId);
+ }
+ }
+ }
+
public long getReplicaId() {
return replicaId;
} | ['fe/fe-core/src/main/java/com/starrocks/load/OlapDeleteJob.java', 'fe/fe-core/src/main/java/com/starrocks/task/PushTask.java', 'fe/fe-core/src/main/java/com/starrocks/common/MarkedCountDownLatch.java', 'fe/fe-core/src/main/java/com/starrocks/leader/LeaderImpl.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 18,914,418 | 3,826,410 | 461,671 | 2,365 | 7,414 | 1,353 | 138 | 4 | 2,968 | 304 | 846 | 71 | 0 | 4 | 2023-05-12T01:59:14 | 5,115 | Java | {'Java': 29776837, 'C++': 27957184, 'C': 338709, 'Python': 280032, 'Thrift': 259942, 'CMake': 170285, 'Shell': 104253, 'ANTLR': 86095, 'HTML': 26561, 'Dockerfile': 24829, 'JavaScript': 10136, 'Makefile': 7808, 'CSS': 6187, 'Yacc': 4189, 'Lex': 1752, 'Mustache': 959} | Apache License 2.0 |
1,075 | reactor/reactor-core/206/204 | reactor | reactor-core | https://github.com/reactor/reactor-core/issues/204 | https://github.com/reactor/reactor-core/pull/206 | https://github.com/reactor/reactor-core/pull/206 | 1 | fixes | Self Suppression IllegalArgumentException when 'onErrorResume' propagates existing exception | Sometime conditional logic is required to determine if an error signal should be handled or propagated. The easiest and most flexible way to do this is via the use of something like this:
```
flux.onErrorResume(e -> {
if(something){
return just(someValue);
else {
throw propagate(e);
});
```
In this above example the else clause propagates the existing exception. This fails though due to FluxResume attempting to do `e.addSuppressed(e)` [here](https://github.com/reactor/reactor-core/blob/master/src/main/java/reactor/core/publisher/FluxResume.java#L92)
| de3a2bbbdadc767ba568373feec5d5a72a568e65 | 6327441f30b599594a31db4d5e1a4604274e5219 | https://github.com/reactor/reactor-core/compare/de3a2bbbdadc767ba568373feec5d5a72a568e65...6327441f30b599594a31db4d5e1a4604274e5219 | diff --git a/src/main/java/reactor/core/publisher/FluxResume.java b/src/main/java/reactor/core/publisher/FluxResume.java
index 17120d9d6..cdd99d31f 100644
--- a/src/main/java/reactor/core/publisher/FluxResume.java
+++ b/src/main/java/reactor/core/publisher/FluxResume.java
@@ -89,7 +89,9 @@ final class FluxResume<T> extends FluxSource<T, T> {
p = nextFactory.apply(t);
} catch (Throwable e) {
Throwable _e = Operators.onOperatorError(e);
- _e.addSuppressed(t);
+ if(t != _e) {
+ _e.addSuppressed(t);
+ }
subscriber.onError(_e);
return;
}
diff --git a/src/test/java/reactor/core/publisher/FluxResumeTest.java b/src/test/java/reactor/core/publisher/FluxResumeTest.java
index 58977f228..016c00fe5 100644
--- a/src/test/java/reactor/core/publisher/FluxResumeTest.java
+++ b/src/test/java/reactor/core/publisher/FluxResumeTest.java
@@ -18,6 +18,7 @@ package reactor.core.publisher;
import org.junit.Assert;
import org.junit.Test;
import reactor.test.subscriber.AssertSubscriber;
+import reactor.core.Exceptions;
public class FluxResumeTest {
/*
@@ -222,4 +223,18 @@ public class FluxResumeTest {
.assertError(NullPointerException.class);
}
+ @Test
+ public void errorPropagated() {
+ AssertSubscriber<Integer> ts = AssertSubscriber.create(0);
+
+ Exception exception = new NullPointerException("forced failure");
+ Flux.<Integer>error(exception).onErrorResumeWith(v -> {
+ throw Exceptions.propagate(v);
+ }).subscribe(ts);
+
+ ts.assertNoValues()
+ .assertNotComplete()
+ .assertErrorWith(e -> Assert.assertSame(exception, e));
+ }
+
} | ['src/test/java/reactor/core/publisher/FluxResumeTest.java', 'src/main/java/reactor/core/publisher/FluxResume.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,977,113 | 488,605 | 75,285 | 258 | 83 | 27 | 4 | 1 | 581 | 68 | 131 | 13 | 1 | 1 | 2016-10-11T12:15:36 | 4,602 | Java | {'Java': 8928316, 'Kotlin': 48023} | Apache License 2.0 |
1,067 | reactor/reactor-core/3492/3359 | reactor | reactor-core | https://github.com/reactor/reactor-core/issues/3359 | https://github.com/reactor/reactor-core/pull/3492 | https://github.com/reactor/reactor-core/pull/3492 | 1 | closes | EmitterProcessor queue not cleared on immediate cancellation | `EmitterProcessor#remove` has support to discard the buffer once the last subscriber is gone. However, it returns early if the subscribers array is already `EMPTY`. For cases where the subscription is immediately cancelled (e.g. `.take(0)`) this may leak the buffered elements.
Here is a repro case:
```
@Test
void shouldClearBufferOnCancellation() {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
Many<Integer> sink = Sinks.many().unicast().onBackpressureBuffer(queue);
sink.tryEmitNext(1);
sink.tryEmitNext(2);
sink.tryEmitNext(3);
assertThat(queue).hasSize(3);
sink.asFlux().take(0).blockLast();
assertThat(queue).isEmpty();
}
```
As a workaround `.takeWhile(x -> false)` does make the test pass for example. | 75d48b443b2e0038519e362063417a79d544e200 | 258e2852c0ffffa710b0ae745315d151b0185cab | https://github.com/reactor/reactor-core/compare/75d48b443b2e0038519e362063417a79d544e200...258e2852c0ffffa710b0ae745315d151b0185cab | diff --git a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java
index cedbf7d68..47ffd686e 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import java.util.Queue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.Consumer;
import java.util.stream.Stream;
import org.reactivestreams.Publisher;
@@ -33,6 +34,8 @@ import reactor.core.Exceptions;
import reactor.core.Fuseable;
import reactor.core.Scannable;
import reactor.core.publisher.Sinks.EmitResult;
+import reactor.util.Logger;
+import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import reactor.util.concurrent.Queues;
import reactor.util.context.Context;
@@ -70,6 +73,8 @@ import static reactor.core.publisher.FluxPublish.PublishSubscriber.TERMINATED;
public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements InternalManySink<T>,
Sinks.ManyWithUpstream<T> {
+ static final Logger log = Loggers.getLogger(EmitterProcessor.class);
+
@SuppressWarnings("rawtypes")
static final FluxPublish.PubSubInner[] EMPTY = new FluxPublish.PublishInner[0];
@@ -133,13 +138,32 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
*/
@Deprecated
public static <E> EmitterProcessor<E> create(int bufferSize, boolean autoCancel) {
- return new EmitterProcessor<>(autoCancel, bufferSize);
+ return new EmitterProcessor<>(autoCancel, bufferSize, null);
+ }
+
+ /**
+ * Create a new {@link EmitterProcessor} using the provided backlog size and auto-cancellation.
+ *
+ * @param <E> Type of processed signals
+ * @param bufferSize the internal buffer size to hold signals
+ * @param autoCancel automatically cancel
+ *
+ * @return a fresh processor
+ * @deprecated use {@link Sinks.MulticastSpec#onBackpressureBuffer(int, boolean) Sinks.many().multicast().onBackpressureBuffer(bufferSize, autoCancel)}
+ * (or the unsafe variant if you're sure about external synchronization). To be removed in 3.5.
+ */
+ @Deprecated
+ public static <E> EmitterProcessor<E> create(int bufferSize, boolean autoCancel, Consumer<? super E> onDiscardHook) {
+ return new EmitterProcessor<>(autoCancel, bufferSize, onDiscardHook);
}
final int prefetch;
final boolean autoCancel;
+ @Nullable
+ final Consumer<? super T> onDiscard;
+
volatile Subscription s;
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<EmitterProcessor, Subscription> S =
@@ -182,12 +206,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
Throwable.class,
"error");
- EmitterProcessor(boolean autoCancel, int prefetch) {
+ EmitterProcessor(boolean autoCancel, int prefetch, @Nullable Consumer<? super T> onDiscard) {
if (prefetch < 1) {
throw new IllegalArgumentException("bufferSize must be strictly positive, " + "was: " + prefetch);
}
this.autoCancel = autoCancel;
this.prefetch = prefetch;
+ this.onDiscard = onDiscard;
//doesn't use INIT/CANCELLED distinction, contrary to FluxPublish)
//see remove()
SUBSCRIBERS.lazySet(this, EMPTY);
@@ -200,7 +225,12 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
@Override
public Context currentContext() {
- return Operators.multiSubscribersContext(subscribers);
+ if (onDiscard != null) {
+ return Operators.enableOnDiscard(Operators.multiSubscribersContext(subscribers), onDiscard);
+ }
+ else {
+ return Operators.multiSubscribersContext(subscribers);
+ }
}
@@ -213,9 +243,18 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
done = true;
CancellationException detachException = new CancellationException("the ManyWithUpstream sink had a Subscription to an upstream which has been manually cancelled");
if (ERROR.compareAndSet(EmitterProcessor.this, null, detachException)) {
+ if (WIP.getAndIncrement(this) != 0) {
+ return true;
+ }
Queue<T> q = queue;
if (q != null) {
- q.clear();
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
}
for (FluxPublish.PubSubInner<T> inner : terminate()) {
inner.actual.onError(detachException);
@@ -250,7 +289,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (inner.isCancelled()) {
remove(inner);
}
- drain();
+ drain(null);
}
else {
Throwable e = error;
@@ -275,7 +314,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
return EmitResult.FAIL_TERMINATED;
}
done = true;
- drain();
+ drain(null);
return EmitResult.OK;
}
@@ -292,7 +331,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
}
if (Exceptions.addThrowable(ERROR, this, t)) {
done = true;
- drain();
+ drain(null);
return EmitResult.OK;
}
else {
@@ -303,7 +342,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
@Override
public void onNext(T t) {
if (sourceMode == Fuseable.ASYNC) {
- drain();
+ drain(t);
return;
}
emitNext(t, Sinks.EmitFailureHandler.FAIL_FAST);
@@ -340,7 +379,8 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (!q.offer(t)) {
return subscribers == EMPTY ? EmitResult.FAIL_ZERO_SUBSCRIBER : EmitResult.FAIL_OVERFLOW;
}
- drain();
+
+ drain(t);
return EmitResult.OK;
}
@@ -387,7 +427,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (m == Fuseable.SYNC) {
sourceMode = m;
queue = f;
- drain();
+ drain(null);
return;
}
else if (m == Fuseable.ASYNC) {
@@ -443,8 +483,23 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
return super.scanUnsafe(key);
}
- final void drain() {
+ final void drain(@Nullable T dataSignalOfferedBeforeDrain) {
if (WIP.getAndIncrement(this) != 0) {
+ Consumer<? super T> discardHook = this.onDiscard;
+ if (dataSignalOfferedBeforeDrain != null) {
+ if (discardHook != null && isCancelled()) {
+ try {
+ discardHook.accept(dataSignalOfferedBeforeDrain);
+ }
+ catch (Throwable t) {
+ log.warn("Error in discard hook", t);
+ }
+ }
+ else if (done) {
+ Operators.onNextDropped(dataSignalOfferedBeforeDrain,
+ currentContext());
+ }
+ }
return;
}
@@ -458,11 +513,12 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
boolean empty = q == null || q.isEmpty();
- if (checkTerminated(d, empty)) {
+ if (checkTerminated(d, empty, null)) {
return;
}
FluxPublish.PubSubInner<T>[] a = subscribers;
+ Consumer<? super T> onDiscardHook = onDiscard;
if (a != EMPTY && !empty) {
long maxRequested = Long.MAX_VALUE;
@@ -492,9 +548,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
d = true;
v = null;
}
- if (checkTerminated(d, v == null)) {
+ empty = v == null;
+ if (checkTerminated(d, empty, v)) {
return;
}
+ if (!empty && onDiscardHook != null) {
+ discard(v, onDiscardHook);
+ }
if (sourceMode != Fuseable.SYNC) {
s.request(1);
}
@@ -519,7 +579,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
empty = v == null;
- if (checkTerminated(d, empty)) {
+ if (checkTerminated(d, empty, v)) {
return;
}
@@ -528,7 +588,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (sourceMode == Fuseable.SYNC) {
//the q is empty
done = true;
- checkTerminated(true, true);
+ checkTerminated(true, true, null);
}
break;
}
@@ -555,7 +615,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
}
else if ( sourceMode == Fuseable.SYNC ) {
done = true;
- if (checkTerminated(true, empty)) { //empty can be true if no subscriber
+ if (checkTerminated(true, empty, null)) { //empty can be true if no subscriber
break;
}
}
@@ -572,13 +632,23 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
return SUBSCRIBERS.getAndSet(this, TERMINATED);
}
- boolean checkTerminated(boolean d, boolean empty) {
+ boolean checkTerminated(boolean d, boolean empty, @Nullable T value) {
if (s == Operators.cancelledSubscription()) {
if (autoCancel) {
terminate();
+
Queue<T> q = queue;
if (q != null) {
- q.clear();
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ if (value != null) {
+ discard(value, hook);
+ }
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
}
}
return true;
@@ -588,7 +658,16 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (e != null && e != Exceptions.TERMINATED) {
Queue<T> q = queue;
if (q != null) {
- q.clear();
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ if (value != null) {
+ discard(value, hook);
+ }
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
}
for (FluxPublish.PubSubInner<T> inner : terminate()) {
inner.actual.onError(e);
@@ -605,6 +684,31 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
return false;
}
+ static <T> void discardQueue(Queue<T> q, Consumer<? super T> hook) {
+ for (; ; ) {
+ T toDiscard = q.poll();
+ if (toDiscard == null) {
+ break;
+ }
+
+ try {
+ hook.accept(toDiscard);
+ }
+ catch (Throwable t) {
+ log.warn("Error while discarding a queue element, continuing with next queue element", t);
+ }
+ }
+ }
+
+ static <T> void discard(T value, Consumer<? super T> hook) {
+ try {
+ hook.accept(value);
+ }
+ catch (Throwable t) {
+ log.warn("Error while discarding a queue element, continuing with next queue element", t);
+ }
+ }
+
final boolean add(EmitterInner<T> inner) {
for (; ; ) {
FluxPublish.PubSubInner<T>[] a = subscribers;
@@ -624,7 +728,27 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
final void remove(FluxPublish.PubSubInner<T> inner) {
for (; ; ) {
FluxPublish.PubSubInner<T>[] a = subscribers;
- if (a == TERMINATED || a == EMPTY) {
+ if (a == EMPTY) {
+ // means cancelled without adding
+ if (autoCancel && Operators.terminate(S, this)) {
+ if (WIP.getAndIncrement(this) != 0) {
+ return;
+ }
+ terminate();
+ Queue<T> q = queue;
+ if (q != null) {
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
+ }
+ }
+ return;
+ }
+ else if (a == TERMINATED) {
return;
}
int n = a.length;
@@ -659,7 +783,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
terminate();
Queue<T> q = queue;
if (q != null) {
- q.clear();
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
}
}
return;
@@ -683,13 +813,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
@Override
void drainParent() {
- parent.drain();
+ parent.drain(null);
}
@Override
void removeAndDrainParent() {
parent.remove(this);
- parent.drain();
+ parent.drain(null);
}
}
diff --git a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java
index e9183e4ba..16ceea978 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package reactor.core.publisher;
import java.time.Duration;
import java.util.Queue;
+import java.util.function.Consumer;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
@@ -420,6 +421,31 @@ public final class Sinks {
* @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels
*/
<T> ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel);
+
+ /**
+ * A {@link Sinks.ManyWithUpstream} with the following characteristics:
+ * <ul>
+ * <li>Multicast</li>
+ * <li>Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize}
+ * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.</li>
+ * <li>Backpressure : this sink honors downstream demand by conforming to the lowest demand in case
+ * of multiple subscribers.<br>If the difference between multiple subscribers is too high compared to {@code bufferSize}:
+ * <ul><li>{@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}</li>
+ * <li>{@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting}
+ * an {@link Exceptions#failWithOverflow() overflow error}.</li></ul>
+ * </li>
+ * <li>Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber}
+ * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements
+ * that have been buffered due to backpressure/warm up.</li>
+ * </ul>
+ * <p>
+ * <img class="marble" src="doc-files/marbles/sinkWarmup.svg" alt="">
+ *
+ * @param bufferSize the maximum queue size
+ * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels
+ * @param onDiscardHook should be called when values from queue are cleared
+ */
+ <T> ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook);
}
/**
@@ -557,6 +583,31 @@ public final class Sinks {
*/
<T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel);
+ /**
+ * A {@link Sinks.Many} with the following characteristics:
+ * <ul>
+ * <li>Multicast</li>
+ * <li>Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize}
+ * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.</li>
+ * <li>Backpressure : this sink honors downstream demand by conforming to the lowest demand in case
+ * of multiple subscribers.<br>If the difference between multiple subscribers is too high compared to {@code bufferSize}:
+ * <ul><li>{@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}</li>
+ * <li>{@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting}
+ * an {@link Exceptions#failWithOverflow() overflow error}.</li></ul>
+ * </li>
+ * <li>Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber}
+ * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements
+ * that have been buffered due to backpressure/warm up.</li>
+ * </ul>
+ * <p>
+ * <img class="marble" src="doc-files/marbles/sinkWarmup.svg" alt="">
+ *
+ * @param bufferSize the maximum queue size
+ * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels
+ * @param onDiscardHook should be called when values from queue are cleared
+ */
+ <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook);
+
/**
A {@link Sinks.Many} with the following characteristics:
* <ul>
diff --git a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java
index 33d6f45ce..cb4d48f70 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import java.time.Duration;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.Consumer;
import reactor.core.Disposable;
import reactor.core.publisher.Sinks.Empty;
@@ -109,17 +110,22 @@ final class SinksSpecs {
@Override
public <T> Sinks.Many<T> onBackpressureBuffer() {
- return new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE);
+ return new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null);
}
@Override
public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize) {
- return new SinkManyEmitterProcessor<>(true, bufferSize);
+ return new SinkManyEmitterProcessor<>(true, bufferSize, null);
}
@Override
public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel) {
- return new SinkManyEmitterProcessor<>(autoCancel, bufferSize);
+ return new SinkManyEmitterProcessor<>(autoCancel, bufferSize, null);
+ }
+
+ @Override
+ public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> hook) {
+ return new EmitterProcessor<>(autoCancel, bufferSize, hook);
}
@Override
@@ -179,12 +185,17 @@ final class SinksSpecs {
@Override
public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer() {
- return new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE);
+ return new SinkManyEmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null);
}
@Override
public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel) {
- return new SinkManyEmitterProcessor<>(autoCancel, bufferSize);
+ return new SinkManyEmitterProcessor<>(autoCancel, bufferSize, null);
+ }
+
+ @Override
+ public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> hook) {
+ return new EmitterProcessor<>(autoCancel, bufferSize, hook);
}
}
@@ -252,6 +263,13 @@ final class SinksSpecs {
return wrapMany(new SinkManyEmitterProcessor<>(autoCancel, bufferSize));
}
+ @Override
+ public <T> Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook) {
+ @SuppressWarnings("deprecation") // EmitterProcessor will be removed in 3.5.
+ final EmitterProcessor<T> original = EmitterProcessor.create(bufferSize, autoCancel, onDiscardHook);
+ return wrapMany(original);
+ }
+
@Override
public <T> Many<T> directAllOrNothing() {
final SinkManyBestEffort<T> original = SinkManyBestEffort.createAllOrNothing();
@@ -351,6 +369,7 @@ final class SinksSpecs {
}
@Override
+
public <T> Many<T> onBackpressureBuffer(Queue<T> queue) {
final SinkManyUnicast<T> original = SinkManyUnicast.create(queue);
return wrapMany(original);
diff --git a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java
index d32f9e7f1..fc8556136 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -530,9 +530,9 @@ public final class UnicastProcessor<T> extends FluxProcessor<T, T>
this.actual = actual;
if (cancelled) {
this.hasDownstream = false;
- } else {
- drain(null);
}
+
+ drain(null);
} else {
Operators.error(actual, new IllegalStateException("UnicastProcessor " +
"allows only a single Subscriber"));
@@ -556,7 +556,7 @@ public final class UnicastProcessor<T> extends FluxProcessor<T, T>
doTerminate();
- if (WIP.getAndIncrement(this) == 0) {
+ if (actual != null && WIP.getAndIncrement(this) == 0) {
if (!outputFused) {
// discard MUST be happening only and only if there is no racing on elements consumption
// which is guaranteed by the WIP guard here in case non-fused output
diff --git a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java
index f1cc13d99..acffdc76b 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java
@@ -172,6 +172,12 @@ public class OnDiscardShouldNotLeakTest {
DiscardScenario.sinkSource("unicastSink", Sinks.unsafe().many().unicast()::onBackpressureBuffer, null),
DiscardScenario.sinkSource("unicastSinkAndPublishOn", Sinks.unsafe().many().unicast()::onBackpressureBuffer,
f -> f.publishOn(Schedulers.immediate())),
+ DiscardScenario.sinkSource("multicastBufferSink",
+ () -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release),
+ null),
+ DiscardScenario.sinkSource("multicastBufferSinkAndPublishOn",
+ () -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release),
+ f -> f.publishOn(Schedulers.immediate())),
DiscardScenario.fluxSource("singleOrEmpty", f -> f.singleOrEmpty().onErrorReturn(Tracked.RELEASED)),
DiscardScenario.fluxSource("collect", f -> f.collect(ArrayList::new, ArrayList::add)
.doOnSuccess(l -> l.forEach(Tracked::safeRelease))
@@ -656,7 +662,11 @@ public class OnDiscardShouldNotLeakTest {
Sinks.Many<Tracked> sink = sinksManySupplier.get();
//noinspection CallingSubscribeInNonBlockingScope
main.flux().subscribe(
- v -> sink.emitNext(v, FAIL_FAST),
+ v -> {
+ if (sink.tryEmitNext(v) != Sinks.EmitResult.OK) {
+ v.release();
+ }
+ },
e -> sink.emitError(e, FAIL_FAST),
() -> sink.emitComplete(FAIL_FAST));
Flux<Tracked> finalFlux = sink.asFlux();
diff --git a/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java b/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java
index 449d47892..9b72087e5 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
+import org.assertj.core.api.Assertions;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@@ -40,6 +41,7 @@ import reactor.core.Scannable;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.test.AutoDisposingExtension;
+import reactor.test.MemoryUtils;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;
import reactor.test.subscriber.AssertSubscriber;
@@ -62,6 +64,21 @@ class SinkManyEmitterProcessorTest {
@RegisterExtension
AutoDisposingExtension afterTest = new AutoDisposingExtension();
+ //https://github.com/reactor/reactor-core/issues/3359
+ @Test
+ void shouldClearBufferOnCancellation() {
+ MemoryUtils.OffHeapDetector tracker = new MemoryUtils.OffHeapDetector();
+ EmitterProcessor<MemoryUtils.Tracked> source = EmitterProcessor.create(32, true, MemoryUtils.Tracked::release);
+
+ Assertions.assertThat(source.tryEmitNext(tracker.track(1))).isEqualTo(Sinks.EmitResult.OK);
+ Assertions.assertThat(source.tryEmitNext(tracker.track(2))).isEqualTo(Sinks.EmitResult.OK);
+ Assertions.assertThat(source.tryEmitNext(tracker.track(3))).isEqualTo(Sinks.EmitResult.OK);
+
+ source.take(0).blockLast();
+
+ tracker.assertNoLeaks();
+ }
+
@Test
void smokeTestManyWithUpstream() {
@@ -862,7 +879,7 @@ class SinkManyEmitterProcessorTest {
AssertSubscriber<Object> testSubscriber1 = new AssertSubscriber<>(Context.of("key", "value1"));
AssertSubscriber<Object> testSubscriber2 = new AssertSubscriber<>(Context.of("key", "value2"));
- SinkManyEmitterProcessor<Object> sinkManyEmitterProcessor = new SinkManyEmitterProcessor<>(false, 1);
+ SinkManyEmitterProcessor<Object> sinkManyEmitterProcessor = new SinkManyEmitterProcessor<>(false, 1, null);
sinkManyEmitterProcessor.subscribe(testSubscriber1);
sinkManyEmitterProcessor.subscribe(testSubscriber2);
diff --git a/reactor-core/src/test/java/reactor/test/MemoryUtils.java b/reactor-core/src/test/java/reactor/test/MemoryUtils.java
index 55223eeb3..e32ba8420 100644
--- a/reactor-core/src/test/java/reactor/test/MemoryUtils.java
+++ b/reactor-core/src/test/java/reactor/test/MemoryUtils.java
@@ -18,6 +18,7 @@ package reactor.test;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
@@ -170,6 +171,8 @@ public class MemoryUtils {
*/
public static final Tracked RELEASED = new Tracked("RELEASED", true);
+ final List<String> touches = new ArrayList<>();
+
/**
* Check if an arbitrary object is a {@link Tracked}, and if so release it.
*
@@ -210,6 +213,10 @@ public class MemoryUtils {
set(true);
}
+ public void touch(String msg) {
+ touches.add(msg);
+ }
+
/**
* Check if this {@link Tracked} object has been released.
*
@@ -221,6 +228,10 @@ public class MemoryUtils {
@Override
public boolean equals(Object o) {
+ if (o instanceof String) {
+ touch(o.toString());
+ return false;
+ }
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -237,10 +248,16 @@ public class MemoryUtils {
//NOTE: AssertJ has a special representation of AtomicBooleans, so we override it in AssertionsUtils
@Override
public String toString() {
- return "Tracked{" +
- " id=" + identifier +
- " released=" + get() +
- " }";
+ return get()
+ ? "Tracked{" +
+ " id=" + identifier +
+ " released=" + get() +
+ " }"
+ : "Tracked{" +
+ " id=" + identifier +
+ " released=" + get() +
+ " touches=" + touches +
+ " }";
}
}
} | ['reactor-core/src/main/java/reactor/core/publisher/Sinks.java', 'reactor-core/src/test/java/reactor/test/MemoryUtils.java', 'reactor-core/src/test/java/reactor/core/publisher/SinkManyEmitterProcessorTest.java', 'reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java', 'reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 4,080,238 | 1,014,099 | 138,124 | 496 | 10,881 | 2,762 | 270 | 4 | 770 | 80 | 186 | 23 | 0 | 1 | 2023-06-07T17:41:26 | 4,602 | Java | {'Java': 8928316, 'Kotlin': 48023} | Apache License 2.0 |
1,068 | reactor/reactor-core/3486/3359 | reactor | reactor-core | https://github.com/reactor/reactor-core/issues/3359 | https://github.com/reactor/reactor-core/pull/3486 | https://github.com/reactor/reactor-core/pull/3486 | 1 | closes | EmitterProcessor queue not cleared on immediate cancellation | `EmitterProcessor#remove` has support to discard the buffer once the last subscriber is gone. However, it returns early if the subscribers array is already `EMPTY`. For cases where the subscription is immediately cancelled (e.g. `.take(0)`) this may leak the buffered elements.
Here is a repro case:
```
@Test
void shouldClearBufferOnCancellation() {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
Many<Integer> sink = Sinks.many().unicast().onBackpressureBuffer(queue);
sink.tryEmitNext(1);
sink.tryEmitNext(2);
sink.tryEmitNext(3);
assertThat(queue).hasSize(3);
sink.asFlux().take(0).blockLast();
assertThat(queue).isEmpty();
}
```
As a workaround `.takeWhile(x -> false)` does make the test pass for example. | 8549191d09486a6baf94712f1ec6ca6bf1e76ccf | 236c84f7e96c7e5426cf1c25bbece4584d8ad088 | https://github.com/reactor/reactor-core/compare/8549191d09486a6baf94712f1ec6ca6bf1e76ccf...236c84f7e96c7e5426cf1c25bbece4584d8ad088 | diff --git a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java
index fbd251e96..82319a6d3 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import java.util.Queue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.Consumer;
import java.util.stream.Stream;
import org.reactivestreams.Publisher;
@@ -33,6 +34,8 @@ import reactor.core.Exceptions;
import reactor.core.Fuseable;
import reactor.core.Scannable;
import reactor.core.publisher.Sinks.EmitResult;
+import reactor.util.Logger;
+import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import reactor.util.concurrent.Queues;
import reactor.util.context.Context;
@@ -70,6 +73,8 @@ import static reactor.core.publisher.FluxPublish.PublishSubscriber.TERMINATED;
public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements InternalManySink<T>,
Sinks.ManyWithUpstream<T> {
+ static final Logger log = Loggers.getLogger(EmitterProcessor.class);
+
@SuppressWarnings("rawtypes")
static final FluxPublish.PubSubInner[] EMPTY = new FluxPublish.PublishInner[0];
@@ -133,13 +138,32 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
*/
@Deprecated
public static <E> EmitterProcessor<E> create(int bufferSize, boolean autoCancel) {
- return new EmitterProcessor<>(autoCancel, bufferSize);
+ return new EmitterProcessor<>(autoCancel, bufferSize, null);
+ }
+
+ /**
+ * Create a new {@link EmitterProcessor} using the provided backlog size and auto-cancellation.
+ *
+ * @param <E> Type of processed signals
+ * @param bufferSize the internal buffer size to hold signals
+ * @param autoCancel automatically cancel
+ *
+ * @return a fresh processor
+ * @deprecated use {@link Sinks.MulticastSpec#onBackpressureBuffer(int, boolean) Sinks.many().multicast().onBackpressureBuffer(bufferSize, autoCancel)}
+ * (or the unsafe variant if you're sure about external synchronization). To be removed in 3.5.
+ */
+ @Deprecated
+ public static <E> EmitterProcessor<E> create(int bufferSize, boolean autoCancel, Consumer<? super E> onDiscardHook) {
+ return new EmitterProcessor<>(autoCancel, bufferSize, onDiscardHook);
}
final int prefetch;
final boolean autoCancel;
+ @Nullable
+ final Consumer<? super T> onDiscard;
+
volatile Subscription s;
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<EmitterProcessor, Subscription> S =
@@ -182,12 +206,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
Throwable.class,
"error");
- EmitterProcessor(boolean autoCancel, int prefetch) {
+ EmitterProcessor(boolean autoCancel, int prefetch, @Nullable Consumer<? super T> onDiscard) {
if (prefetch < 1) {
throw new IllegalArgumentException("bufferSize must be strictly positive, " + "was: " + prefetch);
}
this.autoCancel = autoCancel;
this.prefetch = prefetch;
+ this.onDiscard = onDiscard;
//doesn't use INIT/CANCELLED distinction, contrary to FluxPublish)
//see remove()
SUBSCRIBERS.lazySet(this, EMPTY);
@@ -200,7 +225,12 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
@Override
public Context currentContext() {
- return Operators.multiSubscribersContext(subscribers);
+ if (onDiscard != null) {
+ return Operators.enableOnDiscard(Operators.multiSubscribersContext(subscribers), onDiscard);
+ }
+ else {
+ return Operators.multiSubscribersContext(subscribers);
+ }
}
@@ -213,9 +243,18 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
done = true;
CancellationException detachException = new CancellationException("the ManyWithUpstream sink had a Subscription to an upstream which has been manually cancelled");
if (ERROR.compareAndSet(EmitterProcessor.this, null, detachException)) {
+ if (WIP.getAndIncrement(this) != 0) {
+ return true;
+ }
Queue<T> q = queue;
if (q != null) {
- q.clear();
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
}
for (FluxPublish.PubSubInner<T> inner : terminate()) {
inner.actual.onError(detachException);
@@ -250,7 +289,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (inner.isCancelled()) {
remove(inner);
}
- drain();
+ drain(null);
}
else {
Throwable e = error;
@@ -275,7 +314,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
return EmitResult.FAIL_TERMINATED;
}
done = true;
- drain();
+ drain(null);
return EmitResult.OK;
}
@@ -292,7 +331,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
}
if (Exceptions.addThrowable(ERROR, this, t)) {
done = true;
- drain();
+ drain(null);
return EmitResult.OK;
}
else {
@@ -303,7 +342,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
@Override
public void onNext(T t) {
if (sourceMode == Fuseable.ASYNC) {
- drain();
+ drain(t);
return;
}
emitNext(t, Sinks.EmitFailureHandler.FAIL_FAST);
@@ -340,7 +379,8 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (!q.offer(t)) {
return subscribers == EMPTY ? EmitResult.FAIL_ZERO_SUBSCRIBER : EmitResult.FAIL_OVERFLOW;
}
- drain();
+
+ drain(t);
return EmitResult.OK;
}
@@ -387,7 +427,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (m == Fuseable.SYNC) {
sourceMode = m;
queue = f;
- drain();
+ drain(null);
return;
}
else if (m == Fuseable.ASYNC) {
@@ -443,8 +483,23 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
return super.scanUnsafe(key);
}
- final void drain() {
+ final void drain(@Nullable T dataSignalOfferedBeforeDrain) {
if (WIP.getAndIncrement(this) != 0) {
+ Consumer<? super T> discardHook = this.onDiscard;
+ if (dataSignalOfferedBeforeDrain != null) {
+ if (discardHook != null && isCancelled()) {
+ try {
+ discardHook.accept(dataSignalOfferedBeforeDrain);
+ }
+ catch (Throwable t) {
+ log.warn("Error in discard hook", t);
+ }
+ }
+ else if (done) {
+ Operators.onNextDropped(dataSignalOfferedBeforeDrain,
+ currentContext());
+ }
+ }
return;
}
@@ -458,11 +513,12 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
boolean empty = q == null || q.isEmpty();
- if (checkTerminated(d, empty)) {
+ if (checkTerminated(d, empty, null)) {
return;
}
FluxPublish.PubSubInner<T>[] a = subscribers;
+ Consumer<? super T> onDiscardHook = onDiscard;
if (a != EMPTY && !empty) {
long maxRequested = Long.MAX_VALUE;
@@ -492,9 +548,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
d = true;
v = null;
}
- if (checkTerminated(d, v == null)) {
+ empty = v == null;
+ if (checkTerminated(d, empty, v)) {
return;
}
+ if (!empty && onDiscardHook != null) {
+ discard(v, onDiscardHook);
+ }
if (sourceMode != Fuseable.SYNC) {
s.request(1);
}
@@ -519,7 +579,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
empty = v == null;
- if (checkTerminated(d, empty)) {
+ if (checkTerminated(d, empty, v)) {
return;
}
@@ -528,7 +588,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (sourceMode == Fuseable.SYNC) {
//the q is empty
done = true;
- checkTerminated(true, true);
+ checkTerminated(true, true, null);
}
break;
}
@@ -555,7 +615,7 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
}
else if ( sourceMode == Fuseable.SYNC ) {
done = true;
- if (checkTerminated(true, empty)) { //empty can be true if no subscriber
+ if (checkTerminated(true, empty, null)) { //empty can be true if no subscriber
break;
}
}
@@ -572,13 +632,23 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
return SUBSCRIBERS.getAndSet(this, TERMINATED);
}
- boolean checkTerminated(boolean d, boolean empty) {
+ boolean checkTerminated(boolean d, boolean empty, @Nullable T value) {
if (s == Operators.cancelledSubscription()) {
if (autoCancel) {
terminate();
+
Queue<T> q = queue;
if (q != null) {
- q.clear();
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ if (value != null) {
+ discard(value, hook);
+ }
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
}
}
return true;
@@ -588,7 +658,16 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
if (e != null && e != Exceptions.TERMINATED) {
Queue<T> q = queue;
if (q != null) {
- q.clear();
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ if (value != null) {
+ discard(value, hook);
+ }
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
}
for (FluxPublish.PubSubInner<T> inner : terminate()) {
inner.actual.onError(e);
@@ -605,6 +684,31 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
return false;
}
+ static <T> void discardQueue(Queue<T> q, Consumer<? super T> hook) {
+ for (; ; ) {
+ T toDiscard = q.poll();
+ if (toDiscard == null) {
+ break;
+ }
+
+ try {
+ hook.accept(toDiscard);
+ }
+ catch (Throwable t) {
+ log.warn("Error while discarding a queue element, continuing with next queue element", t);
+ }
+ }
+ }
+
+ static <T> void discard(T value, Consumer<? super T> hook) {
+ try {
+ hook.accept(value);
+ }
+ catch (Throwable t) {
+ log.warn("Error while discarding a queue element, continuing with next queue element", t);
+ }
+ }
+
final boolean add(EmitterInner<T> inner) {
for (; ; ) {
FluxPublish.PubSubInner<T>[] a = subscribers;
@@ -624,7 +728,27 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
final void remove(FluxPublish.PubSubInner<T> inner) {
for (; ; ) {
FluxPublish.PubSubInner<T>[] a = subscribers;
- if (a == TERMINATED || a == EMPTY) {
+ if (a == EMPTY) {
+ // means cancelled without adding
+ if (autoCancel && Operators.terminate(S, this)) {
+ if (WIP.getAndIncrement(this) != 0) {
+ return;
+ }
+ terminate();
+ Queue<T> q = queue;
+ if (q != null) {
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
+ }
+ }
+ return;
+ }
+ else if (a == TERMINATED) {
return;
}
int n = a.length;
@@ -659,7 +783,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
terminate();
Queue<T> q = queue;
if (q != null) {
- q.clear();
+ Consumer<? super T> hook = this.onDiscard;
+ if (hook != null) {
+ discardQueue(q, hook);
+ }
+ else {
+ q.clear();
+ }
}
}
return;
@@ -683,13 +813,13 @@ public final class EmitterProcessor<T> extends FluxProcessor<T, T> implements In
@Override
void drainParent() {
- parent.drain();
+ parent.drain(null);
}
@Override
void removeAndDrainParent() {
parent.remove(this);
- parent.drain();
+ parent.drain(null);
}
}
diff --git a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java
index e9183e4ba..16ceea978 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/Sinks.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/Sinks.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package reactor.core.publisher;
import java.time.Duration;
import java.util.Queue;
+import java.util.function.Consumer;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
@@ -420,6 +421,31 @@ public final class Sinks {
* @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels
*/
<T> ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel);
+
+ /**
+ * A {@link Sinks.ManyWithUpstream} with the following characteristics:
+ * <ul>
+ * <li>Multicast</li>
+ * <li>Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize}
+ * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.</li>
+ * <li>Backpressure : this sink honors downstream demand by conforming to the lowest demand in case
+ * of multiple subscribers.<br>If the difference between multiple subscribers is too high compared to {@code bufferSize}:
+ * <ul><li>{@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}</li>
+ * <li>{@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting}
+ * an {@link Exceptions#failWithOverflow() overflow error}.</li></ul>
+ * </li>
+ * <li>Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber}
+ * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements
+ * that have been buffered due to backpressure/warm up.</li>
+ * </ul>
+ * <p>
+ * <img class="marble" src="doc-files/marbles/sinkWarmup.svg" alt="">
+ *
+ * @param bufferSize the maximum queue size
+ * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels
+ * @param onDiscardHook should be called when values from queue are cleared
+ */
+ <T> ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook);
}
/**
@@ -557,6 +583,31 @@ public final class Sinks {
*/
<T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel);
+ /**
+ * A {@link Sinks.Many} with the following characteristics:
+ * <ul>
+ * <li>Multicast</li>
+ * <li>Without {@link Subscriber}: warm up. Remembers up to {@code bufferSize}
+ * elements pushed via {@link Many#tryEmitNext(Object)} before the first {@link Subscriber} is registered.</li>
+ * <li>Backpressure : this sink honors downstream demand by conforming to the lowest demand in case
+ * of multiple subscribers.<br>If the difference between multiple subscribers is too high compared to {@code bufferSize}:
+ * <ul><li>{@link Many#tryEmitNext(Object) tryEmitNext} will return {@link EmitResult#FAIL_OVERFLOW}</li>
+ * <li>{@link Many#emitNext(Object, Sinks.EmitFailureHandler) emitNext} will terminate the sink by {@link Many#emitError(Throwable, Sinks.EmitFailureHandler) emitting}
+ * an {@link Exceptions#failWithOverflow() overflow error}.</li></ul>
+ * </li>
+ * <li>Replaying: No replay of values seen by earlier subscribers. Only forwards to a {@link Subscriber}
+ * the elements that have been pushed to the sink AFTER this subscriber was subscribed, or elements
+ * that have been buffered due to backpressure/warm up.</li>
+ * </ul>
+ * <p>
+ * <img class="marble" src="doc-files/marbles/sinkWarmup.svg" alt="">
+ *
+ * @param bufferSize the maximum queue size
+ * @param autoCancel should the sink fully shutdowns (not publishing anymore) when the last subscriber cancels
+ * @param onDiscardHook should be called when values from queue are cleared
+ */
+ <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook);
+
/**
A {@link Sinks.Many} with the following characteristics:
* <ul>
diff --git a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java
index e72e7fec0..f5242dcb2 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import java.time.Duration;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.Consumer;
import reactor.core.Disposable;
import reactor.core.publisher.Sinks.Empty;
@@ -109,17 +110,22 @@ final class SinksSpecs {
@Override
public <T> Sinks.Many<T> onBackpressureBuffer() {
- return new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE);
+ return new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null);
}
@Override
public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize) {
- return new EmitterProcessor<>(true, bufferSize);
+ return new EmitterProcessor<>(true, bufferSize, null);
}
@Override
public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel) {
- return new EmitterProcessor<>(autoCancel, bufferSize);
+ return new EmitterProcessor<>(autoCancel, bufferSize, null);
+ }
+
+ @Override
+ public <T> Sinks.Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> hook) {
+ return new EmitterProcessor<>(autoCancel, bufferSize, hook);
}
@Override
@@ -179,12 +185,17 @@ final class SinksSpecs {
@Override
public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer() {
- return new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE);
+ return new EmitterProcessor<>(true, Queues.SMALL_BUFFER_SIZE, null);
}
@Override
public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel) {
- return new EmitterProcessor<>(autoCancel, bufferSize);
+ return new EmitterProcessor<>(autoCancel, bufferSize, null);
+ }
+
+ @Override
+ public <T> Sinks.ManyWithUpstream<T> multicastOnBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> hook) {
+ return new EmitterProcessor<>(autoCancel, bufferSize, hook);
}
}
@@ -258,6 +269,13 @@ final class SinksSpecs {
return wrapMany(original);
}
+ @Override
+ public <T> Many<T> onBackpressureBuffer(int bufferSize, boolean autoCancel, Consumer<? super T> onDiscardHook) {
+ @SuppressWarnings("deprecation") // EmitterProcessor will be removed in 3.5.
+ final EmitterProcessor<T> original = EmitterProcessor.create(bufferSize, autoCancel, onDiscardHook);
+ return wrapMany(original);
+ }
+
@Override
public <T> Many<T> directAllOrNothing() {
final SinkManyBestEffort<T> original = SinkManyBestEffort.createAllOrNothing();
@@ -367,6 +385,7 @@ final class SinksSpecs {
}
@Override
+
public <T> Many<T> onBackpressureBuffer(Queue<T> queue) {
@SuppressWarnings("deprecation") // UnicastProcessor will be removed in 3.5.
final UnicastProcessor<T> original = UnicastProcessor.create(queue);
diff --git a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java
index d21f4280b..5f11a4140 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -530,9 +530,9 @@ public final class UnicastProcessor<T> extends FluxProcessor<T, T>
this.actual = actual;
if (cancelled) {
this.hasDownstream = false;
- } else {
- drain(null);
}
+
+ drain(null);
} else {
Operators.error(actual, new IllegalStateException("UnicastProcessor " +
"allows only a single Subscriber"));
@@ -556,7 +556,7 @@ public final class UnicastProcessor<T> extends FluxProcessor<T, T>
doTerminate();
- if (WIP.getAndIncrement(this) == 0) {
+ if (actual != null && WIP.getAndIncrement(this) == 0) {
if (!outputFused) {
// discard MUST be happening only and only if there is no racing on elements consumption
// which is guaranteed by the WIP guard here in case non-fused output
diff --git a/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java b/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java
index bd04e9936..3f7c69a8b 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,6 +27,7 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
+import org.assertj.core.api.Assertions;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@@ -42,6 +43,7 @@ import reactor.core.Scannable;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.test.AutoDisposingExtension;
+import reactor.test.MemoryUtils;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;
import reactor.test.subscriber.AssertSubscriber;
@@ -65,6 +67,21 @@ public class EmitterProcessorTest {
@RegisterExtension
AutoDisposingExtension afterTest = new AutoDisposingExtension();
+ //https://github.com/reactor/reactor-core/issues/3359
+ @Test
+ void shouldClearBufferOnCancellation() {
+ MemoryUtils.OffHeapDetector tracker = new MemoryUtils.OffHeapDetector();
+ EmitterProcessor<MemoryUtils.Tracked> source = EmitterProcessor.create(32, true, MemoryUtils.Tracked::release);
+
+ Assertions.assertThat(source.tryEmitNext(tracker.track(1))).isEqualTo(Sinks.EmitResult.OK);
+ Assertions.assertThat(source.tryEmitNext(tracker.track(2))).isEqualTo(Sinks.EmitResult.OK);
+ Assertions.assertThat(source.tryEmitNext(tracker.track(3))).isEqualTo(Sinks.EmitResult.OK);
+
+ source.take(0).blockLast();
+
+ tracker.assertNoLeaks();
+ }
+
@Test
void smokeTestManyWithUpstream() {
@@ -1012,7 +1029,7 @@ public class EmitterProcessorTest {
AssertSubscriber<Object> testSubscriber1 = new AssertSubscriber<>(Context.of("key", "value1"));
AssertSubscriber<Object> testSubscriber2 = new AssertSubscriber<>(Context.of("key", "value2"));
- EmitterProcessor<Object> emitterProcessor = new EmitterProcessor<>(false, 1);
+ EmitterProcessor<Object> emitterProcessor = new EmitterProcessor<>(false, 1, null);
emitterProcessor.subscribe(testSubscriber1);
emitterProcessor.subscribe(testSubscriber2);
diff --git a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java
index f0cbb8abb..0d6b4f822 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2020-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -152,6 +152,12 @@ public class OnDiscardShouldNotLeakTest {
DiscardScenario.sinkSource("unicastSink", Sinks.unsafe().many().unicast()::onBackpressureBuffer, null),
DiscardScenario.sinkSource("unicastSinkAndPublishOn", Sinks.unsafe().many().unicast()::onBackpressureBuffer,
f -> f.publishOn(Schedulers.immediate())),
+ DiscardScenario.sinkSource("multicastBufferSink",
+ () -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release),
+ null),
+ DiscardScenario.sinkSource("multicastBufferSinkAndPublishOn",
+ () -> Sinks.unsafe().many().multicast().onBackpressureBuffer(32, true, Tracked::release),
+ f -> f.publishOn(Schedulers.immediate())),
DiscardScenario.fluxSource("singleOrEmpty", f -> f.singleOrEmpty().onErrorReturn(Tracked.RELEASED)),
DiscardScenario.fluxSource("collect", f -> f.collect(ArrayList::new, ArrayList::add)
.doOnSuccess(l -> l.forEach(Tracked::safeRelease))
@@ -617,7 +623,11 @@ public class OnDiscardShouldNotLeakTest {
Sinks.Many<Tracked> sink = sinksManySupplier.get();
//noinspection CallingSubscribeInNonBlockingScope
main.flux().subscribe(
- v -> sink.emitNext(v, FAIL_FAST),
+ v -> {
+ if (sink.tryEmitNext(v) != Sinks.EmitResult.OK) {
+ v.release();
+ }
+ },
e -> sink.emitError(e, FAIL_FAST),
() -> sink.emitComplete(FAIL_FAST));
Flux<Tracked> finalFlux = sink.asFlux();
diff --git a/reactor-core/src/test/java/reactor/test/MemoryUtils.java b/reactor-core/src/test/java/reactor/test/MemoryUtils.java
index 54084c403..289cd9e23 100644
--- a/reactor-core/src/test/java/reactor/test/MemoryUtils.java
+++ b/reactor-core/src/test/java/reactor/test/MemoryUtils.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2018-2021 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2018-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | ['reactor-core/src/main/java/reactor/core/publisher/Sinks.java', 'reactor-core/src/test/java/reactor/core/publisher/EmitterProcessorTest.java', 'reactor-core/src/test/java/reactor/test/MemoryUtils.java', 'reactor-core/src/main/java/reactor/core/publisher/UnicastProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/EmitterProcessor.java', 'reactor-core/src/main/java/reactor/core/publisher/SinksSpecs.java', 'reactor-core/src/test/java/reactor/core/publisher/OnDiscardShouldNotLeakTest.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 3,793,901 | 946,852 | 129,078 | 463 | 10,801 | 2,752 | 270 | 4 | 770 | 80 | 186 | 23 | 0 | 1 | 2023-06-02T12:09:35 | 4,602 | Java | {'Java': 8928316, 'Kotlin': 48023} | Apache License 2.0 |
1,071 | reactor/reactor-core/3156/3137 | reactor | reactor-core | https://github.com/reactor/reactor-core/issues/3137 | https://github.com/reactor/reactor-core/pull/3156 | https://github.com/reactor/reactor-core/pull/3156 | 2 | closes | ClassCastException when using Hooks | <!--- Provide a general summary of the issue in the Title above -->
We have a registered Hook for metrics purposes, which transforms Monos and Fluxes.
When using in in conjunction with `collectList` and `flatMap`, we get a `ClassCastException` (see example below):
```
java.lang.ClassCastException: class reactor.core.publisher.FluxDoFinally$DoFinallySubscriber cannot be cast to class reactor.core.Fuseable$QueueSubscription (reactor.core.publisher.FluxDoFinally$DoFinallySubscriber and reactor.core.Fuseable$QueueSubscription are in unnamed module of loader 'app')
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:177)
at reactor.core.publisher.FluxDoFinally$DoFinallySubscriber.onSubscribe(FluxDoFinally.java:107)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:178)
at reactor.core.publisher.MonoCollectList$MonoCollectListSubscriber.onSubscribe(MonoCollectList.java:78)
at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53)
at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59)
at reactor.core.publisher.Mono.subscribe(Mono.java:4397)
at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:200)
at reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53)
at reactor.core.publisher.Mono.subscribe(Mono.java:4382)
at reactor.core.publisher.Mono.block(Mono.java:1706)
at com.aviloo.testing.actor.HookProblemTest.reproduceClassCastExceptionWithHooks(HookProblemTest.java:27)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99)
at reactor.core.publisher.Mono.block(Mono.java:1707)
... 71 more
```
It seems that the hook transforms the subscription such that it does not implement `QueueSubscription` anymore.
## Expected Behavior
No exception.
## Actual Behavior
See description.
## Steps to Reproduce
This is the most minimal example I could come up with.
```java
@Test
public void reproduceClassCastExceptionWithHooks() throws Exception {
Hooks.onLastOperator(objectPublisher -> {
if (objectPublisher instanceof Mono) {
return Hooks.convertToMonoBypassingHooks(objectPublisher, false)
.doOnSubscribe(subscription -> {
})
.doFinally(signalType -> {
});
} else {
return objectPublisher;
}
});
Mono.just(1)
.flatMap(fsm -> Flux.just(1, 2, 3).collectList())
// .flatMap(Mono::just) // this will solve the ClassCastException --> workaround
.block();
}
```
## Possible Solution
Workaround: Add a "kind of no-op" transformation. See comment in unit test. Still, this is very uggly, since you would have to add this to every such occurence...
Is there anything else we could do? Or did we miss something? How do you think about it?
## Your Environment
Ubuntu 22.04
Java temurin-17.0.4
reactor 3.4.21
| 4768c43f0e6cd3ff2806e6cfc8e659f88b39b513 | ff5769678f6d7c498aa5bb547e7116f131bdf965 | https://github.com/reactor/reactor-core/compare/4768c43f0e6cd3ff2806e6cfc8e659f88b39b513...ff5769678f6d7c498aa5bb547e7116f131bdf965 | diff --git a/reactor-core/src/main/java/reactor/core/publisher/Flux.java b/reactor-core/src/main/java/reactor/core/publisher/Flux.java
index 6ac402e20..222ad4336 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/Flux.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/Flux.java
@@ -8445,6 +8445,10 @@ public abstract class Flux<T> implements CorePublisher<T> {
CorePublisher publisher = Operators.onLastAssembly(this);
CoreSubscriber subscriber = Operators.toCoreSubscriber(actual);
+ if (subscriber instanceof Fuseable.QueueSubscription && this != publisher && this instanceof Fuseable && !(publisher instanceof Fuseable)) {
+ subscriber = new FluxHide.SuppressFuseableSubscriber<>(subscriber);
+ }
+
try {
if (publisher instanceof OptimizableOperator) {
OptimizableOperator operator = (OptimizableOperator) publisher;
diff --git a/reactor-core/src/main/java/reactor/core/publisher/Mono.java b/reactor-core/src/main/java/reactor/core/publisher/Mono.java
index c665a457a..f79e56640 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/Mono.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/Mono.java
@@ -4375,6 +4375,10 @@ public abstract class Mono<T> implements CorePublisher<T> {
CorePublisher publisher = Operators.onLastAssembly(this);
CoreSubscriber subscriber = Operators.toCoreSubscriber(actual);
+ if (subscriber instanceof Fuseable.QueueSubscription && this != publisher && this instanceof Fuseable && !(publisher instanceof Fuseable)) {
+ subscriber = new FluxHide.SuppressFuseableSubscriber<>(subscriber);
+ }
+
try {
if (publisher instanceof OptimizableOperator) {
OptimizableOperator operator = (OptimizableOperator) publisher;
diff --git a/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java b/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java
index 63a1a612b..b1920212f 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/HooksTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -70,7 +70,6 @@ public class HooksTest {
}
}
-
@Test
public void staticActivationOfOperatorDebug() {
String oldProp = System.setProperty("reactor.trace.operatorStacktrace", "true");
@@ -142,6 +141,7 @@ public class HooksTest {
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook = p -> p;
Hooks.onEachOperator(hook);
+
assertThat(Hooks.onEachOperatorHook).isSameAs(hook);
}
@@ -1254,4 +1254,30 @@ public class HooksTest {
}
};
}
+
+ // https://github.com/reactor/reactor-core/issues/3137
+ @Test
+ public void reproduceClassCastExceptionWithHooks() {
+ Hooks.onLastOperator(objectPublisher -> {
+ if (objectPublisher instanceof Mono) {
+ return Hooks.convertToMonoBypassingHooks(objectPublisher, false)
+ .doFinally(signalType -> {
+ });
+ } else {
+ return objectPublisher;
+ }
+ });
+
+ try {
+ Mono.just(1)
+ .flatMap(fsm -> Mono.just(1)
+ .doOnSubscribe(subscription -> {
+ }))
+ .doOnSubscribe(subscription -> {
+ })
+ .block();
+ } finally {
+ Hooks.resetOnLastOperator();
+ }
+ }
} | ['reactor-core/src/test/java/reactor/core/publisher/HooksTest.java', 'reactor-core/src/main/java/reactor/core/publisher/Mono.java', 'reactor-core/src/main/java/reactor/core/publisher/Flux.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,738,196 | 932,081 | 127,518 | 458 | 444 | 86 | 8 | 2 | 10,536 | 394 | 2,208 | 144 | 0 | 2 | 2022-08-16T10:32:46 | 4,602 | Java | {'Java': 8928316, 'Kotlin': 48023} | Apache License 2.0 |
1,069 | reactor/reactor-core/3351/3336 | reactor | reactor-core | https://github.com/reactor/reactor-core/issues/3336 | https://github.com/reactor/reactor-core/pull/3351 | https://github.com/reactor/reactor-core/pull/3351 | 1 | closes | FlatMapDelayError hangs on callable source error | <!--- Provide a general summary of the issue in the Title above -->
FlatMapDelayError does not propagate an onError signal when a callable source produces an error.
It also does not cancel the upstream subscription. This results in a hanging flux that can never complete because it
does not process any more values from the upstream publisher nor does it signal a termination to downstream subscribers.
Notably this only occurs when the error is from a callable source. When the mapping function throws the error directly
then the behavior is as expected where the backlog is consumed and the flux terminates with an error. However when the
operator is modified with onErrorConsume the error is properly swallowed and processing continues.
This does not affect concatMapDelayError as far as I have been able to test
<!--- /!\\ Make sure to follow the Contribution Guidelines, notably for security issues and questions:
https://github.com/reactor/.github/blob/main/CONTRIBUTING.md
https://pivotal.io/security
https://github.com/reactor/.github/blob/main/CONTRIBUTING.md#question-do-you-have-a-question
-->
## Expected Behavior
<!--- Tell us what you think should happen. -->
FlatMapDelayError should cancel the upstream subscription, process the backlog, then emit an onError response
## Actual Behavior
<!--- Tell us what happens instead of the expected behavior. -->
FlatMapDelayError never completes when callable source throws an error
## Possible Solution
<!--- Not obligatory, but you can suggest a fix/reason for the bug. -->
This behavior seems to have been introduced here
https://github.com/reactor/reactor-core/commit/af0cb628ece3c0a543512ea9913c4ff72ba18566#diff-3ad99cc26a2bc1707dda2203da9a667ccf3abdd52aac45ee6b2c4cea438a842fR361-R363.
However I do not know the side effects well enough to give a full solution.
Additionally it appears that this is caused by some optimization around the flatMap operator as there is a current test which utilizes .hide() on the error flux and completes successfully
linked here https://github.com/reactor/reactor-core/blob/912441f7d36adfb84f06595cecd8895b7518d8c9/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java#L604
A difference when using hide though is that the upstream subscription is still never cancelled so there is still a deviation of behavior from the thrown case as this would cause hot infinite publishers to never propagate the error and continue requesting events.
## Steps to Reproduce
<!---Provide a link to a live example, or an unambiguous set of steps to
reproduce this bug, eg. a unit test. Include code to reproduce, if relevant.
Most projects use JUnit5 now (like in snippet below; otherwise use JUnit4).
-->
Below are examples for the direct throw vs callable source
```java
@Test
void workingFlatMapDelayError() {
Flux.just(0, 1, 2, 3).log()
.flatMapDelayError(integer -> {
throw new RuntimeException(); // Cancels upstream subscription after consuming one event
}, 1, 1)
.as(StepVerifier::create)
.expectError()
.verify(Duration.ofSeconds(1)); // Completes as expected
}
@Test
void hangingFlatMapDelayError() {
Flux.just(0, 1, 2, 3).log()
.flatMapDelayError(integer -> {
return Flux.error(new RuntimeException()); // Does not cancel upstream subscription
}, 1, 1)
.as(StepVerifier::create)
.expectError()
.verify(Duration.ofSeconds(1)); // Triggers timeout
}
@Test
void deoptimizedFlatMapDelayError() {
Flux.just(0, 1, 2, 3).log()
.flatMapDelayError(integer -> {
return Flux.error(new RuntimeException()).hide(); // Does not cancel upstream subscription
}, 1, 1)
.as(StepVerifier::create)
.expectError()
.verify(Duration.ofSeconds(1)); // Completes after consuming all events
}
```
## Your Environment
<!--- Include as many relevant details about the environment you experienced the bug in. -->
<!--- Especially, always include the version(s) of Reactor library/libraries you used! -->
* Reactor version(s) used: reactor-core 3.5.2, reactor-test 3.5.2
* Other relevant libraries versions (eg. `netty`, ...): N/A
* JVM version (`java -version`): 17
* OS and version (eg `uname -a`): Windows 11 | 3dbc0701a061f7e20e304e0475a5ddac1745bddd | 075639613aeec1890f7d10ba4e747a261da6adde | https://github.com/reactor/reactor-core/compare/3dbc0701a061f7e20e304e0475a5ddac1745bddd...075639613aeec1890f7d10ba4e747a261da6adde | diff --git a/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java b/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java
index f3959edd3..e14d6eb1f 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -416,6 +416,7 @@ final class FluxFlatMap<T, R> extends InternalFluxOperator<T, R> {
onError(Operators.onOperatorError(s, e_, t, ctx));
}
Operators.onDiscard(t, ctx);
+ tryEmitScalar(null);
return;
}
tryEmitScalar(v);
diff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java
index 7176da584..599772402 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2022 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,7 +42,6 @@ import reactor.core.Scannable;
import reactor.core.TestLoggerExtension;
import reactor.core.publisher.FluxPeekFuseableTest.AssertQueueSubscription;
import reactor.core.scheduler.Schedulers;
-import reactor.test.util.LoggerUtils;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;
import reactor.test.subscriber.AssertSubscriber;
@@ -1869,4 +1868,41 @@ public class FluxFlatMapTest {
.expectError(NoSuchMethodException.class)
.verify();
}
+
+ static class FluxFlatMapDelayError3336Test {
+
+ @Test
+ void workingFlatMapDelayError() {
+ Flux.just(0, 1, 2, 3)
+ .flatMapDelayError(integer -> {
+ throw new RuntimeException(); // Cancels upstream subscription after consuming one event
+ }, 1, 1)
+ .as(StepVerifier::create)
+ .expectError()
+ .verify(Duration.ofSeconds(1)); // Completes as expected
+ }
+
+ @Test
+ void hangingFlatMapDelayError() {
+ Flux.just(0, 1, 2, 3)
+ .flatMapDelayError(integer -> {
+ return Flux.error(new RuntimeException()); // Does not cancel upstream subscription
+ }, 1, 1)
+ .as(StepVerifier::create)
+ .expectError()
+ .verify(Duration.ofSeconds(1)); // Triggers timeout
+ }
+
+ @Test
+ void deoptimizedFlatMapDelayError() {
+ Flux.just(0, 1, 2, 3)
+ .flatMapDelayError(integer -> {
+ return Flux.error(new RuntimeException())
+ .hide(); // Does not cancel upstream subscription
+ }, 1, 1)
+ .as(StepVerifier::create)
+ .expectError()
+ .verify(Duration.ofSeconds(1)); // Completes after consuming all events
+ }
+ }
} | ['reactor-core/src/main/java/reactor/core/publisher/FluxFlatMap.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxFlatMapTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,998,388 | 995,207 | 135,651 | 489 | 186 | 51 | 3 | 1 | 4,430 | 532 | 1,016 | 88 | 5 | 1 | 2023-02-13T14:27:02 | 4,602 | Java | {'Java': 8928316, 'Kotlin': 48023} | Apache License 2.0 |
1,070 | reactor/reactor-core/3262/3253 | reactor | reactor-core | https://github.com/reactor/reactor-core/issues/3253 | https://github.com/reactor/reactor-core/pull/3262 | https://github.com/reactor/reactor-core/pull/3262 | 1 | closes | Mono and Flux with onErrorContinue hangs on network errors (thrown by Netty) | When I use an `onErrorContinue` on a `Mono` or a `Flux` that gets its input from a `WebClient`, the whole chain hangs in case a network error is thrown. I've seen this behaviour with errors caused by a connection timeout, read timeout, unknown host and a refused connection.
Please note that I created this bug in reactor-core, because this is the place where `onErrorContinue` is defined. I suspect that this bug is not specific to the netty http client, but I haven't tested that.
## Expected Behavior
I expect the program to continue and not to cause any thread to hang.
## Actual Behavior
The thread that executes the Mono (or Flux) blocks forever.
## Steps to Reproduce
You can use the following junit 5 tests (one for Mono and one for Flux) to reproduce this issue. This test instantiates a WebClient with a 200ms response timeout. This client is then used to do a call to "https://httpstat.us/200?sleep=500" that will return a 200 response only after 500ms. This way we force a response timeout to be thrown.
A failing test means that the `block()` did not return any result within 5 seconds.
```java
public class NettyReactorTest {
private final WebClient webClient;
public NettyReactorTest() {
final ReactorClientHttpConnector httpConnector = new ReactorClientHttpConnector(
HttpClient.create().responseTimeout(Duration.ofMillis(200)));
this.webClient = WebClient.builder()
.baseUrl("https://httpstat.us")
.clientConnector(httpConnector)
.build();
}
@Test
public void testMonoOnErrorContinueDoesNotHangOnTimeouts() {
Mono<ResponseEntity<Void>> call = webClient.get()
.uri("/200?sleep=500")
.retrieve()
.toBodilessEntity()
.onErrorContinue((e, o) -> {
});
Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> call.block());
}
@Test
public void testFluxOnErrorContinueDoesNotHangOnTimeouts() {
Mono<ResponseEntity<Void>> call = webClient.get()
.uri("/200?sleep=500")
.retrieve()
.toBodilessEntity();
Mono<List<ResponseEntity<Void>>> calls = Flux.fromIterable(List.of(1, 2, 3))
.flatMap(i -> call)
.onErrorContinue((e, o) -> {})
.collectList();
Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> calls.block());
}
}
```
## Extra information
When we take a thread dump a little while after we run the test (that blocks) we see that the thread that calls `block()` is stuck on the `Mono.block()` operator:
```
junit-timeout-thread-1
jdk.internal.misc.Unsafe.park(boolean, long) Unsafe.java (native)
java.util.concurrent.locks.LockSupport.park(Object) LockSupport.java:194
java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt() AbstractQueuedSynchronizer.java:885
java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(int) AbstractQueuedSynchronizer.java:1039
java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(int) AbstractQueuedSynchronizer.java:1345
java.util.concurrent.CountDownLatch.await() CountDownLatch.java:232
reactor.core.publisher.BlockingSingleSubscriber.blockingGet() BlockingSingleSubscriber.java:87
reactor.core.publisher.Mono.block() Mono.java:1707
NettyReactorTest.lambda$testMonoOnErrorContinueDoesNotHangOnTimeouts$1(Mono) NettyReactorTest.java:52
NettyReactorTest$$Lambda$529.get()
org.junit.jupiter.api.AssertTimeout.lambda$assertTimeoutPreemptively$4(AtomicReference, ThrowingSupplier) AssertTimeout.java:138
org.junit.jupiter.api.AssertTimeout$$Lambda$530.call()
java.util.concurrent.FutureTask.run() FutureTask.java:264
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) ThreadPoolExecutor.java:1128
java.util.concurrent.ThreadPoolExecutor$Worker.run() ThreadPoolExecutor.java:628
java.lang.Thread.run() Thread.java:829
```
## Possible Solution
Not a solution, but more of a way to mitigate the impact.
I am aware that `onErrorContinue` is a specialised operator and that for my specific case I could (and should) have used `onErrorResume`. Indeed, replacing `onErrorContinue` with `onErrorResume` in the above tests makes the problem go away. So, perhaps I am just another case of someone using it wrongly and "tripping up on it" (https://github.com/reactor/reactor-core/issues/2184).
Yet, this seemingly innocent code causes a rather nasty issue that should either be:
* fixed if this is indeed a bug or
* prevented if this is an unjust use of the `onErrorContinue` operator.
For the latter, I like @simonbasle's suggestion to move this operator to an `unsafe()` subgroup. This would have prevented me from using it and use `onErrorResume` instead as suggested in the documentation.
## Your Environment
* Reactor version(s) used: 3.4.22
* Other relevant libraries versions (eg. `netty`, ...):
** netty: 1.0.22
** spring / spring-web: 5.3.22
* JVM version (`java -version`): OpenJDK Runtime Environment Zulu11.58+15-CA (build 11.0.16+8-LTS)
* OS and version (eg `uname -a`): Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64 x86_64 (macOS Monterey)
| b31b331e1c37bf468320185474d39bc504afea99 | 0cc9e9831f1609f268c9f45de7d0782615cc0309 | https://github.com/reactor/reactor-core/compare/b31b331e1c37bf468320185474d39bc504afea99...0cc9e9831f1609f268c9f45de7d0782615cc0309 | diff --git a/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java b/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java
index 3283bd781..540501b5c 100644
--- a/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java
+++ b/reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2021 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@ import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.util.annotation.Nullable;
+import reactor.util.context.Context;
import reactor.util.context.ContextView;
/**
@@ -539,69 +540,73 @@ public final class RetryBackoffSpec extends Retry {
@Override
public Flux<Long> generateCompanion(Flux<RetrySignal> t) {
validateArguments();
- return t.concatMap(retryWhenState -> {
- //capture the state immediately
- RetrySignal copy = retryWhenState.copy();
- Throwable currentFailure = copy.failure();
- long iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries();
-
- if (currentFailure == null) {
- return Mono.error(new IllegalStateException("Retry.RetrySignal#failure() not expected to be null"));
- }
-
- if (!errorFilter.test(currentFailure)) {
- return Mono.error(currentFailure);
- }
-
- if (iteration >= maxAttempts) {
- return Mono.error(retryExhaustedGenerator.apply(this, copy));
- }
-
- Duration nextBackoff;
- try {
- nextBackoff = minBackoff.multipliedBy((long) Math.pow(2, iteration));
- if (nextBackoff.compareTo(maxBackoff) > 0) {
+ return Flux.deferContextual(cv ->
+ t.contextWrite(cv)
+ .concatMap(retryWhenState -> {
+ //capture the state immediately
+ RetrySignal copy = retryWhenState.copy();
+ Throwable currentFailure = copy.failure();
+ long iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries();
+
+ if (currentFailure == null) {
+ return Mono.error(new IllegalStateException("Retry.RetrySignal#failure() not expected to be null"));
+ }
+
+ if (!errorFilter.test(currentFailure)) {
+ return Mono.error(currentFailure);
+ }
+
+ if (iteration >= maxAttempts) {
+ return Mono.error(retryExhaustedGenerator.apply(this, copy));
+ }
+
+ Duration nextBackoff;
+ try {
+ nextBackoff = minBackoff.multipliedBy((long) Math.pow(2, iteration));
+ if (nextBackoff.compareTo(maxBackoff) > 0) {
+ nextBackoff = maxBackoff;
+ }
+ }
+ catch (ArithmeticException overflow) {
nextBackoff = maxBackoff;
}
- }
- catch (ArithmeticException overflow) {
- nextBackoff = maxBackoff;
- }
-
- //short-circuit delay == 0 case
- if (nextBackoff.isZero()) {
- return RetrySpec.applyHooks(copy, Mono.just(iteration),
+
+ //short-circuit delay == 0 case
+ if (nextBackoff.isZero()) {
+ return RetrySpec.applyHooks(copy, Mono.just(iteration),
+ syncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry);
+ }
+
+ ThreadLocalRandom random = ThreadLocalRandom.current();
+
+ long jitterOffset;
+ try {
+ jitterOffset = nextBackoff.multipliedBy((long) (100 * jitterFactor))
+ .dividedBy(100)
+ .toMillis();
+ }
+ catch (ArithmeticException ae) {
+ jitterOffset = Math.round(Long.MAX_VALUE * jitterFactor);
+ }
+ long lowBound = Math.max(minBackoff.minus(nextBackoff)
+ .toMillis(), -jitterOffset);
+ long highBound = Math.min(maxBackoff.minus(nextBackoff)
+ .toMillis(), jitterOffset);
+
+ long jitter;
+ if (highBound == lowBound) {
+ if (highBound == 0) jitter = 0;
+ else jitter = random.nextLong(highBound);
+ }
+ else {
+ jitter = random.nextLong(lowBound, highBound);
+ }
+ Duration effectiveBackoff = nextBackoff.plusMillis(jitter);
+ return RetrySpec.applyHooks(copy, Mono.delay(effectiveBackoff,
+ backoffSchedulerSupplier.get()),
syncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry);
- }
-
- ThreadLocalRandom random = ThreadLocalRandom.current();
-
- long jitterOffset;
- try {
- jitterOffset = nextBackoff.multipliedBy((long) (100 * jitterFactor))
- .dividedBy(100)
- .toMillis();
- }
- catch (ArithmeticException ae) {
- jitterOffset = Math.round(Long.MAX_VALUE * jitterFactor);
- }
- long lowBound = Math.max(minBackoff.minus(nextBackoff)
- .toMillis(), -jitterOffset);
- long highBound = Math.min(maxBackoff.minus(nextBackoff)
- .toMillis(), jitterOffset);
-
- long jitter;
- if (highBound == lowBound) {
- if (highBound == 0) jitter = 0;
- else jitter = random.nextLong(highBound);
- }
- else {
- jitter = random.nextLong(lowBound, highBound);
- }
- Duration effectiveBackoff = nextBackoff.plusMillis(jitter);
- return RetrySpec.applyHooks(copy, Mono.delay(effectiveBackoff,
- backoffSchedulerSupplier.get()),
- syncPreRetry, syncPostRetry, asyncPreRetry, asyncPostRetry);
- });
+ })
+ .contextWrite(c -> Context.empty())
+ );
}
}
diff --git a/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java b/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java
index 55c3ae989..710ff4de8 100644
--- a/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java
+++ b/reactor-core/src/main/java/reactor/util/retry/RetrySpec.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2020-2021 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2020-2022 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@ import java.util.function.Predicate;
import reactor.core.Exceptions;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
+import reactor.util.context.Context;
import reactor.util.context.ContextView;
/**
@@ -353,25 +354,30 @@ public final class RetrySpec extends Retry {
@Override
public Flux<Long> generateCompanion(Flux<RetrySignal> flux) {
- return flux.concatMap(retryWhenState -> {
- //capture the state immediately
- RetrySignal copy = retryWhenState.copy();
- Throwable currentFailure = copy.failure();
- long iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries();
+ return Flux.deferContextual(cv ->
+ flux
+ .contextWrite(cv)
+ .concatMap(retryWhenState -> {
+ //capture the state immediately
+ RetrySignal copy = retryWhenState.copy();
+ Throwable currentFailure = copy.failure();
+ long iteration = isTransientErrors ? copy.totalRetriesInARow() : copy.totalRetries();
- if (currentFailure == null) {
- return Mono.error(new IllegalStateException("RetryWhenState#failure() not expected to be null"));
- }
- else if (!errorFilter.test(currentFailure)) {
- return Mono.error(currentFailure);
- }
- else if (iteration >= maxAttempts) {
- return Mono.error(retryExhaustedGenerator.apply(this, copy));
- }
- else {
- return applyHooks(copy, Mono.just(iteration), doPreRetry, doPostRetry, asyncPreRetry, asyncPostRetry);
- }
- });
+ if (currentFailure == null) {
+ return Mono.error(new IllegalStateException("RetryWhenState#failure() not expected to be null"));
+ }
+ else if (!errorFilter.test(currentFailure)) {
+ return Mono.error(currentFailure);
+ }
+ else if (iteration >= maxAttempts) {
+ return Mono.error(retryExhaustedGenerator.apply(this, copy));
+ }
+ else {
+ return applyHooks(copy, Mono.just(iteration), doPreRetry, doPostRetry, asyncPreRetry, asyncPostRetry);
+ }
+ })
+ .contextWrite(c -> Context.empty())
+ );
}
//===================
diff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java
index ceab36edb..1eb0dbad5 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java
@@ -58,6 +58,33 @@ public class FluxRetryWhenTest {
Flux<Integer> rangeError = Flux.concat(Flux.range(1, 2),
Flux.error(new RuntimeException("forced failure 0")));
+ @Test
+ //https://github.com/reactor/reactor-core/issues/3253
+ public void shouldFailWhenOnErrorContinueEnabled() {
+ Mono.create(sink -> {
+ throw new RuntimeException("blah");
+ })
+ .retryWhen(Retry.indefinitely().filter(t -> false))
+ .onErrorContinue((e, o) -> {})
+ .as(StepVerifier::create)
+ .expectError()
+ .verify(Duration.ofSeconds(10));
+ }
+
+ @Test
+ //https://github.com/reactor/reactor-core/issues/3253
+ public void shouldWorkAsExpected() {
+ Mono.just(1)
+ .map(v -> { // ensure original context is propagated
+ throw new RuntimeException("boom");
+ })
+ .retryWhen(Retry.indefinitely().filter(t -> false))
+ .onErrorContinue((e, o) -> {})
+ .as(StepVerifier::create)
+ .expectComplete()
+ .verify(Duration.ofSeconds(10));
+ }
+
@Test
public void dontRepeat() {
AssertSubscriber<Integer> ts = AssertSubscriber.create(); | ['reactor-core/src/main/java/reactor/util/retry/RetrySpec.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxRetryWhenTest.java', 'reactor-core/src/main/java/reactor/util/retry/RetryBackoffSpec.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,974,838 | 989,269 | 134,931 | 486 | 6,265 | 1,511 | 173 | 2 | 5,454 | 534 | 1,293 | 102 | 3 | 2 | 2022-11-01T09:13:00 | 4,602 | Java | {'Java': 8928316, 'Kotlin': 48023} | Apache License 2.0 |
1,066 | reactor/reactor-core/3555/3554 | reactor | reactor-core | https://github.com/reactor/reactor-core/issues/3554 | https://github.com/reactor/reactor-core/pull/3555 | https://github.com/reactor/reactor-core/pull/3555 | 2 | closes | `FluxGroupBy`'s `GroupedFlux` does not propagate the `Subscription` to the second (rejected) `Subscriber` | When calling flatMap on a Publisher which throws an exception upon subscription, there are certain cases where checkTerminated throws a NPE and masks the actual exception. Furthermore flatMap never terminates.
## Expected Behavior
flatMap terminates with the actual Error
## Actual Behavior
NPE and no Termination. Stacktrace from the example below
```
2023-08-02 13:04:02 ERROR Operators - Operator called default onErrorDropped
java.lang.NullPointerException: null
at reactor.core.publisher.FluxFlatMap$FlatMapMain.checkTerminated(FluxFlatMap.java:840) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.drainLoop(FluxFlatMap.java:609) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.drain(FluxFlatMap.java:589) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onError(FluxFlatMap.java:452) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxGroupBy$UnicastGroupedFlux.subscribe(FluxGroupBy.java:721) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxRetry$RetrySubscriber.resubscribe(FluxRetry.java:117) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxRetry.subscribeOrReturn(FluxRetry.java:52) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.Flux.subscribe(Flux.java:8759) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:427) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxGroupBy$GroupByMain.drainLoop(FluxGroupBy.java:393) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxGroupBy$GroupByMain.drain(FluxGroupBy.java:329) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxGroupBy$GroupByMain.onNext(FluxGroupBy.java:207) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxArray$ArraySubscription.slowPath(FluxArray.java:127) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxArray$ArraySubscription.request(FluxArray.java:100) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxGroupBy$GroupByMain.onSubscribe(FluxGroupBy.java:171) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.core.publisher.Flux.subscribe(Flux.java:8773) ~[reactor-core-3.5.8.jar:3.5.8]
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.toVerifierAndSubscribe(DefaultStepVerifierBuilder.java:891) ~[reactor-test-3.5.8.jar:3.5.8]
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:831) ~[reactor-test-3.5.8.jar:3.5.8]
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:823) ~[reactor-test-3.5.8.jar:3.5.8]
at reactor.test.DefaultStepVerifierBuilder.verifyErrorSatisfies(DefaultStepVerifierBuilder.java:685) ~[reactor-test-3.5.8.jar:3.5.8]
```
## Steps to Reproduce
```kotlin
@Test
fun flatMapExceptionTest() {
StepVerifier.create(Flux.just(1, 2, 3, 4, 5, 6)
.groupBy {
it > 3
}
.flatMap {
it.flatMap<Int> { Mono.error(Error("whoopsies")) }.retry(2)
}
).verifyErrorSatisfies {
assertThat(it).hasMessage("whoopsies")
}
}
```
The actual error here (GroupedFlux allows only one Subscriber) is hidden by the NPE
## Possible Solution
Null check? Not sure if there is more behind it.
## Your Environment
* Reactor version(s) used: 3.5.8
* JVM version (`java -version`): openjdk version "11.0.17" 2022-10-18 LTS
* OS and version (eg `uname -a`): Linux S0155454 6.2.0-26-generic
| b38936e387c31c36044f55448dce5033c580bc9c | 91a201de9651a2242d4ec66cda310d9b18f125fc | https://github.com/reactor/reactor-core/compare/b38936e387c31c36044f55448dce5033c580bc9c...91a201de9651a2242d4ec66cda310d9b18f125fc | diff --git a/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java b/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java
index 30cad47c3..08092c8e0 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -718,7 +718,7 @@ final class FluxGroupBy<T, K, V> extends InternalFluxOperator<T, GroupedFlux<K,
drain();
}
else {
- actual.onError(new IllegalStateException(
+ Operators.error(actual, new IllegalStateException(
"GroupedFlux allows only one Subscriber"));
}
}
diff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java
index fdfeb524d..00d974d06 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.
+ * Copyright (c) 2016-2023 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,6 +47,16 @@ import static org.assertj.core.api.Assertions.fail;
public class FluxGroupByTest extends
FluxOperatorTest<String, GroupedFlux<Integer, String>> {
+ @Test
+ // see https://github.com/reactor/reactor-core/issues/3554
+ void flatMapExceptionTest() {
+ Flux.just(1, 2, 3, 4, 5, 6)
+ .groupBy(it -> it > 3)
+ .flatMap(it -> it.flatMap(__ -> Mono.error(new RuntimeException("whoopsies"))).retry(2))
+ .as(StepVerifier::create)
+ .verifyErrorSatisfies(it -> assertThat(it).hasMessage("GroupedFlux allows only one Subscriber"));
+ }
+
@Test
@Tag("slow")
//see https://github.com/reactor/reactor-core/issues/2730 | ['reactor-core/src/main/java/reactor/core/publisher/FluxGroupBy.java', 'reactor-core/src/test/java/reactor/core/publisher/FluxGroupByTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,812,390 | 951,638 | 129,701 | 464 | 262 | 59 | 4 | 1 | 3,961 | 222 | 1,214 | 61 | 0 | 2 | 2023-08-03T15:10:30 | 4,602 | Java | {'Java': 8928316, 'Kotlin': 48023} | Apache License 2.0 |
1,072 | reactor/reactor-core/2216/2196 | reactor | reactor-core | https://github.com/reactor/reactor-core/issues/2196 | https://github.com/reactor/reactor-core/pull/2216 | https://github.com/reactor/reactor-core/pull/2216 | 1 | fix | repeatWhenEmpty hangs on cancel when discard hook is present | ## Expected Behavior
It should be safe to cancel the sequence.
## Actual Behavior
Cancelling a sequence which is in a `repeatWhenEmpty()` loop will cause issues when a discard hook has been registered. In that case `Operators.onDiscardMultiple()` is invoked with the iterator used to keep track of the current iteration and the hook would be called for every remaining number up to `Long.MAX_VALUE`.
## Steps to Reproduce
This test case will succeed when removing the `doOnDiscard()` operator.
```java
@Test
public void shouldCompleteEventually()
{
StepVerifier.create(Mono.empty()
.repeatWhenEmpty(Repeat.once())
.doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release))
.thenAwait()
.thenCancel()
.verify(Duration.ofSeconds(5));
}
```
## Possible Solution
Probably we should treat the remaining iterations in a way that they can be safely discarded without bothering any application level hooks. Also, I guess `FluxStream` should not be considered "knownToBeFinite" if its size is `Long.MAX_VALUE`.
## Your Environment
* Reactor version(s) used: 3.3.6.RELEASE
| 19d1c1c9808641b2d50922a3c9cc800fbc33d4c6 | f6a5f5b920aec6a55b7887e252feb5aa112e4392 | https://github.com/reactor/reactor-core/compare/19d1c1c9808641b2d50922a3c9cc800fbc33d4c6...f6a5f5b920aec6a55b7887e252feb5aa112e4392 | diff --git a/reactor-core/src/main/java/reactor/core/publisher/Mono.java b/reactor-core/src/main/java/reactor/core/publisher/Mono.java
index 6cd3bd838..14e668db1 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/Mono.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/Mono.java
@@ -27,6 +27,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
@@ -133,9 +134,9 @@ public abstract class Mono<T> implements Publisher<T> {
* }
* }
* };
- *
+ *
* client.addListener(listener);
- *
+ *
* sink.onDispose(() -> client.removeListener(listener));
* });
* </code></pre>
@@ -2675,7 +2676,7 @@ public abstract class Mono<T> implements Publisher<T> {
/**
* Hides the identity of this {@link Mono} instance.
- *
+ *
* <p>The main purpose of this operator is to prevent certain identity-based
* optimizations from happening, mostly for diagnostic purposes.
*
@@ -2684,7 +2685,7 @@ public abstract class Mono<T> implements Publisher<T> {
public final Mono<T> hide() {
return onAssembly(new MonoHide<>(this));
}
-
+
/**
* Ignores onNext signal (dropping it) and only propagates termination events.
*
@@ -3416,23 +3417,16 @@ public abstract class Mono<T> implements Publisher<T> {
* as long as the companion {@link Publisher} produces an onNext signal and the maximum number of repeats isn't exceeded.
*/
public final Mono<T> repeatWhenEmpty(int maxRepeat, Function<Flux<Long>, ? extends Publisher<?>> repeatFactory) {
- return Mono.defer(() -> {
- Flux<Long> iterations;
-
- if(maxRepeat == Integer.MAX_VALUE) {
- iterations = Flux.fromStream(LongStream.range(0, Long.MAX_VALUE).boxed());
+ return Mono.defer(() -> this.repeatWhen(o -> {
+ if (maxRepeat == Integer.MAX_VALUE) {
+ return repeatFactory.apply(o.index().map(Tuple2::getT1));
}
else {
- iterations = Flux
- .range(0, maxRepeat)
- .map(Integer::longValue)
- .concatWith(Flux.error(new IllegalStateException("Exceeded maximum number of repeats"), true));
+ return repeatFactory.apply(o.index().map(Tuple2::getT1)
+ .take(maxRepeat)
+ .concatWith(Flux.error(new IllegalStateException("Exceeded maximum number of repeats"), true)));
}
-
- return this.repeatWhen(o -> repeatFactory.apply(o
- .zipWith(iterations, 1, (c, i) -> i)))
- .next();
- });
+ }).next());
}
diff --git a/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java b/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java
index 3bff20b94..e000821f5 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java
@@ -18,8 +18,10 @@ package reactor.core.publisher;
import org.junit.Assert;
import org.junit.Test;
+import reactor.test.StepVerifier;
import reactor.test.subscriber.AssertSubscriber;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -91,4 +93,13 @@ public class MonoRepeatWhenEmptyTest {
Assert.assertEquals(Arrays.asList(0L, 1L), iterations);
}
+ @Test(timeout = 1000L)
+ public void gh2196_discardHandlerHang() {
+ StepVerifier.create(Mono.empty()
+ .repeatWhenEmpty(f -> f.next())
+ .doOnDiscard(Object.class, System.out::println))
+ .thenAwait()
+ .thenCancel()
+ .verify();
+ }
} | ['reactor-core/src/test/java/reactor/core/publisher/MonoRepeatWhenEmptyTest.java', 'reactor-core/src/main/java/reactor/core/publisher/Mono.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,953,786 | 734,107 | 104,103 | 385 | 947 | 237 | 30 | 1 | 1,209 | 139 | 252 | 28 | 0 | 1 | 2020-06-23T14:00:57 | 4,602 | Java | {'Java': 8928316, 'Kotlin': 48023} | Apache License 2.0 |
3,322 | vespa-engine/vespa/14164/14153 | vespa-engine | vespa | https://github.com/vespa-engine/vespa/issues/14153 | https://github.com/vespa-engine/vespa/pull/14164 | https://github.com/vespa-engine/vespa/pull/14164 | 1 | resolves | bm25 does not give any relevance score for fields defined outside the document | /search/?yql=select%20*%20from%20sources%20*%20where%20titlebest%20contains%20"best"%3B&ranking=titlebest
=>
`"relevance": 0,`
/search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20"best"%3B&ranking=title
=>
`"relevance": 0.31872690041420326,`
Schema:
```
schema music {
document music {
field title type string {
indexing: summary | index
index: enable-bm25
}
}
field titlebest type string {
stemming: best
indexing: input title | summary | index
index: enable-bm25
}
rank-profile title {
first-phase {
expression: bm25(title)
}
}
rank-profile titlebest {`
first-phase {
expression: bm25(titlebest)
}
}
}
``` | f454184d22c6c46d23710f7cfda988ee40efa641 | 5fa9bce02e30aa93cf986a3d946363df35a50cc0 | https://github.com/vespa-engine/vespa/compare/f454184d22c6c46d23710f7cfda988ee40efa641...5fa9bce02e30aa93cf986a3d946363df35a50cc0 | diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/Search.java b/config-model/src/main/java/com/yahoo/searchdefinition/Search.java
index 0ab8a2308a4..3a60a75f75f 100644
--- a/config-model/src/main/java/com/yahoo/searchdefinition/Search.java
+++ b/config-model/src/main/java/com/yahoo/searchdefinition/Search.java
@@ -394,6 +394,9 @@ public class Search implements ImmutableSearch {
if (current.isPrefix()) {
consolidated.setPrefix(true);
}
+ if (current.useInterleavedFeatures()) {
+ consolidated.setInterleavedFeatures(true);
+ }
if (consolidated.getRankType() == null) {
consolidated.setRankType(current.getRankType());
diff --git a/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java b/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java
index f992d5ee0ba..1734c58ddc9 100644
--- a/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java
@@ -8,7 +8,9 @@ import org.junit.Test;
import java.io.IOException;
+import static com.yahoo.config.model.test.TestUtil.joinLines;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
/**
* Rank settings
@@ -34,4 +36,27 @@ public class IndexSettingsTestCase extends SchemaTestCase {
assertEquals(Stemming.MULTIPLE, multiStemmed.getStemming(search));
}
+ @Test
+ public void requireThatInterlavedFeaturesAreSetOnExtraField() throws ParseException {
+ SearchBuilder builder = SearchBuilder.createFromString(joinLines(
+ "search test {",
+ " document test {",
+ " field content type string {",
+ " indexing: index | summary",
+ " index: enable-bm25",
+ " }",
+ " }",
+ " field extra type string {",
+ " indexing: input content | index | summary",
+ " index: enable-bm25",
+ " }",
+ "}"
+ ));
+ Search search = builder.getSearch();
+ Index contentIndex = search.getIndex("content");
+ assertTrue(contentIndex.useInterleavedFeatures());
+ Index extraIndex = search.getIndex("extra");
+ assertTrue(extraIndex.useInterleavedFeatures());
+ }
+
} | ['config-model/src/main/java/com/yahoo/searchdefinition/Search.java', 'config-model/src/test/java/com/yahoo/searchdefinition/IndexSettingsTestCase.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 20,798,737 | 4,247,905 | 549,412 | 5,592 | 127 | 22 | 3 | 1 | 748 | 66 | 222 | 35 | 0 | 1 | 2020-08-26T10:58:41 | 4,562 | Java | {'Java': 42949616, 'C++': 30143509, 'Go': 685517, 'CMake': 604483, 'Shell': 271272, 'JavaScript': 73336, 'Python': 56537, 'C': 54788, 'HTML': 54520, 'CSS': 40916, 'TLA': 36167, 'Perl': 23134, 'Roff': 17506, 'Yacc': 14735, 'Objective-C': 12547, 'Lex': 11499, 'Ruby': 10690, 'ANTLR': 7984, 'LLVM': 6152, 'Makefile': 5906, 'PigLatin': 5724, 'Raku': 3729, 'GAP': 3312, 'Kotlin': 1870, 'Emacs Lisp': 91} | Apache License 2.0 |
3,812 | muzei/muzei/46/45 | muzei | muzei | https://github.com/muzei/muzei/issues/45 | https://github.com/muzei/muzei/pull/46 | https://github.com/muzei/muzei/pull/46 | 2 | fixes | Bad image URL crashes Muzei | I'm writing an extension, which pulls the image URLs from a web site. When the URL is formatted incorrectly, Muzei crashes. It should be made more error tolerant. Most of the time this shouldn't be a problem, but if the web site designer changes the site, the code retrieving the image URLs could be bad/incorrect until the extension can be updated.
To duplicate, publish artwork using a URI like "www.example.com".
Here is the stack trace:
03-06 22:48:08.053 20350-5944/? E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[TaskQueueService]
Process: net.nurik.roman.muzei, PID: 20350
java.lang.NullPointerException
at com.google.android.apps.muzei.util.IOUtil.readFullyWriteToOutputStream(IOUtil.java:210)
at com.google.android.apps.muzei.util.IOUtil.readFullyWriteToFile(IOUtil.java:202)
at com.google.android.apps.muzei.ArtworkCache.maybeDownloadCurrentArtworkSync(ArtworkCache.java:122)
at com.google.android.apps.muzei.TaskQueueService.onHandleIntent(TaskQueueService.java:56)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
| a9d2ccfaeccabad26f9c6eba26355882654cc4c1 | bb64b9572c3c66d656bd6301fc231cec083d1111 | https://github.com/muzei/muzei/compare/a9d2ccfaeccabad26f9c6eba26355882654cc4c1...bb64b9572c3c66d656bd6301fc231cec083d1111 | diff --git a/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java b/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java
index efffc15e..225ae342 100644
--- a/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java
+++ b/main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java
@@ -58,6 +58,10 @@ public class IOUtil {
}
String scheme = uri.getScheme();
+ if (scheme == null) {
+ throw new OpenUriException(false, new IOException("Uri had no scheme"));
+ }
+
InputStream in = null;
if ("content".equals(scheme)) {
try {
@@ -118,7 +122,6 @@ public class IOUtil {
} catch (MalformedURLException e) {
throw new OpenUriException(false, e);
-
} catch (IOException e) {
if (conn != null && responseCode > 0) {
throw new OpenUriException( | ['main/src/main/java/com/google/android/apps/muzei/util/IOUtil.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 552,584 | 113,670 | 14,734 | 78 | 131 | 26 | 5 | 1 | 1,328 | 103 | 311 | 17 | 0 | 0 | 2014-03-09T23:37:23 | 4,519 | Kotlin | {'Kotlin': 1044847, 'Python': 283216, 'Java': 116450, 'HTML': 36975, 'JavaScript': 32588, 'SCSS': 30501, 'CSS': 23867} | Apache License 2.0 |
1,441 | geysermc/geyser/316/307 | geysermc | geyser | https://github.com/GeyserMC/Geyser/issues/307 | https://github.com/GeyserMC/Geyser/pull/316 | https://github.com/GeyserMC/Geyser/pull/316 | 1 | closes | Xbox, Switch crashes when loading in a dimension that is not the overworld | <!--- Please follow this format COMPLETELY and make sure the bug you are reporting has not been reported yet. Reports should contain as much information or context as possible to help us find the problem. Simply creating an issue on a vague topic will not help us at all, and if you are unsure if something should belong here, please contact us on [Discord](http://discord.geysermc.org).-->
<!--- Issues pertaining to connection problem, or anything of that covered on the [Common Issues](https://github.com/GeyserMC/Geyser/wiki/Common-Issues) do not belong here and only clutter this issue tracker. -->
**Describe the bug**
Xbox crashes when the player is joining into The Nether or The End.
**To Reproduce**
Join Geyser on Xbox with your player loading into The End or The Nether.
**Expected behavior**
Minecraft does not crash.
**Server Version**
Paper 161
**Geyser Version**
Master 25, Inventory 11
**Minecraft: Bedrock Edition Version**
1.14.30 Xbox
| e5f08403357add9dc1d1800b9c117d3864ab7f83 | f04a267d98c1edc03ab5af0e2d392992f4c78deb | https://github.com/geysermc/geyser/compare/e5f08403357add9dc1d1800b9c117d3864ab7f83...f04a267d98c1edc03ab5af0e2d392992f4c78deb | diff --git a/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java b/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java
index 6fffcda8..cf6c2ee2 100644
--- a/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java
+++ b/connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java
@@ -27,6 +27,7 @@ package org.geysermc.connector.network;
import com.nukkitx.protocol.bedrock.BedrockPacket;
import com.nukkitx.protocol.bedrock.packet.*;
+import org.geysermc.common.AuthType;
import org.geysermc.common.IGeyserConfiguration;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
@@ -107,7 +108,7 @@ public class UpstreamPacketHandler extends LoggingPacketHandler {
@Override
public boolean handle(MovePlayerPacket packet) {
- if (!session.isLoggedIn() && !session.isLoggingIn()) {
+ if (!session.isLoggedIn() && !session.isLoggingIn() && session.getConnector().getAuthType() == AuthType.ONLINE) {
// TODO it is safer to key authentication on something that won't change (UUID, not username)
if (!couldLoginUserByName(session.getAuthData().getName())) {
LoginEncryptionUtils.showLoginWindow(session);
diff --git a/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java b/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java
index 749dacb2..d5b2e75d 100644
--- a/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java
+++ b/connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java
@@ -149,15 +149,6 @@ public class GeyserSession implements CommandSender {
public void connect(RemoteServer remoteServer) {
startGame();
this.remoteServer = remoteServer;
- if (connector.getAuthType() != AuthType.ONLINE) {
- connector.getLogger().info(
- "Attempting to login using " + connector.getAuthType().name().toLowerCase() + " mode... " +
- (connector.getAuthType() == AuthType.OFFLINE ?
- "authentication is disabled." : "authentication will be encrypted"
- )
- );
- authenticate(authData.getName());
- }
ChunkUtils.sendEmptyChunks(this, playerEntity.getPosition().toInt(), 0, false);
@@ -174,6 +165,18 @@ public class GeyserSession implements CommandSender {
upstream.sendPacket(playStatusPacket);
}
+ public void login() {
+ if (connector.getAuthType() != AuthType.ONLINE) {
+ connector.getLogger().info(
+ "Attempting to login using " + connector.getAuthType().name().toLowerCase() + " mode... " +
+ (connector.getAuthType() == AuthType.OFFLINE ?
+ "authentication is disabled." : "authentication will be encrypted"
+ )
+ );
+ authenticate(authData.getName());
+ }
+ }
+
public void authenticate(String username) {
authenticate(username, "");
}
@@ -184,7 +187,7 @@ public class GeyserSession implements CommandSender {
return;
}
- loggedIn = true;
+ loggingIn = true;
// new thread so clients don't timeout
new Thread(() -> {
try {
diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java
index 54a5112d..87da2d00 100644
--- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java
+++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java
@@ -40,6 +40,7 @@ public class BedrockSetLocalPlayerAsInitializedTranslator extends PacketTranslat
if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) {
if (!session.getUpstream().isInitialized()) {
session.getUpstream().setInitialized(true);
+ session.login();
for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) {
if (!entity.isValid()) {
diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java
index 0d6caaed..34fe2271 100644
--- a/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java
+++ b/connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java
@@ -29,7 +29,6 @@ import org.geysermc.connector.entity.PlayerEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
-import org.geysermc.connector.utils.ChunkUtils;
import org.geysermc.connector.utils.DimensionUtils;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerJoinGamePacket;
@@ -69,7 +68,6 @@ public class JavaJoinGameTranslator extends PacketTranslator<ServerJoinGamePacke
session.setRenderDistance(packet.getViewDistance());
if (DimensionUtils.javaToBedrock(packet.getDimension()) != entity.getDimension()) {
- ChunkUtils.sendEmptyChunks(session, entity.getPosition().toInt(), 3, true);
DimensionUtils.switchDimension(session, packet.getDimension());
}
} | ['connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockSetLocalPlayerAsInitializedTranslator.java', 'connector/src/main/java/org/geysermc/connector/network/translators/java/JavaJoinGameTranslator.java', 'connector/src/main/java/org/geysermc/connector/network/session/GeyserSession.java', 'connector/src/main/java/org/geysermc/connector/network/UpstreamPacketHandler.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 762,725 | 164,911 | 19,418 | 233 | 1,454 | 272 | 29 | 4 | 983 | 144 | 224 | 22 | 2 | 0 | 2020-04-11T19:25:32 | 4,071 | Java | {'Java': 3890490, 'Kotlin': 27417} | MIT License |
1,439 | geysermc/geyser/203/207 | geysermc | geyser | https://github.com/GeyserMC/Geyser/issues/207 | https://github.com/GeyserMC/Geyser/pull/203 | https://github.com/GeyserMC/Geyser/pull/203#issuecomment-598746853 | 2 | fix | Xbox cannot seem to join the server but other platforms can | **Describe the bug**
Ive attempted to get my xbox to join my Geyser server running the inventory branch and floodgate and i receive the error "We were unable to connect you."
**To Reproduce**
Steps to reproduce the behavior:
1. Attempt to join the Geyser Lan game on a xbox
4. See error
**Expected behavior**
To be able to join
Add any other context about the problem here.
I attempted to join with the Xbox Geyser branch but it didnt seem to work either
| 105ce2b3b59a40c8438a88207c33d00dccd393a6 | 9f36ba14cd32c7e1f9f0dac21602dfb2f711a658 | https://github.com/geysermc/geyser/compare/105ce2b3b59a40c8438a88207c33d00dccd393a6...9f36ba14cd32c7e1f9f0dac21602dfb2f711a658 | diff --git a/common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java b/common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java
index ee14fc90..0705d169 100644
--- a/common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java
+++ b/common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java
@@ -42,7 +42,8 @@ public enum DeviceOS {
DEDICATED,
ORBIS,
NX,
- SWITCH;
+ SWITCH,
+ XBOX_ONE;
private static final DeviceOS[] VALUES = values();
| ['common/src/main/java/org/geysermc/floodgate/util/DeviceOS.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 690,628 | 148,188 | 17,416 | 215 | 40 | 11 | 3 | 1 | 471 | 83 | 109 | 14 | 0 | 0 | 2020-03-11T22:05:36 | 4,071 | Java | {'Java': 3890490, 'Kotlin': 27417} | MIT License |
1,440 | geysermc/geyser/347/333 | geysermc | geyser | https://github.com/GeyserMC/Geyser/issues/333 | https://github.com/GeyserMC/Geyser/pull/347 | https://github.com/GeyserMC/Geyser/pull/347 | 2 | fixes | Pistons disappear from inventory when getting them from creative tab | **Description**
Piston items dissapear from inventory after obtaining them via creative tab.
(getting them from the ground works well both on creative and survival)
**To Reproduce**
1. Make sure your gamemode is creative
2. Find piston or sticky piston in your creative tab
3. Try to put it to your inventory
**Expected behavior**
Pistons shouldn't disappear from your inventory.
**Server Version**
Paper 1.15.2 git-183
**Geyser Version**
inventory #14
**Minecraft: Bedrock Edition Version**
1.14.30
| 1cb2e658e02f60db32b280ec70d1132821d15de8 | d7b8f088990fcfdc9748eadbce47766b21fb6aaa | https://github.com/geysermc/geyser/compare/1cb2e658e02f60db32b280ec70d1132821d15de8...d7b8f088990fcfdc9748eadbce47766b21fb6aaa | diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java
index 8ca95159..0bcbf4b7 100644
--- a/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java
+++ b/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java
@@ -118,6 +118,13 @@ public class ItemTranslator {
return itemEntry;
}
}
+ // If item find was unsuccessful first time, we try again while ignoring damage
+ // Fixes piston, sticky pistons, dispensers and droppers turning into air from creative inventory
+ for (ItemEntry itemEntry : Toolbox.ITEM_ENTRIES.values()) {
+ if (itemEntry.getBedrockId() == data.getId()) {
+ return itemEntry;
+ }
+ }
GeyserConnector.getInstance().getLogger().debug("Missing mapping for bedrock item " + data.getId() + ":" + data.getDamage());
return ItemEntry.AIR; | ['connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 971,532 | 209,382 | 23,920 | 281 | 386 | 76 | 7 | 1 | 525 | 73 | 123 | 21 | 0 | 0 | 2020-04-15T19:27:55 | 4,071 | Java | {'Java': 3890490, 'Kotlin': 27417} | MIT License |
1,444 | geysermc/geyser/170/157 | geysermc | geyser | https://github.com/GeyserMC/Geyser/issues/157 | https://github.com/GeyserMC/Geyser/pull/170 | https://github.com/GeyserMC/Geyser/pull/170 | 2 | fixes | Swimming Action Bugged | **Describe the bug**
Once you enter swimming mode, you can't exit it resulting in death by Drowning as you cannot reach land.
**To Reproduce**
Steps to reproduce the behavior:
1. Dive into an Ocean
2. Enter Swimming Mode
4. Try exiting Swimming Mode
**Expected behavior**
Enter and exit swimming mode based on Client Input.
**Screenshots**
If necessary, I will upload footage of the bug in action.
**Server version**
This server is running Paper version git-Paper-98 (MC: 1.15.2) (Implementing API version 1.15.2-R0.1-SNAPSHOT)
**Geyser version**
Jenkins Latest
**Bedrock version**
1.14.2
**Additional context**
currently nothing else to say. | 5913cb616419f5abd1e566d5eddaedc1acbfe6b5 | 2d0a5841064e06b9d05cf85617b29c84b8dfc94b | https://github.com/geysermc/geyser/compare/5913cb616419f5abd1e566d5eddaedc1acbfe6b5...2d0a5841064e06b9d05cf85617b29c84b8dfc94b | diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java
index 56e573c6..e5bec698 100644
--- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java
+++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java
@@ -56,6 +56,14 @@ public class BedrockActionTranslator extends PacketTranslator<PlayerActionPacket
// Don't put anything here as respawn is already handled
// in BedrockRespawnTranslator
break;
+ case START_SWIMMING:
+ ClientPlayerStatePacket startSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING);
+ session.getDownstream().getSession().send(startSwimPacket);
+ break;
+ case STOP_SWIMMING:
+ ClientPlayerStatePacket stopSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.STOP_SPRINTING);
+ session.getDownstream().getSession().send(stopSwimPacket);
+ break;
case START_GLIDE:
case STOP_GLIDE:
ClientPlayerStatePacket glidePacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_ELYTRA_FLYING); | ['connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 648,516 | 139,188 | 16,321 | 205 | 555 | 107 | 8 | 1 | 677 | 95 | 167 | 26 | 0 | 0 | 2020-02-15T10:21:10 | 4,071 | Java | {'Java': 3890490, 'Kotlin': 27417} | MIT License |
1,442 | geysermc/geyser/305/218 | geysermc | geyser | https://github.com/GeyserMC/Geyser/issues/218 | https://github.com/GeyserMC/Geyser/pull/305 | https://github.com/GeyserMC/Geyser/pull/305 | 1 | fixes | Bricks slab and trap door can't be placed properly | **Describe the bug**
When player place a bricks slab or a trap door it just fall down.
More information in the video
[video](https://streamable.com/zptei)
**To Reproduce**
Steps to reproduce the behavior:
1. Setup server with geyser
2. Place a brick slab or a trap door
3. See error
**Expected behavior**
Brick slab and trap door can stay where they are and not falling down
**Screenshots**
See video above
**Server version**
paper 1.15 latest
**Geyser version**
Jenkins inventory branch latest
**Bedrock version**
latest
| 27f4879f0a9db8f620c769bda347d672c83f463b | 23d98bb25f89919ff4f913f9bd7bf411cdec4d3b | https://github.com/geysermc/geyser/compare/27f4879f0a9db8f620c769bda347d672c83f463b...23d98bb25f89919ff4f913f9bd7bf411cdec4d3b | diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java
index ebc45ff0..206f42d1 100644
--- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java
+++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java
@@ -33,12 +33,10 @@ import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;
-import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;
import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction;
import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;
import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerActionPacket;
-import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;
import com.nukkitx.math.vector.Vector3i;
import com.nukkitx.protocol.bedrock.packet.PlayStatusPacket;
@@ -101,10 +99,7 @@ public class BedrockActionTranslator extends PacketTranslator<PlayerActionPacket
session.getDownstream().getSession().send(stopSleepingPacket);
break;
case BLOCK_INTERACT:
- ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(position,
- BlockFace.values()[packet.getFace()],
- Hand.MAIN_HAND, 0, 0, 0, false);
- session.getDownstream().getSession().send(blockPacket);
+ // Handled in BedrockInventoryTransactionTranslator
break;
case START_BREAK:
ClientPlayerActionPacket startBreakingPacket = new ClientPlayerActionPacket(PlayerAction.START_DIGGING, new Position(packet.getBlockPosition().getX(),
diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java
index c9547514..94903246 100644
--- a/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java
+++ b/connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java
@@ -25,6 +25,7 @@
package org.geysermc.connector.network.translators.bedrock;
+import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
@@ -41,7 +42,6 @@ import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlaye
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.packet.InventoryTransactionPacket;
-import org.geysermc.connector.network.translators.block.BlockTranslator;
@Translator(packet = InventoryTransactionPacket.class)
public class BedrockInventoryTransactionTranslator extends PacketTranslator<InventoryTransactionPacket> {
@@ -50,14 +50,26 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator<Inve
public void translate(InventoryTransactionPacket packet, GeyserSession session) {
switch (packet.getTransactionType()) {
case ITEM_USE:
- if (packet.getActionType() == 1) {
- ClientPlayerUseItemPacket useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND);
- session.getDownstream().getSession().send(useItemPacket);
- } else if (packet.getActionType() == 2) {
- PlayerAction action = session.getGameMode() == GameMode.CREATIVE ? PlayerAction.START_DIGGING : PlayerAction.FINISH_DIGGING;
- Position pos = new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ());
- ClientPlayerActionPacket breakPacket = new ClientPlayerActionPacket(action, pos, BlockFace.values()[packet.getFace()]);
- session.getDownstream().getSession().send(breakPacket);
+ switch (packet.getActionType()) {
+ case 0:
+ ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket(
+ new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
+ BlockFace.values()[packet.getFace()],
+ Hand.MAIN_HAND,
+ packet.getClickPosition().getX(), packet.getClickPosition().getY(), packet.getClickPosition().getZ(),
+ false);
+ session.getDownstream().getSession().send(blockPacket);
+ break;
+ case 1:
+ ClientPlayerUseItemPacket useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND);
+ session.getDownstream().getSession().send(useItemPacket);
+ break;
+ case 2:
+ PlayerAction action = session.getGameMode() == GameMode.CREATIVE ? PlayerAction.START_DIGGING : PlayerAction.FINISH_DIGGING;
+ Position pos = new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ());
+ ClientPlayerActionPacket breakPacket = new ClientPlayerActionPacket(action, pos, BlockFace.values()[packet.getFace()]);
+ session.getDownstream().getSession().send(breakPacket);
+ break;
}
break;
case ITEM_RELEASE: | ['connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockInventoryTransactionTranslator.java', 'connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockActionTranslator.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 762,283 | 164,888 | 19,409 | 233 | 3,117 | 546 | 37 | 2 | 557 | 81 | 132 | 28 | 1 | 0 | 2020-04-10T18:50:00 | 4,071 | Java | {'Java': 3890490, 'Kotlin': 27417} | MIT License |
1,443 | geysermc/geyser/274/253 | geysermc | geyser | https://github.com/GeyserMC/Geyser/issues/253 | https://github.com/GeyserMC/Geyser/pull/274 | https://github.com/GeyserMC/Geyser/pull/274 | 1 | fixes | Geyser does not shut down with /geyser shutdown, or Control-C after a player has joined | **Describe the bug**
`/geyser shutdown` does not fully shutdown Geyser after a player has joined through Geyser - in Linux, two Control-Cs are required to terminate the process.
**To Reproduce**
Steps to reproduce the behavior:
1. Run Geyser
2. Join Geyser
3. Try to shutdown Geyser
**Expected behavior**
Geyser cleanly shuts down.
**Geyser version**
Jenkins Inventory Latest
| ade40d5a8b34e848b9c71d16427317e429bc6f07 | 8e1b5de4b0143ad980a0fc71f3bbc90b324289f3 | https://github.com/geysermc/geyser/compare/ade40d5a8b34e848b9c71d16427317e429bc6f07...8e1b5de4b0143ad980a0fc71f3bbc90b324289f3 | diff --git a/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java b/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java
index 7df8a4ef..ac21215c 100644
--- a/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java
+++ b/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java
@@ -52,7 +52,7 @@ public class GeyserLogger extends SimpleTerminalConsole implements IGeyserLogger
@Override
protected void shutdown() {
- GeyserConnector.getInstance().shutdown();
+ GeyserConnector.getInstance().getBootstrap().onDisable();
}
@Override
diff --git a/connector/src/main/java/org/geysermc/connector/GeyserConnector.java b/connector/src/main/java/org/geysermc/connector/GeyserConnector.java
index d33bda9a..714bd5ae 100644
--- a/connector/src/main/java/org/geysermc/connector/GeyserConnector.java
+++ b/connector/src/main/java/org/geysermc/connector/GeyserConnector.java
@@ -49,6 +49,7 @@ import java.net.InetSocketAddress;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.CompletableFuture;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -142,6 +143,40 @@ public class GeyserConnector {
bootstrap.getGeyserLogger().info("Shutting down Geyser.");
shuttingDown = true;
+ if (players.size() >= 1) {
+ bootstrap.getGeyserLogger().info("Kicking " + players.size() + " player(s)");
+
+ for (GeyserSession playerSession : players.values()) {
+ playerSession.disconnect("Geyser Proxy shutting down.");
+ }
+
+ CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {
+ @Override
+ public void run() {
+ // Simulate a long-running Job
+ try {
+ while (true) {
+ if (players.size() == 0) {
+ return;
+ }
+
+ TimeUnit.MILLISECONDS.sleep(100);
+ }
+ } catch (InterruptedException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ });
+
+ // Block and wait for the future to complete
+ try {
+ future.get();
+ bootstrap.getGeyserLogger().info("Kicked all players");
+ } catch (Exception e) {
+ // Quietly fail
+ }
+ }
+
generalThreadPool.shutdown();
bedrockServer.close();
players.clear();
@@ -149,6 +184,8 @@ public class GeyserConnector {
authType = null;
commandMap.getCommands().clear();
commandMap = null;
+
+ bootstrap.getGeyserLogger().info("Geyser shutdown successfully.");
}
public void addPlayer(GeyserSession player) {
diff --git a/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java b/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java
index 4694d0fd..2222cdef 100644
--- a/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java
+++ b/connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java
@@ -48,6 +48,11 @@ public class StopCommand extends GeyserCommand {
if (!sender.isConsole() && connector.getPlatformType() == PlatformType.STANDALONE) {
return;
}
+
connector.shutdown();
+
+ if (connector.getPlatformType() == PlatformType.STANDALONE) {
+ System.exit(0);
+ }
}
} | ['bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/console/GeyserLogger.java', 'connector/src/main/java/org/geysermc/connector/command/defaults/StopCommand.java', 'connector/src/main/java/org/geysermc/connector/GeyserConnector.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 738,490 | 160,116 | 18,755 | 230 | 1,594 | 271 | 44 | 3 | 393 | 57 | 98 | 15 | 0 | 0 | 2020-04-06T13:38:06 | 4,071 | Java | {'Java': 3890490, 'Kotlin': 27417} | MIT License |
248 | killbill/killbill/1289/1288 | killbill | killbill | https://github.com/killbill/killbill/issues/1288 | https://github.com/killbill/killbill/pull/1289 | https://github.com/killbill/killbill/pull/1289 | 1 | fixes | NPE in /1.0/kb/invoices/:invoiceId/payments | Aborted `payment_attempts` can have a corresponding row in `invoice_payments` with a `NULL` `payment_id` (note that the `payment_cookie_id` i.e. the `payment_attempts. transaction_external_key` won't be `NULL` though):
```
MySQL [killbill]> select * from invoice_payments order by record_id desc limit 1\\G
*************************** 1. row ***************************
record_id: 3
id: e7f6b1d0-3823-4c5b-9226-12327af64492
type: ATTEMPT
invoice_id: 742a1a60-58f8-4ed2-b9db-b1816a741f44
payment_id: NULL
payment_date: 2012-05-02 00:37:59
amount: 0.000000000
currency: USD
processed_currency: USD
payment_cookie_id: bac67833-ac7c-458d-8e2a-659c0cdfb0b6
linked_invoice_payment_id: NULL
success: 0
created_by: PaymentRequestProcessor
created_date: 2012-05-02 00:37:59
account_record_id: 1
tenant_record_id: 0
1 row in set (0.00 sec)
```
This can trigger a NPE here: https://github.com/killbill/killbill/blob/1be24a4a144e80abcf45a5982deb7c1f2e22aa3b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java#L623
```
java.lang.NullPointerException: null
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:877)
at com.google.common.collect.ImmutableSet$Builder.add(ImmutableSet.java:483)
at com.google.common.collect.ImmutableSet.copyOf(ImmutableSet.java:248)
at com.google.common.collect.ImmutableSet.copyOf(ImmutableSet.java:230)
at org.killbill.billing.jaxrs.resources.InvoiceResource.getPaymentsForInvoice(InvoiceResource.java:620)
``` | 1be24a4a144e80abcf45a5982deb7c1f2e22aa3b | 35e7720d186913255dab22053598ebfed436a7c7 | https://github.com/killbill/killbill/compare/1be24a4a144e80abcf45a5982deb7c1f2e22aa3b...35e7720d186913255dab22053598ebfed436a7c7 | diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java
index 6d1def04a1..b917d4a740 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java
@@ -25,6 +25,7 @@ import java.net.URI;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -83,6 +84,7 @@ import org.killbill.billing.payment.api.InvoicePaymentApi;
import org.killbill.billing.payment.api.Payment;
import org.killbill.billing.payment.api.PaymentApi;
import org.killbill.billing.payment.api.PaymentApiException;
+import org.killbill.billing.payment.api.PaymentOptions;
import org.killbill.billing.payment.api.PluginProperty;
import org.killbill.billing.tenant.api.TenantApiException;
import org.killbill.billing.tenant.api.TenantKV.TenantKey;
@@ -110,7 +112,6 @@ import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
@@ -617,12 +618,12 @@ public class InvoiceResource extends JaxRsResourceBase {
final Invoice invoice = invoiceApi.getInvoice(invoiceId, tenantContext);
// Extract unique set of paymentId for this invoice
- final Set<UUID> invoicePaymentIds = ImmutableSet.copyOf(Iterables.transform(invoice.getPayments(), new Function<InvoicePayment, UUID>() {
- @Override
- public UUID apply(final InvoicePayment input) {
- return input.getPaymentId();
+ final Set<UUID> invoicePaymentIds = new HashSet<UUID>();
+ for (final InvoicePayment invoicePayment : invoice.getPayments()) {
+ if (invoicePayment.getPaymentId() != null) {
+ invoicePaymentIds.add(invoicePayment.getPaymentId());
}
- }));
+ }
if (invoicePaymentIds.isEmpty()) {
return Response.status(Status.OK).entity(ImmutableList.<InvoicePaymentJson>of()).build();
}
@@ -655,6 +656,7 @@ public class InvoiceResource extends JaxRsResourceBase {
public Response createInstantPayment(@PathParam("invoiceId") final UUID invoiceId,
final InvoicePaymentJson payment,
@QueryParam(QUERY_PAYMENT_EXTERNAL) @DefaultValue("false") final Boolean externalPayment,
+ @QueryParam(QUERY_PAYMENT_CONTROL_PLUGIN_NAME) final List<String> paymentControlPluginNames,
@QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@@ -672,8 +674,9 @@ public class InvoiceResource extends JaxRsResourceBase {
final UUID paymentMethodId = externalPayment ? null :
(payment.getPaymentMethodId() != null ? payment.getPaymentMethodId() : account.getPaymentMethodId());
- final InvoicePayment result = createPurchaseForInvoice(account, invoiceId, payment.getPurchasedAmount(), paymentMethodId, externalPayment,
- payment.getPaymentExternalKey(), null, pluginProperties, callContext);
+ final PaymentOptions paymentOptions = createControlPluginApiPaymentOptions(externalPayment, paymentControlPluginNames);
+ final InvoicePayment result = createPurchaseForInvoice(account, invoiceId, payment.getPurchasedAmount(), paymentMethodId,
+ payment.getPaymentExternalKey(), null, pluginProperties, paymentOptions, callContext);
return result != null ?
uriBuilder.buildResponse(uriInfo, InvoicePaymentResource.class, "getInvoicePayment", result.getPaymentId(), request) :
Response.status(Status.NO_CONTENT).build();
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java
index 2f61bd1b57..4726ddc8ad 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java
@@ -22,7 +22,6 @@ import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URI;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -553,7 +552,35 @@ public abstract class JaxRsResourceBase implements JaxrsResource {
return properties;
}
- protected InvoicePayment createPurchaseForInvoice(final Account account, final UUID invoiceId, final BigDecimal amountToPay, final UUID paymentMethodId, final Boolean externalPayment, final String paymentExternalKey, final String transactionExternalKey, final Iterable<PluginProperty> pluginProperties, final CallContext callContext) throws PaymentApiException {
+ protected InvoicePayment createPurchaseForInvoice(final Account account,
+ final UUID invoiceId,
+ final BigDecimal amountToPay,
+ final UUID paymentMethodId,
+ final Boolean externalPayment,
+ final String paymentExternalKey,
+ final String transactionExternalKey,
+ final Iterable<PluginProperty> pluginProperties,
+ final CallContext callContext) throws PaymentApiException {
+ return createPurchaseForInvoice(account,
+ invoiceId,
+ amountToPay,
+ paymentMethodId,
+ paymentExternalKey,
+ transactionExternalKey,
+ pluginProperties,
+ createInvoicePaymentControlPluginApiPaymentOptions(externalPayment),
+ callContext);
+ }
+
+ protected InvoicePayment createPurchaseForInvoice(final Account account,
+ final UUID invoiceId,
+ final BigDecimal amountToPay,
+ final UUID paymentMethodId,
+ final String paymentExternalKey,
+ final String transactionExternalKey,
+ final Iterable<PluginProperty> pluginProperties,
+ final PaymentOptions paymentOptions,
+ final CallContext callContext) throws PaymentApiException {
try {
return invoicePaymentApi.createPurchaseForInvoicePayment(account,
invoiceId,
@@ -564,7 +591,7 @@ public abstract class JaxRsResourceBase implements JaxrsResource {
paymentExternalKey,
transactionExternalKey,
pluginProperties,
- createInvoicePaymentControlPluginApiPaymentOptions(externalPayment),
+ paymentOptions,
callContext);
} catch (final PaymentApiException e) {
if (e.getCode() == ErrorCode.PAYMENT_PLUGIN_EXCEPTION.getCode() /* &&
diff --git a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java
index 4e8856125a..a0facd3ff9 100644
--- a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java
+++ b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java
@@ -1,6 +1,6 @@
/*
- * Copyright 2014-2015 Groupon, Inc
- * Copyright 2014-2015 The Billing Project, LLC
+ * Copyright 2014-2020 Groupon, Inc
+ * Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
@@ -19,14 +19,12 @@ package org.killbill.billing.jaxrs;
import java.math.BigDecimal;
import java.util.Arrays;
-import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
-import javax.ws.rs.HEAD;
import org.joda.time.DateTime;
import org.killbill.billing.ObjectType;
@@ -38,6 +36,8 @@ import org.killbill.billing.client.model.Tags;
import org.killbill.billing.client.model.gen.Account;
import org.killbill.billing.client.model.gen.AuditLog;
import org.killbill.billing.client.model.gen.ComboPaymentTransaction;
+import org.killbill.billing.client.model.gen.Invoice;
+import org.killbill.billing.client.model.gen.InvoicePayment;
import org.killbill.billing.client.model.gen.Payment;
import org.killbill.billing.client.model.gen.PaymentMethod;
import org.killbill.billing.client.model.gen.PaymentMethodPluginDetail;
@@ -219,6 +219,50 @@ public class TestPayment extends TestJaxrsBase {
}
}
+ @Test(groups = "slow", description = "https://github.com/killbill/killbill/issues/1288")
+ public void testWithAbortedInvoicePayment() throws Exception {
+ mockPaymentProviderPlugin.makeNextPaymentFailWithError();
+ final Account account = createAccountWithPMBundleAndSubscriptionAndWaitForFirstInvoice(false);
+ // Getting Invoice #2 (first after Trial period)
+ final Invoice failedInvoice = accountApi.getInvoicesForAccount(account.getAccountId(), null, null, RequestOptions.empty()).get(1);
+
+ // Verify initial state
+ final Payments initialPayments = accountApi.getPaymentsForAccount(account.getAccountId(), true, false, ImmutableMap.<String, String>of(), AuditLevel.NONE, requestOptions);
+ Assert.assertEquals(initialPayments.size(), 1);
+ Assert.assertEquals(initialPayments.get(0).getTransactions().size(), 1);
+ Assert.assertEquals(initialPayments.get(0).getTransactions().get(0).getStatus(), TransactionStatus.PAYMENT_FAILURE);
+ Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().size(), 2);
+ Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().get(0).getStateName(), "RETRIED");
+ Assert.assertEquals(initialPayments.get(0).getPaymentAttempts().get(1).getStateName(), "SCHEDULED");
+ final InvoicePayments initialInvoicePayments = invoiceApi.getPaymentsForInvoice(failedInvoice.getInvoiceId(), requestOptions);
+ Assert.assertEquals(initialInvoicePayments.size(), 1);
+ Assert.assertEquals(initialInvoicePayments.get(0).getPaymentId(), initialPayments.get(0).getPaymentId());
+
+ // Trigger manually an invoice payment but make the control plugin abort it
+ mockPaymentControlProviderPlugin.setAborted(true);
+ final HashMultimap<String, String> queryParams = HashMultimap.create();
+ queryParams.putAll("controlPluginName", Arrays.<String>asList(MockPaymentControlProviderPlugin.PLUGIN_NAME));
+ final RequestOptions inputOptions = RequestOptions.builder()
+ .withCreatedBy(createdBy)
+ .withReason(reason)
+ .withComment(comment)
+ .withQueryParams(queryParams).build();
+ final InvoicePayment invoicePayment = new InvoicePayment();
+ invoicePayment.setPurchasedAmount(failedInvoice.getBalance());
+ invoicePayment.setAccountId(failedInvoice.getAccountId());
+ invoicePayment.setTargetInvoiceId(failedInvoice.getInvoiceId());
+ final InvoicePayment invoicePaymentNull = invoiceApi.createInstantPayment(failedInvoice.getInvoiceId(), invoicePayment, true, null, inputOptions);
+ Assert.assertNull(invoicePaymentNull);
+
+ // Verify new state
+ final Payments updatedPayments = accountApi.getPaymentsForAccount(account.getAccountId(), true, false, ImmutableMap.<String, String>of(), AuditLevel.NONE, requestOptions);
+ Assert.assertEquals(updatedPayments.size(), 1);
+ Assert.assertEquals(updatedPayments.get(0).getPaymentId(), initialPayments.get(0).getPaymentId());
+ final InvoicePayments updatedInvoicePayments = invoiceApi.getPaymentsForInvoice(failedInvoice.getInvoiceId(), requestOptions);
+ Assert.assertEquals(updatedInvoicePayments.size(), 1);
+ Assert.assertEquals(updatedInvoicePayments.get(0).getPaymentId(), updatedPayments.get(0).getPaymentId());
+ }
+
@Test(groups = "slow")
public void testWithFailedPaymentAndScheduledAttemptsGetInvoicePayment() throws Exception {
mockPaymentProviderPlugin.makeNextPaymentFailWithError(); | ['profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestPayment.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/JaxRsResourceBase.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 6,411,254 | 1,198,901 | 138,507 | 1,026 | 4,350 | 551 | 52 | 2 | 1,747 | 104 | 470 | 34 | 1 | 2 | 2020-04-02T10:59:13 | 4,053 | Java | {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593} | Apache License 2.0 |
247 | killbill/killbill/1371/1370 | killbill | killbill | https://github.com/killbill/killbill/issues/1370 | https://github.com/killbill/killbill/pull/1371 | https://github.com/killbill/killbill/pull/1371 | 1 | fixes | Sub-millisecond precision in catalog date can lead to duplicate invoice items | If the catalog effective date is set to `2020-09-16T10:34:25.348646Z` for instance, the DDL must support sub-millisecond precision (by default, it doesn't). | 0b850e9bcf5b632c2422691d6f2c731d179f4f84 | 2796799bb8a7e73acfde0dfd1d318852ade8ca8d | https://github.com/killbill/killbill/compare/0b850e9bcf5b632c2422691d6f2c731d179f4f84...2796799bb8a7e73acfde0dfd1d318852ade8ca8d | diff --git a/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java b/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java
index 398f49bb61..65c0cd69cb 100644
--- a/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java
+++ b/invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java
@@ -25,6 +25,7 @@ import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
+import org.joda.time.Seconds;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
@@ -127,7 +128,11 @@ public class InvoiceItemCatalogBase extends InvoiceItemBase implements InvoiceIt
return false;
}
final InvoiceItemCatalogBase that = (InvoiceItemCatalogBase) o;
- if (catalogEffectiveDate != null && that.catalogEffectiveDate != null && catalogEffectiveDate.compareTo(that.catalogEffectiveDate) != 0) {
+ if (catalogEffectiveDate != null &&
+ that.catalogEffectiveDate != null &&
+ catalogEffectiveDate.compareTo(that.catalogEffectiveDate) != 0 &&
+ // https://github.com/killbill/killbill/issues/1370
+ Math.abs(Seconds.secondsBetween(catalogEffectiveDate, that.catalogEffectiveDate).getSeconds()) != 0) {
return false;
} else if (catalogEffectiveDate == null || that.catalogEffectiveDate == null) {
/* At least one such item has a 'null' catalogEffectiveDate, reflecting a prior 0.22 release item
diff --git a/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java b/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java
index 43e974cdd4..8c1bbd0698 100644
--- a/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java
+++ b/invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java
@@ -22,6 +22,7 @@ import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
+import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.killbill.billing.invoice.model.TaxInvoiceItem;
import org.testng.Assert;
@@ -243,6 +244,29 @@ public class TestInvoiceItemDao extends InvoiceTestSuiteWithEmbeddedDB {
createAndVerifyExternalCharge(new BigDecimal("10.2"), Currency.MGA);
}
+ @Test(groups = "slow", description = "https://github.com/killbill/killbill/issues/1370")
+ public void testFixedPriceWithSubMillisecondCatalogEffectiveDateInvoiceSqlDao() throws EntityPersistenceException {
+ final UUID invoiceId = UUID.randomUUID();
+ final UUID accountId = account.getId();
+ final LocalDate startDate = new LocalDate(2012, 4, 1);
+
+ final InvoiceItem fixedPriceInvoiceItem = new FixedPriceInvoiceItem(invoiceId,
+ accountId,
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ "test product",
+ "test plan",
+ "test phase",
+ new DateTime("2020-09-16T10:34:25.348646Z"),
+ startDate,
+ TEN,
+ Currency.USD);
+ invoiceUtil.createInvoiceItem(fixedPriceInvoiceItem, context);
+
+ final InvoiceItemModelDao savedItem = invoiceUtil.getInvoiceItemById(fixedPriceInvoiceItem.getId(), context);
+ assertSameInvoiceItem(fixedPriceInvoiceItem, savedItem);
+ }
+
private void createAndVerifyExternalCharge(final BigDecimal amount, final Currency currency) throws EntityPersistenceException {
final InvoiceItem externalChargeInvoiceItem = new ExternalChargeInvoiceItem(UUID.randomUUID(), account.getId(), UUID.randomUUID(),
UUID.randomUUID().toString(), new LocalDate(2012, 4, 1), new LocalDate(2012, 5, 1), amount, currency, null); | ['invoice/src/test/java/org/killbill/billing/invoice/dao/TestInvoiceItemDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/model/InvoiceItemCatalogBase.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 6,434,529 | 1,203,210 | 139,094 | 1,027 | 533 | 113 | 7 | 1 | 156 | 21 | 46 | 1 | 0 | 0 | 2020-10-07T16:22:07 | 4,053 | Java | {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593} | Apache License 2.0 |
246 | killbill/killbill/1427/1422 | killbill | killbill | https://github.com/killbill/killbill/issues/1422 | https://github.com/killbill/killbill/pull/1427 | https://github.com/killbill/killbill/pull/1427 | 1 | fixes | Search endpoint issue | ```
GET http://127.0.0.1:8080/1.0/kb/accounts/search/john?offset=0&limit=1&accountWithBalance=true&accountWithBalanceAndCBA=false
```
Results in:
```
org.glassfish.jersey.server.internal.process.MappableException: java.lang.IllegalArgumentException: The template variable 'searchKey' has no value
```
It looks like we need to update `JaxrsUriBuilder` and pass the search key as such (instead of params):
```
uriBuilder.resolveTemplate("searchKey", "john")
```
This is likely a regression from https://github.com/killbill/killbill/issues/1384. | 535e3f5278786dae29bef6da40bd0ca1cff46426 | d7661c8d75f73248928f0e2b1e5c542f428e4b1f | https://github.com/killbill/killbill/compare/535e3f5278786dae29bef6da40bd0ca1cff46426...d7661c8d75f73248928f0e2b1e5c542f428e4b1f | diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java
index 0d414e234a..f86d400bf5 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java
@@ -230,9 +230,14 @@ public class AccountResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<Account> accounts = accountUserApi.getAccounts(offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(AccountResource.class, "getAccounts", accounts.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(),
- QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(),
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(AccountResource.class,
+ "getAccounts",
+ accounts.getNextOffset(),
+ limit,
+ ImmutableMap.<String, String>of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(),
+ QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(),
+ QUERY_AUDIT, auditMode.getLevel().toString()),
+ ImmutableMap.<String, String>of());
return buildStreamingPaginationResponse(accounts,
new Function<Account, AccountJson>() {
@Override
@@ -260,10 +265,14 @@ public class AccountResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<Account> accounts = accountUserApi.searchAccounts(searchKey, offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(AccountResource.class, "searchAccounts", accounts.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey,
- QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(),
- QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(),
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(AccountResource.class,
+ "searchAccounts",
+ accounts.getNextOffset(),
+ limit,
+ ImmutableMap.<String, String>of(QUERY_ACCOUNT_WITH_BALANCE, accountWithBalance.toString(),
+ QUERY_ACCOUNT_WITH_BALANCE_AND_CBA, accountWithBalanceAndCBA.toString(),
+ QUERY_AUDIT, auditMode.getLevel().toString()),
+ ImmutableMap.<String, String>of("searchKey", searchKey));
return buildStreamingPaginationResponse(accounts,
new Function<Account, AccountJson>() {
@Override
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java
index 3f7afc8d8c..ed30c1b7bf 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java
@@ -313,6 +313,7 @@ public class AdminResource extends JaxRsResourceBase {
"triggerInvoiceGenerationForParkedAccounts",
tags.getNextOffset(),
limit,
+ ImmutableMap.<String, String>of(),
ImmutableMap.<String, String>of());
return Response.status(Status.OK)
.entity(json)
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java
index ea2d0a1180..5a15ec0952 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java
@@ -193,7 +193,7 @@ public class BundleResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<SubscriptionBundle> bundles = subscriptionApi.getSubscriptionBundles(offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, "getBundles", bundles.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, "getBundles", bundles.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of());
final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>());
return buildStreamingPaginationResponse(bundles,
new Function<SubscriptionBundle, BundleJson>() {
@@ -228,8 +228,7 @@ public class BundleResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<SubscriptionBundle> bundles = subscriptionApi.searchSubscriptionBundles(searchKey, offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(BundleResource.class, "searchBundles", bundles.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey,
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(BundleResource.class,"searchBundles", bundles.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of("searchKey", searchKey));
final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>());
return buildStreamingPaginationResponse(bundles,
new Function<SubscriptionBundle, BundleJson>() {
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java
index 271042051a..b273aa6091 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java
@@ -98,7 +98,7 @@ public class CustomFieldResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws CustomFieldApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<CustomField> customFields = customFieldUserApi.getCustomFields(offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "getCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "getCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of());
return buildStreamingPaginationResponse(customFields,
new Function<CustomField, CustomFieldJson>() {
@@ -135,10 +135,15 @@ public class CustomFieldResource extends JaxRsResourceBase {
customFieldUserApi.searchCustomFields(fieldName, fieldValue, ObjectType.valueOf(objectType), offset, limit, tenantContext) :
customFieldUserApi.searchCustomFields(fieldName, ObjectType.valueOf(objectType), offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "searchCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of("objectType", objectType,
- "fieldName", fieldName,
- "fieldValue", MoreObjects.firstNonNull(fieldValue, ""),
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class,
+ "searchCustomFields",
+ customFields.getNextOffset(),
+ limit,
+ ImmutableMap.<String, String>of("objectType", objectType,
+ "fieldName", fieldName,
+ "fieldValue", MoreObjects.firstNonNull(fieldValue, ""),
+ QUERY_AUDIT, auditMode.getLevel().toString()),
+ ImmutableMap.<String, String>of());
return buildStreamingPaginationResponse(customFields,
new Function<CustomField, CustomFieldJson>() {
@Override
@@ -166,8 +171,7 @@ public class CustomFieldResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws CustomFieldApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<CustomField> customFields = customFieldUserApi.searchCustomFields(searchKey, offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "searchCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey,
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(CustomFieldResource.class, "searchCustomFields", customFields.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of("searchKey", searchKey));
return buildStreamingPaginationResponse(customFields,
new Function<CustomField, CustomFieldJson>() {
@Override
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java
index 451811c6f3..7053e9425b 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java
@@ -270,7 +270,7 @@ public class InvoiceResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws InvoiceApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<Invoice> invoices = invoiceApi.getInvoices(offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, "getInvoices", invoices.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, "getInvoices", invoices.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of());
final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>());
@@ -302,8 +302,7 @@ public class InvoiceResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws SubscriptionApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<Invoice> invoices = invoiceApi.searchInvoices(searchKey, offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, "searchInvoices", invoices.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey,
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(InvoiceResource.class, "searchInvoices", invoices.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of("searchKey", searchKey));
final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>());
return buildStreamingPaginationResponse(invoices,
new Function<Invoice, InvoiceJson>() {
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java
index 5402912ebe..605bc77310 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java
@@ -168,8 +168,13 @@ public class PaymentMethodResource extends JaxRsResourceBase {
paymentMethods = paymentApi.getPaymentMethods(offset, limit, pluginName, withPluginInfo, pluginProperties, tenantContext);
}
- final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class, "getPaymentMethods", paymentMethods.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class,
+ "getPaymentMethods",
+ paymentMethods.getNextOffset(),
+ limit,
+ ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),
+ QUERY_AUDIT, auditMode.getLevel().toString()),
+ ImmutableMap.<String, String>of());
final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>());
final Map<UUID, Account> accounts = new HashMap<UUID, Account>();
@@ -226,9 +231,13 @@ public class PaymentMethodResource extends JaxRsResourceBase {
paymentMethods = paymentApi.searchPaymentMethods(searchKey, offset, limit, pluginName, withPluginInfo, pluginProperties, tenantContext);
}
- final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class, "searchPaymentMethods", paymentMethods.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey,
- QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(PaymentMethodResource.class,
+ "searchPaymentMethods",
+ paymentMethods.getNextOffset(),
+ limit,
+ ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),
+ QUERY_AUDIT, auditMode.getLevel().toString()),
+ ImmutableMap.<String, String>of("searchKey", searchKey));
final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>());
final Map<UUID, Account> accounts = new HashMap<UUID, Account>();
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java
index bbe6e4aa62..99934df39e 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java
@@ -178,8 +178,13 @@ public class PaymentResource extends ComboPaymentResource {
payments = paymentApi.getPayments(offset, limit, pluginName, withPluginInfo, withAttempts, pluginProperties, tenantContext);
}
- final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class, "getPayments", payments.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class,
+ "getPayments",
+ payments.getNextOffset(),
+ limit,
+ ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),
+ QUERY_AUDIT, auditMode.getLevel().toString()),
+ ImmutableMap.<String, String>of());
final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>());
return buildStreamingPaginationResponse(payments,
@@ -224,9 +229,13 @@ public class PaymentResource extends ComboPaymentResource {
payments = paymentApi.searchPayments(searchKey, offset, limit, pluginName, withPluginInfo, withAttempts, pluginProperties, tenantContext);
}
- final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class, "searchPayments", payments.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey,
- QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(PaymentResource.class,
+ "searchPayments",
+ payments.getNextOffset(),
+ limit,
+ ImmutableMap.<String, String>of(QUERY_PAYMENT_METHOD_PLUGIN_NAME, Strings.nullToEmpty(pluginName),
+ QUERY_AUDIT, auditMode.getLevel().toString()),
+ ImmutableMap.<String, String>of("searchKey", searchKey));
final AtomicReference<Map<UUID, AccountAuditLogs>> accountsAuditLogs = new AtomicReference<Map<UUID, AccountAuditLogs>>(new HashMap<UUID, AccountAuditLogs>());
return buildStreamingPaginationResponse(payments,
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java
index 9762fb8c05..bb76391d56 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java
@@ -98,7 +98,7 @@ public class TagResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws TagApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<Tag> tags = tagUserApi.getTags(offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(TagResource.class, "getTags", tags.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(TagResource.class, "getTags", tags.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of());
final Map<UUID, TagDefinition> tagDefinitionsCache = new HashMap<UUID, TagDefinition>();
for (final TagDefinition tagDefinition : tagUserApi.getTagDefinitions(tenantContext)) {
@@ -132,8 +132,7 @@ public class TagResource extends JaxRsResourceBase {
@javax.ws.rs.core.Context final HttpServletRequest request) throws TagApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Pagination<Tag> tags = tagUserApi.searchTags(searchKey, offset, limit, tenantContext);
- final URI nextPageUri = uriBuilder.nextPage(TagResource.class, "searchTags", tags.getNextOffset(), limit, ImmutableMap.<String, String>of("searchKey", searchKey,
- QUERY_AUDIT, auditMode.getLevel().toString()));
+ final URI nextPageUri = uriBuilder.nextPage(TagResource.class, "searchTags", tags.getNextOffset(), limit, ImmutableMap.<String, String>of(QUERY_AUDIT, auditMode.getLevel().toString()), ImmutableMap.<String, String>of("searchKey", searchKey));
final Map<UUID, TagDefinition> tagDefinitionsCache = new HashMap<UUID, TagDefinition>();
for (final TagDefinition tagDefinition : tagUserApi.getTagDefinitions(tenantContext)) {
tagDefinitionsCache.put(tagDefinition.getId(), tagDefinition);
diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java
index 6d9f9b666c..d57cb06701 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java
@@ -117,7 +117,12 @@ public class JaxrsUriBuilder {
return objectId != null ? uriBuilder.build(objectId) : uriBuilder.build();
}
- public URI nextPage(final Class<? extends JaxrsResource> theClass, final String getMethodName, final Long nextOffset, final Long limit, final Map<String, String> params) {
+ public URI nextPage(final Class<? extends JaxrsResource> theClass,
+ final String getMethodName,
+ final Long nextOffset,
+ final Long limit,
+ final Map<String, String> queryParams,
+ final Map<String, String> pathParams) {
if (nextOffset == null || limit == null) {
// End of pagination?
return null;
@@ -125,8 +130,11 @@ public class JaxrsUriBuilder {
final UriBuilder uriBuilder = getUriBuilder(theClass, getMethodName).queryParam(JaxRsResourceBase.QUERY_SEARCH_OFFSET, nextOffset)
.queryParam(JaxRsResourceBase.QUERY_SEARCH_LIMIT, limit);
- for (final String key : params.keySet()) {
- uriBuilder.queryParam(key, params.get(key));
+ for (final String key : queryParams.keySet()) {
+ uriBuilder.queryParam(key, queryParams.get(key));
+ }
+ for (final String key : pathParams.keySet()) {
+ uriBuilder.resolveTemplate(key, pathParams.get(key));
}
return uriBuilder.build();
}
diff --git a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java
index d6bbd1b5d6..46dc3cc8bb 100644
--- a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java
+++ b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java
@@ -118,13 +118,27 @@ public class TestAccount extends TestJaxrsBase {
public void testAccountOk() throws Exception {
final Account input = createAccount();
+ // Create a second account (https://github.com/killbill/killbill/issues/1422 regression testing)
+ final Account secondAccount = createAccount();
+ final Account retrievedSecondAccount = accountApi.getAccountByKey(secondAccount.getExternalKey(), requestOptions);
+ Assert.assertEquals(secondAccount, retrievedSecondAccount);
+
// Retrieves by external key
final Account retrievedAccount = accountApi.getAccountByKey(input.getExternalKey(), requestOptions);
- Assert.assertTrue(retrievedAccount.equals(input));
+ Assert.assertEquals(input, retrievedAccount);
// Try search endpoint
searchAccount(input, retrievedAccount);
+ // Force limit=1 (https://github.com/killbill/killbill/issues/1422 regression testing)
+ final Accounts allAccounts = accountApi.searchAccounts(input.getCompany(), 0L, 1L, false, false, AuditLevel.NONE, requestOptions);
+ // Company name is the same for both accounts
+ Assert.assertEquals(allAccounts.size(), 1);
+ Assert.assertEquals(allAccounts.get(0).getExternalKey(), retrievedAccount.getExternalKey());
+ final Accounts secondPage = allAccounts.getNext();
+ Assert.assertEquals(secondPage.size(), 1);
+ Assert.assertEquals(secondPage.get(0).getExternalKey(), retrievedSecondAccount.getExternalKey());
+
// Update Account
final Account newInput = new Account(input.getAccountId(),
"zozo", 4, input.getExternalKey(), "[email protected]", 18,
@@ -445,9 +459,6 @@ public class TestAccount extends TestJaxrsBase {
// Search by email
doSearchAccount(input.getEmail(), output);
- // Search by company name
- doSearchAccount(input.getCompany(), output);
-
// Search by external key.
// Note: we will always find a match since we don't update it
final List<Account> accountsByExternalKey = accountApi.searchAccounts(input.getExternalKey(), requestOptions); | ['jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AdminResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/TagResource.java', 'profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestAccount.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/InvoiceResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/util/JaxrsUriBuilder.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/CustomFieldResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/AccountResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/BundleResource.java', 'jaxrs/src/main/java/org/killbill/billing/jaxrs/resources/PaymentMethodResource.java'] | {'.java': 10} | 10 | 10 | 0 | 0 | 10 | 6,492,754 | 1,215,206 | 140,489 | 1,042 | 15,066 | 2,117 | 109 | 9 | 563 | 46 | 148 | 17 | 2 | 3 | 2021-04-20T12:04:32 | 4,053 | Java | {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593} | Apache License 2.0 |
245 | killbill/killbill/1530/1528 | killbill | killbill | https://github.com/killbill/killbill/issues/1528 | https://github.com/killbill/killbill/pull/1530 | https://github.com/killbill/killbill/pull/1530#discussion_r751898548 | 1 | close | Pending subscription shows a `PENDING` state after being canceled | Scenario:
1. Create a subscription with an future start (billing) date -> `PENDING` state
2. Cancel the subscription immediately -> This will default to the future start date
3. Fetch the subscription and check the state -> `CANCELLED` state
It seems that in step 3. `state` is incorrectly showing `PENDING` | 2b80b0445c7baf1f613425bb236a8cb36f1f377a | 9890c11b6b4cdcdb5c3196f890fa672cb250da44 | https://github.com/killbill/killbill/compare/2b80b0445c7baf1f613425bb236a8cb36f1f377a...9890c11b6b4cdcdb5c3196f890fa672cb250da44 | diff --git a/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java b/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java
index 1a9e0cfa83..157269856b 100644
--- a/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java
+++ b/subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java
@@ -184,6 +184,7 @@ public class DefaultSubscriptionBase extends EntityBase implements SubscriptionB
throw new IllegalStateException("Should return a valid EntitlementState");
}
+
@Override
public EntitlementSourceType getSourceType() {
if (transitions == null) {
diff --git a/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java b/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java
index aa74d92dc7..3d7680b140 100644
--- a/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java
+++ b/subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java
@@ -509,17 +509,22 @@ public class TestUserApiCancel extends SubscriptionTestSuiteWithEmbeddedDB {
assertEquals(subscription.getStartDate().compareTo(startDate.toDateTime(accountData.getReferenceTime())), 0);
subscription.cancelWithPolicy(BillingActionPolicy.IMMEDIATE, callContext);
+
+ final DefaultSubscriptionBase subscription2 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);
+ assertEquals(subscription2.getStartDate().compareTo(subscription.getStartDate()), 0);
+ assertEquals(subscription2.getState(), Entitlement.EntitlementState.PENDING);
testListener.pushExpectedEvents(NextEvent.CREATE, NextEvent.CANCEL);
clock.addDays(5);
assertListenerStatus();
- final DefaultSubscriptionBase subscription2 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);
- assertEquals(subscription2.getStartDate().compareTo(subscription.getStartDate()), 0);
- assertEquals(subscription2.getState(), Entitlement.EntitlementState.CANCELLED);
- assertNull(subscription2.getCurrentPlan());
+ final DefaultSubscriptionBase subscription3 = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);
+ assertEquals(subscription3.getStartDate().compareTo(subscription.getStartDate()), 0);
+ assertEquals(subscription3.getState(), Entitlement.EntitlementState.CANCELLED);
+ assertNull(subscription3.getCurrentPlan());
}
-
+
+
@Test(groups = "slow", description="See https://github.com/killbill/killbill/issues/1207")
public void testDoubleFutureLaterCancellation() throws SubscriptionBaseApiException { | ['subscription/src/main/java/org/killbill/billing/subscription/api/user/DefaultSubscriptionBase.java', 'subscription/src/test/java/org/killbill/billing/subscription/api/user/TestUserApiCancel.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 6,580,195 | 1,232,435 | 142,320 | 1,051 | 1 | 1 | 1 | 1 | 313 | 50 | 72 | 6 | 0 | 0 | 2021-11-17T08:47:31 | 4,053 | Java | {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593} | Apache License 2.0 |
251 | killbill/killbill/1075/1074 | killbill | killbill | https://github.com/killbill/killbill/issues/1074 | https://github.com/killbill/killbill/pull/1075 | https://github.com/killbill/killbill/pull/1075 | 1 | fixes | Wrong computed invoice target date for non-UTC TZ | See [mailing-list thread](https://groups.google.com/forum/#!msg/killbilling-users/ChJ7DeOQCzk/BQzCL5E0BAAJ). | 938aa3e7d3c8c980cfa3b9416927ca7ae69e2dd9 | b6860e565acc632e859e67ab72721f9a06d7aef1 | https://github.com/killbill/killbill/compare/938aa3e7d3c8c980cfa3b9416927ca7ae69e2dd9...b6860e565acc632e859e67ab72721f9a06d7aef1 | diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java
index a7140c378f..0e8cd1a603 100644
--- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java
+++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java
@@ -426,15 +426,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen
return (DefaultSubscriptionBase) sub;
}
- protected Account createAccountWithOsgiPaymentMethod(final AccountData accountData) throws Exception {
- return createAccountWithPaymentMethod(accountData, BeatrixIntegrationModule.OSGI_PLUGIN_NAME);
- }
-
protected Account createAccountWithNonOsgiPaymentMethod(final AccountData accountData) throws Exception {
- return createAccountWithPaymentMethod(accountData, BeatrixIntegrationModule.NON_OSGI_PLUGIN_NAME);
- }
-
- private Account createAccountWithPaymentMethod(final AccountData accountData, final String paymentPluginName) throws Exception {
final Account account = accountUserApi.createAccount(accountData, callContext);
assertNotNull(account);
@@ -442,7 +434,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen
final PaymentMethodPlugin info = createPaymentMethodPlugin();
- paymentApi.addPaymentMethod(account, UUID.randomUUID().toString(), paymentPluginName, true, info, PLUGIN_PROPERTIES, callContext);
+ paymentApi.addPaymentMethod(account, UUID.randomUUID().toString(), BeatrixIntegrationModule.NON_OSGI_PLUGIN_NAME, true, info, PLUGIN_PROPERTIES, callContext);
return accountUserApi.getAccountById(account.getId(), callContext);
}
@@ -451,6 +443,10 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen
}
protected AccountData getAccountData(@Nullable final Integer billingDay) {
+ return getAccountData(billingDay, DateTimeZone.UTC);
+ }
+
+ protected AccountData getAccountData(@Nullable final Integer billingDay, final DateTimeZone tz) {
final MockAccountBuilder builder = new MockAccountBuilder()
.name(UUID.randomUUID().toString().substring(1, 8))
.firstNameLength(6)
@@ -460,7 +456,7 @@ public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implemen
.externalKey(UUID.randomUUID().toString().substring(1, 8))
.currency(Currency.USD)
.referenceTime(clock.getUTCNow())
- .timeZone(DateTimeZone.UTC);
+ .timeZone(tz);
if (billingDay != null) {
builder.billingCycleDayLocal(billingDay);
}
diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java
index 3d5c66a248..455173d6ee 100644
--- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java
+++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java
@@ -1,7 +1,7 @@
/*
* Copyright 2010-2013 Ning, Inc.
- * Copyright 2014-2016 Groupon, Inc
- * Copyright 2014-2016 The Billing Project, LLC
+ * Copyright 2014-2018 Groupon, Inc
+ * Copyright 2014-2018 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
@@ -20,9 +20,10 @@ package org.killbill.billing.beatrix.integration;
import java.util.Collection;
import java.util.List;
-import java.util.UUID;
import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
+import org.joda.time.LocalDate;
import org.killbill.billing.ObjectType;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.api.TestApiListener.NextEvent;
@@ -30,13 +31,8 @@ import org.killbill.billing.catalog.api.BillingPeriod;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.entitlement.api.DefaultEntitlement;
import org.killbill.billing.invoice.api.Invoice;
-import org.killbill.billing.invoice.api.InvoiceStatus;
import org.killbill.billing.invoice.api.InvoiceUserApi;
-import org.killbill.billing.util.api.TagApiException;
-import org.killbill.billing.util.api.TagDefinitionApiException;
import org.killbill.billing.util.api.TagUserApi;
-import org.killbill.billing.util.tag.ControlTagType;
-import org.killbill.billing.util.tag.Tag;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -102,4 +98,47 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase {
assertEquals(invoices.size(), 1);
}
+ @Test(groups = "slow", description = "https://github.com/killbill/killbill/issues/1074")
+ public void testAutoInvoiceOffWithTZ() throws Exception {
+ clock.setTime(new DateTime(2018, 12, 1, 0, 25, 0, 0));
+
+ account = createAccountWithNonOsgiPaymentMethod(getAccountData(null, DateTimeZone.forID("America/Los_Angeles")));
+ assertEquals(account.getBillCycleDayLocal(), (Integer) 0);
+
+ final DefaultEntitlement bpEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey", productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);
+ assertNotNull(bpEntitlement);
+ assertEquals(accountUserApi.getAccountById(account.getId(), callContext).getBillCycleDayLocal(), (Integer) 30);
+
+ List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext);
+ assertEquals(invoices.size(), 1);
+ assertEquals(invoices.get(0).getInvoiceItems().size(), 1);
+ assertEquals(invoices.get(0).getTargetDate(), new LocalDate(2018, 11, 30));
+ assertEquals(invoices.get(0).getInvoiceItems().get(0).getStartDate(), new LocalDate(2018, 11, 30));
+
+ clock.setTime(new DateTime(2018, 12, 30, 0, 20, 0, 0));
+ assertEquals(clock.getUTCToday(), new LocalDate(2018, 12, 30));
+ assertEquals(clock.getUTCNow().toDateTime(account.getTimeZone()).toLocalDate(), new LocalDate(2018, 12, 29));
+ // Still in trial
+ assertListenerStatus();
+ assertEquals(entitlementApi.getEntitlementForId(bpEntitlement.getId(), callContext).getLastActivePhase().getName(), "shotgun-monthly-trial");
+ assertEquals(invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext).size(), 1);
+
+ // Adding / Removing AUTO_INVOICING_OFF shouldn't have any impact
+ add_AUTO_INVOICING_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+ remove_AUTO_INVOICING_OFF_Tag(account.getId(), ObjectType.ACCOUNT, NextEvent.NULL_INVOICE);
+
+ assertListenerStatus();
+ assertEquals(entitlementApi.getEntitlementForId(bpEntitlement.getId(), callContext).getLastActivePhase().getName(), "shotgun-monthly-trial");
+ assertEquals(invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext).size(), 1);
+
+ busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);
+ clock.setTime(new DateTime(2018, 12, 31, 0, 25, 0, 0));
+ assertListenerStatus();
+
+ invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext);
+ assertEquals(invoices.size(), 2);
+ assertEquals(invoices.get(1).getTargetDate(), new LocalDate(2018, 12, 30));
+ assertEquals(invoices.get(1).getInvoiceItems().get(0).getStartDate(), new LocalDate(2018, 12, 30));
+ assertEquals(invoices.get(1).getInvoiceItems().get(0).getEndDate(), new LocalDate(2019, 1, 30));
+ }
}
diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java
index f901875e05..4715f25131 100644
--- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java
+++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java
@@ -1,7 +1,7 @@
/*
* Copyright 2010-2013 Ning, Inc.
- * Copyright 2014-2017 Groupon, Inc
- * Copyright 2014-2017 The Billing Project, LLC
+ * Copyright 2014-2018 Groupon, Inc
+ * Copyright 2014-2018 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
@@ -22,21 +22,15 @@ import java.math.BigDecimal;
import java.util.Collection;
import org.joda.time.DateTime;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
import org.killbill.billing.ObjectType;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.api.TestApiListener.NextEvent;
import org.killbill.billing.catalog.api.BillingPeriod;
-import org.killbill.billing.catalog.api.PriceListSet;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.entitlement.api.DefaultEntitlement;
import org.killbill.billing.invoice.api.Invoice;
-import org.killbill.billing.subscription.api.user.SubscriptionBaseBundle;
-import org.killbill.billing.util.config.definition.PaymentConfig;
-
-import com.google.inject.Inject;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
@@ -45,10 +39,8 @@ import static org.testng.Assert.assertTrue;
public class TestIntegrationWithAutoPayOff extends TestIntegrationBase {
private Account account;
- private SubscriptionBaseBundle bundle;
private String productName;
private BillingPeriod term;
- private String planSetName;
@Override
@BeforeMethod(groups = "slow")
@@ -62,7 +54,6 @@ public class TestIntegrationWithAutoPayOff extends TestIntegrationBase {
assertNotNull(account);
productName = "Shotgun";
term = BillingPeriod.MONTHLY;
- planSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
}
@Test(groups = "slow")
@@ -242,7 +233,6 @@ public class TestIntegrationWithAutoPayOff extends TestIntegrationBase {
}
-
private void addDelayBceauseOfLackOfCorrectSynchro() {
// TODO When removing the tag, the payment system will schedule retries for payments that are in non terminal state
// The issue is that at this point we know the event went on the bus but we don't know if the listener in payment completed
diff --git a/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java b/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java
index 767cd30d00..2bc350b107 100644
--- a/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java
+++ b/invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java
@@ -326,7 +326,7 @@ public class InvoiceDispatcher {
LocalDate inputTargetDate = inputTargetDateMaybeNull;
// A null inputTargetDate is only allowed in UPCOMING_INVOICE dryRun mode to have the system compute it
if (inputTargetDate == null && !upcomingInvoiceDryRun) {
- inputTargetDate = clock.getUTCToday();
+ inputTargetDate = context.toLocalDate(clock.getUTCNow());
}
Preconditions.checkArgument(inputTargetDate != null || upcomingInvoiceDryRun, "inputTargetDate is required in non dryRun mode");
| ['beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationBase.java', 'invoice/src/main/java/org/killbill/billing/invoice/InvoiceDispatcher.java', 'beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java', 'beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 6,223,188 | 1,167,835 | 135,115 | 1,018 | 122 | 25 | 2 | 1 | 108 | 3 | 39 | 1 | 1 | 0 | 2018-12-11T10:22:16 | 4,053 | Java | {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593} | Apache License 2.0 |
257 | killbill/killbill/405/118 | killbill | killbill | https://github.com/killbill/killbill/issues/118 | https://github.com/killbill/killbill/pull/405 | https://github.com/killbill/killbill/pull/405 | 1 | fixed | Invoice formatter display wrong currency symbol | First of all, the code is using the locale to set the currency formatter. For instance in
DefaultInvoiceFormatter:
```
public String getFormattedPaidAmount() {
final NumberFormat number = NumberFormat.getCurrencyInstance(locale);
return number.format(getPaidAmount().doubleValue());
}
```
The number format returned is based on the locale which is 'good' so it knows how to display the dots, comma, ... but wrong it comes to display the currency symbol.
| 2eda0f052c5c04c53b18bf249c02ba489881349b | 43afb0759795e3ffdf748925e592b65738e00f25 | https://github.com/killbill/killbill/compare/2eda0f052c5c04c53b18bf249c02ba489881349b...43afb0759795e3ffdf748925e592b65738e00f25 | diff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java
index 8ae278acfc..a3fed268b4 100644
--- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java
+++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java
@@ -17,24 +17,22 @@
package org.killbill.billing.invoice.template.formatters;
import java.math.BigDecimal;
-import java.text.NumberFormat;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
+import java.util.Map;
import java.util.UUID;
+import org.joda.money.CurrencyUnit;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.killbill.billing.callcontext.InternalTenantContext;
-import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory;
-import org.killbill.billing.tenant.api.TenantInternalApi;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.currency.api.CurrencyConversion;
import org.killbill.billing.currency.api.CurrencyConversionApi;
@@ -45,17 +43,18 @@ import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.invoice.api.InvoicePayment;
import org.killbill.billing.invoice.api.formatters.InvoiceFormatter;
+import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory;
import org.killbill.billing.invoice.model.CreditAdjInvoiceItem;
import org.killbill.billing.invoice.model.CreditBalanceAdjInvoiceItem;
import org.killbill.billing.invoice.model.DefaultInvoice;
import org.killbill.billing.util.template.translation.TranslatorConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
-import static org.killbill.billing.util.DefaultAmountFormatter.round;
-
/**
* Format invoice fields
*/
@@ -70,8 +69,11 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
private final CurrencyConversionApi currencyConversionApi;
private final InternalTenantContext context;
private final ResourceBundleFactory bundleFactory;
+ private Map<java.util.Currency, Locale> currencyLocaleMap;
- public DefaultInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale, final CurrencyConversionApi currencyConversionApi, final ResourceBundleFactory bundleFactory, final InternalTenantContext context) {
+ public DefaultInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale,
+ final CurrencyConversionApi currencyConversionApi, final ResourceBundleFactory bundleFactory,
+ final InternalTenantContext context, Map<java.util.Currency, Locale> currencyLocaleMap) {
this.config = config;
this.invoice = invoice;
this.dateFormatter = DateTimeFormat.mediumDate().withLocale(locale);
@@ -79,6 +81,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
this.currencyConversionApi = currencyConversionApi;
this.bundleFactory = bundleFactory;
this.context = context;
+ this.currencyLocaleMap = currencyLocaleMap;
}
@Override
@@ -198,35 +201,56 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
@Override
public BigDecimal getChargedAmount() {
- return round(Objects.firstNonNull(invoice.getChargedAmount(), BigDecimal.ZERO));
+ return Objects.firstNonNull(invoice.getChargedAmount(), BigDecimal.ZERO);
}
@Override
public BigDecimal getOriginalChargedAmount() {
- return round(Objects.firstNonNull(invoice.getOriginalChargedAmount(), BigDecimal.ZERO));
+ return Objects.firstNonNull(invoice.getOriginalChargedAmount(), BigDecimal.ZERO);
}
@Override
public BigDecimal getBalance() {
- return round(Objects.firstNonNull(invoice.getBalance(), BigDecimal.ZERO));
+ return Objects.firstNonNull(invoice.getBalance(), BigDecimal.ZERO);
}
@Override
public String getFormattedChargedAmount() {
- final NumberFormat number = NumberFormat.getCurrencyInstance(locale);
- return number.format(getChargedAmount().doubleValue());
+ return getFormattedAmountByLocaleAndInvoiceCurrency(getChargedAmount());
}
@Override
public String getFormattedPaidAmount() {
- final NumberFormat number = NumberFormat.getCurrencyInstance(locale);
- return number.format(getPaidAmount().doubleValue());
+ return getFormattedAmountByLocaleAndInvoiceCurrency(getPaidAmount());
}
@Override
public String getFormattedBalance() {
- final NumberFormat number = NumberFormat.getCurrencyInstance(locale);
- return number.format(getBalance().doubleValue());
+ return getFormattedAmountByLocaleAndInvoiceCurrency(getBalance());
+ }
+
+ // Returns the formatted amount with the correct currency symbol that is get from the invoice currency.
+ private String getFormattedAmountByLocaleAndInvoiceCurrency(BigDecimal amount) {
+
+ String invoiceCurrencyCode = invoice.getCurrency().toString();
+ CurrencyUnit currencyUnit = CurrencyUnit.of(invoiceCurrencyCode);
+
+ final DecimalFormat numberFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale);
+ DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols();
+ dfs.setInternationalCurrencySymbol(currencyUnit.getCurrencyCode());
+
+ try {
+ final java.util.Currency currency = java.util.Currency.getInstance(invoiceCurrencyCode);
+ dfs.setCurrencySymbol(currency.getSymbol(currencyLocaleMap.get(currency)));
+ } catch (Exception e) {
+ dfs.setCurrencySymbol(currencyUnit.getSymbol(locale));
+ }
+
+ numberFormatter.setDecimalFormatSymbols(dfs);
+ numberFormatter.setMinimumFractionDigits(currencyUnit.getDefaultFractionDigits());
+ numberFormatter.setMaximumFractionDigits(currencyUnit.getDefaultFractionDigits());
+
+ return numberFormatter.format(amount.doubleValue());
}
@Override
@@ -288,7 +312,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
@Override
public BigDecimal getPaidAmount() {
- return round(Objects.firstNonNull(invoice.getPaidAmount(), BigDecimal.ZERO));
+ return Objects.firstNonNull(invoice.getPaidAmount(), BigDecimal.ZERO);
}
@Override
@@ -337,13 +361,18 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
return invoice;
}
+ @SuppressWarnings("UnusedDeclaration")
+ protected Map<java.util.Currency, Locale> getCurrencyLocaleMap() {
+ return currencyLocaleMap;
+ }
+
@Override
public BigDecimal getCreditedAmount() {
- return round(Objects.firstNonNull(invoice.getCreditedAmount(), BigDecimal.ZERO));
+ return Objects.firstNonNull(invoice.getCreditedAmount(), BigDecimal.ZERO);
}
@Override
public BigDecimal getRefundedAmount() {
- return round(Objects.firstNonNull(invoice.getRefundedAmount(), BigDecimal.ZERO));
+ return Objects.firstNonNull(invoice.getRefundedAmount(), BigDecimal.ZERO);
}
}
diff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java
index 890fb30338..6496df73f5 100644
--- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java
+++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java
@@ -16,7 +16,10 @@
package org.killbill.billing.invoice.template.formatters;
+import java.util.Currency;
+import java.util.HashMap;
import java.util.Locale;
+import java.util.Map;
import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.billing.currency.api.CurrencyConversionApi;
@@ -24,7 +27,6 @@ import org.killbill.billing.invoice.api.Invoice;
import org.killbill.billing.invoice.api.formatters.InvoiceFormatter;
import org.killbill.billing.invoice.api.formatters.InvoiceFormatterFactory;
import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory;
-import org.killbill.billing.tenant.api.TenantInternalApi;
import org.killbill.billing.util.template.translation.TranslatorConfig;
public class DefaultInvoiceFormatterFactory implements InvoiceFormatterFactory {
@@ -32,6 +34,17 @@ public class DefaultInvoiceFormatterFactory implements InvoiceFormatterFactory {
@Override
public InvoiceFormatter createInvoiceFormatter(final TranslatorConfig config, final Invoice invoice, final Locale locale, CurrencyConversionApi currencyConversionApi,
final ResourceBundleFactory bundleFactory, final InternalTenantContext context) {
- return new DefaultInvoiceFormatter(config, invoice, locale, currencyConversionApi, bundleFactory, context);
+
+ // this initialization relies on System.currentTimeMillis() instead of the Kill Bill clock (it won't be accurate when moving the clock)
+ Map<Currency, Locale> currencyLocaleMap = new HashMap<Currency, Locale>();
+ for (Locale localeItem : Locale.getAvailableLocales()) {
+ try {
+ java.util.Currency currency = java.util.Currency.getInstance(localeItem);
+ currencyLocaleMap.put(currency, localeItem);
+ }catch (Exception e){
+ }
+ }
+
+ return new DefaultInvoiceFormatter(config, invoice, locale, currencyConversionApi, bundleFactory, context, currencyLocaleMap);
}
}
diff --git a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java
index 51ddcc637a..5516c8ca90 100644
--- a/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java
+++ b/invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java
@@ -36,14 +36,10 @@ import org.killbill.billing.util.LocaleUtils;
import org.killbill.billing.util.template.translation.DefaultCatalogTranslator;
import org.killbill.billing.util.template.translation.Translator;
import org.killbill.billing.util.template.translation.TranslatorConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
-import static org.killbill.billing.util.DefaultAmountFormatter.round;
-
/**
* Format invoice item fields
*/
@@ -71,7 +67,7 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {
@Override
public BigDecimal getAmount() {
- return round(Objects.firstNonNull(item.getAmount(), BigDecimal.ZERO));
+ return Objects.firstNonNull(item.getAmount(), BigDecimal.ZERO);
}
@Override
@@ -168,7 +164,7 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {
@Override
public BigDecimal getRate() {
- return round(BigDecimal.ZERO);
+ return BigDecimal.ZERO;
}
@Override
diff --git a/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java b/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java
index df0a9d7a08..6d5cc0afb0 100644
--- a/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java
+++ b/invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java
@@ -34,7 +34,6 @@ import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.invoice.api.InvoicePaymentType;
import org.killbill.billing.invoice.api.formatters.InvoiceFormatter;
-import org.killbill.billing.invoice.api.formatters.InvoiceFormatterFactory;
import org.killbill.billing.invoice.api.formatters.ResourceBundleFactory.ResourceBundleType;
import org.killbill.billing.invoice.model.CreditAdjInvoiceItem;
import org.killbill.billing.invoice.model.CreditBalanceAdjInvoiceItem;
@@ -89,7 +88,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {
Assert.assertEquals(invoice.getCreditedAmount().doubleValue(), 0.00);
// Verify the merge
- final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext);
+ final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext, getAvailableLocales());
final List<InvoiceItem> invoiceItems = formatter.getInvoiceItems();
Assert.assertEquals(invoiceItems.size(), 1);
Assert.assertEquals(invoiceItems.get(0).getInvoiceItemType(), InvoiceItemType.FIXED);
@@ -143,7 +142,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {
Assert.assertEquals(invoice.getRefundedAmount().doubleValue(), -1.00);
// Verify the merge
- final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext);
+ final InvoiceFormatter formatter = new DefaultInvoiceFormatter(config, invoice, Locale.US, null, resourceBundleFactory, internalCallContext, getAvailableLocales());
final List<InvoiceItem> invoiceItems = formatter.getInvoiceItems();
Assert.assertEquals(invoiceItems.size(), 4);
Assert.assertEquals(invoiceItems.get(0).getInvoiceItemType(), InvoiceItemType.FIXED);
@@ -160,7 +159,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {
public void testFormattedAmount() throws Exception {
final FixedPriceInvoiceItem fixedItemEUR = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,
UUID.randomUUID().toString(), UUID.randomUUID().toString(),
- new LocalDate(), new BigDecimal("1499.95"), Currency.EUR);
+ new LocalDate(), new BigDecimal("1499.952"), Currency.EUR);
final Invoice invoiceEUR = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.EUR);
invoiceEUR.addInvoiceItem(fixedItemEUR);
@@ -186,6 +185,158 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {
Locale.FRANCE);
}
+ @Test(groups = "fast")
+ public void testFormattedAmountFranceAndJPY() throws Exception {
+
+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,
+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),
+ new LocalDate(), new BigDecimal("1500.00"), Currency.JPY);
+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.JPY);
+ invoice.addInvoiceItem(fixedItem);
+
+ checkOutput(invoice,
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" +
+ "</tr>",
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>1 500 ¥</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>0 ¥</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>1 500 ¥</strong></td>\\n" +
+ "</tr>",
+ Locale.FRANCE);
+ }
+
+ @Test(groups = "fast")
+ public void testFormattedAmountUSAndBTC() throws Exception {
+
+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,
+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),
+ new LocalDate(), new BigDecimal("1105.28843439"), Currency.BTC);
+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.BTC);
+ invoice.addInvoiceItem(fixedItem);
+
+ checkOutput(invoice,
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" +
+ "</tr>",
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>BTC1,105.28843439</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>BTC0.00000000</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>BTC1,105.28843439</strong></td>\\n" +
+ "</tr>",
+ Locale.US);
+ }
+
+ @Test(groups = "fast")
+ public void testFormattedAmountUSAndEUR() throws Exception {
+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,
+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),
+ new LocalDate(), new BigDecimal("2635.14"), Currency.EUR);
+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.EUR);
+ invoice.addInvoiceItem(fixedItem);
+
+ checkOutput(invoice,
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" +
+ "</tr>",
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>€2,635.14</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>€0.00</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>€2,635.14</strong></td>\\n" +
+ "</tr>",
+ Locale.US);
+ }
+
+ @Test(groups = "fast")
+ public void testFormattedAmountUSAndBRL() throws Exception {
+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,
+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),
+ new LocalDate(), new BigDecimal("2635.14"), Currency.BRL);
+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.BRL);
+ invoice.addInvoiceItem(fixedItem);
+
+ checkOutput(invoice,
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" +
+ "</tr>",
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>R$2,635.14</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>R$0.00</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>R$2,635.14</strong></td>\\n" +
+ "</tr>",
+ Locale.US);
+ }
+
+ @Test(groups = "fast")
+ public void testFormattedAmountUSAndGBP() throws Exception {
+ final FixedPriceInvoiceItem fixedItem = new FixedPriceInvoiceItem(UUID.randomUUID(), UUID.randomUUID(), null, null,
+ UUID.randomUUID().toString(), UUID.randomUUID().toString(),
+ new LocalDate(), new BigDecimal("1499.95"), Currency.GBP);
+ final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), new LocalDate(), new LocalDate(), Currency.GBP);
+ invoice.addInvoiceItem(fixedItem);
+
+ checkOutput(invoice,
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedChargedAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedPaidAmount}}</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>{{invoice.formattedBalance}}</strong></td>\\n" +
+ "</tr>",
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>£1,499.95</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>£0.00</strong></td>\\n" +
+ "</tr>\\n" +
+ "<tr>\\n" +
+ " <td class=\\"amount\\"><strong>£1,499.95</strong></td>\\n" +
+ "</tr>",
+ Locale.US);
+ }
+
@Test(groups = "fast")
public void testProcessedCurrencyExists() throws Exception {
final Invoice invoice = new DefaultInvoice(UUID.randomUUID(), clock.getUTCNow(), UUID.randomUUID(), new Integer(234), new LocalDate(), new LocalDate(), Currency.BRL, Currency.USD, false);
@@ -329,7 +480,7 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {
data.put("text", translator);
- data.put("invoice", new DefaultInvoiceFormatter(config, invoice, Locale.US, currencyConversionApi, resourceBundleFactory, internalCallContext));
+ data.put("invoice", new DefaultInvoiceFormatter(config, invoice, Locale.US, currencyConversionApi, resourceBundleFactory, internalCallContext, getAvailableLocales()));
final String formattedText = templateEngine.executeTemplateText(template, data);
@@ -338,9 +489,23 @@ public class TestDefaultInvoiceFormatter extends InvoiceTestSuiteNoDB {
private void checkOutput(final Invoice invoice, final String template, final String expected, final Locale locale) {
final Map<String, Object> data = new HashMap<String, Object>();
- data.put("invoice", new DefaultInvoiceFormatter(config, invoice, locale, null, resourceBundleFactory, internalCallContext));
+ data.put("invoice", new DefaultInvoiceFormatter(config, invoice, locale, null, resourceBundleFactory, internalCallContext, getAvailableLocales()));
final String formattedText = templateEngine.executeTemplateText(template, data);
Assert.assertEquals(formattedText, expected);
}
+
+ private Map<java.util.Currency, Locale> getAvailableLocales() {
+ Map<java.util.Currency, Locale> currencyLocaleMap = new HashMap<java.util.Currency, Locale>();
+
+ currencyLocaleMap.put(java.util.Currency.getInstance(Locale.US), Locale.US);
+ currencyLocaleMap.put(java.util.Currency.getInstance(Locale.FRANCE), Locale.FRANCE);
+ currencyLocaleMap.put(java.util.Currency.getInstance(Locale.JAPAN), Locale.JAPAN);
+ currencyLocaleMap.put(java.util.Currency.getInstance(Locale.UK), Locale.UK);
+ Locale brLocale = new Locale("pt", "BR");
+ currencyLocaleMap.put(java.util.Currency.getInstance(brLocale), brLocale);
+
+ return currencyLocaleMap;
+ }
+
} | ['invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatter.java', 'invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceFormatterFactory.java', 'invoice/src/test/java/org/killbill/billing/invoice/template/formatters/TestDefaultInvoiceFormatter.java', 'invoice/src/main/java/org/killbill/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 4,510,922 | 859,544 | 101,923 | 872 | 5,674 | 993 | 96 | 3 | 475 | 63 | 96 | 12 | 0 | 1 | 2015-10-06T20:03:50 | 4,053 | Java | {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593} | Apache License 2.0 |
253 | killbill/killbill/1016/1015 | killbill | killbill | https://github.com/killbill/killbill/issues/1015 | https://github.com/killbill/killbill/pull/1016 | https://github.com/killbill/killbill/pull/1016 | 1 | fixes | Possible double payments with invoice payments in UNKNOWN state | Scenario:
1. Invoice payment in `UNKNOWN` state
2. Trigger a new successful payment by calling `invoicePaymentApi.createPurchaseForInvoicePayment`
3. Fix the original payment (`UNKNOWN -> SUCCESS`)
Result: the invoice ends up double payed and the invoice balance is negative (absolute value is the amount of the payment).
| 08ffcbbd2cf366a9f26603248384fab50722da14 | 29a6f930250b640dd511002a6a60597509e24a10 | https://github.com/killbill/killbill/compare/08ffcbbd2cf366a9f26603248384fab50722da14...29a6f930250b640dd511002a6a60597509e24a10 | diff --git a/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java b/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java
index ffe6ad5e9a..e6534c81d5 100644
--- a/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java
+++ b/api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java
@@ -84,5 +84,7 @@ public interface InvoiceInternalApi {
public List<InvoicePayment> getInvoicePaymentsByAccount(UUID accountId, TenantContext context);
+ public List<InvoicePayment> getInvoicePaymentsByInvoice(UUID invoiceId, InternalTenantContext context);
+
public InvoicePayment getInvoicePaymentByCookieId(String cookieId, TenantContext context);
}
diff --git a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java
index b00c5e308a..4eca162eba 100644
--- a/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java
+++ b/beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java
@@ -1095,4 +1095,139 @@ public class TestInvoicePayment extends TestIntegrationBase {
Assert.assertEquals(payments.get(0).getTransactions().size(), 1);
}
+
+ @Test(groups = "slow")
+ public void testWithUNKNOWNPaymentFixedToSuccess() throws Exception {
+ // Verify integration with Overdue in that particular test
+ final String configXml = "<overdueConfig>" +
+ " <accountOverdueStates>" +
+ " <initialReevaluationInterval>" +
+ " <unit>DAYS</unit><number>1</number>" +
+ " </initialReevaluationInterval>" +
+ " <state name=\\"OD1\\">" +
+ " <condition>" +
+ " <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
+ " <unit>DAYS</unit><number>1</number>" +
+ " </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
+ " </condition>" +
+ " <externalMessage>Reached OD1</externalMessage>" +
+ " <blockChanges>true</blockChanges>" +
+ " <disableEntitlementAndChangesBlocked>false</disableEntitlementAndChangesBlocked>" +
+ " </state>" +
+ " </accountOverdueStates>" +
+ "</overdueConfig>";
+ final InputStream is = new ByteArrayInputStream(configXml.getBytes());
+ final DefaultOverdueConfig config = XMLLoader.getObjectFromStreamNoValidation(is, DefaultOverdueConfig.class);
+ overdueConfigCache.loadDefaultOverdueConfig(config);
+
+ clock.setDay(new LocalDate(2012, 4, 1));
+
+ final AccountData accountData = getAccountData(1);
+ final Account account = createAccountWithNonOsgiPaymentMethod(accountData);
+ accountChecker.checkAccount(account.getId(), accountData, callContext);
+
+ checkODState(OverdueWrapper.CLEAR_STATE_NAME, account.getId());
+
+ paymentPlugin.makeNextPaymentUnknown();
+
+ final DefaultEntitlement baseEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "bundleKey", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);
+
+ addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_PLUGIN_ERROR, NextEvent.INVOICE_PAYMENT_ERROR);
+
+ invoiceChecker.checkChargedThroughDate(baseEntitlement.getId(), new LocalDate(2012, 6, 1), callContext);
+
+ final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext);
+ assertEquals(invoices.size(), 2);
+
+ final Invoice invoice1 = invoices.get(0).getInvoiceItems().get(0).getInvoiceItemType() == InvoiceItemType.RECURRING ?
+ invoices.get(0) : invoices.get(1);
+ assertTrue(invoice1.getBalance().compareTo(new BigDecimal("249.95")) == 0);
+ assertTrue(invoice1.getPaidAmount().compareTo(BigDecimal.ZERO) == 0);
+ assertTrue(invoice1.getChargedAmount().compareTo(new BigDecimal("249.95")) == 0);
+ assertEquals(invoice1.getPayments().size(), 1);
+ assertEquals(invoice1.getPayments().get(0).getAmount().compareTo(BigDecimal.ZERO), 0);
+ assertEquals(invoice1.getPayments().get(0).getCurrency(), Currency.USD);
+ assertFalse(invoice1.getPayments().get(0).isSuccess());
+ assertNotNull(invoice1.getPayments().get(0).getPaymentId());
+
+ final BigDecimal accountBalance1 = invoiceUserApi.getAccountBalance(account.getId(), callContext);
+ assertTrue(accountBalance1.compareTo(new BigDecimal("249.95")) == 0);
+
+ final List<Payment> payments = paymentApi.getAccountPayments(account.getId(), false, true, ImmutableList.<PluginProperty>of(), callContext);
+ assertEquals(payments.size(), 1);
+ assertEquals(payments.get(0).getPurchasedAmount().compareTo(BigDecimal.ZERO), 0);
+ assertEquals(payments.get(0).getTransactions().size(), 1);
+ assertEquals(payments.get(0).getTransactions().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0);
+ assertEquals(payments.get(0).getTransactions().get(0).getCurrency(), Currency.USD);
+ assertEquals(payments.get(0).getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0);
+ assertEquals(payments.get(0).getTransactions().get(0).getProcessedCurrency(), Currency.USD);
+ assertEquals(payments.get(0).getTransactions().get(0).getTransactionStatus(), TransactionStatus.UNKNOWN);
+ assertEquals(payments.get(0).getPaymentAttempts().size(), 1);
+ assertEquals(payments.get(0).getPaymentAttempts().get(0).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME);
+ assertEquals(payments.get(0).getPaymentAttempts().get(0).getStateName(), "ABORTED");
+
+ // Verify account transitions to OD1
+ addDaysAndCheckForCompletion(2, NextEvent.BLOCK);
+ checkODState("OD1", account.getId());
+
+ // Verify we cannot trigger double payments
+ try {
+ invoicePaymentApi.createPurchaseForInvoicePayment(account,
+ invoice1.getId(),
+ payments.get(0).getPaymentMethodId(),
+ null,
+ invoice1.getBalance(),
+ invoice1.getCurrency(),
+ clock.getUTCNow(),
+ null,
+ null,
+ ImmutableList.<PluginProperty>of(),
+ PAYMENT_OPTIONS,
+ callContext);
+ Assert.fail();
+ } catch (final PaymentApiException e) {
+ Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_API_ABORTED.getCode());
+ assertListenerStatus();
+ }
+
+ // Transition the payment to success
+ final PaymentTransaction existingPaymentTransaction = payments.get(0).getTransactions().get(0);
+ final PaymentTransaction updatedPaymentTransaction = Mockito.mock(PaymentTransaction.class);
+ Mockito.when(updatedPaymentTransaction.getId()).thenReturn(existingPaymentTransaction.getId());
+ Mockito.when(updatedPaymentTransaction.getExternalKey()).thenReturn(existingPaymentTransaction.getExternalKey());
+ Mockito.when(updatedPaymentTransaction.getTransactionType()).thenReturn(existingPaymentTransaction.getTransactionType());
+ Mockito.when(updatedPaymentTransaction.getProcessedAmount()).thenReturn(new BigDecimal("249.95"));
+ Mockito.when(updatedPaymentTransaction.getProcessedCurrency()).thenReturn(existingPaymentTransaction.getCurrency());
+ busHandler.pushExpectedEvents(NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT, NextEvent.BLOCK);
+ adminPaymentApi.fixPaymentTransactionState(payments.get(0), updatedPaymentTransaction, TransactionStatus.SUCCESS, null, null, ImmutableList.<PluginProperty>of(), callContext);
+ assertListenerStatus();
+
+ checkODState(OverdueWrapper.CLEAR_STATE_NAME, account.getId());
+
+ final Invoice invoice2 = invoiceUserApi.getInvoice(invoice1.getId(), callContext);
+ assertTrue(invoice2.getBalance().compareTo(BigDecimal.ZERO) == 0);
+ assertTrue(invoice2.getPaidAmount().compareTo(new BigDecimal("249.95")) == 0);
+ assertTrue(invoice2.getChargedAmount().compareTo(new BigDecimal("249.95")) == 0);
+ assertEquals(invoice2.getPayments().size(), 1);
+ assertEquals(invoice2.getPayments().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0);
+ assertEquals(invoice2.getPayments().get(0).getCurrency(), Currency.USD);
+ assertTrue(invoice2.getPayments().get(0).isSuccess());
+ assertNotNull(invoice2.getPayments().get(0).getPaymentId());
+
+ final BigDecimal accountBalance2 = invoiceUserApi.getAccountBalance(account.getId(), callContext);
+ assertTrue(accountBalance2.compareTo(BigDecimal.ZERO) == 0);
+
+ final List<Payment> payments2 = paymentApi.getAccountPayments(account.getId(), false, true, ImmutableList.<PluginProperty>of(), callContext);
+ assertEquals(payments2.size(), 1);
+ assertEquals(payments2.get(0).getPurchasedAmount().compareTo(new BigDecimal("249.95")), 0);
+ assertEquals(payments2.get(0).getTransactions().size(), 1);
+ assertEquals(payments2.get(0).getTransactions().get(0).getAmount().compareTo(new BigDecimal("249.95")), 0);
+ assertEquals(payments2.get(0).getTransactions().get(0).getCurrency(), Currency.USD);
+ assertEquals(payments2.get(0).getTransactions().get(0).getProcessedAmount().compareTo(new BigDecimal("249.95")), 0);
+ assertEquals(payments2.get(0).getTransactions().get(0).getProcessedCurrency(), Currency.USD);
+ assertEquals(payments2.get(0).getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS);
+ assertEquals(payments2.get(0).getPaymentAttempts().size(), 1);
+ assertEquals(payments2.get(0).getPaymentAttempts().get(0).getPluginName(), InvoicePaymentControlPluginApi.PLUGIN_NAME);
+ assertEquals(payments2.get(0).getPaymentAttempts().get(0).getStateName(), "SUCCESS");
+ }
}
diff --git a/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java b/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java
index 0f2cba226c..1b9e082849 100644
--- a/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java
+++ b/invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java
@@ -217,6 +217,18 @@ public class DefaultInvoiceInternalApi implements InvoiceInternalApi {
));
}
+ @Override
+ public List<InvoicePayment> getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) {
+ return ImmutableList.<InvoicePayment>copyOf(Collections2.transform(dao.getInvoicePaymentsByInvoice(invoiceId, context),
+ new Function<InvoicePaymentModelDao, InvoicePayment>() {
+ @Override
+ public InvoicePayment apply(final InvoicePaymentModelDao input) {
+ return new DefaultInvoicePayment(input);
+ }
+ }
+ ));
+ }
+
@Override
public InvoicePayment getInvoicePaymentByCookieId(final String cookieId, final TenantContext context) {
final InvoicePaymentModelDao invoicePaymentModelDao = dao.getInvoicePaymentByCookieId(cookieId, internalCallContextFactory.createInternalTenantContext(context.getAccountId(), ObjectType.ACCOUNT, context));
diff --git a/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java b/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java
index 963e6c9cf4..cc48631f72 100644
--- a/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java
+++ b/invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java
@@ -559,6 +559,16 @@ public class DefaultInvoiceDao extends EntityDaoBase<InvoiceModelDao, Invoice, I
});
}
+ @Override
+ public List<InvoicePaymentModelDao> getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) {
+ return transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper<List<InvoicePaymentModelDao>>() {
+ @Override
+ public List<InvoicePaymentModelDao> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception {
+ return entitySqlDaoWrapperFactory.become(InvoicePaymentSqlDao.class).getAllPaymentsForInvoiceIncludedInit(invoiceId.toString(), context);
+ }
+ });
+ }
+
@Override
public InvoicePaymentModelDao getInvoicePaymentByCookieId(final String cookieId, final InternalTenantContext context) {
return transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper<InvoicePaymentModelDao>() {
diff --git a/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java b/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java
index 8d4f871c8b..e7c77901b5 100644
--- a/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java
+++ b/invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java
@@ -66,6 +66,8 @@ public interface InvoiceDao extends EntityDao<InvoiceModelDao, Invoice, InvoiceA
List<InvoicePaymentModelDao> getInvoicePaymentsByAccount(InternalTenantContext context);
+ List<InvoicePaymentModelDao> getInvoicePaymentsByInvoice(final UUID invoiceId, InternalTenantContext context);
+
InvoicePaymentModelDao getInvoicePaymentByCookieId(String cookieId, InternalTenantContext internalTenantContext);
BigDecimal getAccountBalance(UUID accountId, InternalTenantContext context);
diff --git a/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java b/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java
index b51ee616f0..32499dff55 100644
--- a/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java
+++ b/invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java
@@ -233,6 +233,19 @@ public class MockInvoiceDao extends MockEntityDaoBase<InvoiceModelDao, Invoice,
return result;
}
+ @Override
+ public List<InvoicePaymentModelDao> getInvoicePaymentsByInvoice(final UUID invoiceId, final InternalTenantContext context) {
+ final List<InvoicePaymentModelDao> result = new LinkedList<InvoicePaymentModelDao>();
+ synchronized (monitor) {
+ for (final InvoicePaymentModelDao payment : payments.values()) {
+ if (invoiceId.equals(payment.getInvoiceId())) {
+ result.add(payment);
+ }
+ }
+ }
+ return result;
+ }
+
@Override
public List<InvoicePaymentModelDao> getInvoicePaymentsByAccount(final InternalTenantContext context) {
diff --git a/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java b/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java
index ecb7dd218c..01277a9b92 100644
--- a/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java
+++ b/payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java
@@ -55,6 +55,7 @@ import org.killbill.billing.payment.api.PaymentApiException;
import org.killbill.billing.payment.api.PluginProperty;
import org.killbill.billing.payment.api.TransactionStatus;
import org.killbill.billing.payment.api.TransactionType;
+import org.killbill.billing.payment.core.janitor.IncompletePaymentTransactionTask;
import org.killbill.billing.payment.dao.PaymentDao;
import org.killbill.billing.payment.dao.PaymentModelDao;
import org.killbill.billing.payment.dao.PaymentTransactionModelDao;
@@ -321,7 +322,6 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi
return new DefaultPriorPaymentControlResult(true);
}
-
// Get account and check if it is child and payment is delegated to parent => abort
final AccountData accountData = accountApi.getAccountById(invoice.getAccountId(), internalContext);
@@ -340,7 +340,7 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi
// Do we have a paymentMethod ?
if (paymentControlPluginContext.getPaymentMethodId() == null) {
- log.warn("Payment for invoiceId='{}' was not triggered, accountId='{}' doesn't have a default payment method", getInvoiceId(pluginProperties), paymentControlPluginContext.getAccountId());
+ log.warn("Payment for invoiceId='{}' was not triggered, accountId='{}' doesn't have a default payment method", invoiceId, paymentControlPluginContext.getAccountId());
invoiceApi.recordPaymentAttemptCompletion(invoiceId,
paymentControlPluginContext.getAmount(),
paymentControlPluginContext.getCurrency(),
@@ -359,6 +359,16 @@ public final class InvoicePaymentControlPluginApi implements PaymentControlPlugi
return new DefaultPriorPaymentControlResult(true);
}
+ final List<InvoicePayment> existingInvoicePayments = invoiceApi.getInvoicePaymentsByInvoice(invoiceId, internalContext);
+ for (final InvoicePayment existingInvoicePayment : existingInvoicePayments) {
+ final List<PaymentTransactionModelDao> existingTransactions = paymentDao.getPaymentTransactionsByExternalKey(existingInvoicePayment.getPaymentCookieId(), internalContext);
+ for (final PaymentTransactionModelDao existingTransaction : existingTransactions) {
+ if (existingTransaction.getTransactionStatus() == TransactionStatus.UNKNOWN) {
+ log.warn("Existing paymentTransactionId='{}' for invoiceId='{}' in UNKNOWN state", existingTransaction.getId(), invoiceId);
+ return new DefaultPriorPaymentControlResult(true);
+ }
+ }
+ }
//
// Insert attempt row with a success = false status to implement a two-phase commit strategy and guard against scenario where payment would go through
diff --git a/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java b/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java
index 32bba1c8da..78004a59c5 100644
--- a/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java
+++ b/payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java
@@ -1,7 +1,7 @@
/*
* Copyright 2010-2013 Ning, Inc.
- * Copyright 2014-2016 Groupon, Inc
- * Copyright 2014-2016 The Billing Project, LLC
+ * Copyright 2014-2018 Groupon, Inc
+ * Copyright 2014-2018 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
@@ -76,6 +76,7 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi {
private final AtomicBoolean makeNextPaymentFailWithException = new AtomicBoolean(false);
private final AtomicBoolean makeAllPaymentsFailWithError = new AtomicBoolean(false);
private final AtomicBoolean makeNextPaymentPending = new AtomicBoolean(false);
+ private final AtomicBoolean makeNextPaymentUnknown = new AtomicBoolean(false);
private final AtomicInteger makePluginWaitSomeMilliseconds = new AtomicInteger(0);
private final AtomicReference<BigDecimal> overrideNextProcessedAmount = new AtomicReference<BigDecimal>();
private final AtomicReference<Currency> overrideNextProcessedCurrency = new AtomicReference<Currency>();
@@ -206,6 +207,7 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi {
makeNextPaymentFailWithError.set(false);
makeNextPaymentFailWithCancellation.set(false);
makeNextPaymentPending.set(false);
+ makeNextPaymentUnknown.set(false);
makePluginWaitSomeMilliseconds.set(0);
overrideNextProcessedAmount.set(null);
paymentMethods.clear();
@@ -222,6 +224,10 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi {
makeNextPaymentPending.set(true);
}
+ public void makeNextPaymentUnknown() {
+ makeNextPaymentUnknown.set(true);
+ }
+
public void makeNextPaymentFailWithCancellation() {
makeNextPaymentFailWithCancellation.set(true);
}
@@ -465,6 +471,8 @@ public class MockPaymentProviderPlugin implements PaymentPluginApi {
status = PaymentPluginStatus.CANCELED;
} else if (makeNextPaymentPending.getAndSet(false)) {
status = PaymentPluginStatus.PENDING;
+ } else if (makeNextPaymentUnknown.getAndSet(false)) {
+ status = PaymentPluginStatus.UNDEFINED;
} else {
status = PaymentPluginStatus.PROCESSED;
} | ['beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestInvoicePayment.java', 'invoice/src/test/java/org/killbill/billing/invoice/dao/MockInvoiceDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/api/svcs/DefaultInvoiceInternalApi.java', 'api/src/main/java/org/killbill/billing/invoice/api/InvoiceInternalApi.java', 'invoice/src/main/java/org/killbill/billing/invoice/dao/InvoiceDao.java', 'invoice/src/main/java/org/killbill/billing/invoice/dao/DefaultInvoiceDao.java', 'payment/src/test/java/org/killbill/billing/payment/provider/MockPaymentProviderPlugin.java', 'payment/src/main/java/org/killbill/billing/payment/invoice/InvoicePaymentControlPluginApi.java'] | {'.java': 8} | 8 | 8 | 0 | 0 | 8 | 6,119,816 | 1,147,700 | 132,717 | 1,008 | 3,226 | 500 | 40 | 5 | 331 | 45 | 68 | 8 | 0 | 0 | 2018-06-28T01:11:20 | 4,053 | Java | {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593} | Apache License 2.0 |
256 | killbill/killbill/550/548 | killbill | killbill | https://github.com/killbill/killbill/issues/548 | https://github.com/killbill/killbill/pull/550 | https://github.com/killbill/killbill/pull/550 | 1 | fixes | DefaultPaymentGatewayApi doesn't respect isAborted flag | We should make sure 422 is returned if the HPP payment is aborted by a control plugin.
| 071796f5dcb8dd7c52fd8a0cd28aa0cf1a6a0120 | 13fd4001d59e59868186e2a306146d572be750dc | https://github.com/killbill/killbill/compare/071796f5dcb8dd7c52fd8a0cd28aa0cf1a6a0120...13fd4001d59e59868186e2a306146d572be750dc | diff --git a/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java b/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java
index ec17b19c60..09685fa60b 100644
--- a/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java
+++ b/payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java
@@ -34,6 +34,7 @@ import org.killbill.billing.control.plugin.api.PriorPaymentControlResult;
import org.killbill.billing.payment.core.PaymentExecutors;
import org.killbill.billing.payment.core.PaymentGatewayProcessor;
import org.killbill.billing.payment.core.sm.control.ControlPluginRunner;
+import org.killbill.billing.payment.core.sm.control.PaymentControlApiAbortException;
import org.killbill.billing.payment.dispatcher.PluginDispatcher;
import org.killbill.billing.payment.dispatcher.PluginDispatcher.PluginDispatcherReturnType;
import org.killbill.billing.payment.plugin.api.GatewayNotification;
@@ -147,6 +148,8 @@ public class DefaultPaymentGatewayApi extends DefaultApiBase implements PaymentG
PaymentApiType.HPP, null, HPPType.BUILD_FORM_DESCRIPTOR,
null, null, true, paymentControlPluginNames, properties, callContext);
+ } catch (final PaymentControlApiAbortException e) {
+ throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_API_ABORTED, e.getPluginName());
} catch (final PaymentControlApiException e) {
throw new PaymentApiException(e, ErrorCode.PAYMENT_PLUGIN_EXCEPTION, e);
}
diff --git a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java
index f2b1472cc3..1ee36fc04a 100644
--- a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java
+++ b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java
@@ -25,7 +25,6 @@ import javax.annotation.Nullable;
import javax.inject.Inject;
import org.joda.time.DateTime;
-import org.killbill.billing.ErrorCode;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.callcontext.DefaultCallContext;
import org.killbill.billing.catalog.api.Currency;
@@ -38,7 +37,6 @@ import org.killbill.billing.control.plugin.api.PaymentControlContext;
import org.killbill.billing.control.plugin.api.PaymentControlPluginApi;
import org.killbill.billing.control.plugin.api.PriorPaymentControlResult;
import org.killbill.billing.osgi.api.OSGIServiceRegistration;
-import org.killbill.billing.payment.api.PaymentApiException;
import org.killbill.billing.payment.api.PluginProperty;
import org.killbill.billing.payment.api.TransactionType;
import org.killbill.billing.payment.retry.DefaultFailureCallResult;
diff --git a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java
index c3524e5bd6..33b4df4b54 100644
--- a/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java
+++ b/payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java
@@ -22,7 +22,7 @@ import org.killbill.billing.control.plugin.api.PaymentControlApiException;
/**
* Created by arodrigues on 5/6/16.
*/
-class PaymentControlApiAbortException extends PaymentControlApiException {
+public class PaymentControlApiAbortException extends PaymentControlApiException {
private final String pluginName;
public PaymentControlApiAbortException(final String pluginName) {
diff --git a/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java b/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java
index 680221b084..3aa3554519 100644
--- a/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java
+++ b/payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java
@@ -21,6 +21,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
+import org.killbill.billing.ErrorCode;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.control.plugin.api.OnFailurePaymentControlResult;
import org.killbill.billing.control.plugin.api.OnSuccessPaymentControlResult;
@@ -152,6 +153,20 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD
}
+ @Test(groups = "fast")
+ public void testBuildFormDescriptorWithPaymentControlAbortedPayment() throws PaymentApiException {
+ plugin.setAborted(true);
+
+ // Set a random UUID to verify the plugin will successfully override it
+ try {
+ paymentGatewayApi.buildFormDescriptorWithPaymentControl(account, UUID.randomUUID(), ImmutableList.<PluginProperty>of(), ImmutableList.<PluginProperty>of(), paymentOptions, callContext);
+ Assert.fail();
+ } catch (PaymentApiException e) {
+ Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_API_ABORTED.getCode());
+ }
+
+ }
+
public static class TestPaymentGatewayApiValidationPlugin implements PaymentControlPluginApi {
public static final String VALIDATION_PLUGIN_NAME = "TestPaymentGatewayApiValidationPlugin";
@@ -216,13 +231,20 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD
private Iterable<PluginProperty> newOnResultProperties;
private Iterable<PluginProperty> removedOnResultProperties;
+ private boolean aborted;
+
public TestPaymentGatewayApiControlPlugin() {
+ this.aborted = false;
this.newPriorCallProperties = ImmutableList.of();
this.removedPriorCallProperties = ImmutableList.of();
this.newOnResultProperties = ImmutableList.of();
this.removedOnResultProperties = ImmutableList.of();
}
+ public void setAborted(final boolean aborted) {
+ this.aborted = aborted;
+ }
+
public void setPriorCallProperties(final Iterable<PluginProperty> newPriorCallProperties, final Iterable<PluginProperty> removedPriorCallProperties) {
this.newPriorCallProperties = newPriorCallProperties;
this.removedPriorCallProperties = removedPriorCallProperties;
@@ -235,7 +257,7 @@ public class TestPaymentGatewayApiWithPaymentControl extends PaymentTestSuiteNoD
@Override
public PriorPaymentControlResult priorCall(final PaymentControlContext paymentControlContext, final Iterable<PluginProperty> properties) throws PaymentControlApiException {
- return new DefaultPriorPaymentControlResult(false, account.getPaymentMethodId(), null, null, getAdjustedProperties(properties, newPriorCallProperties, removedPriorCallProperties));
+ return new DefaultPriorPaymentControlResult(aborted, account.getPaymentMethodId(), null, null, getAdjustedProperties(properties, newPriorCallProperties, removedPriorCallProperties));
}
@Override | ['payment/src/main/java/org/killbill/billing/payment/api/DefaultPaymentGatewayApi.java', 'payment/src/main/java/org/killbill/billing/payment/core/sm/control/ControlPluginRunner.java', 'payment/src/main/java/org/killbill/billing/payment/core/sm/control/PaymentControlApiAbortException.java', 'payment/src/test/java/org/killbill/billing/payment/api/TestPaymentGatewayApiWithPaymentControl.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 4,876,641 | 926,318 | 109,381 | 927 | 596 | 95 | 7 | 3 | 87 | 17 | 20 | 2 | 0 | 0 | 2016-05-21T03:51:18 | 4,053 | Java | {'Java': 13504959, 'JavaScript': 136386, 'CSS': 105855, 'Shell': 23107, 'HTML': 16358, 'PLpgSQL': 14609, 'Ruby': 9048, 'Mustache': 4593} | Apache License 2.0 |