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] | repo_stars
int64 10
44.3k
| repo_language
stringclasses 8
values | repo_languages
stringclasses 296
values | repo_license
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
308 | apache/fluo/837/835 | apache | fluo | https://github.com/apache/fluo/issues/835 | https://github.com/apache/fluo/pull/837 | https://github.com/apache/fluo/pull/837 | 1 | fixes | Collision trace logging does not hex escape data | While trying to debug some unexpected collisions in webindex, I noticed that logging of collisions does not hex escape binary data like other transaction trace logging does.
```
17:48:45.466 [Fluo-0002-007-async-commits] TRACE fluo.tx.collisions - txid: 14580734 trigger: p:1prp:net.analystratings>.www>o>/stocks/NYSE/LCI/ page new 14536153
17:48:45.466 [Fluo-0002-007-async-commits] TRACE fluo.tx.collisions - txid: 14580734 class: webindex.data.fluo.PageObserver
17:48:45.466 [Fluo-0002-007-async-commits] TRACE fluo.tx.collisions - txid: 14580734 collisions: {um:u:679:^C^Acom.reuters>.www>o>/finance/stocks/companyProfile?symbol=LC�^@^@^@^@^@�{�=[u v ], um:u:366:^C^A�^Agov.sec>.www>o>/Archives/edgar/data/57725/000120919115012121/xslF345X03/doc4.xml^@^@^@^@^@�{�=[u v ]}
``` | 88fbff6ef1d1673a267dff2e86d73aaf73042430 | 6a05f6cc53619b666d672df2c43a6813c332e1de | https://github.com/apache/fluo/compare/88fbff6ef1d1673a267dff2e86d73aaf73042430...6a05f6cc53619b666d672df2c43a6813c332e1de | diff --git a/modules/core/src/main/java/org/apache/fluo/core/log/TracingTransaction.java b/modules/core/src/main/java/org/apache/fluo/core/log/TracingTransaction.java
index 62f61a18..0753cd41 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/log/TracingTransaction.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/log/TracingTransaction.java
@@ -37,6 +37,8 @@ import org.apache.fluo.core.util.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.apache.fluo.core.util.Hex.encNonAscii;
+
public class TracingTransaction extends AbstractTransactionBase implements AsyncTransaction,
Snapshot {
@@ -52,12 +54,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
private Class<?> clazz;
private boolean committed = false;
- private static String enc(Bytes b) {
- return Hex.encNonAscii(b);
- }
-
- private static String enc(Column c) {
- return Hex.encNonAscii(c);
+ private static String toStringEncNonAscii(Column c) {
+ return encNonAscii(c);
}
public TracingTransaction(AsyncTransaction tx) {
@@ -68,32 +66,37 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
this(tx, null, clazz, txExecId);
}
- private String encB(Collection<Bytes> columns) {
+ private String toStringEncNonAsciiCB(Collection<Bytes> columns) {
return Iterators.toString(Iterators.transform(columns.iterator(), Hex::encNonAscii));
}
- private String encRC(Collection<RowColumn> ret) {
+ private String toStringEncNonAsciiCRC(Collection<RowColumn> ret) {
return Iterators.toString(Iterators.transform(ret.iterator(), Hex::encNonAscii));
}
- private String encRC(Map<Bytes, Map<Column, Bytes>> ret) {
- return Iterators.toString(Iterators.transform(ret.entrySet().iterator(), e -> enc(e.getKey())
- + "=" + encC(e.getValue())));
+ private String toStringEncNonAsciiMBMCB(Map<Bytes, Map<Column, Bytes>> ret) {
+ return Iterators.toString(Iterators.transform(ret.entrySet().iterator(),
+ e -> encNonAscii(e.getKey()) + "=" + toStringEncNonAsciiMCB(e.getValue())));
}
- private String encRCM(Map<RowColumn, Bytes> ret) {
+ private String toStringEncNonAsciiMRCB(Map<RowColumn, Bytes> ret) {
return Iterators.toString(Iterators.transform(ret.entrySet().iterator(),
- e -> Hex.encNonAscii(e.getKey()) + "=" + enc(e.getValue())));
+ e -> encNonAscii(e.getKey()) + "=" + encNonAscii(e.getValue())));
}
- private String encC(Collection<Column> columns) {
+ private String toStringEncNonAsciiCC(Collection<Column> columns) {
return Iterators.toString(Iterators.transform(columns.iterator(), Hex::encNonAscii));
}
- private String encC(Map<Column, Bytes> ret) {
- return Iterators.toString(Iterators.transform(ret.entrySet().iterator(), e -> enc(e.getKey())
- + "=" + enc(e.getValue())));
+ private String toStringEncNonAsciiMCB(Map<Column, Bytes> ret) {
+ return Iterators.toString(Iterators.transform(ret.entrySet().iterator(),
+ e -> toStringEncNonAscii(e.getKey()) + "=" + encNonAscii(e.getValue())));
+ }
+
+ private String toStringEncNonAsciiMBSC(Map<Bytes, Set<Column>> m) {
+ return Iterators.toString(Iterators.transform(m.entrySet().iterator(),
+ e -> encNonAscii(e.getKey()) + "=" + toStringEncNonAsciiCC(e.getValue())));
}
public TracingTransaction(AsyncTransaction tx, Notification notification, Class<?> clazz,
@@ -108,8 +111,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
log.trace("txid: {} begin() thread: {}", txid, Thread.currentThread().getId());
if (notification != null) {
- log.trace("txid: {} trigger: {} {} {}", txid, enc(notification.getRow()),
- enc(notification.getColumn()), notification.getTimestamp());
+ log.trace("txid: {} trigger: {} {} {}", txid, encNonAscii(notification.getRow()),
+ toStringEncNonAscii(notification.getColumn()), notification.getTimestamp());
}
if (clazz != null) {
@@ -127,7 +130,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
public Bytes get(Bytes row, Column column) {
Bytes ret = tx.get(row, column);
if (log.isTraceEnabled()) {
- log.trace("txid: {} get({}, {}) -> {}", txid, enc(row), enc(column), enc(ret));
+ log.trace("txid: {} get({}, {}) -> {}", txid, encNonAscii(row), toStringEncNonAscii(column),
+ encNonAscii(ret));
}
return ret;
}
@@ -136,7 +140,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
public Map<Column, Bytes> get(Bytes row, Set<Column> columns) {
Map<Column, Bytes> ret = tx.get(row, columns);
if (log.isTraceEnabled()) {
- log.trace("txid: {} get({}, {}) -> {}", txid, enc(row), encC(columns), encC(ret));
+ log.trace("txid: {} get({}, {}) -> {}", txid, encNonAscii(row),
+ toStringEncNonAsciiCC(columns), toStringEncNonAsciiMCB(ret));
}
return ret;
}
@@ -145,7 +150,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
public Map<Bytes, Map<Column, Bytes>> get(Collection<Bytes> rows, Set<Column> columns) {
Map<Bytes, Map<Column, Bytes>> ret = tx.get(rows, columns);
if (log.isTraceEnabled()) {
- log.trace("txid: {} get({}, {}) -> {}", txid, encB(rows), encC(columns), encRC(ret));
+ log.trace("txid: {} get({}, {}) -> {}", txid, toStringEncNonAsciiCB(rows),
+ toStringEncNonAsciiCC(columns), toStringEncNonAsciiMBMCB(ret));
}
return ret;
}
@@ -154,7 +160,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
public Map<RowColumn, Bytes> get(Collection<RowColumn> rowColumns) {
Map<RowColumn, Bytes> ret = tx.get(rowColumns);
if (log.isTraceEnabled()) {
- log.trace("txid: {} get({}) -> {}", txid, encRC(rowColumns), encRCM(ret));
+ log.trace("txid: {} get({}) -> {}", txid, toStringEncNonAsciiCRC(rowColumns),
+ toStringEncNonAsciiMRCB(ret));
}
return ret;
}
@@ -167,7 +174,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
@Override
public void setWeakNotification(Bytes row, Column col) {
if (log.isTraceEnabled()) {
- log.trace("txid: {} setWeakNotification({}, {})", txid, enc(row), enc(col));
+ log.trace("txid: {} setWeakNotification({}, {})", txid, encNonAscii(row),
+ toStringEncNonAscii(col));
}
tx.setWeakNotification(row, col);
}
@@ -175,7 +183,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
@Override
public void set(Bytes row, Column col, Bytes value) throws AlreadySetException {
if (log.isTraceEnabled()) {
- log.trace("txid: {} set({}, {}, {})", txid, enc(row), enc(col), enc(value));
+ log.trace("txid: {} set({}, {}, {})", txid, encNonAscii(row), toStringEncNonAscii(col),
+ encNonAscii(value));
}
tx.set(row, col, value);
}
@@ -183,7 +192,7 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
@Override
public void delete(Bytes row, Column col) throws AlreadySetException {
if (log.isTraceEnabled()) {
- log.trace("txid: {} delete({}, {})", txid, enc(row), enc(col));
+ log.trace("txid: {} delete({}, {})", txid, encNonAscii(row), toStringEncNonAscii(col));
}
tx.delete(row, col);
}
@@ -212,7 +221,8 @@ public class TracingTransaction extends AbstractTransactionBase implements Async
collisionLog.trace("txid: {} class: {}", txid, clazz.getName());
}
- collisionLog.trace("txid: {} collisions: {}", txid, tx.getStats().getRejected());
+ collisionLog.trace("txid: {} collisions: {}", txid, toStringEncNonAsciiMBSC(tx.getStats()
+ .getRejected()));
}
@Override
diff --git a/modules/integration/src/test/java/org/apache/fluo/integration/TestUtil.java b/modules/integration/src/test/java/org/apache/fluo/integration/TestUtil.java
index fe9ee27b..61ce45e1 100644
--- a/modules/integration/src/test/java/org/apache/fluo/integration/TestUtil.java
+++ b/modules/integration/src/test/java/org/apache/fluo/integration/TestUtil.java
@@ -17,18 +17,26 @@ package org.apache.fluo.integration;
import org.apache.fluo.api.client.SnapshotBase;
import org.apache.fluo.api.client.TransactionBase;
+import org.apache.fluo.api.data.Bytes;
import org.apache.fluo.api.data.Column;
public class TestUtil {
private TestUtil() {}
+ private static final Bytes ZERO = Bytes.of("0");
+
+ public static void increment(TransactionBase tx, Bytes row, Column col, int val) {
+ int prev = 0;
+ String prevStr = tx.get(row, col, ZERO).toString();
+ prev = Integer.parseInt(prevStr);
+ tx.set(row, col, Bytes.of(prev + val + ""));
+ }
+
public static void increment(TransactionBase tx, String row, Column col, int val) {
int prev = 0;
- String prevStr = tx.gets(row, col);
- if (prevStr != null) {
- prev = Integer.parseInt(prevStr);
- }
+ String prevStr = tx.gets(row, col, "0");
+ prev = Integer.parseInt(prevStr);
tx.set(row, col, prev + val + "");
}
diff --git a/modules/integration/src/test/java/org/apache/fluo/integration/log/LogIT.java b/modules/integration/src/test/java/org/apache/fluo/integration/log/LogIT.java
index 7e1e2794..fe712fe1 100644
--- a/modules/integration/src/test/java/org/apache/fluo/integration/log/LogIT.java
+++ b/modules/integration/src/test/java/org/apache/fluo/integration/log/LogIT.java
@@ -56,12 +56,20 @@ public class LogIT extends ITBaseMini {
private static final Column STAT_COUNT = new Column("stat", "count");
static class SimpleLoader implements Loader {
-
public void load(TransactionBase tx, Context context) throws Exception {
TestUtil.increment(tx, "r1", new Column("a", "b"), 1);
}
}
+ static class SimpleBinaryLoader implements Loader {
+
+ private static final Bytes ROW = Bytes.of(new byte[] {'r', '1', 13});
+
+ public void load(TransactionBase tx, Context context) throws Exception {
+ TestUtil.increment(tx, ROW, new Column(Bytes.of("a"), Bytes.of(new byte[] {0, 9})), 1);
+ }
+ }
+
static class TriggerLoader implements Loader {
int r;
@@ -147,7 +155,7 @@ public class LogIT extends ITBaseMini {
try (LoaderExecutor le = client.newLoaderExecutor()) {
for (int i = 0; i < 20; i++) {
- le.execute(new SimpleLoader());
+ le.execute(new SimpleBinaryLoader());
le.execute(new TriggerLoader(i));
}
}
@@ -166,13 +174,13 @@ public class LogIT extends ITBaseMini {
String pattern;
- pattern = ".*txid: (\\\\d+) class: org.apache.fluo.integration.log.LogIT\\\\$SimpleLoader";
- pattern += ".*txid: \\\\1 collisions: \\\\Q{r1=[a b ]}\\\\E.*";
+ pattern = ".*txid: (\\\\d+) class: org.apache.fluo.integration.log.LogIT\\\\$SimpleBinaryLoader";
+ pattern += ".*txid: \\\\1 collisions: \\\\Q[r1\\\\x0d=[a \\\\x00\\\\x09 ]]\\\\E.*";
Assert.assertTrue(logMsgs.matches(pattern));
pattern = ".*txid: (\\\\d+) trigger: \\\\d+ stat count \\\\d+";
pattern += ".*txid: \\\\1 class: org.apache.fluo.integration.log.LogIT\\\\$TestObserver";
- pattern += ".*txid: \\\\1 collisions: \\\\Q{all=[stat count ]}\\\\E.*";
+ pattern += ".*txid: \\\\1 collisions: \\\\Q[all=[stat count ]]\\\\E.*";
Assert.assertTrue(logMsgs.matches(pattern));
}
| ['modules/integration/src/test/java/org/apache/fluo/integration/log/LogIT.java', 'modules/core/src/main/java/org/apache/fluo/core/log/TracingTransaction.java', 'modules/integration/src/test/java/org/apache/fluo/integration/TestUtil.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 828,150 | 182,682 | 24,938 | 189 | 4,069 | 1,007 | 64 | 1 | 785 | 64 | 287 | 6 | 0 | 1 | 1970-01-01T00:24:54 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
309 | apache/fluo/836/834 | apache | fluo | https://github.com/apache/fluo/issues/834 | https://github.com/apache/fluo/pull/836 | https://github.com/apache/fluo/pull/836 | 1 | fixes | Seeing spurious NPE in worker logs | Saw the following exception in worker logs while testing 1.1.0-SNAP. I was using commit 4055cdfbe13eb34f8830db3ba2201c6428d26fd4
I think at [Oracle client line 117][1] that `leaderSelector` needs to be created before stating `pathChildrenCache`
[1]: https://github.com/apache/incubator-fluo/blob/4055cdfbe13eb34f8830db3ba2201c6428d26fd4/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleClient.java#L117
```
java.lang.NullPointerException: null
at org.apache.fluo.core.oracle.OracleClient$TimestampRetriever.childEvent(OracleClient.java:145) ~[fluo-core-1.1.0-incubating-SNAPSHOT.jar:1.1.0-incubating-SNAPSHOT]
at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:516) [curator-recipes-2.7.1.jar:na]
at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:510) [curator-recipes-2.7.1.jar:na]
at org.apache.curator.framework.listen.ListenerContainer$1.run(ListenerContainer.java:92) [curator-framework-2.7.1.jar:na]
at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:262) [guava-13.0.1.jar:na]
at org.apache.curator.framework.listen.ListenerContainer.forEach(ListenerContainer.java:84) [curator-framework-2.7.1.jar:na]
at org.apache.curator.framework.recipes.cache.PathChildrenCache.callListeners(PathChildrenCache.java:508) [curator-recipes-2.7.1.jar:na]
at org.apache.curator.framework.recipes.cache.EventOperation.invoke(EventOperation.java:35) [curator-recipes-2.7.1.jar:na]
at org.apache.curator.framework.recipes.cache.PathChildrenCache$9.run(PathChildrenCache.java:759) [curator-recipes-2.7.1.jar:na]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_131]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_131]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_131]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
``` | 4055cdfbe13eb34f8830db3ba2201c6428d26fd4 | 26c01b98b332b54038ddc1775accd389d554a417 | https://github.com/apache/fluo/compare/4055cdfbe13eb34f8830db3ba2201c6428d26fd4...26c01b98b332b54038ddc1775accd389d554a417 | diff --git a/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleClient.java b/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleClient.java
index 66a0c9e6..d8eaed4c 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleClient.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleClient.java
@@ -111,13 +111,13 @@ public class OracleClient implements AutoCloseable {
Thread.sleep(200);
}
+ leaderSelector = new LeaderSelector(curatorFramework, ZookeeperPath.ORACLE_SERVER, this);
+
pathChildrenCache =
new PathChildrenCache(curatorFramework, ZookeeperPath.ORACLE_SERVER, true);
pathChildrenCache.getListenable().addListener(this);
pathChildrenCache.start();
- leaderSelector = new LeaderSelector(curatorFramework, ZookeeperPath.ORACLE_SERVER, this);
-
connect();
}
doWork(); | ['modules/core/src/main/java/org/apache/fluo/core/oracle/OracleClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 828,150 | 182,682 | 24,938 | 189 | 205 | 40 | 4 | 1 | 2,395 | 85 | 679 | 26 | 1 | 1 | 1970-01-01T00:24:54 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
310 | apache/fluo/563/562 | apache | fluo | https://github.com/apache/fluo/issues/562 | https://github.com/apache/fluo/pull/563 | https://github.com/apache/fluo/pull/563 | 1 | closed | Stop timing out while retrieving ResourceReport when starting Fluo application | This exception puts Fluo in a weird state as the YARN application ID is not written to Zookeeper. In this case, Fluo should just keep on trying to get the ResourceReport and a exception should not be thrown.
```
java.lang.IllegalStateException: java.lang.IllegalStateException: Failed to get resource report
at io.fluo.cluster.runner.YarnAppRunner.start(YarnAppRunner.java:251)
at io.fluo.cluster.command.FluoCommand.main(FluoCommand.java:76)
Caused by: java.lang.IllegalStateException: Failed to get resource report
at io.fluo.cluster.runner.YarnAppRunner.getResourceReport(YarnAppRunner.java:304)
at io.fluo.cluster.runner.YarnAppRunner.start(YarnAppRunner.java:230)
... 1 more
```
| 50d5fde1f9f47db07c313d9e7e6f6fa6fcf5a117 | 96af2864b70a5702cd422d797a80c1041b1f7345 | https://github.com/apache/fluo/compare/50d5fde1f9f47db07c313d9e7e6f6fa6fcf5a117...96af2864b70a5702cd422d797a80c1041b1f7345 | diff --git a/modules/cluster/src/main/java/io/fluo/cluster/runner/YarnAppRunner.java b/modules/cluster/src/main/java/io/fluo/cluster/runner/YarnAppRunner.java
index f9af6095..66e129a9 100644
--- a/modules/cluster/src/main/java/io/fluo/cluster/runner/YarnAppRunner.java
+++ b/modules/cluster/src/main/java/io/fluo/cluster/runner/YarnAppRunner.java
@@ -227,7 +227,7 @@ public class YarnAppRunner extends ClusterAppRunner implements AutoCloseable {
twillId.getBytes(StandardCharsets.UTF_8), CuratorUtil.NodeExistsPolicy.OVERWRITE);
// set app id in zookeeper
- String appId = getResourceReport(controller).getApplicationId();
+ String appId = getResourceReport(controller, -1).getApplicationId();
Preconditions.checkNotNull(appId, "Failed to retrieve YARN app ID from Twill");
CuratorUtil.putData(getAppCurator(config), ZookeeperPath.YARN_APP_ID,
appId.getBytes(StandardCharsets.UTF_8), CuratorUtil.NodeExistsPolicy.OVERWRITE);
@@ -289,7 +289,11 @@ public class YarnAppRunner extends ClusterAppRunner implements AutoCloseable {
}
}
- private ResourceReport getResourceReport(TwillController controller) {
+ /**
+ * Attempts to retrieves ResourceReport until maxWaitMs time is reached.
+ * Set maxWaitMs to -1 to retry forever.
+ */
+ private ResourceReport getResourceReport(TwillController controller, int maxWaitMs) {
ResourceReport report = controller.getResourceReport();
int elapsed = 0;
while (report == null) {
@@ -300,8 +304,14 @@ public class YarnAppRunner extends ClusterAppRunner implements AutoCloseable {
throw new IllegalStateException(e);
}
elapsed += 500;
- if (elapsed > 30000) {
- throw new IllegalStateException("Failed to get resource report");
+ if ((maxWaitMs != -1) && (elapsed > maxWaitMs)) {
+ String msg = String.format("Exceeded max wait time to retrieve ResourceReport from Twill."
+ + " Elapsed time = %s ms", elapsed);
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ if ((elapsed % 10000) == 0) {
+ log.info("Waiting for ResourceReport from Twill. Elapsed time = {} ms", elapsed);
}
}
return report;
@@ -309,7 +319,7 @@ public class YarnAppRunner extends ClusterAppRunner implements AutoCloseable {
private boolean isReady(TwillController controller) {
try {
- if (getResourceReport(controller) != null) {
+ if (getResourceReport(controller, 30000) != null) {
return true;
}
} catch (Exception e) {
@@ -357,7 +367,7 @@ public class YarnAppRunner extends ClusterAppRunner implements AutoCloseable {
}
if (extraInfo) {
- ResourceReport report = getResourceReport(controller);
+ ResourceReport report = getResourceReport(controller, 30000);
Collection<TwillRunResources> resources;
resources = report.getRunnableResources(FluoOracleMain.ORACLE_NAME);
System.out.println("\\nThe application has " + resources.size() + " of " | ['modules/cluster/src/main/java/io/fluo/cluster/runner/YarnAppRunner.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 638,382 | 143,432 | 20,357 | 142 | 1,234 | 256 | 22 | 1 | 726 | 66 | 171 | 12 | 0 | 1 | 1970-01-01T00:24:04 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
326 | apache/fluo/69/67 | apache | fluo | https://github.com/apache/fluo/issues/67 | https://github.com/apache/fluo/pull/69 | https://github.com/apache/fluo/pull/69 | 1 | closes | Oracle is advertising its IP address as 0.0.0.0 in Zookeeper | This is preventing remote oracle clients from connecting to the Oracle in a distributed environment. This should be changed to the hostname of the machine where the oracle resides.
| 4c71b7f1c9b1890abfdc0be2403a1eda56a4898a | 2a5582750dbf02dc3e948e1188548addfec316ae | https://github.com/apache/fluo/compare/4c71b7f1c9b1890abfdc0be2403a1eda56a4898a...2a5582750dbf02dc3e948e1188548addfec316ae | diff --git a/modules/core/src/main/java/accismus/impl/OracleServer.java b/modules/core/src/main/java/accismus/impl/OracleServer.java
index 0104cf4c..3b13c9e6 100644
--- a/modules/core/src/main/java/accismus/impl/OracleServer.java
+++ b/modules/core/src/main/java/accismus/impl/OracleServer.java
@@ -16,9 +16,11 @@
*/
package accismus.impl;
-import accismus.impl.support.CuratorCnxnListener;
-import accismus.impl.thrift.OracleService;
-import com.google.common.annotations.VisibleForTesting;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.InetSocketAddress;
+
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
@@ -36,7 +38,10 @@ import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.net.InetSocketAddress;
+import accismus.impl.support.CuratorCnxnListener;
+import accismus.impl.thrift.OracleService;
+
+import com.google.common.annotations.VisibleForTesting;
/**
* Oracle server is the responsible for providing incrementing logical timestamps to clients. It should never
@@ -148,6 +153,12 @@ public class OracleServer extends LeaderSelectorListenerAdapter implements Oracl
return addr;
}
+
+ private String getHostName() throws IOException {
+ Process p = Runtime.getRuntime().exec("hostname");
+ BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ return reader.readLine();
+ }
public synchronized void start() throws Exception {
if (started)
@@ -163,7 +174,9 @@ public class OracleServer extends LeaderSelectorListenerAdapter implements Oracl
Thread.sleep(200);
leaderSelector = new LeaderSelector(curatorFramework, config.getZookeeperRoot() + Constants.Zookeeper.ORACLE_SERVER, this);
- leaderSelector.setId(addr.getHostName() + ":" + addr.getPort());
+ String leaderId = getHostName() + ":" + addr.getPort();
+ leaderSelector.setId(leaderId);
+ log.info("Leader ID = " + leaderId);
leaderSelector.autoRequeue();
leaderSelector.start();
| ['modules/core/src/main/java/accismus/impl/OracleServer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 296,118 | 64,915 | 8,978 | 76 | 926 | 180 | 23 | 1 | 182 | 29 | 32 | 2 | 0 | 0 | 1970-01-01T00:23:25 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
315 | apache/fluo/420/419 | apache | fluo | https://github.com/apache/fluo/issues/419 | https://github.com/apache/fluo/pull/420 | https://github.com/apache/fluo/pull/420 | 1 | fixes | Fluo not building against Accumulo 1.6.2RC4 | the garbage collection iterator is using non public Accumulo API that changed.
| d8885c60a31cf45274c01188225eafd6dad648df | f093dbee29a1f463b381c9a62a379c8e88abaac3 | https://github.com/apache/fluo/compare/d8885c60a31cf45274c01188225eafd6dad648df...f093dbee29a1f463b381c9a62a379c8e88abaac3 | diff --git a/modules/accumulo/src/main/java/io/fluo/accumulo/iterators/GarbageCollectionIterator.java b/modules/accumulo/src/main/java/io/fluo/accumulo/iterators/GarbageCollectionIterator.java
index 8a99a9dd..8dfa8c34 100644
--- a/modules/accumulo/src/main/java/io/fluo/accumulo/iterators/GarbageCollectionIterator.java
+++ b/modules/accumulo/src/main/java/io/fluo/accumulo/iterators/GarbageCollectionIterator.java
@@ -16,6 +16,7 @@
package io.fluo.accumulo.iterators;
import java.io.IOException;
+import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
@@ -30,7 +31,6 @@ import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.data.ArrayByteSequence;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
-import org.apache.accumulo.core.data.KeyValue;
import org.apache.accumulo.core.data.PartialKey;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
@@ -44,6 +44,18 @@ import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
*/
public class GarbageCollectionIterator implements SortedKeyValueIterator<Key,Value> {
+ private static class KeyValue extends SimpleImmutableEntry<Key,Value>{
+ private static final long serialVersionUID = 1L;
+
+ public KeyValue(Key key, Value value) {
+ super(new Key(key), new Value(value));
+ }
+
+ public KeyValue(Key key, byte[] value) {
+ super(new Key(key), new Value(value));
+ }
+ }
+
@VisibleForTesting
static final String OLDEST_ACTIVE_TS_OPT = "timestamp.oldest.active";
@@ -151,7 +163,7 @@ public class GarbageCollectionIterator implements SortedKeyValueIterator<Key,Val
long ts = source.getTopKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;
if (colType == ColumnConstants.TX_DONE_PREFIX) {
- keys.add(new KeyValue(new Key(source.getTopKey()), source.getTopValue().get()));
+ keys.add(new KeyValue(source.getTopKey(), source.getTopValue()));
completeTxs.add(ts);
} else if (colType == ColumnConstants.WRITE_PREFIX) {
boolean keep = false;
@@ -187,7 +199,7 @@ public class GarbageCollectionIterator implements SortedKeyValueIterator<Key,Val
invalidationTime = timePtr;
if (keep) {
- keys.add(new KeyValue(new Key(source.getTopKey()), val));
+ keys.add(new KeyValue(source.getTopKey(), val));
} else if (complete) {
completeTxs.remove(ts);
}
@@ -206,20 +218,20 @@ public class GarbageCollectionIterator implements SortedKeyValueIterator<Key,Val
}
if (keep) {
- keys.add(new KeyValue(new Key(source.getTopKey()), source.getTopValue().get()));
+ keys.add(new KeyValue(source.getTopKey(), source.getTopValue()));
} else if (complete) {
completeTxs.remove(ts);
}
} else if (colType == ColumnConstants.LOCK_PREFIX) {
if (ts > invalidationTime)
- keys.add(new KeyValue(new Key(source.getTopKey()), source.getTopValue().get()));
+ keys.add(new KeyValue(source.getTopKey(), source.getTopValue()));
} else if (colType == ColumnConstants.DATA_PREFIX) {
// can stop looking
break;
} else if (colType == ColumnConstants.ACK_PREFIX) {
if (!sawAck) {
if(ts >= firstWrite)
- keys.add(new KeyValue(new Key(source.getTopKey()), source.getTopValue().get()));
+ keys.add(new KeyValue(source.getTopKey(), source.getTopValue()));
sawAck = true;
}
} else {
@@ -230,9 +242,9 @@ public class GarbageCollectionIterator implements SortedKeyValueIterator<Key,Val
}
for (KeyValue kv : keys) {
- long colType = kv.key.getTimestamp() & ColumnConstants.PREFIX_MASK;
+ long colType = kv.getKey().getTimestamp() & ColumnConstants.PREFIX_MASK;
if (colType == ColumnConstants.TX_DONE_PREFIX) {
- if (completeTxs.contains(kv.key.getTimestamp() & ColumnConstants.TIMESTAMP_MASK)) {
+ if (completeTxs.contains(kv.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK)) {
keysFiltered.add(kv);
}
} else {
@@ -248,7 +260,7 @@ public class GarbageCollectionIterator implements SortedKeyValueIterator<Key,Val
@Override
public Key getTopKey() {
if (position < keysFiltered.size()) {
- return keysFiltered.get(position).key;
+ return keysFiltered.get(position).getKey();
} else {
return source.getTopKey();
}
@@ -257,7 +269,7 @@ public class GarbageCollectionIterator implements SortedKeyValueIterator<Key,Val
@Override
public Value getTopValue() {
if (position < keysFiltered.size()) {
- return new Value(keysFiltered.get(position).value);
+ return keysFiltered.get(position).getValue();
} else {
return source.getTopValue();
} | ['modules/accumulo/src/main/java/io/fluo/accumulo/iterators/GarbageCollectionIterator.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 555,269 | 124,662 | 17,358 | 131 | 1,807 | 373 | 32 | 1 | 79 | 12 | 14 | 2 | 0 | 0 | 1970-01-01T00:23:43 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
317 | apache/fluo/392/391 | apache | fluo | https://github.com/apache/fluo/issues/391 | https://github.com/apache/fluo/pull/392 | https://github.com/apache/fluo/pull/392 | 1 | closes | Remove unnecessary @SuppressWarnings("resource") annotations | At one point `@SuppressWarnings("resource")` annotations were added to the code to reduce false positives from the `Potential resource leak` warning. However, if a user doesn't turn on the warning in Eclipse, another `Unnecessary @SuppressWarnings("resource")` appears. The `Potential resource leak` warning does not provide much value so this should be just assumed off and the annotations should be removed from the code.
| de35439266f77731c2731c51e1c9e949262cbd5e | f13450297079db1fcfb9d9f0289df40fb95a7e4c | https://github.com/apache/fluo/compare/de35439266f77731c2731c51e1c9e949262cbd5e...f13450297079db1fcfb9d9f0289df40fb95a7e4c | diff --git a/modules/core/src/main/java/io/fluo/core/impl/LockResolver.java b/modules/core/src/main/java/io/fluo/core/impl/LockResolver.java
index 31f56634..40f6db3d 100644
--- a/modules/core/src/main/java/io/fluo/core/impl/LockResolver.java
+++ b/modules/core/src/main/java/io/fluo/core/impl/LockResolver.java
@@ -91,7 +91,6 @@ public class LockResolver {
* the wall time that the transaction that encountered the lock first saw the lock
* @return true if all locks passed in were resolved (rolled forward or back)
*/
- @SuppressWarnings("resource")
static boolean resolveLocks(Environment env, long startTs, TxStats stats, List<Entry<Key,Value>> locks, long startTime) {
// check if transactor is still alive
diff --git a/modules/core/src/test/java/io/fluo/core/TestBaseImpl.java b/modules/core/src/test/java/io/fluo/core/TestBaseImpl.java
index 69d7a002..439e670b 100644
--- a/modules/core/src/test/java/io/fluo/core/TestBaseImpl.java
+++ b/modules/core/src/test/java/io/fluo/core/TestBaseImpl.java
@@ -69,7 +69,6 @@ public class TestBaseImpl {
this.env = env;
}
- @SuppressWarnings("resource")
TestOracle(int port) throws Exception {
this(new Environment(config, curator, conn, port));
}
diff --git a/modules/core/src/test/java/io/fluo/core/TestTransaction.java b/modules/core/src/test/java/io/fluo/core/TestTransaction.java
index 5d32f144..bfacf451 100644
--- a/modules/core/src/test/java/io/fluo/core/TestTransaction.java
+++ b/modules/core/src/test/java/io/fluo/core/TestTransaction.java
@@ -42,7 +42,6 @@ public class TestTransaction extends TypedTransactionBase implements Transaction
this(new TransactionImpl(env).setTransactor(transactor), new StringEncoder());
}
- @SuppressWarnings("resource")
public TestTransaction(Environment env) {
this(new TransactionImpl(env), new StringEncoder());
}
@@ -52,12 +51,10 @@ public class TestTransaction extends TypedTransactionBase implements Transaction
this.tx = transactionImpl;
}
- @SuppressWarnings("resource")
public TestTransaction(Environment env, Bytes trow, Column tcol) {
this(new TransactionImpl(env, trow, tcol), new StringEncoder());
}
- @SuppressWarnings("resource")
public TestTransaction(Environment env, String trow, Column tcol) {
this(new TransactionImpl(env, Bytes.of(trow), tcol), new StringEncoder());
}
diff --git a/modules/core/src/test/java/io/fluo/core/impl/FailureIT.java b/modules/core/src/test/java/io/fluo/core/impl/FailureIT.java
index d4bb2696..7ac69ebc 100644
--- a/modules/core/src/test/java/io/fluo/core/impl/FailureIT.java
+++ b/modules/core/src/test/java/io/fluo/core/impl/FailureIT.java
@@ -111,7 +111,6 @@ public class FailureIT extends TestBaseImpl {
tx.done();
- @SuppressWarnings("resource")
TransactorNode t2 = new TransactorNode(env);
TestTransaction tx2 = new TestTransaction(env, t2);
@@ -174,7 +173,6 @@ public class FailureIT extends TestBaseImpl {
tx.done();
- @SuppressWarnings("resource")
TransactorNode t2 = new TransactorNode(env);
TestTransaction tx2 = new TestTransaction(env, t2);
@@ -276,7 +274,6 @@ public class FailureIT extends TestBaseImpl {
}
private void rollbackTest(boolean killTransactor) throws Exception {
- @SuppressWarnings("resource")
TransactorNode t1 = new TransactorNode(env);
TestTransaction tx = new TestTransaction(env);
diff --git a/modules/core/src/test/java/io/fluo/core/impl/ParallelScannerIT.java b/modules/core/src/test/java/io/fluo/core/impl/ParallelScannerIT.java
index b460f8e5..177edeac 100644
--- a/modules/core/src/test/java/io/fluo/core/impl/ParallelScannerIT.java
+++ b/modules/core/src/test/java/io/fluo/core/impl/ParallelScannerIT.java
@@ -114,7 +114,6 @@ public class ParallelScannerIT extends TestBaseImpl {
tx1.done();
- @SuppressWarnings("resource")
TransactorNode tNode1 = new TransactorNode(env);
TestTransaction tx2 = new TestTransaction(env, tNode1);
diff --git a/modules/core/src/test/java/io/fluo/core/impl/StochasticBankIT.java b/modules/core/src/test/java/io/fluo/core/impl/StochasticBankIT.java
index 05424861..91b84f95 100644
--- a/modules/core/src/test/java/io/fluo/core/impl/StochasticBankIT.java
+++ b/modules/core/src/test/java/io/fluo/core/impl/StochasticBankIT.java
@@ -56,7 +56,6 @@ public class StochasticBankIT extends TestBaseImpl {
static TypeLayer typeLayer = new TypeLayer(new StringEncoder());
private static AtomicInteger txCount = new AtomicInteger();
- @SuppressWarnings("resource")
@Test
public void testConcurrency() throws Exception {
diff --git a/modules/core/src/test/java/io/fluo/core/impl/TimestampTrackerIT.java b/modules/core/src/test/java/io/fluo/core/impl/TimestampTrackerIT.java
index 13b37c10..f0a1bf06 100644
--- a/modules/core/src/test/java/io/fluo/core/impl/TimestampTrackerIT.java
+++ b/modules/core/src/test/java/io/fluo/core/impl/TimestampTrackerIT.java
@@ -30,7 +30,6 @@ public class TimestampTrackerIT extends TestBaseImpl {
@Test(expected = NoSuchElementException.class)
public void testTsNoElement() {
- @SuppressWarnings("resource")
TimestampTracker tracker = env.getSharedResources().getTimestampTracker();
Assert.assertTrue(tracker.isEmpty());
tracker.getOldestActiveTimestamp(); | ['modules/core/src/test/java/io/fluo/core/impl/FailureIT.java', 'modules/core/src/test/java/io/fluo/core/TestTransaction.java', 'modules/core/src/test/java/io/fluo/core/TestBaseImpl.java', 'modules/core/src/main/java/io/fluo/core/impl/LockResolver.java', 'modules/core/src/test/java/io/fluo/core/impl/StochasticBankIT.java', 'modules/core/src/test/java/io/fluo/core/impl/TimestampTrackerIT.java', 'modules/core/src/test/java/io/fluo/core/impl/ParallelScannerIT.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 585,594 | 131,807 | 18,354 | 142 | 32 | 6 | 1 | 1 | 427 | 61 | 87 | 2 | 0 | 0 | 1970-01-01T00:23:40 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
318 | apache/fluo/389/386 | apache | fluo | https://github.com/apache/fluo/issues/386 | https://github.com/apache/fluo/pull/389 | https://github.com/apache/fluo/pull/389 | 1 | closes | Exception thrown if fluo yarn commands run on empty Zookeeper | This exception is thrown every time the command `fluo-dev deploy` is run with fresh Zookeeper.
No root node '/' exists in ZK which causes exception. Commands should check if root node exists before reading ZK.
```
Exception in thread "YarnTwillRunnerService STARTING" java.lang.RuntimeException: java.util.concurrent.ExecutionException: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /
at com.google.common.base.Throwables.propagate(Throwables.java:160)
at com.google.common.util.concurrent.AbstractIdleService$1$1.run(AbstractIdleService.java:47)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.ExecutionException: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /
at com.google.common.util.concurrent.AbstractFuture$Sync.getValue(AbstractFuture.java:294)
at com.google.common.util.concurrent.AbstractFuture$Sync.get(AbstractFuture.java:281)
at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:116)
at org.apache.twill.yarn.YarnTwillRunnerService.startUp(YarnTwillRunnerService.java:304)
at com.google.common.util.concurrent.AbstractIdleService$1$1.run(AbstractIdleService.java:43)
... 1 more
```
| de35439266f77731c2731c51e1c9e949262cbd5e | 156db0f5ccf163589e6876efdb40ae91e1429aef | https://github.com/apache/fluo/compare/de35439266f77731c2731c51e1c9e949262cbd5e...156db0f5ccf163589e6876efdb40ae91e1429aef | diff --git a/modules/cluster/src/main/java/io/fluo/cluster/yarn/YarnAdmin.java b/modules/cluster/src/main/java/io/fluo/cluster/yarn/YarnAdmin.java
index a15ee0fc..0e1d3f2c 100644
--- a/modules/cluster/src/main/java/io/fluo/cluster/yarn/YarnAdmin.java
+++ b/modules/cluster/src/main/java/io/fluo/cluster/yarn/YarnAdmin.java
@@ -28,6 +28,7 @@ import io.fluo.api.config.FluoConfiguration;
import io.fluo.cluster.FluoOracleMain;
import io.fluo.cluster.FluoWorkerMain;
import io.fluo.cluster.util.LogbackUtil;
+import io.fluo.core.client.FluoAdminImpl;
import io.fluo.core.util.CuratorUtil;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.curator.framework.CuratorFramework;
@@ -258,6 +259,11 @@ public class YarnAdmin {
File configFile = new File(options.getFluoConf() + "/fluo.properties");
config = new FluoConfiguration(configFile);
+
+ if (!FluoAdminImpl.zookeeperInitialized(config)) {
+ System.out.println("ERROR - Fluo has not been initialized yet in Zookeeper at " + config.getZookeepers());
+ System.exit(-1);
+ }
try {
curator = CuratorUtil.newFluoCurator(config); | ['modules/cluster/src/main/java/io/fluo/cluster/yarn/YarnAdmin.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 585,594 | 131,807 | 18,354 | 142 | 249 | 59 | 6 | 1 | 1,258 | 78 | 278 | 19 | 0 | 1 | 1970-01-01T00:23:40 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
319 | apache/fluo/379/378 | apache | fluo | https://github.com/apache/fluo/issues/378 | https://github.com/apache/fluo/pull/379 | https://github.com/apache/fluo/pull/379 | 1 | closes | MutableBytesFactory & MutableBytes are not being found by Accumulo Tserver | Accumulo is not finding the classes because its classpath only includes the fluo-api & fluo-accumulo jars and not fluo-core. The classes should be moved to fluo-accumulo as the Accumulo classpath should avoid including fluo-core.
``` java
Caused by: java.lang.IllegalStateException: java.lang.ClassNotFoundException: io.fluo.core.data.MutableBytesFactory
at io.fluo.api.data.Bytes.<clinit>(Bytes.java:53)
... 23 more
Caused by: java.lang.ClassNotFoundException: io.fluo.core.data.MutableBytesFactory
at org.apache.commons.vfs2.impl.VFSClassLoader.findClass(VFSClassLoader.java:175)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at io.fluo.api.data.Bytes.<clinit>(Bytes.java:51)
```
This bug is preventing Fluo from running as production instance.
| 1083eee23bf890d39e068d74aee46aeb786186ea | 36f1404758cad3a4769b2e8d25350afca6f155f4 | https://github.com/apache/fluo/compare/1083eee23bf890d39e068d74aee46aeb786186ea...36f1404758cad3a4769b2e8d25350afca6f155f4 | diff --git a/modules/core/src/main/java/io/fluo/core/data/MutableBytes.java b/modules/accumulo/src/main/java/io/fluo/accumulo/data/MutableBytes.java
similarity index 99%
rename from modules/core/src/main/java/io/fluo/core/data/MutableBytes.java
rename to modules/accumulo/src/main/java/io/fluo/accumulo/data/MutableBytes.java
index 787e00e3..0de45e21 100644
--- a/modules/core/src/main/java/io/fluo/core/data/MutableBytes.java
+++ b/modules/accumulo/src/main/java/io/fluo/accumulo/data/MutableBytes.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.fluo.core.data;
+package io.fluo.accumulo.data;
import java.io.Serializable;
import java.nio.ByteBuffer;
diff --git a/modules/core/src/main/java/io/fluo/core/data/MutableBytesFactory.java b/modules/accumulo/src/main/java/io/fluo/accumulo/data/MutableBytesFactory.java
similarity index 92%
rename from modules/core/src/main/java/io/fluo/core/data/MutableBytesFactory.java
rename to modules/accumulo/src/main/java/io/fluo/accumulo/data/MutableBytesFactory.java
index 160dd559..ee793e71 100644
--- a/modules/core/src/main/java/io/fluo/core/data/MutableBytesFactory.java
+++ b/modules/accumulo/src/main/java/io/fluo/accumulo/data/MutableBytesFactory.java
@@ -13,12 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.fluo.core.data;
+package io.fluo.accumulo.data;
import io.fluo.api.data.Bytes;
/**
- *
+ * An implementation of BytesFactory
*/
public class MutableBytesFactory implements Bytes.BytesFactory {
diff --git a/modules/api/src/main/java/io/fluo/api/data/Bytes.java b/modules/api/src/main/java/io/fluo/api/data/Bytes.java
index 51f2f704..dc9b2f94 100644
--- a/modules/api/src/main/java/io/fluo/api/data/Bytes.java
+++ b/modules/api/src/main/java/io/fluo/api/data/Bytes.java
@@ -38,7 +38,7 @@ import org.apache.hadoop.io.WritableUtils;
*/
public abstract class Bytes implements Comparable<Bytes> {
- private static final String BYTES_FACTORY_CLASS = "io.fluo.core.data.MutableBytesFactory";
+ private static final String BYTES_FACTORY_CLASS = "io.fluo.accumulo.data.MutableBytesFactory";
public interface BytesFactory {
Bytes get(byte[] data);
diff --git a/modules/core/src/main/java/io/fluo/core/util/ByteUtil.java b/modules/core/src/main/java/io/fluo/core/util/ByteUtil.java
index 7a91523a..ac3f8c15 100644
--- a/modules/core/src/main/java/io/fluo/core/util/ByteUtil.java
+++ b/modules/core/src/main/java/io/fluo/core/util/ByteUtil.java
@@ -15,8 +15,8 @@
*/
package io.fluo.core.util;
+import io.fluo.accumulo.data.MutableBytes;
import io.fluo.api.data.Bytes;
-import io.fluo.core.data.MutableBytes;
import org.apache.accumulo.core.data.ArrayByteSequence;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.hadoop.io.Text;
diff --git a/modules/core/src/test/java/io/fluo/core/data/MutableBytesTest.java b/modules/core/src/test/java/io/fluo/core/data/MutableBytesTest.java
index 7609bdcc..8504b826 100644
--- a/modules/core/src/test/java/io/fluo/core/data/MutableBytesTest.java
+++ b/modules/core/src/test/java/io/fluo/core/data/MutableBytesTest.java
@@ -15,6 +15,7 @@
*/
package io.fluo.core.data;
+import io.fluo.accumulo.data.MutableBytes;
import io.fluo.api.data.Bytes;
import org.junit.Assert;
import org.junit.Test;
diff --git a/modules/mapreduce/src/main/java/io/fluo/mapreduce/MutationBuilder.java b/modules/mapreduce/src/main/java/io/fluo/mapreduce/MutationBuilder.java
index 34f0ebcf..a8168695 100644
--- a/modules/mapreduce/src/main/java/io/fluo/mapreduce/MutationBuilder.java
+++ b/modules/mapreduce/src/main/java/io/fluo/mapreduce/MutationBuilder.java
@@ -17,11 +17,11 @@ package io.fluo.mapreduce;
import java.nio.charset.StandardCharsets;
+import io.fluo.accumulo.data.MutableBytes;
import io.fluo.accumulo.util.ColumnConstants;
import io.fluo.accumulo.values.WriteValue;
import io.fluo.api.data.Bytes;
import io.fluo.api.data.Column;
-import io.fluo.core.data.MutableBytes;
import io.fluo.core.util.ByteUtil;
import io.fluo.core.util.Flutation;
import org.apache.accumulo.core.client.mapreduce.AccumuloOutputFormat; | ['modules/mapreduce/src/main/java/io/fluo/mapreduce/MutationBuilder.java', 'modules/core/src/main/java/io/fluo/core/util/ByteUtil.java', 'modules/core/src/main/java/io/fluo/core/data/MutableBytesFactory.java', 'modules/core/src/test/java/io/fluo/core/data/MutableBytesTest.java', 'modules/core/src/main/java/io/fluo/core/data/MutableBytes.java', 'modules/api/src/main/java/io/fluo/api/data/Bytes.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 583,384 | 131,269 | 18,311 | 142 | 357 | 82 | 6 | 5 | 968 | 74 | 226 | 17 | 0 | 1 | 1970-01-01T00:23:39 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
320 | apache/fluo/330/329 | apache | fluo | https://github.com/apache/fluo/issues/329 | https://github.com/apache/fluo/pull/330 | https://github.com/apache/fluo/pull/330 | 1 | fixes | hash notification log message is misleading | The following message is misleading. After its printed 118 notification were queued for processing, they may not be finished. The word `processed` seems to imply they were finished.
```
19:45:18.389 [HashNotificationFinder ScanTask] DEBUG i.f.core.worker.finder.hash.ScanTask - Scanned 50 of 68 tablets, processed 118 notifications, sleeping 0
```
| abf5dd4fdced4e1e89d1693df7fd90232c04f2fe | 51249a07ef7f3e5f82946d109db0d562a9f01d39 | https://github.com/apache/fluo/compare/abf5dd4fdced4e1e89d1693df7fd90232c04f2fe...51249a07ef7f3e5f82946d109db0d562a9f01d39 | diff --git a/modules/core/src/main/java/io/fluo/core/worker/finder/hash/ScanTask.java b/modules/core/src/main/java/io/fluo/core/worker/finder/hash/ScanTask.java
index 4a49bbcf..85d96529 100644
--- a/modules/core/src/main/java/io/fluo/core/worker/finder/hash/ScanTask.java
+++ b/modules/core/src/main/java/io/fluo/core/worker/finder/hash/ScanTask.java
@@ -103,7 +103,7 @@ class ScanTask implements Runnable {
long sleepTime = Math.max(0, minRetryTime - System.currentTimeMillis());
- log.debug("Scanned {} of {} tablets, processed {} notifications, sleeping {} ", tabletsScanned, tablets.size(), notifications, sleepTime);
+ log.debug("Scanned {} of {} tablets, found {} new notifications, sleeping {} ", tabletsScanned, tablets.size(), notifications, sleepTime);
UtilWaitThread.sleep(sleepTime, stopped);
| ['modules/core/src/main/java/io/fluo/core/worker/finder/hash/ScanTask.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 544,354 | 122,597 | 17,193 | 134 | 295 | 61 | 2 | 1 | 351 | 46 | 84 | 6 | 0 | 1 | 1970-01-01T00:23:35 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
322 | apache/fluo/326/325 | apache | fluo | https://github.com/apache/fluo/issues/325 | https://github.com/apache/fluo/pull/326 | https://github.com/apache/fluo/pull/326 | 1 | closes | FluoInputFormat is configured for wrong Zookeeper connection property | In the `configure()` method of FluoInputFormat the `config.getZookeepers()` is used rather than `config.getAccumuloZookeepers()` to create connection to Accumulo.
| 4edaa615874ea4db9eda615c413b6c35688122bf | 475a4417e6eda92c147dad383e6f87c5a140ec9f | https://github.com/apache/fluo/compare/4edaa615874ea4db9eda615c413b6c35688122bf...475a4417e6eda92c147dad383e6f87c5a140ec9f | diff --git a/modules/mapreduce/src/main/java/io/fluo/mapreduce/FluoInputFormat.java b/modules/mapreduce/src/main/java/io/fluo/mapreduce/FluoInputFormat.java
index b4f1ad74..be879fe2 100644
--- a/modules/mapreduce/src/main/java/io/fluo/mapreduce/FluoInputFormat.java
+++ b/modules/mapreduce/src/main/java/io/fluo/mapreduce/FluoInputFormat.java
@@ -151,7 +151,7 @@ public class FluoInputFormat extends InputFormat<Bytes,ColumnIterator> {
props.store(baos, "");
conf.getConfiguration().set(PROPS_CONF_KEY, new String(baos.toByteArray(), "UTF8"));
- AccumuloInputFormat.setZooKeeperInstance(conf, config.getAccumuloInstance(), config.getZookeepers());
+ AccumuloInputFormat.setZooKeeperInstance(conf, config.getAccumuloInstance(), config.getAccumuloZookeepers());
AccumuloInputFormat.setConnectorInfo(conf, config.getAccumuloUser(), new PasswordToken(config.getAccumuloPassword()));
AccumuloInputFormat.setInputTableName(conf, env.getTable());
AccumuloInputFormat.setScanAuthorizations(conf, env.getAuthorizations()); | ['modules/mapreduce/src/main/java/io/fluo/mapreduce/FluoInputFormat.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 544,093 | 122,553 | 17,187 | 134 | 229 | 52 | 2 | 1 | 163 | 18 | 39 | 2 | 0 | 0 | 1970-01-01T00:23:35 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
307 | apache/fluo/840/839 | apache | fluo | https://github.com/apache/fluo/issues/839 | https://github.com/apache/fluo/pull/840 | https://github.com/apache/fluo/pull/840 | 1 | fixes | Stress test hangs with unprocessed notifications. | When running the Fluo Stress test locally against 1.1.0-SNAPSHOT, sometimes it hangs with unprocessed notifications. These notifications never get processed. I took head dump of the workers and see that the map that tracks notifications has entries in it that indicate notifications are queued. However nothing is being done with these.
```
14:05:18.307 [main] INFO o.a.fluo.cluster.runner.AppRunner - 39855 notifications are still outstanding. Will try again in 199 seconds...
14:08:37.515 [main] INFO o.a.fluo.cluster.runner.AppRunner - 39855 notifications are still outstanding. Will try again in 199 seconds...
14:11:56.717 [main] INFO o.a.fluo.cluster.runner.AppRunner - 39855 notifications are still outstanding. Will try again in 199 seconds...
14:15:15.922 [main] INFO o.a.fluo.cluster.runner.AppRunner - 39855 notifications are still outstanding. Will try again in 199 seconds...
14:18:35.123 [main] INFO o.a.fluo.cluster.runner.AppRunner - 39855 notifications are still outstanding. Will try again in 199 seconds...
``` | 225ffe450c89400926cc21a9cc50bb5eeced9043 | 21746e5cf2955894e5151d3e00b07c95081363e1 | https://github.com/apache/fluo/compare/225ffe450c89400926cc21a9cc50bb5eeced9043...21746e5cf2955894e5151d3e00b07c95081363e1 | diff --git a/modules/core/src/main/java/org/apache/fluo/core/worker/NotificationProcessor.java b/modules/core/src/main/java/org/apache/fluo/core/worker/NotificationProcessor.java
index 3b6bba52..c8216848 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/worker/NotificationProcessor.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/worker/NotificationProcessor.java
@@ -95,7 +95,7 @@ public class NotificationProcessor implements AutoCloseable {
}
}
- if (queuedWork.containsKey(rowCol)) {
+ if (queuedWork.containsKey(rowCol) || recentlyDeleted.contains(rowCol)) {
return false;
}
@@ -164,7 +164,7 @@ public class NotificationProcessor implements AutoCloseable {
}
- private static class NotificationProcessingTask implements Runnable {
+ private class NotificationProcessingTask implements Runnable {
Notification notification;
NotificationFinder notificationFinder;
@@ -184,6 +184,8 @@ public class NotificationProcessor implements AutoCloseable {
// notification should be processed.
if (notificationFinder.shouldProcess(notification)) {
workTask.run();
+ } else {
+ notificationProcessed(notification);
}
} catch (Exception e) {
log.error("Failed to process work " + Hex.encNonAscii(notification), e);
@@ -192,7 +194,7 @@ public class NotificationProcessor implements AutoCloseable {
}
- private static class FutureNotificationTask extends FutureTask<Void> implements
+ private class FutureNotificationTask extends FutureTask<Void> implements
Comparable<FutureNotificationTask> {
private final Notification notification;
diff --git a/modules/core/src/main/java/org/apache/fluo/core/worker/WorkTaskAsync.java b/modules/core/src/main/java/org/apache/fluo/core/worker/WorkTaskAsync.java
index 76c6c664..4f028c1c 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/worker/WorkTaskAsync.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/worker/WorkTaskAsync.java
@@ -85,7 +85,13 @@ public class WorkTaskAsync implements Runnable {
atx = new TracingTransaction(atx, notification, observer.getClass(), observerId);
}
- observer.process(atx, notification.getRow(), notification.getColumn());
+ try {
+ observer.process(atx, notification.getRow(), notification.getColumn());
+ } catch (Exception e) {
+ notificationFinder.failedToProcess(notification, TxResult.ERROR);
+ notificationProcessor.notificationProcessed(notification);
+ throw e;
+ }
CommitManager commitManager = env.getSharedResources().getCommitManager();
commitManager.beginCommit(atx, observerId, new WorkTaskCommitObserver());
diff --git a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
index 1732a298..35f3215f 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
@@ -100,30 +100,30 @@ public class ScanTask implements Runnable {
rangeData.keySet().retainAll(rangeSet);
long minRetryTime = maxSleepTime + System.currentTimeMillis();
- int notifications = 0;
+ ScanCounts ntfyCounts = new ScanCounts();
int tabletsScanned = 0;
try {
for (TableRange tabletRange : ranges) {
TabletData tabletData = rangeData.computeIfAbsent(tabletRange, tr -> new TabletData());
if (System.currentTimeMillis() >= tabletData.retryTime) {
- int count = 0;
+ ScanCounts counts;
PartitionInfo pi = partitionManager.getPartitionInfo();
if (partition.equals(pi)) {
try (Session session =
proccessor.beginAddingNotifications(rc -> tabletRange.contains(rc.getRow()))) {
// notifications could have been asynchronously queued for deletion. Let that
- // happen
- // 1st before scanning
+ // happen 1st before scanning
env.getSharedResources().getBatchWriter().waitForAsyncFlush();
- count = scan(session, partition, tabletRange.getRange());
+ counts = scan(session, partition, tabletRange.getRange());
tabletsScanned++;
}
} else {
break;
}
- tabletData.updateScanCount(count, maxSleepTime);
- notifications += count;
+ tabletData.updateScanCount(counts.added, maxSleepTime);
+ ntfyCounts.added += counts.added;
+ ntfyCounts.seen += counts.seen;
if (stopped.get()) {
break;
}
@@ -139,8 +139,8 @@ public class ScanTask implements Runnable {
qSize = proccessor.size();
- log.debug("Scanned {} of {} tablets, added {} new notifications (total queued {})",
- tabletsScanned, ranges.size(), notifications, qSize);
+ log.debug("Scanned {} of {} tablets. Notifications added: {} seen: {} queued: {}",
+ tabletsScanned, ranges.size(), ntfyCounts.added, ntfyCounts.seen, qSize);
if (!stopped.get()) {
UtilWaitThread.sleep(sleepTime, stopped);
@@ -168,7 +168,13 @@ public class ScanTask implements Runnable {
return wasInt;
}
- private int scan(Session session, PartitionInfo pi, Range range) throws TableNotFoundException {
+ private static class ScanCounts {
+ int seen = 0;
+ int added = 0;
+ }
+
+ private ScanCounts scan(Session session, PartitionInfo pi, Range range)
+ throws TableNotFoundException {
Scanner scanner = env.getConnector().createScanner(env.getTable(), env.getAuthorizations());
scanner.setRange(range);
@@ -179,7 +185,7 @@ public class ScanTask implements Runnable {
NotificationHashFilter.setModulusParams(iterCfg, pi.getMyGroupSize(), pi.getMyIdInGroup());
scanner.addScanIterator(iterCfg);
- int count = 0;
+ ScanCounts counts = new ScanCounts();
for (Entry<Key, Value> entry : scanner) {
if (!pi.equals(partitionManager.getPartitionInfo())) {
@@ -187,13 +193,15 @@ public class ScanTask implements Runnable {
}
if (stopped.get()) {
- return count;
+ return counts;
}
+ counts.seen++;
+
if (session.addNotification(finder, Notification.from(entry.getKey()))) {
- count++;
+ counts.added++;
}
}
- return count;
+ return counts;
}
} | ['modules/core/src/main/java/org/apache/fluo/core/worker/WorkTaskAsync.java', 'modules/core/src/main/java/org/apache/fluo/core/worker/NotificationProcessor.java', 'modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 828,898 | 182,838 | 24,948 | 189 | 2,405 | 464 | 52 | 3 | 1,050 | 133 | 261 | 9 | 0 | 1 | 1970-01-01T00:24:55 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
327 | apache/fluo/61/55 | apache | fluo | https://github.com/apache/fluo/issues/55 | https://github.com/apache/fluo/pull/61 | https://github.com/apache/fluo/pull/61 | 1 | closes | MiniAccismus.waitForObservers() returns before processing is finished | In MiniAccismus, the waitForObservers() method is occasionally returning before all observers are done processing. This is because the method returns if there a no notifications available in the table. However, observers could still be running and creating new notifications.
The method should instead check that no observers are running and no new notifications are in the table before returning.
| aa98781a6b96204ed3c559d4ff670dc673671d92 | 166c2993ed24f935aa6cd4bce693f700f89ba9c1 | https://github.com/apache/fluo/compare/aa98781a6b96204ed3c559d4ff670dc673671d92...166c2993ed24f935aa6cd4bce693f700f89ba9c1 | diff --git a/modules/core/src/main/java/accismus/api/test/MiniAccismus.java b/modules/core/src/main/java/accismus/api/test/MiniAccismus.java
index e89fa064..0a25d75e 100644
--- a/modules/core/src/main/java/accismus/api/test/MiniAccismus.java
+++ b/modules/core/src/main/java/accismus/api/test/MiniAccismus.java
@@ -40,6 +40,33 @@ public class MiniAccismus {
private ExecutorService tp;
private AtomicBoolean shutdownFlag;
+ private int numProcessing = 0;
+
+ private class MiniWorkerTask extends WorkerTask {
+
+ public MiniWorkerTask(Configuration config, AtomicBoolean shutdownFlag) {
+ super(config, shutdownFlag);
+ }
+
+ @Override
+ public void startedProcessing() {
+ synchronized (MiniAccismus.this) {
+ numProcessing++;
+ }
+ }
+
+ @Override
+ public void finishedProcessing(long numProcessed) {
+ synchronized (MiniAccismus.this) {
+ numProcessing--;
+ }
+ }
+ }
+
+ private synchronized boolean isProcessing(Scanner scanner) {
+ return scanner.iterator().hasNext() || numProcessing > 0;
+ }
+
public MiniAccismus(Properties props) {
try {
aconfig = new Configuration(props);
@@ -59,7 +86,7 @@ public class MiniAccismus {
tp = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
- tp.submit(new WorkerTask(aconfig, shutdownFlag));
+ tp.submit(new MiniWorkerTask(aconfig, shutdownFlag));
}
} catch (Exception e) {
@@ -85,14 +112,14 @@ public class MiniAccismus {
}
public void waitForObservers() {
- // TODO create a better implementation
try {
Scanner scanner = aconfig.getConnector().createScanner(aconfig.getTable(), aconfig.getAuthorizations());
scanner.fetchColumnFamily(ByteUtil.toText(Constants.NOTIFY_CF));
- while (scanner.iterator().hasNext()) {
+ while (isProcessing(scanner)) {
Thread.sleep(100);
}
+
} catch (Exception e) {
throw new RuntimeException(e);
}
diff --git a/modules/core/src/main/java/accismus/impl/WorkerTask.java b/modules/core/src/main/java/accismus/impl/WorkerTask.java
index 190fe49a..fe2abc39 100644
--- a/modules/core/src/main/java/accismus/impl/WorkerTask.java
+++ b/modules/core/src/main/java/accismus/impl/WorkerTask.java
@@ -63,9 +63,12 @@ public class WorkerTask implements Runnable {
while (!shutdownFlag.get()) {
long numProcessed = 0;
try {
+ startedProcessing();
numProcessed = worker.processUpdates(colObservers);
} catch (Exception e) {
log.error("Error while processing updates", e);
+ } finally {
+ finishedProcessing(numProcessed);
}
if (numProcessed > 0)
@@ -92,4 +95,8 @@ public class WorkerTask implements Runnable {
}
}
+ public void startedProcessing() {}
+
+ public void finishedProcessing(long numProcessed) {}
+
} | ['modules/core/src/main/java/accismus/impl/WorkerTask.java', 'modules/core/src/main/java/accismus/api/test/MiniAccismus.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 290,823 | 63,895 | 8,827 | 74 | 195 | 32 | 7 | 1 | 403 | 59 | 73 | 4 | 0 | 0 | 1970-01-01T00:23:24 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
821 | azuread/microsoft-authentication-library-for-android/976/967 | azuread | microsoft-authentication-library-for-android | https://github.com/AzureAD/microsoft-authentication-library-for-android/issues/967 | https://github.com/AzureAD/microsoft-authentication-library-for-android/pull/976 | https://github.com/AzureAD/microsoft-authentication-library-for-android/pull/976 | 1 | fix | Cache Migration not performed in below scenarios. See Description. | - Single Account
- Multiple Account - getAccount(id)
- Multiple Account - getAccounts - if an interactive call was already made post adoption of MSAL | 7cfcbf62f7b25d4ccf6989ead34b3ee7648aa635 | 89aab9279aa57a4ee1eb2bc940cfa22338a5b8ff | https://github.com/azuread/microsoft-authentication-library-for-android/compare/7cfcbf62f7b25d4ccf6989ead34b3ee7648aa635...89aab9279aa57a4ee1eb2bc940cfa22338a5b8ff | diff --git a/msal/src/main/java/com/microsoft/identity/client/MultipleAccountPublicClientApplication.java b/msal/src/main/java/com/microsoft/identity/client/MultipleAccountPublicClientApplication.java
index 49dd50a2..58d11be9 100644
--- a/msal/src/main/java/com/microsoft/identity/client/MultipleAccountPublicClientApplication.java
+++ b/msal/src/main/java/com/microsoft/identity/client/MultipleAccountPublicClientApplication.java
@@ -35,30 +35,19 @@ import com.microsoft.identity.client.internal.AsyncResult;
import com.microsoft.identity.client.internal.controllers.MSALControllerFactory;
import com.microsoft.identity.client.internal.controllers.MsalExceptionAdapter;
import com.microsoft.identity.client.internal.controllers.OperationParametersAdapter;
-import com.microsoft.identity.common.adal.internal.cache.IStorageHelper;
-import com.microsoft.identity.common.adal.internal.cache.StorageHelper;
import com.microsoft.identity.common.exception.BaseException;
import com.microsoft.identity.common.internal.cache.ICacheRecord;
-import com.microsoft.identity.common.internal.cache.IShareSingleSignOnState;
-import com.microsoft.identity.common.internal.cache.ISharedPreferencesFileManager;
-import com.microsoft.identity.common.internal.cache.SharedPreferencesFileManager;
import com.microsoft.identity.common.internal.controllers.CommandCallback;
import com.microsoft.identity.common.internal.controllers.CommandDispatcher;
import com.microsoft.identity.common.internal.controllers.LoadAccountCommand;
import com.microsoft.identity.common.internal.controllers.RemoveAccountCommand;
import com.microsoft.identity.common.internal.dto.AccountRecord;
import com.microsoft.identity.common.internal.eststelemetry.PublicApiId;
-import com.microsoft.identity.common.internal.migration.AdalMigrationAdapter;
import com.microsoft.identity.common.internal.migration.TokenMigrationCallback;
-import com.microsoft.identity.common.internal.migration.TokenMigrationUtility;
-import com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAccount;
-import com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken;
import com.microsoft.identity.common.internal.request.OperationParameters;
import com.microsoft.identity.common.internal.result.ResultFuture;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import static com.microsoft.identity.client.internal.MsalUtils.throwOnMainThread;
@@ -110,92 +99,43 @@ public class MultipleAccountPublicClientApplication extends PublicClientApplicat
*/
private void getAccountsInternal(@NonNull final LoadAccountsCallback callback,
@NonNull final String publicApiId) {
- final String methodName = ":getAccounts";
- final List<ICacheRecord> accounts =
- mPublicClientConfiguration
- .getOAuth2TokenCache()
- .getAccountsWithAggregatedAccountData(
- null, // * wildcard
- mPublicClientConfiguration.getClientId()
- );
-
- final Handler handler;
-
- if (null != Looper.myLooper() && Looper.getMainLooper() != Looper.myLooper()) {
- handler = new Handler(Looper.myLooper());
- } else {
- handler = new Handler(Looper.getMainLooper());
- }
-
- if (accounts.isEmpty()) {
- // Create the SharedPreferencesFileManager for the legacy accounts/credentials
- final IStorageHelper storageHelper = new StorageHelper(mPublicClientConfiguration.getAppContext());
- final ISharedPreferencesFileManager sharedPreferencesFileManager =
- new SharedPreferencesFileManager(
- mPublicClientConfiguration.getAppContext(),
- "com.microsoft.aad.adal.cache",
- storageHelper
- );
+ TokenMigrationCallback migrationCallback = new TokenMigrationCallback() {
+ @Override
+ public void onMigrationFinished(int numberOfAccountsMigrated) {
+ final Handler handler;
- // Load the old TokenCacheItems as key/value JSON
- final Map<String, String> credentials = sharedPreferencesFileManager.getAll();
+ if (null != Looper.myLooper() && Looper.getMainLooper() != Looper.myLooper()) {
+ handler = new Handler(Looper.myLooper());
+ } else {
+ handler = new Handler(Looper.getMainLooper());
+ }
- final Map<String, String> redirects = new HashMap<>();
- redirects.put(
- mPublicClientConfiguration.getClientId(), // Our client id
- mPublicClientConfiguration.getRedirectUri() // Our redirect uri
- );
+ try {
+ final OperationParameters params = OperationParametersAdapter.createOperationParameters(mPublicClientConfiguration, mPublicClientConfiguration.getOAuth2TokenCache());
+ final LoadAccountCommand loadAccountCommand = new LoadAccountCommand(
+ params,
+ MSALControllerFactory.getAllControllers(
+ mPublicClientConfiguration.getAppContext(),
+ params.getAuthority(),
+ mPublicClientConfiguration
+ ),
+ getLoadAccountsCallback(callback)
+ );
- new TokenMigrationUtility<MicrosoftAccount, MicrosoftRefreshToken>()._import(
- new AdalMigrationAdapter(
- mPublicClientConfiguration.getAppContext(),
- redirects,
- false
- ),
- credentials,
- (IShareSingleSignOnState<MicrosoftAccount, MicrosoftRefreshToken>) mPublicClientConfiguration.getOAuth2TokenCache(),
- new TokenMigrationCallback() {
+ loadAccountCommand.setPublicApiId(publicApiId);
+ CommandDispatcher.submitSilent(loadAccountCommand);
+ } catch (final MsalClientException e) {
+ handler.post(new Runnable() {
@Override
- public void onMigrationFinished(int numberOfAccountsMigrated) {
- final String extendedMethodName = ":onMigrationFinished";
- com.microsoft.identity.common.internal.logging.Logger.info(
- TAG + methodName + extendedMethodName,
- "Migrated [" + numberOfAccountsMigrated + "] accounts"
- );
+ public void run() {
+ callback.onError(e);
}
- }
- );
- } else {
- // The cache contains items - mark migration as complete
- new AdalMigrationAdapter(
- mPublicClientConfiguration.getAppContext(),
- null, // unused for this path
- false
- ).setMigrationStatus(true);
- }
-
- try {
- final OperationParameters params = OperationParametersAdapter.createOperationParameters(mPublicClientConfiguration, mPublicClientConfiguration.getOAuth2TokenCache());
- final LoadAccountCommand loadAccountCommand = new LoadAccountCommand(
- params,
- MSALControllerFactory.getAllControllers(
- mPublicClientConfiguration.getAppContext(),
- params.getAuthority(),
- mPublicClientConfiguration
- ),
- getLoadAccountsCallback(callback)
- );
-
- loadAccountCommand.setPublicApiId(publicApiId);
- CommandDispatcher.submitSilent(loadAccountCommand);
- } catch (final MsalClientException e) {
- handler.post(new Runnable() {
- @Override
- public void run() {
- callback.onError(e);
+ });
}
- });
- }
+ }
+ };
+
+ performMigration(migrationCallback);
}
@Override
@@ -249,87 +189,94 @@ public class MultipleAccountPublicClientApplication extends PublicClientApplicat
private void getAccountInternal(@NonNull final String identifier,
@NonNull final GetAccountCallback callback,
@NonNull final String publicApiId) {
- final String methodName = ":getAccount";
-
- com.microsoft.identity.common.internal.logging.Logger.verbose(
- TAG + methodName,
- "Get account with the identifier."
- );
-
- try {
- final OperationParameters params = OperationParametersAdapter.createOperationParameters(mPublicClientConfiguration, mPublicClientConfiguration.getOAuth2TokenCache());
- final LoadAccountCommand loadAccountCommand = new LoadAccountCommand(
- params,
- MSALControllerFactory.getAllControllers(
- mPublicClientConfiguration.getAppContext(),
- params.getAuthority(),
- mPublicClientConfiguration
- ),
- new CommandCallback<List<ICacheRecord>, BaseException>() {
- @Override
- public void onTaskCompleted(final List<ICacheRecord> result) {
- if (null == result || result.size() == 0) {
- com.microsoft.identity.common.internal.logging.Logger.verbose(
- TAG + methodName,
- "No account found.");
- callback.onTaskCompleted(null);
- } else {
- // First, transform the result into IAccount + TenantProfile form
- final List<IAccount>
- accounts = AccountAdapter.adapt(result);
-
- final String trimmedIdentifier = identifier.trim();
-
- // Evaluation precedence...
- // 1. home_account_id
- // 2. local_account_id
- // 3. username
- // 4. Give up.
-
- final AccountMatcher accountMatcher = new AccountMatcher(
- homeAccountMatcher,
- localAccountMatcher,
- usernameMatcher
- );
-
- for (final IAccount account : accounts) {
- if (accountMatcher.matches(trimmedIdentifier, account)) {
- callback.onTaskCompleted(account);
- return;
+ TokenMigrationCallback migrationCallback = new TokenMigrationCallback() {
+ @Override
+ public void onMigrationFinished(int numberOfAccountsMigrated) {
+ final String methodName = ":getAccount";
+
+ com.microsoft.identity.common.internal.logging.Logger.verbose(
+ TAG + methodName,
+ "Get account with the identifier."
+ );
+
+ try {
+ final OperationParameters params = OperationParametersAdapter.createOperationParameters(mPublicClientConfiguration, mPublicClientConfiguration.getOAuth2TokenCache());
+ final LoadAccountCommand loadAccountCommand = new LoadAccountCommand(
+ params,
+ MSALControllerFactory.getAllControllers(
+ mPublicClientConfiguration.getAppContext(),
+ params.getAuthority(),
+ mPublicClientConfiguration
+ ),
+ new CommandCallback<List<ICacheRecord>, BaseException>() {
+ @Override
+ public void onTaskCompleted(final List<ICacheRecord> result) {
+ if (null == result || result.size() == 0) {
+ com.microsoft.identity.common.internal.logging.Logger.verbose(
+ TAG + methodName,
+ "No account found.");
+ callback.onTaskCompleted(null);
+ } else {
+ // First, transform the result into IAccount + TenantProfile form
+ final List<IAccount>
+ accounts = AccountAdapter.adapt(result);
+
+ final String trimmedIdentifier = identifier.trim();
+
+ // Evaluation precedence...
+ // 1. home_account_id
+ // 2. local_account_id
+ // 3. username
+ // 4. Give up.
+
+ final AccountMatcher accountMatcher = new AccountMatcher(
+ homeAccountMatcher,
+ localAccountMatcher,
+ usernameMatcher
+ );
+
+ for (final IAccount account : accounts) {
+ if (accountMatcher.matches(trimmedIdentifier, account)) {
+ callback.onTaskCompleted(account);
+ return;
+ }
+ }
+
+ callback.onTaskCompleted(null);
}
}
- callback.onTaskCompleted(null);
- }
- }
+ @Override
+ public void onError(final BaseException exception) {
+ com.microsoft.identity.common.internal.logging.Logger.error(
+ TAG + methodName,
+ exception.getMessage(),
+ exception
+ );
+ callback.onError(MsalExceptionAdapter.msalExceptionFromBaseException(exception));
+ }
- @Override
- public void onError(final BaseException exception) {
- com.microsoft.identity.common.internal.logging.Logger.error(
- TAG + methodName,
- exception.getMessage(),
- exception
- );
- callback.onError(MsalExceptionAdapter.msalExceptionFromBaseException(exception));
- }
+ @Override
+ public void onCancel() {
- @Override
- public void onCancel() {
+ }
+ }
+ );
- }
- }
- );
+ loadAccountCommand.setPublicApiId(publicApiId);
+ CommandDispatcher.submitSilent(loadAccountCommand);
+ } catch (final MsalClientException e) {
+ com.microsoft.identity.common.internal.logging.Logger.error(
+ TAG + methodName,
+ e.getMessage(),
+ e
+ );
+ callback.onError(e);
+ }
+ }
+ };
- loadAccountCommand.setPublicApiId(publicApiId);
- CommandDispatcher.submitSilent(loadAccountCommand);
- } catch (final MsalClientException e) {
- com.microsoft.identity.common.internal.logging.Logger.error(
- TAG + methodName,
- e.getMessage(),
- e
- );
- callback.onError(e);
- }
+ performMigration(migrationCallback);
}
@Override
diff --git a/msal/src/main/java/com/microsoft/identity/client/PublicClientApplication.java b/msal/src/main/java/com/microsoft/identity/client/PublicClientApplication.java
index 35510d41..97f32a4b 100644
--- a/msal/src/main/java/com/microsoft/identity/client/PublicClientApplication.java
+++ b/msal/src/main/java/com/microsoft/identity/client/PublicClientApplication.java
@@ -48,6 +48,8 @@ import com.microsoft.identity.client.internal.AsyncResult;
import com.microsoft.identity.client.internal.controllers.MSALControllerFactory;
import com.microsoft.identity.client.internal.controllers.MsalExceptionAdapter;
import com.microsoft.identity.client.internal.controllers.OperationParametersAdapter;
+import com.microsoft.identity.common.adal.internal.cache.IStorageHelper;
+import com.microsoft.identity.common.adal.internal.cache.StorageHelper;
import com.microsoft.identity.common.adal.internal.tokensharing.TokenShareUtility;
import com.microsoft.identity.common.exception.BaseException;
import com.microsoft.identity.common.exception.ClientException;
@@ -57,8 +59,11 @@ import com.microsoft.identity.common.internal.authorities.Authority;
import com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority;
import com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryB2CAuthority;
import com.microsoft.identity.common.internal.cache.ICacheRecord;
+import com.microsoft.identity.common.internal.cache.IShareSingleSignOnState;
+import com.microsoft.identity.common.internal.cache.ISharedPreferencesFileManager;
import com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache;
import com.microsoft.identity.common.internal.cache.SchemaUtil;
+import com.microsoft.identity.common.internal.cache.SharedPreferencesFileManager;
import com.microsoft.identity.common.internal.controllers.BaseController;
import com.microsoft.identity.common.internal.controllers.CommandCallback;
import com.microsoft.identity.common.internal.controllers.CommandDispatcher;
@@ -70,8 +75,13 @@ import com.microsoft.identity.common.internal.dto.AccountRecord;
import com.microsoft.identity.common.internal.eststelemetry.EstsTelemetry;
import com.microsoft.identity.common.internal.eststelemetry.PublicApiId;
import com.microsoft.identity.common.internal.logging.Logger;
+import com.microsoft.identity.common.internal.migration.AdalMigrationAdapter;
+import com.microsoft.identity.common.internal.migration.TokenMigrationCallback;
+import com.microsoft.identity.common.internal.migration.TokenMigrationUtility;
import com.microsoft.identity.common.internal.net.HttpRequest;
import com.microsoft.identity.common.internal.net.cache.HttpCache;
+import com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAccount;
+import com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectory;
import com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache;
import com.microsoft.identity.common.internal.request.AcquireTokenOperationParameters;
@@ -84,6 +94,7 @@ import com.microsoft.identity.msal.BuildConfig;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
@@ -1821,4 +1832,41 @@ public class PublicClientApplication implements IPublicClientApplication, IToken
throw result.getException();
}
}
+
+ void performMigration(@NonNull final TokenMigrationCallback callback) {
+ final Map<String, String> redirects = new HashMap<>();
+ redirects.put(
+ mPublicClientConfiguration.getClientId(), // Our client id
+ mPublicClientConfiguration.getRedirectUri() // Our redirect uri
+ );
+
+ final AdalMigrationAdapter adalMigrationAdapter = new AdalMigrationAdapter(
+ mPublicClientConfiguration.getAppContext(),
+ redirects,
+ false
+ );
+
+ if (adalMigrationAdapter.getMigrationStatus()) {
+ callback.onMigrationFinished(0);
+ } else {
+ // Create the SharedPreferencesFileManager for the legacy accounts/credentials
+ final IStorageHelper storageHelper = new StorageHelper(mPublicClientConfiguration.getAppContext());
+ final ISharedPreferencesFileManager sharedPreferencesFileManager =
+ new SharedPreferencesFileManager(
+ mPublicClientConfiguration.getAppContext(),
+ "com.microsoft.aad.adal.cache",
+ storageHelper
+ );
+
+ // Load the old TokenCacheItems as key/value JSON
+ final Map<String, String> credentials = sharedPreferencesFileManager.getAll();
+
+ new TokenMigrationUtility<MicrosoftAccount, MicrosoftRefreshToken>()._import(
+ adalMigrationAdapter,
+ credentials,
+ (IShareSingleSignOnState<MicrosoftAccount, MicrosoftRefreshToken>) mPublicClientConfiguration.getOAuth2TokenCache(),
+ callback
+ );
+ }
+ }
}
diff --git a/msal/src/main/java/com/microsoft/identity/client/SingleAccountPublicClientApplication.java b/msal/src/main/java/com/microsoft/identity/client/SingleAccountPublicClientApplication.java
index c967c603..b7242626 100644
--- a/msal/src/main/java/com/microsoft/identity/client/SingleAccountPublicClientApplication.java
+++ b/msal/src/main/java/com/microsoft/identity/client/SingleAccountPublicClientApplication.java
@@ -47,6 +47,7 @@ import com.microsoft.identity.common.internal.controllers.GetCurrentAccountComma
import com.microsoft.identity.common.internal.controllers.RemoveCurrentAccountCommand;
import com.microsoft.identity.common.internal.dto.AccountRecord;
import com.microsoft.identity.common.internal.eststelemetry.PublicApiId;
+import com.microsoft.identity.common.internal.migration.TokenMigrationCallback;
import com.microsoft.identity.common.internal.request.OperationParameters;
import com.microsoft.identity.common.internal.result.ILocalAuthenticationResult;
import com.microsoft.identity.common.internal.result.ResultFuture;
@@ -92,43 +93,50 @@ public class SingleAccountPublicClientApplication extends PublicClientApplicatio
private void getCurrentAccountAsyncInternal(@NonNull final CurrentAccountCallback callback,
@NonNull final String publicApiId) {
- final OperationParameters params = OperationParametersAdapter.createOperationParameters(mPublicClientConfiguration, mPublicClientConfiguration.getOAuth2TokenCache());
- final BaseController controller;
- try {
- controller = MSALControllerFactory.getDefaultController(
- mPublicClientConfiguration.getAppContext(),
- params.getAuthority(),
- mPublicClientConfiguration);
- } catch (MsalClientException e) {
- callback.onError(e);
- return;
- }
-
- final GetCurrentAccountCommand command = new GetCurrentAccountCommand(
- params,
- controller,
- new CommandCallback<List<ICacheRecord>, BaseException>() {
- @Override
- public void onTaskCompleted(final List<ICacheRecord> result) {
- // To simplify the logic, if more than one account is returned, the first account will be picked.
- // We do not support switching from MULTIPLE to SINGLE.
- // See getAccountFromICacheRecordList() for more details.
- checkCurrentAccountNotifyCallback(callback, result);
- }
-
- @Override
- public void onError(final BaseException exception) {
- callback.onError(MsalExceptionAdapter.msalExceptionFromBaseException(exception));
- }
+ TokenMigrationCallback migrationCallback = new TokenMigrationCallback() {
+ @Override
+ public void onMigrationFinished(int numberOfAccountsMigrated) {
+ final OperationParameters params = OperationParametersAdapter.createOperationParameters(mPublicClientConfiguration, mPublicClientConfiguration.getOAuth2TokenCache());
+ final BaseController controller;
+ try {
+ controller = MSALControllerFactory.getDefaultController(
+ mPublicClientConfiguration.getAppContext(),
+ params.getAuthority(),
+ mPublicClientConfiguration);
+ } catch (MsalClientException e) {
+ callback.onError(e);
+ return;
+ }
- @Override
- public void onCancel() {
- //Do nothing
- }
- });
+ final GetCurrentAccountCommand command = new GetCurrentAccountCommand(
+ params,
+ controller,
+ new CommandCallback<List<ICacheRecord>, BaseException>() {
+ @Override
+ public void onTaskCompleted(final List<ICacheRecord> result) {
+ // To simplify the logic, if more than one account is returned, the first account will be picked.
+ // We do not support switching from MULTIPLE to SINGLE.
+ // See getAccountFromICacheRecordList() for more details.
+ checkCurrentAccountNotifyCallback(callback, result);
+ }
+
+ @Override
+ public void onError(final BaseException exception) {
+ callback.onError(MsalExceptionAdapter.msalExceptionFromBaseException(exception));
+ }
+
+ @Override
+ public void onCancel() {
+ //Do nothing
+ }
+ });
+
+ command.setPublicApiId(publicApiId);
+ CommandDispatcher.submitSilent(command);
+ }
+ };
- command.setPublicApiId(publicApiId);
- CommandDispatcher.submitSilent(command);
+ performMigration(migrationCallback);
}
@Override | ['msal/src/main/java/com/microsoft/identity/client/MultipleAccountPublicClientApplication.java', 'msal/src/main/java/com/microsoft/identity/client/SingleAccountPublicClientApplication.java', 'msal/src/main/java/com/microsoft/identity/client/PublicClientApplication.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 630,066 | 116,041 | 14,788 | 90 | 21,704 | 2,949 | 403 | 3 | 151 | 25 | 31 | 3 | 0 | 0 | 1970-01-01T00:26:24 | 181 | Java | {'Java': 1654367, 'Kotlin': 94116, 'Shell': 437} | MIT License |
323 | apache/fluo/324/323 | apache | fluo | https://github.com/apache/fluo/issues/323 | https://github.com/apache/fluo/pull/324 | https://github.com/apache/fluo/pull/324 | 1 | fixes | FluoOutputFormat is dropping zookeepers from config | Trying to run the stress test on a 20 node aws cluster. I have 3 zookeepers. My config looks like the following
```
io.fluo.client.zookeeper.connect=ip-10-1-2-10,ip-10-1-2-11,ip-10-1-2-12/fluo
```
Mappers fail w/ the following exception
```
Caused by: java.lang.IllegalStateException: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /config/accumulo.instance.name
at io.fluo.core.impl.Environment.init(Environment.java:118)
at io.fluo.core.impl.Environment.<init>(Environment.java:95)
at io.fluo.core.client.FluoClientImpl.<init>(FluoClientImpl.java:53)
... 15 more
```
In the mapper log, I found the following. So I think something is dropping everything after the 1st comma.
```
2014-11-12 20:39:25,294 INFO [main] org.apache.zookeeper.ZooKeeper: Initiating client connection, connectString=ip-10-1-2-10 sessionTimeout=30000 watcher=org.apache.curator.ConnectionState@60a46327
```
| 4edaa615874ea4db9eda615c413b6c35688122bf | 0a5876c8fa7e3aabde7790385fb87d6f6ca53523 | https://github.com/apache/fluo/compare/4edaa615874ea4db9eda615c413b6c35688122bf...0a5876c8fa7e3aabde7790385fb87d6f6ca53523 | diff --git a/modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java b/modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java
index 2d8bd37d..156c38bf 100644
--- a/modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java
+++ b/modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java
@@ -28,6 +28,7 @@ import java.util.concurrent.TimeUnit;
import javax.xml.bind.DatatypeConverter;
import com.google.common.base.Charsets;
+import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
@@ -124,6 +125,11 @@ public class FluoConfiguration extends CompositeConfiguration {
public FluoConfiguration(Configuration configuration) {
this();
+ if(configuration instanceof AbstractConfiguration){
+ AbstractConfiguration aconf = (AbstractConfiguration) configuration;
+ aconf.setDelimiterParsingDisabled(true);
+ }
+
addConfiguration(configuration);
}
diff --git a/modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java b/modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java
index 94303279..659cfdce 100644
--- a/modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java
+++ b/modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java
@@ -17,7 +17,9 @@ package io.fluo.api.config;
import java.io.File;
import java.util.NoSuchElementException;
+import java.util.Properties;
+import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
@@ -179,4 +181,17 @@ public class FluoConfigurationTest {
byte[] bytes2 = IOUtils.toByteArray(config.getMetricsYaml());
Assert.assertArrayEquals(bytes1, bytes2);
}
+
+ @Test
+ public void testMultipleZookeepers(){
+ Properties props = new Properties();
+ props.setProperty(FluoConfiguration.CLIENT_ACCUMULO_ZOOKEEPERS_PROP, "zk1,zk2,zk3");
+ props.setProperty(FluoConfiguration.CLIENT_ZOOKEEPER_CONNECT_PROP, "zk1,zk2,zk3/fluo");
+
+ //ran into a bug where this particular constructor was truncating everything after zk1
+ FluoConfiguration config = new FluoConfiguration(ConfigurationConverter.getConfiguration(props));
+ Assert.assertEquals("zk1,zk2,zk3", config.getAccumuloZookeepers());
+ Assert.assertEquals("zk1,zk2,zk3/fluo", config.getZookeepers());
+ }
+
} | ['modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java', 'modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 544,093 | 122,553 | 17,187 | 134 | 257 | 39 | 6 | 1 | 943 | 83 | 273 | 22 | 0 | 3 | 1970-01-01T00:23:35 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
324 | apache/fluo/219/218 | apache | fluo | https://github.com/apache/fluo/issues/218 | https://github.com/apache/fluo/pull/219 | https://github.com/apache/fluo/pull/219 | 1 | closes | Stop accumulo classpath value from being shortened | While working on #214, I discovered that the Accumulo classpath was being shortened when fluo.properties was used to create FluoConfiguration. This is due to the properties file being loaded into a PropertiesConfiguration object that did not have `setDelimiterParsingDisable()` set to true.
This bug needs to be fixed for the alpha release as it causes iterators to not be loaded into Fluo when running on YARN.
| 3340f5d3a909ae76f0c8309d3913b1639574811c | 7d86080479b593684452d96eab574d59d2950c2a | https://github.com/apache/fluo/compare/3340f5d3a909ae76f0c8309d3913b1639574811c...7d86080479b593684452d96eab574d59d2950c2a | diff --git a/modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java b/modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java
index cddf6604..82bfc6b7 100644
--- a/modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java
+++ b/modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java
@@ -112,7 +112,11 @@ public class FluoConfiguration extends CompositeConfiguration {
public FluoConfiguration(File propertiesFile) {
this();
try {
- addConfiguration(new PropertiesConfiguration(propertiesFile));
+ PropertiesConfiguration config = new PropertiesConfiguration();
+ // disabled to prevent accumulo classpath value from being shortened
+ config.setDelimiterParsingDisabled(true);
+ config.load(propertiesFile);
+ addConfiguration(config);
} catch (ConfigurationException e) {
throw new IllegalArgumentException(e);
}
diff --git a/modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java b/modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java
index c1ca9754..59bb8838 100644
--- a/modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java
+++ b/modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java
@@ -15,6 +15,7 @@
*/
package io.fluo.api.config;
+import java.io.File;
import java.util.NoSuchElementException;
import org.junit.Assert;
@@ -70,7 +71,7 @@ public class FluoConfigurationTest {
@Test
public void testSetGet() {
FluoConfiguration config = new FluoConfiguration();
- Assert.assertEquals("path", config.setAccumuloClasspath("path").getAccumuloClasspath());
+ Assert.assertEquals("path1,path2", config.setAccumuloClasspath("path1,path2").getAccumuloClasspath());
Assert.assertEquals("instance", config.setAccumuloInstance("instance").getAccumuloInstance());
Assert.assertEquals("pass", config.setAccumuloPassword("pass").getAccumuloPassword());
Assert.assertEquals("table", config.setAccumuloTable("table").getAccumuloTable());
@@ -144,4 +145,19 @@ public class FluoConfigurationTest {
config.setAccumuloTable("table");
Assert.assertTrue(config.hasRequiredMiniFluoProps());
}
+
+ @Test
+ public void testLoadingPropsFile() {
+ File propsFile = new File("../distribution/src/main/config/fluo.properties");
+ Assert.assertTrue(propsFile.exists());
+
+ FluoConfiguration config = new FluoConfiguration(propsFile);
+ // make sure classpath contains comma. otherwise it was shortened
+ Assert.assertTrue(config.getAccumuloClasspath().contains(","));
+ // check for values set in prop file
+ Assert.assertEquals("localhost", config.getZookeepers());
+ Assert.assertEquals("", config.getAccumuloUser());
+ Assert.assertEquals("", config.getAccumuloPassword());
+ Assert.assertEquals("", config.getAccumuloTable());
+ }
}
diff --git a/modules/cluster/src/main/java/io/fluo/cluster/InitializeTool.java b/modules/cluster/src/main/java/io/fluo/cluster/InitializeTool.java
index 97a891b7..81f71191 100644
--- a/modules/cluster/src/main/java/io/fluo/cluster/InitializeTool.java
+++ b/modules/cluster/src/main/java/io/fluo/cluster/InitializeTool.java
@@ -47,6 +47,8 @@ public class InitializeTool {
options.validateConfig();
Logging.init("init", options.getConfigDir(), options.getLogOutput());
+
+ log.info("Initalizing Fluo using the following properties file: "+options.getFluoProps());
FluoConfiguration config = new FluoConfiguration(new File(options.getFluoProps()));
if (!config.hasRequiredAdminProps()) { | ['modules/api/src/main/java/io/fluo/api/config/FluoConfiguration.java', 'modules/cluster/src/main/java/io/fluo/cluster/InitializeTool.java', 'modules/api/src/test/java/io/fluo/api/config/FluoConfigurationTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 476,316 | 107,491 | 15,095 | 113 | 435 | 74 | 8 | 2 | 414 | 65 | 85 | 4 | 0 | 0 | 1970-01-01T00:23:31 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
305 | apache/fluo/862/860 | apache | fluo | https://github.com/apache/fluo/issues/860 | https://github.com/apache/fluo/pull/862 | https://github.com/apache/fluo/pull/862 | 1 | fixes | Fix name of ParitionManger class | The name of the class `ParitionManager` should be fixed and renamed to `PartitionManager`. | 2703575139ea6a36981981d86c551b6c1ea6c95e | d907f727b37b200e32e38bb2d209463edc6d0146 | https://github.com/apache/fluo/compare/2703575139ea6a36981981d86c551b6c1ea6c95e...d907f727b37b200e32e38bb2d209463edc6d0146 | diff --git a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ParitionManager.java b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/PartitionManager.java
similarity index 98%
rename from modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ParitionManager.java
rename to modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/PartitionManager.java
index 3ebb01e1..f0e6305d 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ParitionManager.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/PartitionManager.java
@@ -67,9 +67,9 @@ import static java.nio.charset.StandardCharsets.UTF_8;
* notifications. This limitation is important for scaling, even if there are 1,000 workers there
* will never be more than 7 to 13 workers scanning a portion of the table.
*/
-public class ParitionManager {
+public class PartitionManager {
- private static final Logger log = LoggerFactory.getLogger(ParitionManager.class);
+ private static final Logger log = LoggerFactory.getLogger(PartitionManager.class);
private final PathChildrenCache childrenCache;
private final PersistentEphemeralNode myESNode;
@@ -267,7 +267,7 @@ public class ParitionManager {
}
}
- ParitionManager(Environment env, long minSleepTime, long maxSleepTime) {
+ PartitionManager(Environment env, long minSleepTime, long maxSleepTime) {
try {
this.curator = env.getSharedResources().getCurator();
this.env = env;
diff --git a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/PartitionNotificationFinder.java b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/PartitionNotificationFinder.java
index c9408504..c3649aaa 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/PartitionNotificationFinder.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/PartitionNotificationFinder.java
@@ -26,7 +26,7 @@ import org.apache.fluo.core.worker.TxResult;
public class PartitionNotificationFinder implements NotificationFinder {
- private ParitionManager paritionManager;
+ private PartitionManager partitionManager;
private Thread scanThread;
private NotificationProcessor processor;
private Environment env;
@@ -49,10 +49,10 @@ public class PartitionNotificationFinder implements NotificationFinder {
env.getConfiguration().getInt(FluoConfigurationImpl.NTFY_FINDER_MAX_SLEEP_TIME_PROP,
FluoConfigurationImpl.NTFY_FINDER_MAX_SLEEP_TIME_DEFAULT);
- paritionManager = new ParitionManager(env, minSleepTime, maxSleepTime);
+ partitionManager = new PartitionManager(env, minSleepTime, maxSleepTime);
scanThread =
- new Thread(new ScanTask(this, processor, paritionManager, env, stopped, minSleepTime,
+ new Thread(new ScanTask(this, processor, partitionManager, env, stopped, minSleepTime,
maxSleepTime));
scanThread.setName(getClass().getSimpleName() + " " + ScanTask.class.getSimpleName());
scanThread.setDaemon(true);
@@ -70,12 +70,12 @@ public class PartitionNotificationFinder implements NotificationFinder {
throw new RuntimeException(e);
}
- paritionManager.stop();
+ partitionManager.stop();
}
@Override
public boolean shouldProcess(Notification notification) {
- return paritionManager.shouldProcess(notification);
+ return partitionManager.shouldProcess(notification);
}
@Override
diff --git a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
index 35f3215f..3ebc6254 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
@@ -47,7 +47,7 @@ public class ScanTask implements Runnable {
private static final Logger log = LoggerFactory.getLogger(ScanTask.class);
private final NotificationFinder finder;
- private final ParitionManager partitionManager;
+ private final PartitionManager partitionManager;
private final NotificationProcessor proccessor;
private final Random rand = new Random();
private final AtomicBoolean stopped;
@@ -58,7 +58,7 @@ public class ScanTask implements Runnable {
private long maxSleepTime;
ScanTask(NotificationFinder finder, NotificationProcessor proccessor,
- ParitionManager partitionManager, Environment env, AtomicBoolean stopped, long minSleepTime,
+ PartitionManager partitionManager, Environment env, AtomicBoolean stopped, long minSleepTime,
long maxSleepTime) {
this.finder = finder;
this.rangeData = new HashMap<>();
diff --git a/modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/HashTest.java b/modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/HashTest.java
index b3496dd4..1d1c5a69 100644
--- a/modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/HashTest.java
+++ b/modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/HashTest.java
@@ -63,7 +63,7 @@ public class HashTest {
byte[] cfcq = NotificationUtil.encodeCol(col);
Key k = new Key(row, ColumnConstants.NOTIFY_CF.toArray(), cfcq, new byte[0], 6);
boolean accept = NotificationHashFilter.accept(k, 7, 3);
- Assert.assertEquals(accept, ParitionManager.shouldProcess(Notification.from(k), 7, 3));
+ Assert.assertEquals(accept, PartitionManager.shouldProcess(Notification.from(k), 7, 3));
return accept;
}
}
diff --git a/modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/PartitionManagerTest.java b/modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/PartitionManagerTest.java
index 8a02edc1..b3d0d648 100644
--- a/modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/PartitionManagerTest.java
+++ b/modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/PartitionManagerTest.java
@@ -59,7 +59,7 @@ public class PartitionManagerTest {
for (int i = 0; i < numWorkers; i++) {
String me = nff.apply(i);
- PartitionInfo pi = ParitionManager.getGroupInfo(me, children, tablets, groupSize);
+ PartitionInfo pi = PartitionManager.getGroupInfo(me, children, tablets, groupSize);
Assert.assertEquals(expectedGroups, pi.getNumGroups());
Assert.assertTrue(pi.getMyGroupSize() >= Math.min(numWorkers, groupSize)
&& pi.getMyGroupSize() <= maxGroupSize); | ['modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ParitionManager.java', 'modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/PartitionManagerTest.java', 'modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/PartitionNotificationFinder.java', 'modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java', 'modules/core/src/test/java/org/apache/fluo/core/worker/finder/hash/HashTest.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 831,237 | 183,403 | 25,009 | 189 | 913 | 177 | 14 | 3 | 90 | 13 | 20 | 1 | 0 | 0 | 1970-01-01T00:24:56 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
306 | apache/fluo/859/858 | apache | fluo | https://github.com/apache/fluo/issues/858 | https://github.com/apache/fluo/pull/859 | https://github.com/apache/fluo/pull/859 | 1 | fixes | Notification scanner slept max time when tablets changed | I noticed this while running the stress test. The test started the Fluo app and then later added splits to the table. Fluo eventually noticed these new splits and when it did scanned 0 tablets and then slept for 5 mins (which is the max time to sleep between tablet scans). This case could be handled in a more responsive way.
```
14:02:52.596 [Fluo-0007-001-Fluo worker partition manager] DEBUG o.a.f.c.w.f.hash.ParitionManager - Updated finder partition info : workers:2 groups:1 groupSize:2 groupId:0 idInGroup:1 #tablets:10
14:02:52.635 [PartitionNotificationFinder ScanTask] DEBUG o.a.f.c.worker.finder.hash.ScanTask - Scanned 0 of 1 tablets. Notifications added: 0 seen: 0 queued: 0
14:07:52.786 [PartitionNotificationFinder ScanTask] DEBUG o.a.f.c.worker.finder.hash.ScanTask - Scanned 10 of 10 tablets. Notifications added: 331 seen: 331 queued: 38
``` | f0403a1d41f994fc36ea0629e426e13b99c0c5dd | c155bdc7d74cac201fca5cd409312c9acd110154 | https://github.com/apache/fluo/compare/f0403a1d41f994fc36ea0629e426e13b99c0c5dd...c155bdc7d74cac201fca5cd409312c9acd110154 | diff --git a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
index 35f3215f..00726a8d 100644
--- a/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
+++ b/modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java
@@ -76,7 +76,6 @@ public class ScanTask implements Runnable {
@Override
public void run() {
-
List<TableRange> ranges = new ArrayList<>();
Set<TableRange> rangeSet = new HashSet<>();
@@ -135,7 +134,12 @@ public class ScanTask implements Runnable {
// nothing to do
}
- long sleepTime = Math.max(minSleepTime, minRetryTime - System.currentTimeMillis());
+ long sleepTime;
+ if (!partition.equals(partitionManager.getPartitionInfo())) {
+ sleepTime = minSleepTime;
+ } else {
+ sleepTime = Math.max(minSleepTime, minRetryTime - System.currentTimeMillis());
+ }
qSize = proccessor.size();
| ['modules/core/src/main/java/org/apache/fluo/core/worker/finder/hash/ScanTask.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 831,084 | 183,372 | 25,005 | 189 | 346 | 68 | 8 | 1 | 876 | 118 | 242 | 7 | 0 | 1 | 1970-01-01T00:24:56 | 181 | Java | {'Java': 1444123, 'Shell': 37149, 'Thrift': 990} | Apache License 2.0 |
905 | archy-x/aureliumskills/149/144 | archy-x | aureliumskills | https://github.com/Archy-X/AureliumSkills/issues/144 | https://github.com/Archy-X/AureliumSkills/pull/149 | https://github.com/Archy-X/AureliumSkills/pull/149 | 1 | fix | Placed dirt, sand, etc. will still drop loot items | ### Server software and version
purpur 1.19.2
### Expected behavior
Placed dirt will not drop loot items
### Actual behavior
Placed dirt will drop loot items, resulting in unlimited items
### How to reproduce
1、place dirt
2、dig the dirt
3、pick up dirt and loot items
4、place dirt...
### Additional information
I configured custom loot file
https://www.youtube.com/watch?v=gCAF7hWudMU
### Agreements
- [X] I am running the latest version of Aurelium Skills
- [X] I am not using an unsupported server software (https://wiki.aurelium.dev/skills/other/incompatibilities)
- [X] My version of Minecraft is supported by Aurelium Skills | 7ce4fe700d59303eb82eac601531efdfcd1d287a | e3ac5dc853cee56cd44136ebfd7eed7751a11565 | https://github.com/archy-x/aureliumskills/compare/7ce4fe700d59303eb82eac601531efdfcd1d287a...e3ac5dc853cee56cd44136ebfd7eed7751a11565 | diff --git a/src/main/java/com/archyx/aureliumskills/loot/handler/BlockLootHandler.java b/src/main/java/com/archyx/aureliumskills/loot/handler/BlockLootHandler.java
index 907d37bb..e1cb9a97 100644
--- a/src/main/java/com/archyx/aureliumskills/loot/handler/BlockLootHandler.java
+++ b/src/main/java/com/archyx/aureliumskills/loot/handler/BlockLootHandler.java
@@ -3,6 +3,7 @@ package com.archyx.aureliumskills.loot.handler;
import com.archyx.aureliumskills.AureliumSkills;
import com.archyx.aureliumskills.ability.Ability;
import com.archyx.aureliumskills.api.event.LootDropCause;
+import com.archyx.aureliumskills.configuration.Option;
import com.archyx.aureliumskills.configuration.OptionL;
import com.archyx.aureliumskills.data.PlayerData;
import com.archyx.aureliumskills.skills.Skill;
@@ -45,6 +46,11 @@ public abstract class BlockLootHandler extends LootHandler implements Listener {
Block block = event.getBlock();
if (getSource(block) == null) return;
+ // Check block replace
+ if (OptionL.getBoolean(Option.CHECK_BLOCK_REPLACE) && plugin.getRegionManager().isPlacedBlock(block)) {
+ return;
+ }
+
Player player = event.getPlayer();
if (blockAbility(player)) return;
| ['src/main/java/com/archyx/aureliumskills/loot/handler/BlockLootHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,196,733 | 258,024 | 30,377 | 297 | 234 | 50 | 6 | 1 | 645 | 91 | 165 | 30 | 2 | 0 | 1970-01-01T00:27:49 | 180 | Java | {'Java': 1225534, 'Kotlin': 4108} | MIT License |
898 | fraunhofer-aisec/cpg/193/192 | fraunhofer-aisec | cpg | https://github.com/Fraunhofer-AISEC/cpg/issues/192 | https://github.com/Fraunhofer-AISEC/cpg/pull/193 | https://github.com/Fraunhofer-AISEC/cpg/pull/193 | 1 | fixes | Field `annotations` must not be null, breaks OGM | Commit 7d56eda487e8ec408b13036581d08b5e9800ff3e breaks the object graph mapper (OGM) of Codyze (and possibly Neo4J) and makes CPG structure ambiguous.
Collection fields of `Node`s must not be null.
Fields of classes in the CPG structure will result in either _edges_ or _properties_ of a node. The clearest way is to make that explicit by using the `@Relationship` annotation to enforce an edge. If that is not present, the OGM will investigate the value of the respective field and see if it is a `Node` type or Collection of `Node`s. This requires the field to be non-null, otherwise the OGM will consider it a property on the one hand, but not be able to provide type information on the other hand.
In its current form, Codyze will run into many `IllegalStateException`s. | d3301f6a1d76b28a571b2446a098bd3d45c74a14 | 14ea7925b60771c2103f3837af39be0266c2adc7 | https://github.com/fraunhofer-aisec/cpg/compare/d3301f6a1d76b28a571b2446a098bd3d45c74a14...14ea7925b60771c2103f3837af39be0266c2adc7 | diff --git a/src/main/java/de/fraunhofer/aisec/cpg/frontends/cpp/CXXLanguageFrontend.java b/src/main/java/de/fraunhofer/aisec/cpg/frontends/cpp/CXXLanguageFrontend.java
index 4f1e2bd0e..5cfe36af0 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/frontends/cpp/CXXLanguageFrontend.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/frontends/cpp/CXXLanguageFrontend.java
@@ -372,7 +372,7 @@ public class CXXLanguageFrontend extends LanguageFrontend {
public void processAttributes(@NonNull Node node, @NonNull IASTAttributeOwner owner) {
if (this.config.processAnnotations) {
// set attributes
- node.setAnnotations(handleAttributes(owner));
+ node.addAnnotations(handleAttributes(owner));
}
}
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/ConstructorDeclaration.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/ConstructorDeclaration.java
index 816a2a126..7a6efb08b 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/ConstructorDeclaration.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/ConstructorDeclaration.java
@@ -55,7 +55,7 @@ public class ConstructorDeclaration extends MethodDeclaration {
c.setBody(methodDeclaration.getBody());
c.setLocation(methodDeclaration.getLocation());
c.setParameters(methodDeclaration.getParameters());
- c.setAnnotations(methodDeclaration.getAnnotations());
+ c.addAnnotations(methodDeclaration.getAnnotations());
c.setIsDefinition(methodDeclaration.isDefinition());
if (!c.isDefinition()) {
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/MethodDeclaration.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/MethodDeclaration.java
index 20361ebbd..f1f8456d0 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/MethodDeclaration.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/MethodDeclaration.java
@@ -59,7 +59,7 @@ public class MethodDeclaration extends FunctionDeclaration {
md.setParameters(functionDeclaration.getParameters());
md.setBody(functionDeclaration.getBody());
md.setType(functionDeclaration.getType());
- md.setAnnotations(functionDeclaration.getAnnotations());
+ md.addAnnotations(functionDeclaration.getAnnotations());
md.setRecordDeclaration(recordDeclaration);
md.setIsDefinition(functionDeclaration.isDefinition());
@@ -80,6 +80,7 @@ public class MethodDeclaration extends FunctionDeclaration {
this.isStatic = isStatic;
}
+ @Nullable
public RecordDeclaration getRecordDeclaration() {
return recordDeclaration;
}
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/Node.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/Node.java
index 4a5ff14fd..e46897645 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/Node.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/Node.java
@@ -29,11 +29,7 @@ package de.fraunhofer.aisec.cpg.graph;
import de.fraunhofer.aisec.cpg.helpers.LocationConverter;
import de.fraunhofer.aisec.cpg.processing.IVisitable;
import de.fraunhofer.aisec.cpg.sarif.PhysicalLocation;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
+import java.util.*;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -74,6 +70,7 @@ public class Node extends IVisitable<Node> {
protected String file;
/** Incoming control flow edges. */
+ @NonNull
@Relationship(value = "EOG", direction = "INCOMING")
protected List<Node> prevEOG = new ArrayList<>();
@@ -87,13 +84,15 @@ public class Node extends IVisitable<Node> {
@Relationship(value = "CFG", direction = "OUTGOING")
protected List<Node> nextCFG = new ArrayList<>();
+ @NonNull
@Relationship(value = "DFG", direction = "INCOMING")
protected Set<Node> prevDFG = new HashSet<>();
+ @NonNull
@Relationship(value = "DFG")
protected Set<Node> nextDFG = new HashSet<>();
- protected Set<TypedefDeclaration> typedefs = new HashSet<>();
+ @NonNull protected Set<TypedefDeclaration> typedefs = new HashSet<>();
/**
* If a node is marked as being a dummy, it means that it was created artificially and does not
@@ -116,7 +115,7 @@ public class Node extends IVisitable<Node> {
/** List of annotations associated with that node. */
@SubGraph("AST")
- protected List<Annotation> annotations;
+ protected List<Annotation> annotations = new ArrayList<>();
public Long getId() {
return id;
@@ -156,11 +155,12 @@ public class Node extends IVisitable<Node> {
this.location = location;
}
+ @NonNull
public List<Node> getPrevEOG() {
return this.prevEOG;
}
- public void setPrevEOG(List<Node> prevEOG) {
+ public void setPrevEOG(@NonNull List<Node> prevEOG) {
this.prevEOG = prevEOG;
}
@@ -178,11 +178,12 @@ public class Node extends IVisitable<Node> {
return this.nextCFG;
}
+ @NonNull
public Set<Node> getNextDFG() {
return nextDFG;
}
- public void setNextDFG(Set<Node> nextDFG) {
+ public void setNextDFG(@NonNull Set<Node> nextDFG) {
this.nextDFG = nextDFG;
}
@@ -198,11 +199,12 @@ public class Node extends IVisitable<Node> {
}
}
+ @NonNull
public Set<Node> getPrevDFG() {
return prevDFG;
}
- public void setPrevDFG(Set<Node> prevDFG) {
+ public void setPrevDFG(@NonNull Set<Node> prevDFG) {
this.prevDFG = prevDFG;
}
@@ -222,11 +224,12 @@ public class Node extends IVisitable<Node> {
this.typedefs.add(typedef);
}
+ @NonNull
public Set<TypedefDeclaration> getTypedefs() {
return typedefs;
}
- public void setTypedefs(Set<TypedefDeclaration> typedefs) {
+ public void setTypedefs(@NonNull Set<TypedefDeclaration> typedefs) {
this.typedefs = typedefs;
}
@@ -259,6 +262,15 @@ public class Node extends IVisitable<Node> {
return this.implicit;
}
+ @NonNull
+ public List<Annotation> getAnnotations() {
+ return annotations;
+ }
+
+ public void addAnnotations(@NonNull Collection<Annotation> annotations) {
+ this.annotations.addAll(annotations);
+ }
+
/**
* If a node should be removed from the graph, just removing it from the AST is not enough (see
* issue #60). It will most probably be referenced somewhere via DFG or EOG edges. Thus, if it
@@ -326,12 +338,4 @@ public class Node extends IVisitable<Node> {
public int hashCode() {
return Objects.hash(name, this.getClass());
}
-
- public void setAnnotations(List<Annotation> annotations) {
- this.annotations = annotations;
- }
-
- public List<Annotation> getAnnotations() {
- return annotations;
- }
} | ['src/main/java/de/fraunhofer/aisec/cpg/graph/MethodDeclaration.java', 'src/main/java/de/fraunhofer/aisec/cpg/graph/Node.java', 'src/main/java/de/fraunhofer/aisec/cpg/frontends/cpp/CXXLanguageFrontend.java', 'src/main/java/de/fraunhofer/aisec/cpg/graph/ConstructorDeclaration.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 782,401 | 176,530 | 23,133 | 147 | 1,684 | 373 | 49 | 4 | 784 | 128 | 194 | 7 | 0 | 0 | 1970-01-01T00:26:36 | 176 | Kotlin | {'Kotlin': 2820067, 'LLVM': 170593, 'Python': 62850, 'C++': 46273, 'Java': 40608, 'C': 31212, 'Go': 28639, 'TypeScript': 4908, 'Shell': 2785, 'JavaScript': 751, 'CMake': 204} | Apache License 2.0 |
896 | fraunhofer-aisec/cpg/309/308 | fraunhofer-aisec | cpg | https://github.com/Fraunhofer-AISEC/cpg/issues/308 | https://github.com/Fraunhofer-AISEC/cpg/pull/309 | https://github.com/Fraunhofer-AISEC/cpg/pull/309 | 1 | fixes | Bug in ExpressionHandler::handleMethodCallExpression | [...] I just tried CPG version 3.3.1. There, another error occurred to me:
```
Unable to calculate the type of a parameter of a method call. Method call: addParameter("label", findString(label)), Parameter: findString(label)
```
The function is indeed not defined but this wasn't an issue with CPG version 3.2.0 (I guess that's because of the updated JavaParser).
Could the flag "failOnError" in the TranslationConfiguration Class perhaps be used to circumvent this issue in the future?
Nevertheless, after removing the undefined methods, the CFG pass is still stuck with CPG version 3.3.1 .
Strangely as before, the removal of the Setters causes the CFG pass to terminate.
_Originally posted by @anon767 in https://github.com/Fraunhofer-AISEC/cpg/issues/307#issuecomment-763588895_ | e68da425e984d9f365f7c5f39096b4e2eb0aeac6 | fe7c17740246c6a5003140b8315331b94ab6cd69 | https://github.com/fraunhofer-aisec/cpg/compare/e68da425e984d9f365f7c5f39096b4e2eb0aeac6...fe7c17740246c6a5003140b8315331b94ab6cd69 | diff --git a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
index 0d49a9f43..536403945 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
@@ -670,7 +670,10 @@ public class ExpressionHandler extends Handler<Statement, Expression, JavaLangua
resolved = methodCallExpr.resolve();
isStatic = resolved.isStatic();
typeString = resolved.getReturnType().describe();
- } catch (UnsolvedSymbolException | NoClassDefFoundError ignored) {
+ } catch (NoClassDefFoundError | RuntimeException ignored) {
+ // Unfortunately, JavaParser also throws a simple RuntimeException instead of an
+ // UnsolvedSymbolException within resolve() if it fails to resolve it under certain
+ // circumstances, we catch all that and continue on our own
log.debug("Could not resolve method {}", methodCallExpr);
}
| ['src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 878,880 | 198,612 | 25,515 | 155 | 382 | 79 | 5 | 1 | 799 | 111 | 196 | 12 | 1 | 1 | 1970-01-01T00:26:51 | 176 | Kotlin | {'Kotlin': 2820067, 'LLVM': 170593, 'Python': 62850, 'C++': 46273, 'Java': 40608, 'C': 31212, 'Go': 28639, 'TypeScript': 4908, 'Shell': 2785, 'JavaScript': 751, 'CMake': 204} | Apache License 2.0 |
899 | fraunhofer-aisec/cpg/173/171 | fraunhofer-aisec | cpg | https://github.com/Fraunhofer-AISEC/cpg/issues/171 | https://github.com/Fraunhofer-AISEC/cpg/pull/173 | https://github.com/Fraunhofer-AISEC/cpg/pull/173 | 1 | fixes | C++ generics with elaborated type specifiers fail to parse | The following: `TypeParser.createFrom("Array<struct Node>", true)` will create a generic type with a type parameter of type `"structNode"`. This seems to happen here, because of some reason this function here will remove all the whitespace within the generic block. Therefore, the type parser cannot correctly identity the `struct` as an elaborated type specifier (which is normally ignored). However, simply removing the function also does not work since then it is parsed as seperate typeblocks and things really start to go wrong :(
https://github.com/Fraunhofer-AISEC/cpg/blob/3f3542015dd6c989b8f8274b89478dfe67922126/src/main/java/de/fraunhofer/aisec/cpg/graph/type/TypeParser.java#L261-L300 | fd198bd4e0ee84c08f2e7425e8b7b45fb9363c9d | 455d021315527c6aae12a5c291275fc87e8ae269 | https://github.com/fraunhofer-aisec/cpg/compare/fd198bd4e0ee84c08f2e7425e8b7b45fb9363c9d...455d021315527c6aae12a5c291275fc87e8ae269 | diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/type/TypeParser.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/type/TypeParser.java
index 2d5accfdb..96c86e6ed 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/type/TypeParser.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/type/TypeParser.java
@@ -61,6 +61,13 @@ public class TypeParser {
private static final String ELABORATED_TYPE_UNION = "union";
private static final String ELABORATED_TYPE_ENUM = "enum";
+ private static final List<String> elaboratedTypes =
+ List.of(
+ ELABORATED_TYPE_CLASS,
+ ELABORATED_TYPE_STRUCT,
+ ELABORATED_TYPE_UNION,
+ ELABORATED_TYPE_ENUM);
+
private TypeParser() {
throw new IllegalStateException("Do not instantiate the TypeParser");
}
@@ -263,6 +270,27 @@ public class TypeParser {
*/
@NonNull
private static String fixGenerics(@NonNull String type) {
+ if (type.contains("<") && type.contains(">") && getLanguage() == TypeManager.Language.CXX) {
+ String generics = type.substring(type.indexOf('<') + 1, type.lastIndexOf('>'));
+
+ /* Explanation from @vfsrfs:
+ * We fist extract the generic string (the substring between < and >). Then, the elaborate
+ * string can either start directly with the elaborate type specifier e.g. struct Node or it
+ * must be preceded by <, \\\\h (horizontal whitespace), or ,. If any other character precedes
+ * the elaborate type specifier then it is not considered to be a type specifier e.g.
+ * mystruct. Then there can be an arbitrary amount of horizontal whitespaces. This is followed
+ * by the elaborate type specifier and at least one more horizontal whitespace, which marks
+ * that it is indeed an elaborate type and not something like structMy.
+ */
+ for (String elaborate : elaboratedTypes) {
+ generics = generics.replaceAll("(^|(?<=[\\\\h,<]))\\\\h*(?<main>" + elaborate + "\\\\h+)", "");
+ }
+ type =
+ type.substring(0, type.indexOf('<') + 1)
+ + generics.trim()
+ + type.substring(type.lastIndexOf('>'));
+ }
+
StringBuilder out = new StringBuilder();
int bracketCount = 0;
int iterator = 0;
@@ -729,7 +757,6 @@ public class TypeParser {
// Note that "const auto ..." will end here with typeName="const" as auto is not supported.
return UnknownType.getUnknownType();
}
- assert counter < typeBlocks.size();
String typeName = typeBlocks.get(counter);
counter++;
diff --git a/src/test/java/de/fraunhofer/aisec/cpg/TypeTests.java b/src/test/java/de/fraunhofer/aisec/cpg/TypeTests.java
index ce901258e..89a470a9d 100644
--- a/src/test/java/de/fraunhofer/aisec/cpg/TypeTests.java
+++ b/src/test/java/de/fraunhofer/aisec/cpg/TypeTests.java
@@ -603,6 +603,51 @@ class TypeTests extends BaseTest {
typeString = "int const &ref2 = a";
result = TypeParser.createFrom(typeString, true);
assertEquals(expected, result);
+
+ // Test 13: Elaborated Type in Generics
+ result = TypeParser.createFrom("Array<struct Node>", true);
+ generics = new ArrayList<>();
+ ObjectType generic =
+ new ObjectType(
+ "Node",
+ Type.Storage.AUTO,
+ new Type.Qualifier(),
+ new ArrayList<>(),
+ ObjectType.Modifier.NOT_APPLICABLE,
+ false);
+ generics.add(generic);
+
+ expected =
+ new ObjectType(
+ "Array",
+ Type.Storage.AUTO,
+ new Type.Qualifier(),
+ generics,
+ ObjectType.Modifier.NOT_APPLICABLE,
+ false);
+ assertEquals(expected, result);
+
+ result = TypeParser.createFrom("Array<myclass >", true);
+ generics = new ArrayList<>();
+ generic =
+ new ObjectType(
+ "myclass",
+ Type.Storage.AUTO,
+ new Type.Qualifier(),
+ new ArrayList<>(),
+ ObjectType.Modifier.NOT_APPLICABLE,
+ false);
+ generics.add(generic);
+
+ expected =
+ new ObjectType(
+ "Array",
+ Type.Storage.AUTO,
+ new Type.Qualifier(),
+ generics,
+ ObjectType.Modifier.NOT_APPLICABLE,
+ false);
+ assertEquals(expected, result);
}
// Tests on the resulting graph | ['src/main/java/de/fraunhofer/aisec/cpg/graph/type/TypeParser.java', 'src/test/java/de/fraunhofer/aisec/cpg/TypeTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 767,123 | 173,075 | 22,732 | 146 | 1,477 | 325 | 29 | 1 | 699 | 82 | 169 | 3 | 1 | 0 | 1970-01-01T00:26:34 | 176 | Kotlin | {'Kotlin': 2820067, 'LLVM': 170593, 'Python': 62850, 'C++': 46273, 'Java': 40608, 'C': 31212, 'Go': 28639, 'TypeScript': 4908, 'Shell': 2785, 'JavaScript': 751, 'CMake': 204} | Apache License 2.0 |
902 | fraunhofer-aisec/cpg/91/83 | fraunhofer-aisec | cpg | https://github.com/Fraunhofer-AISEC/cpg/issues/83 | https://github.com/Fraunhofer-AISEC/cpg/pull/91 | https://github.com/Fraunhofer-AISEC/cpg/pull/91 | 1 | closes | FQN wrong for some static calls | For the following snippet, the fqn is `Cipher.getInstance(...)` but should be `javax.crypto.Cipher.getInstance(...)`
```java
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class BCProviderCipher {
public static void main(String[] args) {
Cipher c4 = Cipher.getInstance("AES", new BouncyCastleProvider());
}
}
```
This probably has something to do with `BouncyCastleProvider` not being available. But still, the CPG could "guess" the fqn quite easily here i imagine | fa053cf7bc8cd38d13f3c6f20b05854eb47a0ac9 | f9082b8df1870f1f342ea6f7b2ffaaf25ed1ef3a | https://github.com/fraunhofer-aisec/cpg/compare/fa053cf7bc8cd38d13f3c6f20b05854eb47a0ac9...f9082b8df1870f1f342ea6f7b2ffaaf25ed1ef3a | diff --git a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
index abeb65285..716907aaf 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
@@ -654,9 +654,13 @@ public class ExpressionHandler
NodeBuilder.newMemberCallExpression(
name, qualifiedName, base, member, methodCallExpr.toString());
} else {
+ String targetClass = this.lang.getQualifiedNameFromImports(scopeName);
+ if (targetClass == null) {
+ targetClass = scopeName;
+ }
callExpression =
NodeBuilder.newStaticCallExpression(
- name, qualifiedName, methodCallExpr.toString(), scopeName);
+ name, qualifiedName, methodCallExpr.toString(), targetClass);
}
} else {
callExpression =
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java
index e0fea0374..47667534e 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java
@@ -323,7 +323,7 @@ public class JavaLanguageFrontend extends LanguageFrontend {
}
public String getQualifiedNameFromImports(String className) {
- if (context != null) {
+ if (context != null && className != null) {
List<String> potentialClassNames = new ArrayList<>();
String prefix = "";
for (String s : className.split("\\\\.")) {
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/StaticCallExpression.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/StaticCallExpression.java
index 38d496083..fa1fe04b8 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/StaticCallExpression.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/StaticCallExpression.java
@@ -26,6 +26,8 @@
package de.fraunhofer.aisec.cpg.graph;
+import org.checkerframework.checker.nullness.qual.NonNull;
+
/**
* A {@link CallExpression} that targets a static function of a different {@link RecordDeclaration},
* without using a static import: <code>SomeClass.invoke()</code>
@@ -38,7 +40,20 @@ public class StaticCallExpression extends CallExpression {
return targetRecord;
}
+ @Override
+ public void setName(@NonNull String name) {
+ super.setName(name);
+ updateFqn();
+ }
+
public void setTargetRecord(String targetRecord) {
this.targetRecord = targetRecord;
+ updateFqn();
+ }
+
+ private void updateFqn() {
+ if (targetRecord != null && !targetRecord.isEmpty() && name != null && !name.isEmpty()) {
+ setFqn(targetRecord + "." + name);
+ }
}
} | ['src/main/java/de/fraunhofer/aisec/cpg/graph/StaticCallExpression.java', 'src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java', 'src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 697,805 | 158,033 | 20,164 | 125 | 765 | 169 | 23 | 3 | 533 | 60 | 120 | 15 | 0 | 1 | 1970-01-01T00:26:27 | 176 | Kotlin | {'Kotlin': 2820067, 'LLVM': 170593, 'Python': 62850, 'C++': 46273, 'Java': 40608, 'C': 31212, 'Go': 28639, 'TypeScript': 4908, 'Shell': 2785, 'JavaScript': 751, 'CMake': 204} | Apache License 2.0 |
901 | fraunhofer-aisec/cpg/97/96 | fraunhofer-aisec | cpg | https://github.com/Fraunhofer-AISEC/cpg/issues/96 | https://github.com/Fraunhofer-AISEC/cpg/pull/97 | https://github.com/Fraunhofer-AISEC/cpg/pull/97 | 1 | fixes | Nodes referring to Java fields are missing parent and location | The following snippet instantiates a field `cipher` in an incorrect/unsafe way. However, the node referring to `cipher` does not have a `parent`, nor a `range` and consequently no `location`.
```
public class SealObject {
private final Cipher cipher;
public SealObject(String Password) throws Exception {
cipher = Cipher.getInstance("SomeUnsafeCipher");
}
}
``` | 5ec244271d3bf49e4e980920d787392be2111325 | 487558afba9539db62484b02eb23112ecc85478a | https://github.com/fraunhofer-aisec/cpg/compare/5ec244271d3bf49e4e980920d787392be2111325...487558afba9539db62484b02eb23112ecc85478a | diff --git a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
index 716907aaf..ea638a22f 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java
@@ -492,7 +492,11 @@ public class ExpressionHandler
if (!field.isStatic()) {
// convert to FieldAccessExpr
FieldAccessExpr fieldAccessExpr = new FieldAccessExpr(new ThisExpr(), field.getName());
+ expr.getRange().ifPresent(fieldAccessExpr::setRange);
+ expr.getTokenRange().ifPresent(fieldAccessExpr::setTokenRange);
+ expr.getParentNode().ifPresent(fieldAccessExpr::setParentNode);
expr.replace(fieldAccessExpr);
+ fieldAccessExpr.getParentNode().ifPresent(expr::setParentNode);
// handle it as a field expression
return (de.fraunhofer.aisec.cpg.graph.Expression) handle(fieldAccessExpr);
@@ -500,7 +504,11 @@ public class ExpressionHandler
FieldAccessExpr fieldAccessExpr =
new FieldAccessExpr(
new NameExpr(field.declaringType().getClassName()), field.getName());
+ expr.getRange().ifPresent(fieldAccessExpr::setRange);
+ expr.getTokenRange().ifPresent(fieldAccessExpr::setTokenRange);
+ expr.getParentNode().ifPresent(fieldAccessExpr::setParentNode);
expr.replace(fieldAccessExpr);
+ fieldAccessExpr.getParentNode().ifPresent(expr::setParentNode);
// handle it as a field expression
return (de.fraunhofer.aisec.cpg.graph.Expression) handle(fieldAccessExpr); | ['src/main/java/de/fraunhofer/aisec/cpg/frontends/java/ExpressionHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 699,043 | 158,387 | 20,208 | 125 | 579 | 118 | 8 | 1 | 394 | 50 | 83 | 11 | 0 | 1 | 1970-01-01T00:26:29 | 176 | Kotlin | {'Kotlin': 2820067, 'LLVM': 170593, 'Python': 62850, 'C++': 46273, 'Java': 40608, 'C': 31212, 'Go': 28639, 'TypeScript': 4908, 'Shell': 2785, 'JavaScript': 751, 'CMake': 204} | Apache License 2.0 |
897 | fraunhofer-aisec/cpg/279/278 | fraunhofer-aisec | cpg | https://github.com/Fraunhofer-AISEC/cpg/issues/278 | https://github.com/Fraunhofer-AISEC/cpg/pull/279 | https://github.com/Fraunhofer-AISEC/cpg/pull/279 | 1 | fixed | Support implicit annotation style in Java | In Java you can either specifiy annotation values for keys directly, such as `@RequestMapping(value = "/test")` or indirectly using `@RequestMapping("hello")`. If you use the latter, then it will be assigned to an attribute named `value`, if it exists.
Currently, the CPG does just ignore this example; it should be parsed as an annotation with a entry of `value` and `"hello"`.
| a45ed0ab080244305a3cfb065000acd3a380ddc1 | 8433084ff937c6a7d077042969eec1f5af140cf3 | https://github.com/fraunhofer-aisec/cpg/compare/a45ed0ab080244305a3cfb065000acd3a380ddc1...8433084ff937c6a7d077042969eec1f5af140cf3 | diff --git a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java
index fbad7a321..70917d820 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java
@@ -39,10 +39,7 @@ import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Node.Parsedness;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.TypeDeclaration;
-import com.github.javaparser.ast.expr.Expression;
-import com.github.javaparser.ast.expr.MemberValuePair;
-import com.github.javaparser.ast.expr.MethodCallExpr;
-import com.github.javaparser.ast.expr.NameExpr;
+import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
@@ -85,6 +82,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
/** Main parser for ONE Java files. */
public class JavaLanguageFrontend extends LanguageFrontend {
+ public static final String THIS = "this";
+ public static final String ANNOTATION_MEMBER_VALUE = "value";
+
private CompilationUnit context;
private ExpressionHandler expressionHandler = new ExpressionHandler(this);
@@ -277,7 +277,7 @@ public class JavaLanguageFrontend extends LanguageFrontend {
return fromImport;
}
}
- if (scope.get().toString().equals("this")) {
+ if (scope.get().toString().equals(THIS)) {
// this is not strictly true. This could also be a function of a superclass,
// but is the best we can do for now.
// if the superclass would be known, this would already be resolved by the Javaresolver
@@ -484,10 +484,9 @@ public class JavaLanguageFrontend extends LanguageFrontend {
var members = new ArrayList<AnnotationMember>();
- for (var child : expr.getChildNodes()) {
- if (child instanceof MemberValuePair) {
- var pair = (MemberValuePair) child;
-
+ // annotations can be specified as member / value pairs
+ if (expr.isNormalAnnotationExpr()) {
+ for (var pair : expr.asNormalAnnotationExpr().getPairs()) {
var member =
newAnnotationMember(
pair.getNameAsString(),
@@ -497,10 +496,24 @@ public class JavaLanguageFrontend extends LanguageFrontend {
members.add(member);
}
+ } else if (expr.isSingleMemberAnnotationExpr()) {
+ var value = expr.asSingleMemberAnnotationExpr().getMemberValue();
- annotation.setMembers(members);
+ if (value != null) {
+ // or as a literal. in this case it is assigned to the annotation member 'value'
+ var member =
+ newAnnotationMember(
+ ANNOTATION_MEMBER_VALUE,
+ (de.fraunhofer.aisec.cpg.graph.statements.expressions.Expression)
+ expressionHandler.handle(value.asLiteralExpr()),
+ getCodeFromRawNode(value));
+
+ members.add(member);
+ }
}
+ annotation.setMembers(members);
+
list.add(annotation);
}
diff --git a/src/test/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontendTest.java b/src/test/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontendTest.java
index 7ed7bbb75..0f33b1dfb 100644
--- a/src/test/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontendTest.java
+++ b/src/test/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontendTest.java
@@ -585,5 +585,18 @@ class JavaLanguageFrontendTest extends BaseTest {
var forField = annotations.get(0);
assertEquals("AnnotatedField", forField.getName());
+
+ field = record.getField("anotherField");
+ assertNotNull(field);
+
+ annotations = field.getAnnotations();
+ assertEquals(1, annotations.size());
+
+ forField = annotations.get(0);
+ assertEquals("AnnotatedField", forField.getName());
+
+ value = forField.getMembers().get(0);
+ assertEquals(JavaLanguageFrontend.ANNOTATION_MEMBER_VALUE, value.getName());
+ assertEquals("myString", ((Literal<String>) value.getValue()).getValue());
}
}
diff --git a/src/test/resources/Annotation.java b/src/test/resources/Annotation.java
index adeb140dd..47f7bb920 100644
--- a/src/test/resources/Annotation.java
+++ b/src/test/resources/Annotation.java
@@ -4,4 +4,6 @@ public class Annotation {
@AnnotatedField
private int field = 1;
+ @AnnotatedField("myString")
+ private int anotherField = 2;
} | ['src/test/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontendTest.java', 'src/test/resources/Annotation.java', 'src/main/java/de/fraunhofer/aisec/cpg/frontends/java/JavaLanguageFrontend.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 875,290 | 197,860 | 25,396 | 155 | 1,481 | 303 | 33 | 1 | 383 | 60 | 87 | 4 | 0 | 0 | 1970-01-01T00:26:46 | 176 | Kotlin | {'Kotlin': 2820067, 'LLVM': 170593, 'Python': 62850, 'C++': 46273, 'Java': 40608, 'C': 31212, 'Go': 28639, 'TypeScript': 4908, 'Shell': 2785, 'JavaScript': 751, 'CMake': 204} | Apache License 2.0 |
900 | fraunhofer-aisec/cpg/101/92 | fraunhofer-aisec | cpg | https://github.com/Fraunhofer-AISEC/cpg/issues/92 | https://github.com/Fraunhofer-AISEC/cpg/pull/101 | https://github.com/Fraunhofer-AISEC/cpg/pull/101 | 1 | resolve | Endless parsing for some files | Sometimes I try to get CPG for one file. But it looks like endless process. I haven't got any errors but the process takes more than 1 hour and I stop it.
I can provide with such several files. | 50d47380d1fbfce1e5ed937099bc3e4104cb59ca | f289991593c9a0e9bfe5cabe442299eae2dc7080 | https://github.com/fraunhofer-aisec/cpg/compare/50d47380d1fbfce1e5ed937099bc3e4104cb59ca...f289991593c9a0e9bfe5cabe442299eae2dc7080 | diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/CallExpression.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/CallExpression.java
index 70a48057a..f5fcfe019 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/CallExpression.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/CallExpression.java
@@ -146,8 +146,6 @@ public class CallExpression extends Expression implements TypeListener {
public String toString() {
return new ToStringBuilder(this, Node.TO_STRING_STYLE)
.appendSuper(super.toString())
- .append("arguments", arguments)
- .append("invokes", invokes)
.append("base", base)
.toString();
}
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/CompoundStatement.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/CompoundStatement.java
index fc5b268e5..98adbaa2f 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/CompoundStatement.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/CompoundStatement.java
@@ -53,10 +53,7 @@ public class CompoundStatement extends Statement {
@Override
public String toString() {
- return new ToStringBuilder(this, Node.TO_STRING_STYLE)
- .appendSuper(super.toString())
- .append("statements", statements)
- .toString();
+ return new ToStringBuilder(this, Node.TO_STRING_STYLE).appendSuper(super.toString()).toString();
}
@Override
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/FunctionDeclaration.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/FunctionDeclaration.java
index d8c214795..d0be77092 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/FunctionDeclaration.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/FunctionDeclaration.java
@@ -203,9 +203,8 @@ public class FunctionDeclaration extends ValueDeclaration {
public String toString() {
return new ToStringBuilder(this, Node.TO_STRING_STYLE)
.appendSuper(super.toString())
- .append("body", body)
.append("type", type)
- .append("parameters", parameters)
+ .append("parameters", parameters.stream().map(ParamVariableDeclaration::getName))
.toString();
}
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/graph/UnaryOperator.java b/src/main/java/de/fraunhofer/aisec/cpg/graph/UnaryOperator.java
index 0af8c2f27..b1f581542 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/graph/UnaryOperator.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/graph/UnaryOperator.java
@@ -185,7 +185,6 @@ public class UnaryOperator extends Expression implements TypeListener {
public String toString() {
return new ToStringBuilder(this, Node.TO_STRING_STYLE)
.appendSuper(super.toString())
- .append("input", input)
.append("operatorCode", operatorCode)
.append("postfix", postfix)
.append("prefix", prefix)
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/helpers/SubgraphWalker.java b/src/main/java/de/fraunhofer/aisec/cpg/helpers/SubgraphWalker.java
index 7a6d5ccd6..ea6a7dd26 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/helpers/SubgraphWalker.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/helpers/SubgraphWalker.java
@@ -400,7 +400,7 @@ public class SubgraphWalker {
if (current instanceof ValueDeclaration) {
- LOGGER.debug("Adding variable {}", current.getCode());
+ LOGGER.trace("Adding variable {}", current.getCode());
if (parentBlock == null) {
LOGGER.warn("Parent block is empty during subgraph run");
} else {
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/passes/EvaluationOrderGraphPass.java b/src/main/java/de/fraunhofer/aisec/cpg/passes/EvaluationOrderGraphPass.java
index ff4563577..66abf9b1c 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/passes/EvaluationOrderGraphPass.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/passes/EvaluationOrderGraphPass.java
@@ -690,20 +690,20 @@ public class EvaluationOrderGraphPass extends Pass {
}
public void setCurrentEOG(Node node) {
- LOGGER.debug("Setting {} to EOG", node);
+ LOGGER.trace("Setting {} to EOG", node);
this.currentEOG = new ArrayList<>();
this.currentEOG.add(node);
}
public <T extends Node> void setCurrentEOGs(List<T> nodes) {
- LOGGER.debug("Setting {} to EOGs", nodes);
+ LOGGER.trace("Setting {} to EOGs", nodes);
this.currentEOG = new ArrayList<>(nodes);
}
public void addToCurrentEOG(List<Node> nodes) {
- LOGGER.debug("Adding {} to current EOG", nodes);
+ LOGGER.trace("Adding {} to current EOG", nodes);
this.currentEOG.addAll(nodes);
}
diff --git a/src/main/java/de/fraunhofer/aisec/cpg/sarif/PhysicalLocation.java b/src/main/java/de/fraunhofer/aisec/cpg/sarif/PhysicalLocation.java
index 907796423..6251361d1 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/sarif/PhysicalLocation.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/sarif/PhysicalLocation.java
@@ -54,6 +54,11 @@ public class PhysicalLocation {
public URI getUri() {
return this.uri;
}
+
+ @Override
+ public String toString() {
+ return this.uri.toASCIIString();
+ }
}
@NonNull private ArtifactLocation artifactLocation;
@@ -78,4 +83,9 @@ public class PhysicalLocation {
public ArtifactLocation getArtifactLocation() {
return this.artifactLocation;
}
+
+ @Override
+ public String toString() {
+ return this.artifactLocation + ":" + this.region.toString();
+ }
} | ['src/main/java/de/fraunhofer/aisec/cpg/graph/FunctionDeclaration.java', 'src/main/java/de/fraunhofer/aisec/cpg/graph/CompoundStatement.java', 'src/main/java/de/fraunhofer/aisec/cpg/graph/UnaryOperator.java', 'src/main/java/de/fraunhofer/aisec/cpg/helpers/SubgraphWalker.java', 'src/main/java/de/fraunhofer/aisec/cpg/passes/EvaluationOrderGraphPass.java', 'src/main/java/de/fraunhofer/aisec/cpg/sarif/PhysicalLocation.java', 'src/main/java/de/fraunhofer/aisec/cpg/graph/CallExpression.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 699,615 | 158,505 | 20,216 | 125 | 1,172 | 250 | 29 | 7 | 197 | 39 | 47 | 3 | 0 | 0 | 1970-01-01T00:26:29 | 176 | Kotlin | {'Kotlin': 2820067, 'LLVM': 170593, 'Python': 62850, 'C++': 46273, 'Java': 40608, 'C': 31212, 'Go': 28639, 'TypeScript': 4908, 'Shell': 2785, 'JavaScript': 751, 'CMake': 204} | Apache License 2.0 |
895 | fraunhofer-aisec/cpg/72/65 | fraunhofer-aisec | cpg | https://github.com/Fraunhofer-AISEC/cpg/issues/65 | https://github.com/Fraunhofer-AISEC/cpg/pull/72 | https://github.com/Fraunhofer-AISEC/cpg/pull/72#issuecomment-595653087 | 1 | closes | NullPointerException in ScopeManager | I am running the CPG on a large code base and I discovered this NPE. I am trying to isolate the file where it occurs, unfortunately I cannot share the whole code base.
Stracktrace
```
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
at com.aybaze.AnalyzeU.AppKt.main(App.kt:37)
Caused by: java.lang.NullPointerException
at de.fraunhofer.aisec.cpg.passes.scopes.ScopeManager.lambda$leaveScope$7(ScopeManager.java:253)
at de.fraunhofer.aisec.cpg.passes.scopes.ScopeManager.getFirstScopeThat(ScopeManager.java:275)
at de.fraunhofer.aisec.cpg.passes.scopes.ScopeManager.getFirstScopeThat(ScopeManager.java:269)
at de.fraunhofer.aisec.cpg.passes.scopes.ScopeManager.leaveScope(ScopeManager.java:253)
at de.fraunhofer.aisec.cpg.passes.EvaluationOrderGraphPass.handleDeclaration(EvaluationOrderGraphPass.java:211)
at de.fraunhofer.aisec.cpg.passes.EvaluationOrderGraphPass.handleDeclaration(EvaluationOrderGraphPass.java:190)
at de.fraunhofer.aisec.cpg.passes.EvaluationOrderGraphPass.handleDeclaration(EvaluationOrderGraphPass.java:177)
at de.fraunhofer.aisec.cpg.passes.EvaluationOrderGraphPass.accept(EvaluationOrderGraphPass.java:100)
at de.fraunhofer.aisec.cpg.passes.EvaluationOrderGraphPass.accept(EvaluationOrderGraphPass.java:59)
at de.fraunhofer.aisec.cpg.TranslationManager.lambda$analyze$0(TranslationManager.java:104)
at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run$$$capture(CompletableFuture.java:1700)
at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java)
at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1692)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
```
| ef80ed0d39b2fc2ec96dffc85665e6ea5cecf065 | a31cb53dd13c2d4b3c76349a6b3cf761ce8f8c05 | https://github.com/fraunhofer-aisec/cpg/compare/ef80ed0d39b2fc2ec96dffc85665e6ea5cecf065...a31cb53dd13c2d4b3c76349a6b3cf761ce8f8c05 | diff --git a/src/main/java/de/fraunhofer/aisec/cpg/passes/scopes/ScopeManager.java b/src/main/java/de/fraunhofer/aisec/cpg/passes/scopes/ScopeManager.java
index c1c6ba86a..e1b988fb1 100644
--- a/src/main/java/de/fraunhofer/aisec/cpg/passes/scopes/ScopeManager.java
+++ b/src/main/java/de/fraunhofer/aisec/cpg/passes/scopes/ScopeManager.java
@@ -250,7 +250,14 @@ public class ScopeManager {
*/
@Nullable
public Scope leaveScope(Node nodeToLeave) {
- Scope leaveScope = getFirstScopeThat(scope -> scope.astNode.equals(nodeToLeave));
+ // Check to return as soon as we know that there is no associated scope, this check could be
+ // omitted
+ // but will increase runtime if leaving a node without scope will happen often.
+ if (!scopeMap.containsKey(nodeToLeave)) {
+ return null;
+ }
+ Scope leaveScope =
+ getFirstScopeThat(scope -> scope.astNode != null && scope.astNode.equals(nodeToLeave));
if (leaveScope == null) {
if (scopeMap.containsKey(nodeToLeave)) {
LOGGER.error( | ['src/main/java/de/fraunhofer/aisec/cpg/passes/scopes/ScopeManager.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 659,478 | 149,222 | 19,067 | 123 | 480 | 104 | 9 | 1 | 2,320 | 87 | 585 | 30 | 0 | 1 | 1970-01-01T00:26:23 | 176 | Kotlin | {'Kotlin': 2820067, 'LLVM': 170593, 'Python': 62850, 'C++': 46273, 'Java': 40608, 'C': 31212, 'Go': 28639, 'TypeScript': 4908, 'Shell': 2785, 'JavaScript': 751, 'CMake': 204} | Apache License 2.0 |
574 | faforever/downlords-faf-client/243/242 | faforever | downlords-faf-client | https://github.com/FAForever/downlords-faf-client/issues/242 | https://github.com/FAForever/downlords-faf-client/pull/243 | https://github.com/FAForever/downlords-faf-client/pull/243 | 1 | fixes | Fix generated avatar in message notification | My avatar is yellow, but in the notification it was some blue one.
I assume it still uses the username when it should use the user ID.
Make sure that for IRC users it still uses the username.
| 10d1770ed3fcc4a6bf447d3dc587973527ed74d1 | d2cac3faa937cd7fb78303faf68d7423694b96f4 | https://github.com/faforever/downlords-faf-client/compare/10d1770ed3fcc4a6bf447d3dc587973527ed74d1...d2cac3faa937cd7fb78303faf68d7423694b96f4 | diff --git a/src/main/java/com/faforever/client/chat/AbstractChatTabController.java b/src/main/java/com/faforever/client/chat/AbstractChatTabController.java
index d63ea7d2..f0cb7f46 100644
--- a/src/main/java/com/faforever/client/chat/AbstractChatTabController.java
+++ b/src/main/java/com/faforever/client/chat/AbstractChatTabController.java
@@ -693,18 +693,23 @@ public abstract class AbstractChatTabController {
}
protected void showNotificationIfNecessary(ChatMessage chatMessage) {
- if (!stage.isFocused() || !stage.isShowing()) {
- notificationService.addNotification(new TransientNotification(
- chatMessage.getUsername(),
- chatMessage.getMessage(),
- IdenticonUtil.createIdenticon(chatMessage.getUsername()),
- new Action(event -> {
- mainController.selectChatTab();
- stage.toFront();
- getRoot().getTabPane().getSelectionModel().select(getRoot());
- }))
- );
+ if (stage.isFocused() && stage.isShowing()) {
+ return;
}
+
+ PlayerInfoBean player = playerService.getPlayerForUsername(chatMessage.getUsername());
+ String identiconSource = player != null ? String.valueOf(player.getId()) : chatMessage.getUsername();
+
+ notificationService.addNotification(new TransientNotification(
+ chatMessage.getUsername(),
+ chatMessage.getMessage(),
+ IdenticonUtil.createIdenticon(identiconSource),
+ new Action(event -> {
+ mainController.selectChatTab();
+ stage.toFront();
+ getRoot().getTabPane().getSelectionModel().select(getRoot());
+ }))
+ );
}
protected String getMessageCssClass(String login) { | ['src/main/java/com/faforever/client/chat/AbstractChatTabController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 999,441 | 213,214 | 32,955 | 436 | 1,135 | 206 | 27 | 1 | 192 | 38 | 42 | 4 | 0 | 0 | 1970-01-01T00:24:26 | 175 | Java | {'Java': 3120337, 'CSS': 69562, 'HTML': 9932, 'Lua': 6869, 'JavaScript': 4215} | MIT License |
1,987 | eventfahrplan/eventfahrplan/363/362 | eventfahrplan | eventfahrplan | https://github.com/EventFahrplan/EventFahrplan/issues/362 | https://github.com/EventFahrplan/EventFahrplan/pull/363 | https://github.com/EventFahrplan/EventFahrplan/pull/363 | 1 | resolves | List of favorites scrolls to the top when returning from details screen | # Environment
- App version: [v.1.49.0](https://github.com/EventFahrplan/EventFahrplan/releases/tag/v.1.49.0)
- Android version: all
- Branch: `master`
- Device: phones & tablets
# How to reproduce
1. Create a long list of favorites which is **longer** then the device screen
2. Scroll to the bottom of the list
3. Tap a session to launch the session details screen
4. Tap the device `BACK` button to return to the favorites list
# Observed behavior
- The list of favorites is shown. The list is scrolled to the **top**.
# Expected behavior
- The list of favorites is shown. The list is scrolled to the **bottom**.
# Hints
- Check if the behavior differs when the conference is in the future, present or past. | bf1a71d972913766f13695bafb4d7b44132b024c | 5e42d05c18412b517c4b1f4aa911cd67c4a35833 | https://github.com/eventfahrplan/eventfahrplan/compare/bf1a71d972913766f13695bafb4d7b44132b024c...5e42d05c18412b517c4b1f4aa911cd67c4a35833 | diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java
index 42bea820..a204aae1 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java
@@ -53,8 +53,11 @@ import static nerd.tuxmobil.fahrplan.congress.extensions.ViewExtensions.requireV
* Activities containing this fragment MUST implement the {@link OnSessionListClick}
* interface.
*/
-public class StarredListFragment extends AbstractListFragment implements AbsListView
- .MultiChoiceModeListener {
+public class StarredListFragment extends AbstractListFragment implements
+ AbsListView.MultiChoiceModeListener,
+ AbsListView.OnScrollListener
+
+{
private static final String LOG_TAG = "StarredListFragment";
public static final String FRAGMENT_TAG = "starred";
@@ -75,6 +78,8 @@ public class StarredListFragment extends AbstractListFragment implements AbsList
*/
private StarredListAdapter mAdapter;
+ private boolean preserveScrollPosition = false;
+
public static StarredListFragment newInstance(boolean sidePane) {
StarredListFragment fragment = new StarredListFragment();
Bundle args = new Bundle();
@@ -100,6 +105,12 @@ public class StarredListFragment extends AbstractListFragment implements AbsList
sidePane = args.getBoolean(BundleKeys.SIDEPANE);
}
setHasOptionsMenu(true);
+
+ Context context = requireContext();
+ starredList = appRepository.loadStarredSessions();
+ Meta meta = appRepository.readMeta();
+ mAdapter = new StarredListAdapter(context, starredList, meta.getNumDays());
+ MyApp.LogDebug(LOG_TAG, "initStarredList: " + starredList.size() + " favorites");
}
@Override
@@ -128,6 +139,8 @@ public class StarredListFragment extends AbstractListFragment implements AbsList
mListView.setHeaderDividersEnabled(false);
mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
mListView.setMultiChoiceModeListener(this);
+ mListView.setAdapter(mAdapter);
+ mListView.setOnScrollListener(this);
return view;
}
@@ -136,17 +149,9 @@ public class StarredListFragment extends AbstractListFragment implements AbsList
@Override
public void onResume() {
super.onResume();
- initStarredList();
- jumpOverPastSessions();
- }
-
- private void initStarredList() {
- Context context = requireContext();
- starredList = appRepository.loadStarredSessions();
- Meta meta = appRepository.readMeta();
- mAdapter = new StarredListAdapter(context, starredList, meta.getNumDays());
- MyApp.LogDebug(LOG_TAG, "initStarredList: " + starredList.size() + " favorites");
- mListView.setAdapter(mAdapter);
+ if (!preserveScrollPosition) {
+ jumpOverPastSessions();
+ }
}
private void jumpOverPastSessions() {
@@ -251,6 +256,18 @@ public class StarredListFragment extends AbstractListFragment implements AbsList
}
+ @Override
+ public void onScrollStateChanged(AbsListView view, int scrollState) {
+ // Nothing to do here.
+ }
+
+ @Override
+ public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
+ if (firstVisibleItem > 0) {
+ preserveScrollPosition = true;
+ }
+ }
+
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return true; | ['app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 239,618 | 45,781 | 6,248 | 48 | 1,678 | 331 | 43 | 1 | 732 | 118 | 188 | 20 | 1 | 0 | 1970-01-01T00:26:50 | 175 | Kotlin | {'Kotlin': 891035, 'Java': 53095} | Apache License 2.0 |
1,993 | eventfahrplan/eventfahrplan/87/81 | eventfahrplan | eventfahrplan | https://github.com/EventFahrplan/EventFahrplan/issues/81 | https://github.com/EventFahrplan/EventFahrplan/pull/87 | https://github.com/EventFahrplan/EventFahrplan/pull/87 | 1 | resolves | EventDetailFragment: IllegalArgumentException: Parameter specified as non-null is null: parameter event | Crash report from a user:
- sent: 22.09.2018
- Version: [1.36.1 (Datenspuren Edition)](https://github.com/johnjohndoe/CampFahrplan/releases/tag/v.1.36.1-Datenspuren-Edition)
- Android version: 8.1.0
- Device model: MI 8
# Stacktrace
``` java
java.lang.RuntimeException: Unable to start activity
ComponentInfo{info.metadude.android.datenspuren.schedule/
nerd.tuxmobil.fahrplan.congress.details.EventDetail}: java.lang.IllegalArgumentException:
Parameter specified as non-null is null: method
kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter event
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2813)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2891)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1614)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6648)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:818)
Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null:
method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter event
at nerd.tuxmobil.fahrplan.congress.utils.EventUrlComposer.<init>(Unknown Source:2)
at nerd.tuxmobil.fahrplan.congress.details.EventDetailFragment.onViewCreated(EventDetailFragment.java:237)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1430)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1335)
at android.app.Activity.performStart(Activity.java:7118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2776)
... 9 more
```
# Log
``` java
0 D: Writing unhandled exception to: /data/user/0/
info.metadude.android.datenspuren.schedule/files/1.36.1 (Datenspuren Edition)-1537567710095.tracedroid
1 D: current handler class=com.android.internal.os.RuntimeInit$KillApplicationHandler
``` | f8d2191e871a6c72bd9c99b257347dde22c3ad84 | 377f5fba206b64615b430f9a0f2b413f78c61113 | https://github.com/eventfahrplan/eventfahrplan/compare/f8d2191e871a6c72bd9c99b257347dde22c3ad84...377f5fba206b64615b430f9a0f2b413f78c61113 | diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/AbstractListFragment.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/AbstractListFragment.java
index 3724beb6..865c9da9 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/AbstractListFragment.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/AbstractListFragment.java
@@ -21,9 +21,13 @@ public abstract class AbstractListFragment extends ListFragment {
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
+ *
+ * @param lecture The lecture which was clicked.
+ * @param requiresScheduleReload Boolean flag to indicate whether the schedule
+ * must be reload from the data source or not.
*/
public interface OnLectureListClick {
- void onLectureListClick(Lecture lecture);
+ void onLectureListClick(Lecture lecture, boolean requiresScheduleReload);
}
}
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListActivity.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListActivity.java
index 895540cd..2891cf48 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListActivity.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListActivity.java
@@ -10,6 +10,7 @@ import nerd.tuxmobil.fahrplan.congress.MyApp;
import nerd.tuxmobil.fahrplan.congress.R;
import nerd.tuxmobil.fahrplan.congress.base.AbstractListFragment;
import nerd.tuxmobil.fahrplan.congress.base.BaseActivity;
+import nerd.tuxmobil.fahrplan.congress.contract.BundleKeys;
import nerd.tuxmobil.fahrplan.congress.details.EventDetail;
import nerd.tuxmobil.fahrplan.congress.models.Lecture;
@@ -27,16 +28,26 @@ public class ChangeListActivity extends BaseActivity implements
int actionBarColor = ContextCompat.getColor(this, R.color.colorActionBar);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(actionBarColor));
+ boolean requiresScheduleReload = false;
+ Intent intent = getIntent();
+ if (intent != null) {
+ Bundle extras = intent.getExtras();
+ if (extras != null) {
+ requiresScheduleReload = extras.getBoolean(BundleKeys.REQUIRES_SCHEDULE_RELOAD, false);
+ }
+ }
+
if (savedInstanceState == null) {
- addFragment(R.id.container, new ChangeListFragment(), ChangeListFragment.FRAGMENT_TAG);
+ ChangeListFragment fragment = ChangeListFragment.newInstance(false, requiresScheduleReload);
+ addFragment(R.id.container, fragment, ChangeListFragment.FRAGMENT_TAG);
MyApp.LogDebug(LOG_TAG, "onCreate fragment created");
}
}
@Override
- public void onLectureListClick(Lecture lecture) {
+ public void onLectureListClick(Lecture lecture, boolean requiresScheduleReload) {
if (lecture != null) {
- EventDetail.startForResult(this, lecture, lecture.day);
+ EventDetail.startForResult(this, lecture, lecture.day, requiresScheduleReload);
}
}
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListFragment.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListFragment.java
index 7764502c..8420073b 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListFragment.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListFragment.java
@@ -37,6 +37,7 @@ public class ChangeListFragment extends AbstractListFragment {
private OnLectureListClick mListener;
private List<Lecture> changesList;
private boolean sidePane = false;
+ private boolean requiresScheduleReload = false;
/**
* The fragment's ListView/GridView.
@@ -49,10 +50,11 @@ public class ChangeListFragment extends AbstractListFragment {
*/
private LectureChangesArrayAdapter mAdapter;
- public static ChangeListFragment newInstance(boolean sidePane) {
+ public static ChangeListFragment newInstance(boolean sidePane, boolean requiresScheduleReload) {
ChangeListFragment fragment = new ChangeListFragment();
Bundle args = new Bundle();
args.putBoolean(BundleKeys.SIDEPANE, sidePane);
+ args.putBoolean(BundleKeys.REQUIRES_SCHEDULE_RELOAD, requiresScheduleReload);
fragment.setArguments(args);
return fragment;
}
@@ -71,6 +73,7 @@ public class ChangeListFragment extends AbstractListFragment {
Bundle args = getArguments();
if (args != null) {
sidePane = args.getBoolean(BundleKeys.SIDEPANE);
+ requiresScheduleReload = args.getBoolean(BundleKeys.REQUIRES_SCHEDULE_RELOAD);
}
FragmentActivity activity = getActivity();
@@ -142,7 +145,7 @@ public class ChangeListFragment extends AbstractListFragment {
position--;
Lecture clicked = changesList.get(mAdapter.getItemIndex(position));
if (clicked.changedIsCanceled) return;
- mListener.onLectureListClick(clicked);
+ mListener.onLectureListClick(clicked, requiresScheduleReload);
}
}
}
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangesDialog.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangesDialog.java
index a81d3b30..93d3686b 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangesDialog.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangesDialog.java
@@ -31,9 +31,10 @@ public class ChangesDialog extends DialogFragment {
private int cancelled;
private int markedAffected;
private String version;
+ private boolean requiresScheduleReload = false;
public static ChangesDialog newInstance(String version, int changed, int added,
- int cancelled, int marked) {
+ int cancelled, int marked, boolean requiresScheduleReload) {
ChangesDialog dialog = new ChangesDialog();
Bundle args = new Bundle();
args.putInt(BundleKeys.CHANGES_DLG_NUM_CHANGED, changed);
@@ -41,6 +42,7 @@ public class ChangesDialog extends DialogFragment {
args.putInt(BundleKeys.CHANGES_DLG_NUM_CANCELLED, cancelled);
args.putInt(BundleKeys.CHANGES_DLG_NUM_MARKED, marked);
args.putString(BundleKeys.CHANGES_DLG_VERSION, version);
+ args.putBoolean(BundleKeys.REQUIRES_SCHEDULE_RELOAD, requiresScheduleReload);
dialog.setArguments(args);
dialog.setCancelable(false);
return dialog;
@@ -56,6 +58,7 @@ public class ChangesDialog extends DialogFragment {
cancelled = args.getInt(BundleKeys.CHANGES_DLG_NUM_CANCELLED);
markedAffected = args.getInt(BundleKeys.CHANGES_DLG_NUM_MARKED);
version = args.getString(BundleKeys.CHANGES_DLG_VERSION);
+ requiresScheduleReload = args.getBoolean(BundleKeys.REQUIRES_SCHEDULE_RELOAD);
}
}
@@ -95,7 +98,7 @@ public class ChangesDialog extends DialogFragment {
flagChangesAsSeen();
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
- ((MainActivity) activity).openLectureChanges();
+ ((MainActivity) activity).openLectureChanges(requiresScheduleReload);
}
}
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/contract/BundleKeys.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/contract/BundleKeys.java
index bb3e8985..a546c372 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/contract/BundleKeys.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/contract/BundleKeys.java
@@ -38,6 +38,10 @@ public interface BundleKeys {
String SIDEPANE =
"nerd.tuxmobil.fahrplan.congress.SIDEPANE";
+ // Schedule reload
+ String REQUIRES_SCHEDULE_RELOAD =
+ "nerd.tuxmobil.fahrplan.congress.REQUIRES_SCHEDULE_RELOAD";
+
// Changes dialog
String CHANGES_DLG_NUM_CHANGED =
"nerd.tuxmobil.fahrplan.congress.ChangesDialog.NUM_CHANGES";
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java
index 000868cd..f7b0c5a5 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java
@@ -23,7 +23,8 @@ public class EventDetail extends BaseActivity {
public static void startForResult(@NonNull Activity activity,
@NonNull Lecture lecture,
- int lectureDay) {
+ int lectureDay,
+ boolean requiresScheduleReload) {
Intent intent = new Intent(activity, EventDetail.class);
intent.putExtra(BundleKeys.EVENT_TITLE, lecture.title);
intent.putExtra(BundleKeys.EVENT_SUBTITLE, lecture.subtitle);
@@ -35,6 +36,7 @@ public class EventDetail extends BaseActivity {
intent.putExtra(BundleKeys.EVENT_TIME, lecture.startTime);
intent.putExtra(BundleKeys.EVENT_DAY, lectureDay);
intent.putExtra(BundleKeys.EVENT_ROOM, lecture.room);
+ intent.putExtra(BundleKeys.REQUIRES_SCHEDULE_RELOAD, requiresScheduleReload);
activity.startActivityForResult(intent, MyApp.EVENTVIEW);
}
@@ -74,6 +76,8 @@ public class EventDetail extends BaseActivity {
intent.getIntExtra(BundleKeys.EVENT_DAY, 0));
args.putString(BundleKeys.EVENT_ROOM,
intent.getStringExtra(BundleKeys.EVENT_ROOM));
+ args.putBoolean(BundleKeys.REQUIRES_SCHEDULE_RELOAD,
+ intent.getBooleanExtra(BundleKeys.REQUIRES_SCHEDULE_RELOAD, false));
eventDetailFragment.setArguments(args);
replaceFragment(R.id.detail, eventDetailFragment,
EventDetailFragment.FRAGMENT_TAG);
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetailFragment.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetailFragment.java
index 91a3d1e5..a474c6eb 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetailFragment.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetailFragment.java
@@ -95,6 +95,8 @@ public class EventDetailFragment extends Fragment {
private Boolean sidePane = false;
+ private boolean requiresScheduleReload = false;
+
private boolean hasArguments = false;
@Override
@@ -128,6 +130,7 @@ public class EventDetailFragment extends Fragment {
links = args.getString(BundleKeys.EVENT_LINKS);
room = args.getString(BundleKeys.EVENT_ROOM);
sidePane = args.getBoolean(BundleKeys.SIDEPANE, false);
+ requiresScheduleReload = args.getBoolean(BundleKeys.REQUIRES_SCHEDULE_RELOAD, false);
hasArguments = true;
}
@@ -146,7 +149,7 @@ public class EventDetailFragment extends Fragment {
locale = getResources().getConfiguration().locale;
- FahrplanFragment.loadLectureList(activity, day, false);
+ FahrplanFragment.loadLectureList(activity, day, requiresScheduleReload);
lecture = eventIdToLecture(event_id);
TextView t;
@@ -328,16 +331,17 @@ public class EventDetailFragment extends Fragment {
return RoomForC3NavConverter.convert(currentRoom);
}
+ @NonNull
private Lecture eventIdToLecture(String eventId) {
if (MyApp.lectureList == null) {
- return null;
+ throw new NullPointerException("Lecture list is null.");
}
for (Lecture lecture : MyApp.lectureList) {
if (lecture.lecture_id.equals(eventId)) {
return lecture;
}
}
- return null;
+ throw new IllegalStateException("Lecture list does not contain eventId: " + eventId);
}
@Override
@@ -377,19 +381,15 @@ public class EventDetailFragment extends Fragment {
}
case R.id.menu_item_share_event:
l = eventIdToLecture(event_id);
- if (l != null) {
- String formattedLecture = SimpleLectureFormat.format(l);
- Context context = getContext();
- if (!LectureSharer.shareSimple(context, formattedLecture)) {
- Toast.makeText(context, R.string.share_error_activity_not_found, Toast.LENGTH_SHORT).show();
- }
+ String formattedLecture = SimpleLectureFormat.format(l);
+ Context context = getContext();
+ if (!LectureSharer.shareSimple(context, formattedLecture)) {
+ Toast.makeText(context, R.string.share_error_activity_not_found, Toast.LENGTH_SHORT).show();
}
return true;
case R.id.menu_item_add_to_calendar:
l = eventIdToLecture(event_id);
- if (l != null) {
- FahrplanMisc.addToCalender(activity, l);
- }
+ FahrplanMisc.addToCalender(activity, l);
return true;
case R.id.menu_item_flag_as_favorite:
if (lecture != null) {
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListActivity.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListActivity.java
index aa9fe8f3..314cb54f 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListActivity.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListActivity.java
@@ -38,9 +38,9 @@ public class StarredListActivity extends BaseActivity implements
}
@Override
- public void onLectureListClick(Lecture lecture) {
+ public void onLectureListClick(Lecture lecture, boolean requiresScheduleReload) {
if (lecture != null) {
- EventDetail.startForResult(this, lecture, lecture.day);
+ EventDetail.startForResult(this, lecture, lecture.day, requiresScheduleReload);
}
}
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java
index 69e8151b..ca95bf7b 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java
@@ -190,7 +190,7 @@ public class StarredListFragment extends AbstractListFragment implements AbsList
// fragment is attached to one) that an item has been selected.
position--;
Lecture clicked = starredList.get(mAdapter.getItemIndex(position));
- mListener.onLectureListClick(clicked);
+ mListener.onLectureListClick(clicked, false);
}
}
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java
index ab3cb512..5c633064 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java
@@ -279,7 +279,7 @@ public class FahrplanFragment extends Fragment implements OnClickListener {
FrameLayout sidePane = getActivity().findViewById(R.id.detail);
if (sidePane != null) {
Lecture lecture = LectureUtils.getLecture(MyApp.lectureList, lecture_id);
- ((MainActivity) getActivity()).openLectureDetail(lecture, mDay);
+ ((MainActivity) getActivity()).openLectureDetail(lecture, mDay, false);
}
intent.removeExtra("lecture_id"); // jump to given lecture_id only once
}
@@ -777,7 +777,7 @@ public class FahrplanFragment extends Fragment implements OnClickListener {
MyApp.LogDebug(LOG_TAG, "Click on " + lecture.title);
MainActivity main = (MainActivity) getActivity();
if (main != null) {
- main.openLectureDetail(lecture, mDay);
+ main.openLectureDetail(lecture, mDay, false);
}
}
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
index d0dfe9dc..3cd2d64e 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
@@ -80,6 +80,7 @@ public class MainActivity extends BaseActivity implements
private ProgressDialog progress = null;
private ProgressBar progressBar = null;
+ private boolean requiresScheduleReload = false;
private boolean showUpdateAction = true;
private static MainActivity instance;
@@ -312,6 +313,7 @@ public class MainActivity extends BaseActivity implements
void showChangesDialog() {
Fragment fragment = findFragment(ChangesDialog.FRAGMENT_TAG);
if (fragment == null) {
+ requiresScheduleReload = true;
List<Lecture> changedLectures = FahrplanMisc.readChanges(this);
AppRepository appRepository = AppRepository.Companion.getInstance(this);
Meta meta = appRepository.readMeta();
@@ -323,7 +325,9 @@ public class MainActivity extends BaseActivity implements
FahrplanMisc.getCancelledLectureCount(changedLectures, false),
FahrplanMisc.getChangedLectureCount(changedLectures, true) +
FahrplanMisc.getNewLectureCount(changedLectures, true) +
- FahrplanMisc.getCancelledLectureCount(changedLectures, true));
+ FahrplanMisc.getCancelledLectureCount(changedLectures, true),
+ requiresScheduleReload
+ );
changesDialog.show(getSupportFragmentManager(), ChangesDialog.FRAGMENT_TAG);
}
}
@@ -354,7 +358,7 @@ public class MainActivity extends BaseActivity implements
startActivityForResult(intent, MyApp.SETTINGS);
return true;
case R.id.menu_item_schedule_changes:
- openLectureChanges();
+ openLectureChanges(requiresScheduleReload);
return true;
case R.id.menu_item_favorites:
openFavorites();
@@ -364,7 +368,7 @@ public class MainActivity extends BaseActivity implements
return super.onOptionsItemSelected(item);
}
- public void openLectureDetail(Lecture lecture, int mDay) {
+ public void openLectureDetail(Lecture lecture, int mDay, boolean requiresScheduleReload) {
if (lecture == null) return;
FrameLayout sidePane = findViewById(R.id.detail);
MyApp.LogDebug(LOG_TAG, "openLectureDetail sidePane=" + sidePane);
@@ -383,12 +387,13 @@ public class MainActivity extends BaseActivity implements
args.putInt(BundleKeys.EVENT_DAY, mDay);
args.putString(BundleKeys.EVENT_ROOM, lecture.room);
args.putBoolean(BundleKeys.SIDEPANE, true);
+ args.putBoolean(BundleKeys.REQUIRES_SCHEDULE_RELOAD, requiresScheduleReload);
EventDetailFragment eventDetailFragment = new EventDetailFragment();
eventDetailFragment.setArguments(args);
replaceFragment(R.id.detail, eventDetailFragment,
EventDetailFragment.FRAGMENT_TAG, EventDetailFragment.FRAGMENT_TAG);
} else {
- EventDetail.startForResult(this, lecture, mDay);
+ EventDetail.startForResult(this, lecture, mDay, requiresScheduleReload);
}
}
@@ -448,9 +453,9 @@ public class MainActivity extends BaseActivity implements
}
@Override
- public void onLectureListClick(Lecture lecture) {
+ public void onLectureListClick(Lecture lecture, boolean requiresScheduleReload) {
if (lecture != null) {
- openLectureDetail(lecture, lecture.day);
+ openLectureDetail(lecture, lecture.day, requiresScheduleReload);
}
}
@@ -506,14 +511,15 @@ public class MainActivity extends BaseActivity implements
}
}
- public void openLectureChanges() {
+ public void openLectureChanges(boolean requiresScheduleReload) {
FrameLayout sidePane = findViewById(R.id.detail);
if (sidePane == null) {
Intent intent = new Intent(this, ChangeListActivity.class);
+ intent.putExtra(BundleKeys.REQUIRES_SCHEDULE_RELOAD, requiresScheduleReload);
startActivityForResult(intent, MyApp.CHANGELOG);
} else {
sidePane.setVisibility(View.VISIBLE);
- replaceFragment(R.id.detail, ChangeListFragment.newInstance(true),
+ replaceFragment(R.id.detail, ChangeListFragment.newInstance(true, requiresScheduleReload),
ChangeListFragment.FRAGMENT_TAG, ChangeListFragment.FRAGMENT_TAG);
}
} | ['app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangesDialog.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetailFragment.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListFragment.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListActivity.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListActivity.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/contract/BundleKeys.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/AbstractListFragment.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/changes/ChangeListFragment.java'] | {'.java': 11} | 11 | 11 | 0 | 0 | 11 | 320,698 | 62,034 | 8,516 | 71 | 6,615 | 1,185 | 103 | 11 | 3,307 | 140 | 753 | 54 | 1 | 2 | 1970-01-01T00:25:42 | 175 | Kotlin | {'Kotlin': 891035, 'Java': 53095} | Apache License 2.0 |
1,992 | eventfahrplan/eventfahrplan/109/42 | eventfahrplan | eventfahrplan | https://github.com/EventFahrplan/EventFahrplan/issues/42 | https://github.com/EventFahrplan/EventFahrplan/pull/109 | https://github.com/EventFahrplan/EventFahrplan/pull/109 | 1 | resolves | Stay at current scroll position when going back from event details view | It is really beneficial for the normal user workflow to stay at the current scroll position.
At the moment, the app **always scrolls back to the current time** and the user has to scroll all the way down again.
Many users go through the schedule and try to decide which lectures/talks to go to.
# Enviroment
- Device vendor: Lenovo/ZUK
- Device model: [ZUK Z1](https://www.gsmarena.com/lenovo_zuk_z1-7511.php) (Smartphone)
- Android version: 5.1.1
- Cyanogen version: 12.1-YOG4PAS9IG
- App version: 1.33.1
# How to reproduce
1. Start the app, navigate to the main view (if necessary)
2. Scroll up or down and tap on a talk to see it's details.
3. Tap the back-button.
4. You are now at the current time again, not where you initially scrolled to.
# Also the following Developer Options were customized
- Window Animation Scale: Off
- Transition Animation Scale: Off
- Animation Duration Scale: Off
| ab016a156562c356d7345ede67827435f04225f2 | e47a60b6aca9109824935591c137bd820c8f1158 | https://github.com/eventfahrplan/eventfahrplan/compare/ab016a156562c356d7345ede67827435f04225f2...e47a60b6aca9109824935591c137bd820c8f1158 | diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java
index 2532aa42..cfab0102 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java
@@ -262,11 +262,6 @@ public class FahrplanFragment extends Fragment implements OnClickListener {
saveCurrentDay(mDay);
}
- if (MyApp.meta.getNumDays() != 0) {
- // auf jeden Fall reload, wenn mit Lecture ID gestartet
- viewDay(lecture_id != null);
- }
-
Log.d(LOG_TAG, "MyApp.task_running = " + MyApp.task_running);
switch (MyApp.task_running) {
case FETCH:
@@ -326,7 +321,10 @@ public class FahrplanFragment extends Fragment implements OnClickListener {
int roomIndex = MyApp.roomList.get(i);
fillRoom(roomView, roomIndex, MyApp.lectureList, boxHeight);
}
- scrollToCurrent(mDay, boxHeight);
+ MainActivity.getInstance().shouldScheduleScrollToCurrentTimeSlot(() -> {
+ scrollToCurrent(mDay, boxHeight);
+ return null;
+ });
updateNavigationMenuSelection();
}
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
index 46bc724f..391f9ae5 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
@@ -30,6 +30,8 @@ import org.ligi.tracedroid.logging.Log;
import java.util.List;
+import kotlin.Unit;
+import kotlin.jvm.functions.Function0;
import nerd.tuxmobil.fahrplan.congress.MyApp;
import nerd.tuxmobil.fahrplan.congress.MyApp.TASKS;
import nerd.tuxmobil.fahrplan.congress.R;
@@ -73,6 +75,7 @@ public class MainActivity extends BaseActivity implements
private ProgressBar progressBar = null;
private boolean requiresScheduleReload = false;
+ private boolean shouldScrollToCurrent = true;
private boolean showUpdateAction = true;
private static MainActivity instance;
@@ -397,6 +400,10 @@ public class MainActivity extends BaseActivity implements
switch (requestCode) {
case MyApp.ALARMLIST:
case MyApp.EVENTVIEW:
+ if (resultCode == Activity.RESULT_CANCELED) {
+ shouldScrollToCurrent = false;
+ }
+ break;
case MyApp.CHANGELOG:
case MyApp.STARRED:
if (resultCode == Activity.RESULT_OK) {
@@ -510,6 +517,13 @@ public class MainActivity extends BaseActivity implements
public void onDenied(int dlgRequestCode) {
}
+ public void shouldScheduleScrollToCurrentTimeSlot(Function0<Unit> scrollToInstructions) {
+ if (shouldScrollToCurrent) {
+ scrollToInstructions.invoke();
+ }
+ shouldScrollToCurrent = true;
+ }
+
public static MainActivity getInstance() {
return instance;
} | ['app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/FahrplanFragment.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 316,870 | 61,072 | 8,383 | 68 | 884 | 168 | 24 | 2 | 930 | 149 | 242 | 26 | 1 | 0 | 1970-01-01T00:25:45 | 175 | Kotlin | {'Kotlin': 891035, 'Java': 53095} | Apache License 2.0 |
1,991 | eventfahrplan/eventfahrplan/111/103 | eventfahrplan | eventfahrplan | https://github.com/EventFahrplan/EventFahrplan/issues/103 | https://github.com/EventFahrplan/EventFahrplan/pull/111 | https://github.com/EventFahrplan/EventFahrplan/pull/111 | 1 | resolves | IllegalStateException: Lecture list does not contain eventId | Crash report from users:
- Sent: 25.12.2018
- App version: [v.1.38.0](https://github.com/EventFahrplan/EventFahrplan/releases/tag/v.1.38.0), [v.1.38.1](https://github.com/EventFahrplan/EventFahrplan/releases/tag/v.1.38.1), [v.1.38.2](https://github.com/EventFahrplan/EventFahrplan/releases/tag/v.1.38.2)
- Android version: 8.0.0
- Device model: -
# Stacktrace
``` java
java.lang.IllegalStateException: Lecture list does not contain eventId: 1020
at nerd.tuxmobil.fahrplan.congress.details.EventDetailFragment.eventIdToLecture(EventDetailFragment.java:337)
at nerd.tuxmobil.fahrplan.congress.details.EventDetailFragment.onOptionsItemSelected(EventDetailFragment.java:384)
at android.support.v4.app.Fragment.performOptionsItemSelected(Fragment.java:2487)
at android.support.v4.app.FragmentManagerImpl.dispatchOptionsItemSelected(FragmentManager.java:3307)
at android.support.v4.app.FragmentController.dispatchOptionsItemSelected(FragmentController.java:344)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:374)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.app.AppCompatDelegateImplV9.onMenuItemSelected(AppCompatDelegateImplV9.java:674)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
```
# Log
``` java
0 D: Writing unhandled exception to: /data/user/0/info.metadude.android.congress.schedule/files/1.38.1-1545740988461.tracedroid
1 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag="70089e17658f6ea3df96cefb1d67ff3c6f46fbd6", numDays=4, subtitle=, title=35th Chaos Communication Congress, version=Columbo 3 1.6 v1.7 0.5 1.0.2 2018-12-24 12:40)
2 D: viewDay(false)
3 D: meta.getNumDays() = 4
4 D: MyApp.task_running = NONE
5 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag="70089e17658f6ea3df96cefb1d67ff3c6f46fbd6", numDays=4, subtitle=, title=35th Chaos Communication Congress, version=Columbo 3 1.6 v1.7 0.5 1.0.2 2018-12-24 12:40)
6 D: viewDay(false)
7 D: lecture_id = null
8 D: MyApp.lectureList contains 192 items.
9 D: onResume
10 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag="70089e17658f6ea3df96cefb1d67ff3c6f46fbd6", numDays=4, subtitle=, title=35th Chaos Communication Congress, version=Columbo 3 1.6 v1.7 0.5 1.0.2 2018-12-24 12:40)
11 D: viewDay(false)
12 D: meta.getNumDays() = 4
13 D: MyApp.task_running = NONE
14 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag="70089e17658f6ea3df96cefb1d67ff3c6f46fbd6", numDays=4, subtitle=, title=35th Chaos Communication Congress, version=Columbo 3 1.6 v1.7 0.5 1.0.2 2018-12-24 12:40)
15 D: viewDay(false)
16 D: lecture_id = null
17 D: MyApp.lectureList contains 192 items.
18 D: onResume
19 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag="70089e17658f6ea3df96cefb1d67ff3c6f46fbd6", numDays=4, subtitle=, title=35th Chaos Communication Congress, version=Columbo 3 1.6 v1.7 0.5 1.0.2 2018-12-24 12:40)
20 D: viewDay(false)
21 D: meta.getNumDays() = 4
22 D: MyApp.task_running = NONE
23 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag="70089e17658f6ea3df96cefb1d67ff3c6f46fbd6", numDays=4, subtitle=, title=35th Chaos Communication Congress, version=Columbo 3 1.6 v1.7 0.5 1.0.2 2018-12-24 12:40)
24 D: viewDay(false)
25 D: lecture_id = null
26 D: MyApp.lectureList contains 174 items.
27 D: onResume
28 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag="70089e17658f6ea3df96cefb1d67ff3c6f46fbd6", numDays=4, subtitle=, title=35th Chaos Communication Congress, version=Columbo 3 1.6 v1.7 0.5 1.0.2 2018-12-24 12:40)
29 D: viewDay(false)
30 D: meta.getNumDays() = 4
31 D: MyApp.task_running = NONE
32 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag="70089e17658f6ea3df96cefb1d67ff3c6f46fbd6", numDays=4, subtitle=, title=35th Chaos Communication Congress, version=Columbo 3 1.6 v1.7 0.5 1.0.2 2018-12-24 12:40)
33 D: viewDay(false)
34 D: lecture_id = null
35 D: MyApp.lectureList = null
36 D: onResume
37 D: current handler class=com.android.internal.os.RuntimeInit$KillApplicationHandler
```
- Above logging has been added in 473f35a68b3f9c13f55411146b6d7ddd361ddfd9 and has been released with v.1.38.1
# Related
- [Issue #81: EventDetailFragment: IllegalArgumentException: Parameter specified as non-null is null: parameter event](https://github.com/EventFahrplan/EventFahrplan/issues/81)
- [Pull request #87: Fix crash when EventDetailFragment attempts to be load with an non existing "event_id".](https://github.com/EventFahrplan/EventFahrplan/pull/87) | 74955970bfcf5360979715f914d24a11e5819999 | 3786a9a2ac1e49529d5e5fddad19c0d2ae077ab2 | https://github.com/eventfahrplan/eventfahrplan/compare/74955970bfcf5360979715f914d24a11e5819999...3786a9a2ac1e49529d5e5fddad19c0d2ae077ab2 | diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/FahrplanMisc.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/FahrplanMisc.java
index e94fb95d..8f351c9e 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/FahrplanMisc.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/FahrplanMisc.java
@@ -274,6 +274,9 @@ public class FahrplanMisc {
if (!l.highlight) {
starredList.remove(l);
}
+ if (l.changedIsCanceled) {
+ starredList.remove(l);
+ }
lectureIndex--;
}
MyApp.LogDebug(LOG_TAG, starredList.size() + " lectures starred."); | ['app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/FahrplanMisc.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 317,320 | 61,142 | 8,395 | 68 | 94 | 17 | 3 | 1 | 5,730 | 433 | 1,828 | 88 | 5 | 2 | 1970-01-01T00:25:46 | 175 | Kotlin | {'Kotlin': 891035, 'Java': 53095} | Apache License 2.0 |
1,990 | eventfahrplan/eventfahrplan/184/127 | eventfahrplan | eventfahrplan | https://github.com/EventFahrplan/EventFahrplan/issues/127 | https://github.com/EventFahrplan/EventFahrplan/pull/184 | https://github.com/EventFahrplan/EventFahrplan/pull/184 | 1 | resolves | Restrict usage while screen is locked | # Environment
- App version: [v.1.38.4](https://github.com/EventFahrplan/EventFahrplan/releases/tag/v.1.38.4)
# How to reproduce
1. Launch the app.
2. Lock the device.
3. Use the app on the **lock screen**.
# Observed behavior
- **All screens** of the app can be used.
# Expected behavior
- Only the **schedule view** and the **event details** view can be visited.
- Lock screen users are **not** be able to visit the **app settings** where they can change the schedule URL.
- Lock screen users are **not** be able to visit the **alarms list** where all alarms can be deleted.
- Lock screen users are **not** be able to visit the **favorites list** where all alarms can be deleted.
# Devices
- Please check both phones and tablets as the screens are set up differently.
# Related
- This feature has been added in 1be512c101c6d4df07a74269c41856289c968229 and released with [v.1.38.4](https://github.com/EventFahrplan/EventFahrplan/releases/tag/v.1.38.4).
| 3c3507ff3a435bb23c9a5953b0f6c086cc635c1e | dbd733fed64589ead1e9f6a51a3d74c63cc6e6e0 | https://github.com/eventfahrplan/eventfahrplan/compare/3c3507ff3a435bb23c9a5953b0f6c086cc635c1e...dbd733fed64589ead1e9f6a51a3d74c63cc6e6e0 | diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/BaseActivity.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/BaseActivity.java
index 34be9483..d602d365 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/BaseActivity.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/BaseActivity.java
@@ -11,7 +11,6 @@ import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
-import android.view.WindowManager;
import nerd.tuxmobil.fahrplan.congress.R;
import nerd.tuxmobil.fahrplan.congress.autoupdate.UpdateService;
@@ -22,12 +21,6 @@ public abstract class BaseActivity extends AppCompatActivity {
private ConnectivityObserver connectivityObserver;
- @Override
- public void onAttachedToWindow() {
- super.onAttachedToWindow();
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
- }
-
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java
index 3a8e63d0..ded55ac7 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java
@@ -9,6 +9,7 @@ import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;
+import android.view.WindowManager;
import nerd.tuxmobil.fahrplan.congress.BuildConfig;
import nerd.tuxmobil.fahrplan.congress.MyApp;
@@ -39,6 +40,12 @@ public class EventDetail extends BaseActivity {
activity.startActivityForResult(intent, MyApp.EVENTVIEW);
}
+ @Override
+ public void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
+ }
+
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
index f5768813..9fd030de 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java
@@ -1,11 +1,13 @@
package nerd.tuxmobil.fahrplan.congress.schedule;
import android.app.Activity;
+import android.app.KeyguardManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
+import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.IdRes;
@@ -23,6 +25,7 @@ import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
+import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
@@ -73,12 +76,22 @@ public class MainActivity extends BaseActivity implements
private ProgressDialog progress = null;
+ private KeyguardManager keyguardManager = null;
+
private ProgressBar progressBar = null;
private boolean requiresScheduleReload = false;
private boolean shouldScrollToCurrent = true;
private boolean showUpdateAction = true;
+ private boolean isScreenLocked = false;
+ private boolean isFavoritesInSidePane = false;
private static MainActivity instance;
+ @Override
+ public void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
+ }
+
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -87,6 +100,7 @@ public class MainActivity extends BaseActivity implements
MyApp.LogDebug(LOG_TAG, "onCreate");
setContentView(R.layout.main_layout);
+ keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
Toolbar toolbar = findViewById(R.id.toolbar);
progressBar = findViewById(R.id.progress);
setSupportActionBar(toolbar);
@@ -264,6 +278,15 @@ public class MainActivity extends BaseActivity implements
@Override
protected void onResume() {
super.onResume();
+ isScreenLocked = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
+ ? keyguardManager.isKeyguardLocked()
+ : keyguardManager.inKeyguardRestrictedInputMode();
+
+ FrameLayout sidePane = findViewById(R.id.detail);
+ if (sidePane != null && isFavoritesInSidePane){
+ sidePane.setVisibility(isScreenLocked ? View.GONE : View.VISIBLE);
+ }
+
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean(BundleKeys.PREFS_CHANGES_SEEN, true) == false) {
showChangesDialog();
@@ -376,6 +399,9 @@ public class MainActivity extends BaseActivity implements
if (sidePane != null) {
sidePane.setVisibility(View.GONE);
}
+ if (fragmentTag.equals(StarredListFragment.FRAGMENT_TAG)) {
+ isFavoritesInSidePane = false;
+ }
removeFragment(fragmentTag);
}
@@ -464,7 +490,9 @@ public class MainActivity extends BaseActivity implements
boolean found = fragment != null;
View sidePane = findViewById(detailView);
if (sidePane != null) {
- sidePane.setVisibility(found ? View.VISIBLE : View.GONE);
+ isFavoritesInSidePane = found && fragment instanceof StarredListFragment;
+ sidePane.setVisibility(isFavoritesInSidePane && isScreenLocked || !found
+ ? View.GONE : View.VISIBLE);
}
}
@@ -481,8 +509,10 @@ public class MainActivity extends BaseActivity implements
if (sidePane == null) {
Intent intent = new Intent(this, StarredListActivity.class);
startActivityForResult(intent, MyApp.STARRED);
- } else {
+ }
+ else if(!isScreenLocked) {
sidePane.setVisibility(View.VISIBLE);
+ isFavoritesInSidePane = true;
replaceFragment(R.id.detail, StarredListFragment.newInstance(true),
StarredListFragment.FRAGMENT_TAG, StarredListFragment.FRAGMENT_TAG);
} | ['app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/MainActivity.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/base/BaseActivity.java', 'app/src/main/java/nerd/tuxmobil/fahrplan/congress/details/EventDetail.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 312,786 | 60,159 | 8,187 | 64 | 1,888 | 371 | 48 | 3 | 981 | 142 | 268 | 23 | 2 | 0 | 1970-01-01T00:26:09 | 175 | Kotlin | {'Kotlin': 891035, 'Java': 53095} | Apache License 2.0 |
1,989 | eventfahrplan/eventfahrplan/206/205 | eventfahrplan | eventfahrplan | https://github.com/EventFahrplan/EventFahrplan/issues/205 | https://github.com/EventFahrplan/EventFahrplan/pull/206 | https://github.com/EventFahrplan/EventFahrplan/pull/206 | 1 | resolves | NullPointerException: Attempt to invoke virtual method 'void AppRepository.cancelLoading()' on a null object reference | Crash report from a user:
- Sent: 22.12.2019 - 24.12.2019
- App version: [v.1.41.0](https://github.com/EventFahrplan/EventFahrplan/releases/tag/v.1.41.0)
- Android version: 9
- Device models: Mi MIX 2, Redmi Note 7
# Stacktrace
``` java
java.lang.RuntimeException: Unable to stop service
nerd.tuxmobil.fahrplan.congress.autoupdate.UpdateService@8162e9e:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
nerd.tuxmobil.fahrplan.congress.repositories.AppRepository.cancelLoading()'
on a null object reference
at android.app.ActivityThread.handleStopService(ActivityThread.java:3796)
at android.app.ActivityThread.access$1800(ActivityThread.java:202)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1717)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:6878)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
nerd.tuxmobil.fahrplan.congress.repositories.AppRepository.cancelLoading()'
on a null object reference
at nerd.tuxmobil.fahrplan.congress.autoupdate.UpdateService.onDestroy(UpdateService.java:142)
at android.app.ActivityThread.handleStopService(ActivityThread.java:3772)
```
# Log
``` java
0 D: Writing unhandled exception to: /data/user/0/info.metadude.android.congress.schedule/files/1.41.0-1576974844041.tracedroid
1 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag=W/"c293fd5f1dd7222a799609a0165508e51bff4da38f47995ab2aea13ccd7959da", numDays=4, subtitle=, title=36th Chaos Communication Congress, version=cat; chaos-west 1.0; open-infra 10; wikipaka 0.4; chaoszone 0.5; komona 0.4; sendezentrum 0.1; lightning Praseodymium; wiki 2019-12-22 00:30)
2 D: viewDay(false)
3 D: meta.getNumDays() = 4
4 D: MyApp.task_running = NONE
5 D: lectureId = null
6 D: MyApp.lectureList contains 192 items.
7 D: onResume
8 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag=W/"c293fd5f1dd7222a799609a0165508e51bff4da38f47995ab2aea13ccd7959da", numDays=4, subtitle=, title=36th Chaos Communication Congress, version=cat; chaos-west 1.0; open-infra 10; wikipaka 0.4; chaoszone 0.5; komona 0.4; sendezentrum 0.1; lightning Praseodymium; wiki 2019-12-22 00:30)
9 D: viewDay(false)
10 D: meta.getNumDays() = 4
11 D: MyApp.task_running = NONE
12 D: lectureId = null
13 D: MyApp.lectureList contains 192 items.
14 D: onResume
15 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag=W/"c293fd5f1dd7222a799609a0165508e51bff4da38f47995ab2aea13ccd7959da", numDays=4, subtitle=, title=36th Chaos Communication Congress, version=cat; chaos-west 1.0; open-infra 10; wikipaka 0.4; chaoszone 0.5; komona 0.4; sendezentrum 0.1; lightning Praseodymium; wiki 2019-12-22 00:30)
16 D: viewDay(false)
17 D: meta.getNumDays() = 4
18 D: MyApp.task_running = NONE
19 D: lectureId = null
20 D: MyApp.lectureList contains 192 items.
21 D: onResume
22 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag=W/"c293fd5f1dd7222a799609a0165508e51bff4da38f47995ab2aea13ccd7959da", numDays=4, subtitle=, title=36th Chaos Communication Congress, version=cat; chaos-west 1.0; open-infra 10; wikipaka 0.4; chaoszone 0.5; komona 0.4; sendezentrum 0.1; lightning Praseodymium; wiki 2019-12-22 00:30)
23 D: viewDay(false)
24 D: meta.getNumDays() = 4
25 D: MyApp.task_running = NONE
26 D: lectureId = null
27 D: MyApp.lectureList contains 192 items.
28 D: onResume
29 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag=W/"c293fd5f1dd7222a799609a0165508e51bff4da38f47995ab2aea13ccd7959da", numDays=4, subtitle=, title=36th Chaos Communication Congress, version=cat; chaos-west 1.0; open-infra 10; wikipaka 0.4; chaoszone 0.5; komona 0.4; sendezentrum 0.1; lightning Praseodymium; wiki 2019-12-22 00:30)
30 D: viewDay(false)
31 D: meta.getNumDays() = 4
32 D: MyApp.task_running = NONE
33 D: lectureId = null
34 D: MyApp.lectureList contains 192 items.
35 D: onResume
36 D: MyApp.meta = Meta(dayChangeHour=0, dayChangeMinute=0, eTag=W/"c293fd5f1dd7222a799609a0165508e51bff4da38f47995ab2aea13ccd7959da", numDays=4, subtitle=, title=36th Chaos Communication Congress, version=cat; chaos-west 1.0; open-infra 10; wikipaka 0.4; chaoszone 0.5; komona 0.4; sendezentrum 0.1; lightning Praseodymium; wiki 2019-12-22 00:30)
37 D: viewDay(false)
38 D: meta.getNumDays() = 4
39 D: MyApp.task_running = NONE
40 D: lectureId = null
41 D: MyApp.lectureList contains 192 items.
```
| 73e003b133e39f1de782b01c5fb76f05673db8df | 9194d67c4768b94fe69232efb84f32df89744316 | https://github.com/eventfahrplan/eventfahrplan/compare/73e003b133e39f1de782b01c5fb76f05673db8df...9194d67c4768b94fe69232efb84f32df89744316 | diff --git a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/autoupdate/UpdateService.java b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/autoupdate/UpdateService.java
index 5eeb19c7..b3110062 100644
--- a/app/src/main/java/nerd/tuxmobil/fahrplan/congress/autoupdate/UpdateService.java
+++ b/app/src/main/java/nerd/tuxmobil/fahrplan/congress/autoupdate/UpdateService.java
@@ -38,7 +38,8 @@ public class UpdateService extends JobIntentService {
private static final String LOG_TAG = "UpdateService";
- private AppRepository appRepository;
+ @SuppressWarnings("squid:S1170")
+ private final AppRepository appRepository = AppRepository.INSTANCE;
public void onParseDone(@NonNull ParseResult result) {
MyApp.LogDebug(LOG_TAG, "parseDone: " + result.isSuccess() + " , numDays=" + MyApp.meta.getNumDays());
@@ -133,7 +134,6 @@ public class UpdateService extends JobIntentService {
stopSelf();
return Unit.INSTANCE;
}, true);
- appRepository = AppRepository.INSTANCE;
connectivityObserver.start();
}
| ['app/src/main/java/nerd/tuxmobil/fahrplan/congress/autoupdate/UpdateService.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 317,474 | 61,253 | 8,296 | 63 | 201 | 37 | 4 | 1 | 4,756 | 446 | 1,572 | 77 | 1 | 2 | 1970-01-01T00:26:17 | 175 | Kotlin | {'Kotlin': 891035, 'Java': 53095} | Apache License 2.0 |
573 | faforever/downlords-faf-client/258/235 | faforever | downlords-faf-client | https://github.com/FAForever/downlords-faf-client/issues/235 | https://github.com/FAForever/downlords-faf-client/pull/258 | https://github.com/FAForever/downlords-faf-client/pull/258 | 1 | fixes | 1v1 ladder games pops up in Play tab for a split second. | I was watching what games was hosted, and I saw a game pop up and disappear almost immediately
named "PlayerX" vs "PlayerY". The game was hosted on Ranaoke abyss. I quickly suspected it was a ladder game. And indeed it was checked the replay 1v1 ladder rating of players.
TL;DR
Ladder matches shows up on hosted games tab for split second.
I guess you can filter them out of popping up somehow? Maybe from the featured mod in the data?
Not a huge issue but hey I report what I find lol
| 53c3b8b494436ad6b7aebae1c4babfc3e8d6ee84 | 815672598ba9f26f47a83a58832826a98b7eb106 | https://github.com/faforever/downlords-faf-client/compare/53c3b8b494436ad6b7aebae1c4babfc3e8d6ee84...815672598ba9f26f47a83a58832826a98b7eb106 | diff --git a/src/main/java/com/faforever/client/game/GameType.java b/src/main/java/com/faforever/client/game/GameType.java
index 9de8e0e7..fb467ffa 100644
--- a/src/main/java/com/faforever/client/game/GameType.java
+++ b/src/main/java/com/faforever/client/game/GameType.java
@@ -5,8 +5,10 @@ import java.util.Map;
public enum GameType {
FAF("faf"),
+ FAF_BETA("fafbeta"),
BALANCE_TESTING("balancetesting"),
- LADDER_1V1("ladder1v1");
+ LADDER_1V1("ladder1v1"),
+ COOP("coop");
public static final GameType DEFAULT = FAF;
diff --git a/src/main/java/com/faforever/client/game/GamesController.java b/src/main/java/com/faforever/client/game/GamesController.java
index db551323..11fb665d 100644
--- a/src/main/java/com/faforever/client/game/GamesController.java
+++ b/src/main/java/com/faforever/client/game/GamesController.java
@@ -43,6 +43,8 @@ import org.springframework.context.ApplicationContext;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.invoke.MethodHandles;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
@@ -53,7 +55,16 @@ import static javafx.beans.binding.Bindings.createStringBinding;
public class GamesController {
- private static final Predicate<GameInfoBean> OPEN_GAMES_PREDICATE = gameInfoBean -> gameInfoBean.getStatus() == GameState.OPEN;
+ private static final Collection<String> DISPLAYED_FEATURED_MODS = Arrays.asList(
+ GameType.FAF.getString(),
+ GameType.FAF_BETA.getString(),
+ GameType.BALANCE_TESTING.getString()
+ );
+
+ private static final Predicate<GameInfoBean> OPEN_CUSTOM_GAMES_PREDICATE = gameInfoBean ->
+ gameInfoBean.getStatus() == GameState.OPEN
+ && DISPLAYED_FEATURED_MODS.contains(gameInfoBean.getFeaturedMod());
+
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@FXML
@@ -127,7 +138,7 @@ public class GamesController {
ObservableList<GameInfoBean> gameInfoBeans = gameService.getGameInfoBeans();
filteredItems = new FilteredList<>(gameInfoBeans);
- filteredItems.setPredicate(OPEN_GAMES_PREDICATE);
+ filteredItems.setPredicate(OPEN_CUSTOM_GAMES_PREDICATE);
if (tilesButton.getId().equals(preferencesService.getPreferences().getGamesViewMode())) {
viewToggleGroup.selectToggle(tilesButton);
@@ -147,9 +158,9 @@ public class GamesController {
CheckBox checkBox = (CheckBox) actionEvent.getSource();
boolean selected = checkBox.isSelected();
if (selected) {
- filteredItems.setPredicate(OPEN_GAMES_PREDICATE);
+ filteredItems.setPredicate(OPEN_CUSTOM_GAMES_PREDICATE);
} else {
- filteredItems.setPredicate(OPEN_GAMES_PREDICATE.and(gameInfoBean -> !gameInfoBean.getPasswordProtected()));
+ filteredItems.setPredicate(OPEN_CUSTOM_GAMES_PREDICATE.and(gameInfoBean -> !gameInfoBean.getPasswordProtected()));
}
}
| ['src/main/java/com/faforever/client/game/GamesController.java', 'src/main/java/com/faforever/client/game/GameType.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,005,417 | 214,368 | 33,153 | 436 | 1,189 | 282 | 23 | 2 | 489 | 92 | 116 | 10 | 0 | 0 | 1970-01-01T00:24:26 | 175 | Java | {'Java': 3120337, 'CSS': 69562, 'HTML': 9932, 'Lua': 6869, 'JavaScript': 4215} | MIT License |
569 | faforever/downlords-faf-client/297/279 | faforever | downlords-faf-client | https://github.com/FAForever/downlords-faf-client/issues/279 | https://github.com/FAForever/downlords-faf-client/pull/297 | https://github.com/FAForever/downlords-faf-client/pull/297 | 1 | fixes | Rejoining IRC-channel is broken | **Steps to reproduce:**
1. Join any channel (e.g. _/join #allhailbrutus_)
2. Close the channel tab
3. Rejoin the channel (send first command again)
**Expected result:** the channel tab opens a second time.
**Observed result:** nothing happens
| a9669953aa8ba566a5aec28723bf4478c111c0b5 | c491aee6d9ff3424c0b3ac276441cf0cf56a1780 | https://github.com/faforever/downlords-faf-client/compare/a9669953aa8ba566a5aec28723bf4478c111c0b5...c491aee6d9ff3424c0b3ac276441cf0cf56a1780 | diff --git a/src/main/java/com/faforever/client/chat/ChatController.java b/src/main/java/com/faforever/client/chat/ChatController.java
index 939e8f86..d3b51f7f 100644
--- a/src/main/java/com/faforever/client/chat/ChatController.java
+++ b/src/main/java/com/faforever/client/chat/ChatController.java
@@ -115,7 +115,10 @@ public class ChatController {
private void removeTab(String playerOrChannelName) {
nameToChatTabController.remove(playerOrChannelName);
- chatsTabPane.getTabs().remove(nameToChatTabController.remove(playerOrChannelName).getRoot());
+
+ if (nameToChatTabController.containsKey(playerOrChannelName)) {
+ chatsTabPane.getTabs().remove(nameToChatTabController.remove(playerOrChannelName).getRoot());
+ }
}
private AbstractChatTabController getOrCreateChannelTab(String channelName) {
diff --git a/src/main/java/com/faforever/client/chat/PircBotXChatService.java b/src/main/java/com/faforever/client/chat/PircBotXChatService.java
index 7a8d6a64..8cd14cec 100644
--- a/src/main/java/com/faforever/client/chat/PircBotXChatService.java
+++ b/src/main/java/com/faforever/client/chat/PircBotXChatService.java
@@ -74,15 +74,9 @@ import static javafx.collections.FXCollections.observableHashMap;
public class PircBotXChatService implements ChatService {
- interface ChatEventListener<T> {
-
- void onEvent(T event);
- }
-
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final int SOCKET_TIMEOUT = 10000;
private final Map<Class<? extends Event>, ArrayList<ChatEventListener>> eventListeners;
-
/**
* Maps channels by name.
*/
@@ -121,7 +115,6 @@ public class PircBotXChatService implements ChatService {
private PircBotX pircBotX;
private CountDownLatch chatConnectedLatch;
private Task<Void> connectionTask;
-
public PircBotXChatService() {
connectionState = new SimpleObjectProperty<>();
eventListeners = new ConcurrentHashMap<>();
@@ -236,6 +229,9 @@ public class PircBotXChatService implements ChatService {
private void onChatUserLeftChannel(String channelName, String username) {
getOrCreateChannel(channelName).removeUser(username);
+ if (userService.getUsername().equalsIgnoreCase(username)) {
+ channels.remove(channelName);
+ }
}
private void onChatUserQuit(String username) {
@@ -436,7 +432,6 @@ public class PircBotXChatService implements ChatService {
}
}
-
@Override
public void addUsersListener(String channelName, MapChangeListener<String, ChatUser> listener) {
getOrCreateChannel(channelName).addUsersListeners(listener);
@@ -563,4 +558,9 @@ public class PircBotXChatService implements ChatService {
public ReadOnlyIntegerProperty unreadMessagesCount() {
return unreadMessagesCount;
}
+
+ interface ChatEventListener<T> {
+
+ void onEvent(T event);
+ }
}
diff --git a/src/test/java/com/faforever/client/chat/PircBotXChatServiceTest.java b/src/test/java/com/faforever/client/chat/PircBotXChatServiceTest.java
index 4bc922ac..494d4dee 100644
--- a/src/test/java/com/faforever/client/chat/PircBotXChatServiceTest.java
+++ b/src/test/java/com/faforever/client/chat/PircBotXChatServiceTest.java
@@ -82,7 +82,9 @@ import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
@@ -301,7 +303,7 @@ public class PircBotXChatServiceTest extends AbstractPlainJavaFxTest {
joinChannelLatch.countDown();
SocialMessage socialMessage = new SocialMessage();
- socialMessage.setChannels(Collections.singletonList(DEFAULT_CHANNEL_NAME));
+ socialMessage.setChannels(Collections.emptyList());
socialMessageListenerCaptor.getValue().accept(socialMessage);
}
@@ -842,4 +844,54 @@ public class PircBotXChatServiceTest extends AbstractPlainJavaFxTest {
verify(notificationService, never()).addNotification(any(TransientNotification.class));
}
+
+ @Test
+ public void testRejoinChannel() throws Exception {
+ OutputChannel outputChannel = mock(OutputChannel.class);
+
+ reset(taskService);
+ when(taskService.submitTask(any())).thenReturn(completedFuture(null));
+
+ String channelToJoin = OTHER_CHANNEL_NAME;
+ when(userService.getUsername()).thenReturn("user1");
+ when(userChannelDao.getChannel(channelToJoin)).thenReturn(otherChannel);
+ when(otherChannel.send()).thenReturn(outputChannel);
+ doAnswer(invocation -> {
+ firePircBotXEvent(createJoinEvent(otherChannel, user1));
+ return null;
+ }).when(outputIrc).joinChannel(channelToJoin);
+ doAnswer(invocation -> {
+ firePircBotXEvent(createPartEvent(otherChannel, user1));
+ return null;
+ }).when(outputChannel).part();
+
+ connect();
+ botStartedFuture.get(TIMEOUT, TIMEOUT_UNIT);
+
+ instance.connectionStateProperty().set(ConnectionState.CONNECTED);
+
+ CountDownLatch firstJoinLatch = new CountDownLatch(1);
+ CountDownLatch secondJoinLatch = new CountDownLatch(1);
+ CountDownLatch leaveLatch = new CountDownLatch(1);
+ instance.addChannelsListener(change -> {
+ if (change.wasAdded()) {
+ if (firstJoinLatch.getCount() > 0) {
+ firstJoinLatch.countDown();
+ } else {
+ secondJoinLatch.countDown();
+ }
+ } else if (change.wasRemoved()) {
+ leaveLatch.countDown();
+ }
+ });
+
+ instance.joinChannel(channelToJoin);
+ assertTrue(firstJoinLatch.await(TIMEOUT, TIMEOUT_UNIT));
+
+ instance.leaveChannel(channelToJoin);
+ assertTrue(leaveLatch.await(TIMEOUT, TIMEOUT_UNIT));
+
+ instance.joinChannel(channelToJoin);
+ assertTrue(secondJoinLatch.await(TIMEOUT, TIMEOUT_UNIT));
+ }
} | ['src/test/java/com/faforever/client/chat/PircBotXChatServiceTest.java', 'src/main/java/com/faforever/client/chat/ChatController.java', 'src/main/java/com/faforever/client/chat/PircBotXChatService.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 1,045,613 | 223,094 | 34,524 | 439 | 537 | 111 | 21 | 2 | 244 | 36 | 65 | 8 | 0 | 0 | 1970-01-01T00:24:29 | 175 | Java | {'Java': 3120337, 'CSS': 69562, 'HTML': 9932, 'Lua': 6869, 'JavaScript': 4215} | MIT License |
571 | faforever/downlords-faf-client/270/183 | faforever | downlords-faf-client | https://github.com/FAForever/downlords-faf-client/issues/183 | https://github.com/FAForever/downlords-faf-client/pull/270 | https://github.com/FAForever/downlords-faf-client/pull/270 | 1 | closes | Chat filter is no longer applied for people joining | When the chat user list is filtered by a name in the search field, this filter is no longer applied to people joining afterwards.
I say "no longer" because I'm 99% sure I explicitly implemented this case, and that it worked :-)
| b95ce4570a3b5d4997d6d7a75634b28802fddd30 | f92b1986c250c6ef3315070f79a7cf9f77920d45 | https://github.com/faforever/downlords-faf-client/compare/b95ce4570a3b5d4997d6d7a75634b28802fddd30...f92b1986c250c6ef3315070f79a7cf9f77920d45 | diff --git a/src/main/java/com/faforever/client/chat/ChannelTabController.java b/src/main/java/com/faforever/client/chat/ChannelTabController.java
index 66a22aba..84bb0818 100644
--- a/src/main/java/com/faforever/client/chat/ChannelTabController.java
+++ b/src/main/java/com/faforever/client/chat/ChannelTabController.java
@@ -418,8 +418,17 @@ public class ChannelTabController extends AbstractChatTabController {
userToChatUserControls.putIfAbsent(username, new HashMap<>(targetPanesForUser.size(), 1));
for (Pane pane : targetPanesForUser) {
- createChatUserControlForPlayerIfNecessary(pane, player);
+ ChatUserItemController chatUserItemController = createChatUserControlForPlayerIfNecessary(pane, player);
+
+ // Apply filter if exists
+ if (!userSearchTextField.textProperty().get().isEmpty()) {
+ chatUserItemController.setVisible(isUsernameMatch(chatUserItemController));
+ }
+ if (filterUserPopup.isShowing()) {
+ filterUserController.filterUser(chatUserItemController);
+ }
}
+
}
private Pane getPaneForSocialStatus(SocialStatus socialStatus) {
diff --git a/src/main/java/com/faforever/client/chat/FilterUserController.java b/src/main/java/com/faforever/client/chat/FilterUserController.java
index 1ce4cbea..e672596a 100644
--- a/src/main/java/com/faforever/client/chat/FilterUserController.java
+++ b/src/main/java/com/faforever/client/chat/FilterUserController.java
@@ -64,14 +64,12 @@ public class FilterUserController {
for (Map<Pane, ChatUserItemController> chatUserControlMap : userToChatUserControls.values()) {
for (Map.Entry<Pane, ChatUserItemController> chatUserControlEntry : chatUserControlMap.entrySet()) {
ChatUserItemController chatUserItemController = chatUserControlEntry.getValue();
- boolean display;
- display = filterUser(chatUserItemController);
- chatUserItemController.setVisible(display);
+ chatUserItemController.setVisible(filterUser(chatUserItemController));
}
}
}
- private boolean filterUser(ChatUserItemController chatUserItemController) {
+ boolean filterUser(ChatUserItemController chatUserItemController) {
return channelTabController.isUsernameMatch(chatUserItemController)
&& isInClan(chatUserItemController)
&& isBoundedByRating(chatUserItemController)
@@ -95,6 +93,10 @@ public class FilterUserController {
@VisibleForTesting
boolean isBoundedByRating(ChatUserItemController chatUserItemController) {
+ if (minRatingFilterField.getText().isEmpty() && maxRatingFilterField.getText().isEmpty()) {
+ return true;
+ }
+
int globalRating = RatingUtil.getGlobalRating(chatUserItemController.getPlayerInfoBean());
int minRating;
int maxRating; | ['src/main/java/com/faforever/client/chat/ChannelTabController.java', 'src/main/java/com/faforever/client/chat/FilterUserController.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 988,845 | 210,562 | 32,629 | 431 | 978 | 189 | 21 | 2 | 229 | 42 | 51 | 4 | 0 | 0 | 1970-01-01T00:24:26 | 175 | Java | {'Java': 3120337, 'CSS': 69562, 'HTML': 9932, 'Lua': 6869, 'JavaScript': 4215} | MIT License |
575 | faforever/downlords-faf-client/204/203 | faforever | downlords-faf-client | https://github.com/FAForever/downlords-faf-client/issues/203 | https://github.com/FAForever/downlords-faf-client/pull/204 | https://github.com/FAForever/downlords-faf-client/pull/204 | 1 | fixes | Exception when cache/theme folders are missing | Please create the following directories before using them:
C:\\ProgramData\\FAForever\\themes
C:\\ProgramData\\FAForever\\cache
Also, we should fix updateTaskbarProgress in MainController.java crashing when the taskBarList hasn't been created yet.
| 84079306e042c5737b09a7eaac1b9e69c797436b | 3826e05fc78ee88af83a06bbcc5108c0f85fab7f | https://github.com/faforever/downlords-faf-client/compare/84079306e042c5737b09a7eaac1b9e69c797436b...3826e05fc78ee88af83a06bbcc5108c0f85fab7f | diff --git a/src/main/java/com/faforever/client/main/MainController.java b/src/main/java/com/faforever/client/main/MainController.java
index 3b54fbc4..d4368528 100644
--- a/src/main/java/com/faforever/client/main/MainController.java
+++ b/src/main/java/com/faforever/client/main/MainController.java
@@ -307,7 +307,7 @@ public class MainController implements OnChoseGameDirectoryListener {
*/
@SuppressWarnings("unchecked")
private void updateTaskbarProgress(@Nullable Double progress) {
- if (taskBarRelatedPointer == null) {
+ if (taskBarRelatedPointer == null || taskBarList == null) {
return;
}
threadPoolExecutor.execute(() -> {
diff --git a/src/main/java/com/faforever/client/theme/ThemeServiceImpl.java b/src/main/java/com/faforever/client/theme/ThemeServiceImpl.java
index cd18a8cc..b5bb8502 100644
--- a/src/main/java/com/faforever/client/theme/ThemeServiceImpl.java
+++ b/src/main/java/com/faforever/client/theme/ThemeServiceImpl.java
@@ -179,6 +179,14 @@ public class ThemeServiceImpl implements ThemeService {
noCatch(() -> watchKeys.put(directory, directory.register(watchService, ENTRY_MODIFY, ENTRY_CREATE, ENTRY_DELETE)));
}
+ private void reloadStylesheet() {
+ String styleSheet = getSceneStyleSheet();
+
+ logger.debug("Changes detected, reloading stylesheet: {}", styleSheet);
+ scenes.forEach(scene -> setStyleSheet(scene, styleSheet));
+ webViews.forEach(webView -> setStyleSheet(webView, getWebViewStyleSheet()));
+ }
+
@Override
public String getThemeFile(String relativeFile) {
Path externalFile = getThemeDirectory(currentTheme.get()).resolve(relativeFile);
@@ -188,14 +196,6 @@ public class ThemeServiceImpl implements ThemeService {
return noCatch(() -> externalFile.toUri().toURL().toString());
}
- private void reloadStylesheet() {
- String styleSheet = getSceneStyleSheet();
-
- logger.debug("Changes detected, reloading stylesheet: {}", styleSheet);
- scenes.forEach(scene -> setStyleSheet(scene, styleSheet));
- webViews.forEach(webView -> setStyleSheet(webView, getWebViewStyleSheet()));
- }
-
private void setStyleSheet(Scene scene, String styleSheet) {
Platform.runLater(() -> scene.getStylesheets().setAll(styleSheet));
}
@@ -211,8 +211,6 @@ public class ThemeServiceImpl implements ThemeService {
}
-
-
@Override
public void setTheme(Theme theme) {
stopWatchingTheme(theme);
@@ -247,6 +245,7 @@ public class ThemeServiceImpl implements ThemeService {
themesByFolderName.clear();
themesByFolderName.put(DEFAULT_THEME_NAME, DEFAULT_THEME);
noCatch(() -> {
+ Files.createDirectories(preferencesService.getThemesDirectory());
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(preferencesService.getThemesDirectory())) {
directoryStream.forEach(this::addThemeDirectory);
}
@@ -273,7 +272,10 @@ public class ThemeServiceImpl implements ThemeService {
private void setStyleSheet(WebView webView, String styleSheetUrl) {
// Always copy to a new file since WebView locks the loaded one
Path cacheDirectory = preferencesService.getCacheDirectory();
+
noCatch(() -> {
+ Files.createDirectories(cacheDirectory);
+
Path tempStyleSheet = Files.createTempFile(cacheDirectory, "style-webview", ".css");
Files.delete(tempStyleSheet);
| ['src/main/java/com/faforever/client/theme/ThemeServiceImpl.java', 'src/main/java/com/faforever/client/main/MainController.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 973,712 | 207,843 | 32,195 | 439 | 866 | 170 | 24 | 2 | 243 | 25 | 54 | 6 | 0 | 0 | 1970-01-01T00:24:17 | 175 | Java | {'Java': 3120337, 'CSS': 69562, 'HTML': 9932, 'Lua': 6869, 'JavaScript': 4215} | MIT License |
64 | jenkinsci/jira-plugin/509/459 | jenkinsci | jira-plugin | https://github.com/jenkinsci/jira-plugin/issues/459 | https://github.com/jenkinsci/jira-plugin/pull/509 | https://github.com/jenkinsci/jira-plugin/pull/509 | 1 | fix | "No Proxy Host"-List is not used | <!--
Never report security issues on GitHub or other public channels (Gitter/Twitter/etc.), follow the instruction from [Jenkins Security](https://jenkins.io/security/).
-->
### Your checklist for this issue
🚨 Please review the [guidelines for contributing](../blob/master/CONTRIBUTING.md) to this repository.
- [x] Jenkins version ==> 2.346.1
- [x] Plugin version ==> 3.7.1
- [x] OS ==> Red Hat Enterprise Linux Server 7.9 (Maipo)
<!--
Put an `x` into the [ ] to show you have filled the information below
Describe your issue below
-->
### Reproduction steps
- Add a Proxy
- Add the Jira-Server to the "No Proxy Host"-List
- Use the Plugin (we use it to read Versions)
### Results
Expected result:
Jira is accesses without the Proxy, since the Jira-Server is on the "No Proxy Host"-List
Actual result:
The Proxy is used to connect to Jira, our Proxy can't resolve the Jira server, and that cause an Error:
See this log:
- http://webproxy.mycompany.example.com:8080 is the Proxy server
- http://jira.otherdomain.example.com:8080 is the Jira Server, and jira.otherdomain.example.com is on the "No Proxy Host"-List
```
Jul 20, 2022 2:02:48 PM FINE org.apache.http.impl.conn.PoolingHttpClientConnectionManager releaseConnection
Connection released: [id: 10088571][route: {}->http://webproxy.mycompany.example.com:8080->http://jira.otherdomain.example.com:8080][total available: 1; route allocated: 1 of 100; total allocated: 1 of 200]
Jul 20, 2022 2:02:48 PM WARNING hudson.plugins.jira.JiraRestService getVersions
Jira REST client get versions error. cause: status code: 502, reason phrase: notresolvable
org.apache.http.client.HttpResponseException: status code: 502, reason phrase: notresolvable
at org.apache.http.impl.client.AbstractResponseHandler.handleResponse(AbstractResponseHandler.java:70)
at org.apache.http.client.fluent.Response.handleResponse(Response.java:90)
at org.apache.http.client.fluent.Response.returnContent(Response.java:97)
at hudson.plugins.jira.JiraRestService.getVersions(JiraRestService.java:232)
at hudson.plugins.jira.JiraSession.getVersions(JiraSession.java:147)
at hudson.plugins.jira.versionparameter.JiraVersionParameterDefinition.getVersions(JiraVersionParameterDefinition.java:69)
at jdk.internal.reflect.GeneratedMethodAccessor1364.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
```
Relates to https://github.com/jenkinsci/jira-plugin/issues/385 where the proxy was first used
| f5e78917864788e17740c45254410bbcfa30f53a | 78e9ced2f217b995c453d2ae03f7f16f546a4d40 | https://github.com/jenkinsci/jira-plugin/compare/f5e78917864788e17740c45254410bbcfa30f53a...78e9ced2f217b995c453d2ae03f7f16f546a4d40 | diff --git a/src/main/java/hudson/plugins/jira/JiraRestService.java b/src/main/java/hudson/plugins/jira/JiraRestService.java
index 11e8d23..592fe7a 100644
--- a/src/main/java/hudson/plugins/jira/JiraRestService.java
+++ b/src/main/java/hudson/plugins/jira/JiraRestService.java
@@ -445,7 +445,13 @@ public class JiraRestService {
ProxyConfiguration proxyConfiguration = Jenkins.get().proxy;
if ( proxyConfiguration != null ) {
final HttpHost proxyHost = new HttpHost( proxyConfiguration.name, proxyConfiguration.port );
- request.viaProxy(proxyHost);
+
+ boolean shouldByPassProxy = proxyConfiguration.getNoProxyHostPatterns().stream().anyMatch(
+ it -> it.matcher(uri.getHost()).matches()
+ );
+
+ if(!shouldByPassProxy)
+ request.viaProxy(proxyHost);
}
return request
diff --git a/src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java b/src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java
index fdbcab7..88564d9 100644
--- a/src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java
+++ b/src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java
@@ -63,6 +63,18 @@ public class JiraRestServiceProxyTest {
assertEquals(localPort, proxyHost.getPort());
}
+ @Test
+ public void withProxyAndNoProxyHosts() throws Exception {
+ int localPort = connector.getLocalPort();
+ Jenkins.get().proxy = new ProxyConfiguration("localhost", localPort);
+ Jenkins.get().proxy.setNoProxyHost("example.com|google.com");
+
+
+ assertNull(getProxyObjectFromRequest());
+
+ }
+
+
@Test
public void withoutProxy() throws Exception {
assertNull(getProxyObjectFromRequest());
@@ -76,7 +88,7 @@ public class JiraRestServiceProxyTest {
Method m = service.getClass().getDeclaredMethod("buildGetRequest", URI.class);
m.setAccessible(true);
- Request buildGetRequestValue = (Request) m.invoke(service, URI.create(""));
+ Request buildGetRequestValue = (Request) m.invoke(service, JIRA_URI);
assertNotNull(buildGetRequestValue);
| ['src/main/java/hudson/plugins/jira/JiraRestService.java', 'src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 330,196 | 65,946 | 9,888 | 73 | 310 | 57 | 8 | 1 | 2,649 | 252 | 651 | 61 | 5 | 1 | 1970-01-01T00:27:55 | 169 | Java | {'Java': 582340, 'HTML': 14979} | MIT License |
823 | auth0/auth0.android/517/461 | auth0 | auth0.android | https://github.com/auth0/Auth0.Android/issues/461 | https://github.com/auth0/Auth0.Android/pull/517 | https://github.com/auth0/Auth0.Android/pull/517 | 1 | fixes | Activity com.auth0.android.provider.AuthenticationActivity has leaked ServiceConnection com.auth0.android.provider.CustomTabsController | ### Describe the problem
```
ActivityThread: Activity com.auth0.android.provider.AuthenticationActivity has leaked ServiceConnection com.auth0.android.provider.CustomTabsController@4a42179 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.auth0.android.provider.AuthenticationActivity has leaked ServiceConnection com.auth0.android.provider.CustomTabsController@4a42179 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1805)
at android.app.LoadedApk.getServiceDispatcherCommon(LoadedApk.java:1677)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1656)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1721)
at android.app.ContextImpl.bindService(ContextImpl.java:1650)
at android.content.ContextWrapper.bindService(ContextWrapper.java:705)
at androidx.browser.customtabs.CustomTabsClient.bindCustomTabsService(CustomTabsClient.java:80)
at com.auth0.android.provider.CustomTabsController.bindService(CustomTabsController.java:72)
at com.auth0.android.provider.AuthenticationActivity.launchAuthenticationIntent(AuthenticationActivity.kt:70)
at com.auth0.android.provider.AuthenticationActivity.onResume(AuthenticationActivity.kt:46)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1446)
at android.app.Activity.performResume(Activity.java:7939)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4195)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4237)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
```
### Reproduction
Happened after updated to version 2.0.0
- **Version of this library used:** 2.0.0
| 2b91d8fdbb8cf8d7a5a234564e4dd473fc52ffbe | 85243558aa2ae68c8d46bec74010906be4bddb9a | https://github.com/auth0/auth0.android/compare/2b91d8fdbb8cf8d7a5a234564e4dd473fc52ffbe...85243558aa2ae68c8d46bec74010906be4bddb9a | diff --git a/auth0/src/main/java/com/auth0/android/provider/CustomTabsController.java b/auth0/src/main/java/com/auth0/android/provider/CustomTabsController.java
index 4e5edde..a4d233c 100644
--- a/auth0/src/main/java/com/auth0/android/provider/CustomTabsController.java
+++ b/auth0/src/main/java/com/auth0/android/provider/CustomTabsController.java
@@ -31,7 +31,7 @@ class CustomTabsController extends CustomTabsServiceConnection {
@NonNull
private final CustomTabsOptions customTabsOptions;
- private boolean isBound;
+ private boolean didTryToBind;
@VisibleForTesting
CustomTabsController(@NonNull Context context, @NonNull CustomTabsOptions options) {
@@ -67,11 +67,13 @@ class CustomTabsController extends CustomTabsServiceConnection {
public void bindService() {
Log.v(TAG, "Trying to bind the service");
Context context = this.context.get();
- isBound = false;
+ didTryToBind = false;
+ boolean wasBound = false;
if (context != null && preferredPackage != null) {
- isBound = CustomTabsClient.bindCustomTabsService(context, preferredPackage, this);
+ didTryToBind = true;
+ wasBound = CustomTabsClient.bindCustomTabsService(context, preferredPackage, this);
}
- Log.v(TAG, "Bind request result: " + isBound);
+ Log.v(TAG, String.format("Bind request result (%s): %s", preferredPackage, wasBound));
}
/**
@@ -80,9 +82,9 @@ class CustomTabsController extends CustomTabsServiceConnection {
public void unbindService() {
Log.v(TAG, "Trying to unbind the service");
Context context = this.context.get();
- if (isBound && context != null) {
+ if (didTryToBind && context != null) {
context.unbindService(this);
- isBound = false;
+ didTryToBind = false;
}
}
diff --git a/auth0/src/test/java/com/auth0/android/provider/CustomTabsControllerTest.java b/auth0/src/test/java/com/auth0/android/provider/CustomTabsControllerTest.java
index 331309a..cfc84a5 100644
--- a/auth0/src/test/java/com/auth0/android/provider/CustomTabsControllerTest.java
+++ b/auth0/src/test/java/com/auth0/android/provider/CustomTabsControllerTest.java
@@ -93,12 +93,12 @@ public class CustomTabsControllerTest {
}
@Test
- public void shouldNotUnbindIfNotBound() throws Exception {
+ public void shouldUnbindEvenIfNotBound() throws Exception {
bindService(controller, false);
connectBoundService();
controller.unbindService();
- verify(context, never()).unbindService(any(ServiceConnection.class));
+ verify(context).unbindService(any(ServiceConnection.class));
}
@Test | ['auth0/src/main/java/com/auth0/android/provider/CustomTabsController.java', 'auth0/src/test/java/com/auth0/android/provider/CustomTabsControllerTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 91,117 | 17,777 | 2,314 | 24 | 691 | 155 | 14 | 1 | 2,581 | 94 | 524 | 37 | 0 | 1 | 1970-01-01T00:27:12 | 163 | Kotlin | {'Kotlin': 772321, 'Java': 370150} | MIT License |
826 | auth0/auth0.android/266/261 | auth0 | auth0.android | https://github.com/auth0/Auth0.Android/issues/261 | https://github.com/auth0/Auth0.Android/pull/266 | https://github.com/auth0/Auth0.Android/pull/266 | 1 | closes | NPE in com.auth0.android.authentication.storage.CredentialsManager | ### Description
> NullPointerException inside com.auth0.android.authentication.storage.CredentialsManager
### Reproduction
Reproduced in user on fabric.
> Details of crash:
```
Non-fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at com.auth0.android.authentication.storage.CredentialsManager.getCredentials + 101(CredentialsManager.java:101)
at com.android.test.app.auth.MoreScreenFragment.onViewCreated + 113(MoreScreenFragment.java:113)
at androidx.fragment.app.FragmentManagerImpl.moveToState + 892(FragmentManagerImpl.java:892)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState + 1238(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState + 1303(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps + 439(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps + 2079(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether + 1869(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute + 1824(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions + 1727(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run + 150(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback + 883(Handler.java:883)
at android.os.Handler.dispatchMessage + 100(Handler.java:100)
at android.os.Looper.loop + 214(Looper.java:214)
at android.app.ActivityThread.main + 7356(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run + 492(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main + 930(ZygoteInit.java:930)
```
### Environment
> Please provide the following:
- Version of library : implementation 'com.auth0.android:auth0:1.19.0'
- Android OS Version: 10
- Device: Pixel 3a XL
### Suggestion
Looks like you should just add null safe condition [here](https://github.com/auth0/Auth0.Android/blob/master/auth0/src/main/java/com/auth0/android/authentication/storage/CredentialsManager.java#L101):
```
if (cacheExpiresAt != null && cacheExpiresAt > getCurrentTimeInMillis()) {
callback.onSuccess(recreateCredentials(idToken, accessToken, tokenType, refreshToken, new Date(expiresAt), scope));
return;
}
``` | b47b84ed91ffef7a8158d235c2568530faa0103f | 9a02595e6ff0d9a29799a23d957a3ad0bcda2296 | https://github.com/auth0/auth0.android/compare/b47b84ed91ffef7a8158d235c2568530faa0103f...9a02595e6ff0d9a29799a23d957a3ad0bcda2296 | diff --git a/auth0/src/main/java/com/auth0/android/authentication/storage/CredentialsManager.java b/auth0/src/main/java/com/auth0/android/authentication/storage/CredentialsManager.java
index 2594e03..17840fc 100644
--- a/auth0/src/main/java/com/auth0/android/authentication/storage/CredentialsManager.java
+++ b/auth0/src/main/java/com/auth0/android/authentication/storage/CredentialsManager.java
@@ -93,6 +93,9 @@ public class CredentialsManager {
Long expiresAt = storage.retrieveLong(KEY_EXPIRES_AT);
String scope = storage.retrieveString(KEY_SCOPE);
Long cacheExpiresAt = storage.retrieveLong(KEY_CACHE_EXPIRES_AT);
+ if (cacheExpiresAt == null) {
+ cacheExpiresAt = expiresAt;
+ }
if (isEmpty(accessToken) && isEmpty(idToken) || expiresAt == null) {
callback.onFailure(new CredentialsManagerException("No Credentials were previously set."));
diff --git a/auth0/src/test/java/com/auth0/android/authentication/storage/CredentialsManagerTest.java b/auth0/src/test/java/com/auth0/android/authentication/storage/CredentialsManagerTest.java
index 2db4b40..0d9f037 100644
--- a/auth0/src/test/java/com/auth0/android/authentication/storage/CredentialsManagerTest.java
+++ b/auth0/src/test/java/com/auth0/android/authentication/storage/CredentialsManagerTest.java
@@ -116,7 +116,7 @@ public class CredentialsManagerTest {
prepareJwtDecoderMock(new Date(accessTokenExpirationTime));
manager.saveCredentials(credentials);
- verify(storage).store("com.auth0.id_token", (String)null);
+ verify(storage).store("com.auth0.id_token", (String) null);
verify(storage).store("com.auth0.access_token", "accessToken");
verify(storage).store("com.auth0.refresh_token", "refreshToken");
verify(storage).store("com.auth0.token_type", "type");
@@ -235,6 +235,25 @@ public class CredentialsManagerTest {
assertThat(exception.getMessage(), is("Credentials have expired and no Refresh Token was available to renew them."));
}
+ @Test
+ public void shouldNotFailOnGetCredentialsWhenCacheExpiresAtNotSetButExpiresAtIsPresent() {
+ verifyNoMoreInteractions(client);
+
+ when(storage.retrieveString("com.auth0.id_token")).thenReturn("idToken");
+ when(storage.retrieveString("com.auth0.access_token")).thenReturn("accessToken");
+ when(storage.retrieveString("com.auth0.token_type")).thenReturn("type");
+ long expirationTime = CredentialsMock.CURRENT_TIME_MS + 123456L * 1000;
+ when(storage.retrieveLong("com.auth0.expires_at")).thenReturn(expirationTime);
+ when(storage.retrieveLong("com.auth0.cache_expires_at")).thenReturn(null);
+ when(storage.retrieveString("com.auth0.scope")).thenReturn("scope");
+
+ manager.getCredentials(callback);
+
+ verify(callback).onSuccess(credentialsCaptor.capture());
+ Credentials retrievedCredentials = credentialsCaptor.getValue();
+ assertThat(retrievedCredentials, is(notNullValue()));
+ }
+
@Test
public void shouldGetNonExpiredCredentialsFromStorage() {
verifyNoMoreInteractions(client); | ['auth0/src/test/java/com/auth0/android/authentication/storage/CredentialsManagerTest.java', 'auth0/src/main/java/com/auth0/android/authentication/storage/CredentialsManager.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 361,892 | 72,945 | 9,329 | 80 | 90 | 20 | 3 | 1 | 2,648 | 160 | 577 | 45 | 1 | 2 | 1970-01-01T00:26:14 | 163 | Kotlin | {'Kotlin': 772321, 'Java': 370150} | MIT License |
827 | auth0/auth0.android/120/119 | auth0 | auth0.android | https://github.com/auth0/Auth0.Android/issues/119 | https://github.com/auth0/Auth0.Android/pull/120 | https://github.com/auth0/Auth0.Android/pull/120 | 1 | fixes | NPE when resuming AuthenticationActivity | Has anyone else encountered this error?
After calling `WebAuthProvider.init(auth0)...start()` to display the chrome tab view simply tapping "Back" or the "Close" button results in a crash:
```
09-29 14:41:39.355 11231 11231 E AndroidRuntime: java.lang.RuntimeException: Unable to resume activity {com.dat.template/com.auth0.android.provider.AuthenticationActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] java.lang.String.split(java.lang.String)' on a null object reference
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3645)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3685)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1643)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:105)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.os.Looper.loop(Looper.java:164)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6541)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] java.lang.String.split(java.lang.String)' on a null object reference
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.auth0.android.jwt.JWT.splitToken(JWT.java:209)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.auth0.android.jwt.JWT.decode(JWT.java:200)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.auth0.android.jwt.JWT.<init>(JWT.java:40)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.auth0.android.provider.OAuthManager.assertValidNonce(OAuthManager.java:186)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.auth0.android.provider.OAuthManager.resumeAuthorization(OAuthManager.java:116)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.auth0.android.provider.WebAuthProvider.resume(WebAuthProvider.java:361)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.auth0.android.provider.AuthenticationActivity.deliverSuccessfulAuthenticationResult(AuthenticationActivity.java:117)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at com.auth0.android.provider.AuthenticationActivity.onResume(AuthenticationActivity.java:78)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1354)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.app.Activity.performResume(Activity.java:7079)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3620)
09-29 14:41:39.355 11231 11231 E AndroidRuntime: ... 8 more
``` | bff4601e6f02b3f713bdfc4c1f9ed6877bc1b14c | 38ca0e4e239d0ff594f78ee06173be1fedac62e6 | https://github.com/auth0/auth0.android/compare/bff4601e6f02b3f713bdfc4c1f9ed6877bc1b14c...38ca0e4e239d0ff594f78ee06173be1fedac62e6 | diff --git a/auth0/src/main/java/com/auth0/android/provider/AuthenticationActivity.java b/auth0/src/main/java/com/auth0/android/provider/AuthenticationActivity.java
index 8450fec..ccd6054 100644
--- a/auth0/src/main/java/com/auth0/android/provider/AuthenticationActivity.java
+++ b/auth0/src/main/java/com/auth0/android/provider/AuthenticationActivity.java
@@ -14,6 +14,7 @@ public class AuthenticationActivity extends Activity {
static final String EXTRA_USE_BROWSER = "com.auth0.android.EXTRA_USE_BROWSER";
static final String EXTRA_USE_FULL_SCREEN = "com.auth0.android.EXTRA_USE_FULL_SCREEN";
static final String EXTRA_CONNECTION_NAME = "com.auth0.android.EXTRA_CONNECTION_NAME";
+ static final String EXTRA_AUTHORIZE_URI = "com.auth0.android.EXTRA_AUTHORIZE_URI";
private static final String EXTRA_INTENT_LAUNCHED = "com.auth0.android.EXTRA_INTENT_LAUNCHED";
private boolean intentLaunched;
@@ -21,7 +22,7 @@ public class AuthenticationActivity extends Activity {
static void authenticateUsingBrowser(Context context, Uri authorizeUri) {
Intent intent = new Intent(context, AuthenticationActivity.class);
- intent.setData(authorizeUri);
+ intent.putExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI, authorizeUri);
intent.putExtra(AuthenticationActivity.EXTRA_USE_BROWSER, true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
@@ -29,7 +30,7 @@ public class AuthenticationActivity extends Activity {
static void authenticateUsingWebView(Activity activity, Uri authorizeUri, int requestCode, String connection, boolean useFullScreen) {
Intent intent = new Intent(activity, AuthenticationActivity.class);
- intent.setData(authorizeUri);
+ intent.putExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI, authorizeUri);
intent.putExtra(AuthenticationActivity.EXTRA_USE_BROWSER, false);
intent.putExtra(AuthenticationActivity.EXTRA_USE_FULL_SCREEN, useFullScreen);
intent.putExtra(AuthenticationActivity.EXTRA_CONNECTION_NAME, connection);
@@ -77,6 +78,7 @@ public class AuthenticationActivity extends Activity {
if (getIntent().getData() != null) {
deliverSuccessfulAuthenticationResult(getIntent());
}
+ setResult(RESULT_CANCELED);
finish();
}
@@ -91,7 +93,7 @@ public class AuthenticationActivity extends Activity {
private void launchAuthenticationIntent() {
Bundle extras = getIntent().getExtras();
- final Uri authorizeUri = getIntent().getData();
+ Uri authorizeUri = extras.getParcelable(EXTRA_AUTHORIZE_URI);
if (!extras.getBoolean(EXTRA_USE_BROWSER, true)) {
Intent intent = new Intent(this, WebAuthActivity.class);
intent.setData(authorizeUri);
diff --git a/auth0/src/test/java/com/auth0/android/provider/AuthenticationActivityTest.java b/auth0/src/test/java/com/auth0/android/provider/AuthenticationActivityTest.java
index d76a999..3d62083 100644
--- a/auth0/src/test/java/com/auth0/android/provider/AuthenticationActivityTest.java
+++ b/auth0/src/test/java/com/auth0/android/provider/AuthenticationActivityTest.java
@@ -23,6 +23,7 @@ import org.robolectric.util.ActivityController;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasData;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasFlag;
+import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.notNullValue;
@@ -144,9 +145,6 @@ public class AuthenticationActivityTest {
activityController.pause().stop();
//Browser is shown
- Intent authenticationResultIntent = new Intent();
- authenticationResultIntent.setData(null);
- activityController.newIntent(authenticationResultIntent);
activityController.start().resume();
assertThat(activity.getDeliveredIntent(), is(nullValue()));
@@ -254,9 +252,7 @@ public class AuthenticationActivityTest {
activityController.pause().stop();
//WebViewActivity is shown
- Intent authenticationResultIntent = new Intent();
- authenticationResultIntent.setData(resultUri);
- activityShadow.receiveResult(webViewIntent.intent, Activity.RESULT_CANCELED, authenticationResultIntent);
+ activityShadow.receiveResult(webViewIntent.intent, Activity.RESULT_CANCELED, null);
assertThat(activity.getDeliveredIntent(), is(nullValue()));
assertThat(activity.isFinishing(), is(true));
@@ -274,9 +270,10 @@ public class AuthenticationActivityTest {
Assert.assertThat(intent, is(notNullValue()));
Assert.assertThat(intent, hasComponent(AuthenticationActivity.class.getName()));
Assert.assertThat(intent, hasFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP));
- Assert.assertThat(intent, hasData(uri));
+ Assert.assertThat(intent, not(hasData(uri)));
Bundle extras = intent.getExtras();
+ Assert.assertThat((Uri) extras.getParcelable(AuthenticationActivity.EXTRA_AUTHORIZE_URI), is(uri));
Assert.assertThat(extras.containsKey(AuthenticationActivity.EXTRA_CONNECTION_NAME), is(false));
Assert.assertThat(extras.containsKey(AuthenticationActivity.EXTRA_USE_FULL_SCREEN), is(false));
Assert.assertThat(extras.containsKey(AuthenticationActivity.EXTRA_USE_BROWSER), is(true));
@@ -293,9 +290,10 @@ public class AuthenticationActivityTest {
Assert.assertThat(intent, is(notNullValue()));
Assert.assertThat(intent, hasComponent(AuthenticationActivity.class.getName()));
Assert.assertThat(intent, hasFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP));
- Assert.assertThat(intent, hasData(uri));
+ Assert.assertThat(intent, not(hasData(uri)));
Bundle extras = intentCaptor.getValue().getExtras();
+ Assert.assertThat((Uri) extras.getParcelable(AuthenticationActivity.EXTRA_AUTHORIZE_URI), is(uri));
Assert.assertThat(extras.containsKey(AuthenticationActivity.EXTRA_CONNECTION_NAME), is(true));
Assert.assertThat(extras.getString(AuthenticationActivity.EXTRA_CONNECTION_NAME), is("facebook"));
Assert.assertThat(extras.containsKey(AuthenticationActivity.EXTRA_USE_FULL_SCREEN), is(true));
diff --git a/auth0/src/test/java/com/auth0/android/provider/WebAuthProviderTest.java b/auth0/src/test/java/com/auth0/android/provider/WebAuthProviderTest.java
index 4a9e710..887926b 100644
--- a/auth0/src/test/java/com/auth0/android/provider/WebAuthProviderTest.java
+++ b/auth0/src/test/java/com/auth0/android/provider/WebAuthProviderTest.java
@@ -139,7 +139,7 @@ public class WebAuthProviderTest {
WebAuthProvider.init(account)
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithName("redirect_uri"));
@@ -154,7 +154,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithName("redirect_uri"));
@@ -170,7 +170,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, not(hasParamWithName("connection")));
@@ -185,7 +185,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("connection", "my-connection"));
@@ -200,7 +200,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("connection", "some-connection"));
@@ -214,7 +214,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("connection", "my-connection"));
@@ -227,7 +227,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("connection", "some-connection"));
@@ -241,7 +241,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, not(hasParamWithName("audience")));
@@ -256,7 +256,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("audience", "https://mydomain.auth0.com/myapi"));
@@ -271,7 +271,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("audience", "https://google.com/apis"));
@@ -285,7 +285,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("audience", "https://mydomain.auth0.com/myapi"));
@@ -298,7 +298,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("audience", "https://google.com/apis"));
@@ -313,7 +313,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("scope", "openid"));
@@ -328,7 +328,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("scope", "openid email contacts"));
@@ -343,7 +343,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("scope", "profile super_scope"));
@@ -357,7 +357,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("scope", "openid email contacts"));
@@ -370,7 +370,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("scope", "profile super_scope"));
@@ -385,7 +385,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, not(hasParamWithName("connection_scope")));
@@ -400,7 +400,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("connection_scope", "openid email contacts"));
@@ -415,7 +415,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("connection_scope", "profile super_scope"));
@@ -429,7 +429,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("connection_scope", "openid email contacts"));
@@ -442,7 +442,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("connection_scope", "the scope of my connection"));
@@ -457,7 +457,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue(is("state"), not(isEmptyOrNullString())));
@@ -470,7 +470,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue(is("state"), not(isEmptyOrNullString())));
@@ -485,7 +485,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("state", "1234567890"));
@@ -500,7 +500,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("state", "abcdefg"));
@@ -514,7 +514,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("state", "1234567890"));
@@ -527,7 +527,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("state", "abcdefg"));
@@ -542,7 +542,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, not(hasParamWithName("nonce")));
@@ -555,7 +555,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, not(hasParamWithName("nonce")));
@@ -568,7 +568,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue(is("nonce"), not(isEmptyOrNullString())));
@@ -582,7 +582,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue(is("nonce"), not(isEmptyOrNullString())));
@@ -596,7 +596,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("nonce", "1234567890"));
@@ -610,7 +610,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("nonce", "1234567890"));
@@ -626,7 +626,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("nonce", "1234567890"));
@@ -642,7 +642,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("nonce", "abcdefg"));
@@ -657,7 +657,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("nonce", "1234567890"));
@@ -671,7 +671,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("nonce", "abcdefg"));
@@ -709,7 +709,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("client_id", "clientId"));
@@ -721,7 +721,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue(is("auth0Client"), not(isEmptyOrNullString())));
@@ -733,7 +733,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("redirect_uri", "https://domain/android/com.auth0.android.auth0/callback"));
@@ -747,7 +747,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("response_type", "code"));
@@ -760,7 +760,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("response_type", "token"));
@@ -773,7 +773,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("response_type", "id_token"));
@@ -786,7 +786,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("response_type", "code"));
@@ -799,7 +799,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("response_type", "code token"));
@@ -812,7 +812,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("response_type", "code id_token"));
@@ -825,7 +825,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("response_type", "id_token token"));
@@ -838,7 +838,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("response_type", "code id_token token"));
@@ -854,7 +854,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("a", "valid"));
@@ -867,7 +867,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
Set<String> params = uri.getQueryParameterNames();
@@ -887,7 +887,7 @@ public class WebAuthProviderTest {
Uri baseUriString = Uri.parse(account.getAuthorizeUrl());
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasScheme(baseUriString.getScheme()));
@@ -904,7 +904,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, hasParamWithValue("nonce", "a-nonce"));
@@ -921,7 +921,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, not(hasParamWithName("nonce")));
@@ -938,7 +938,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
assertThat(uri, not(hasParamWithName("nonce")));
@@ -961,9 +961,10 @@ public class WebAuthProviderTest {
assertThat(intent, is(notNullValue()));
assertThat(intent, hasComponent(AuthenticationActivity.class.getName()));
assertThat(intent, hasFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP));
- assertThat(intent.getData(), is(notNullValue()));
+ assertThat(intent.getData(), is(nullValue()));
Bundle extras = intentCaptor.getValue().getExtras();
+ assertThat(extras.getParcelable(AuthenticationActivity.EXTRA_AUTHORIZE_URI), is(notNullValue()));
assertThat(extras.containsKey(AuthenticationActivity.EXTRA_CONNECTION_NAME), is(false));
assertThat(extras.containsKey(AuthenticationActivity.EXTRA_USE_FULL_SCREEN), is(false));
assertThat(extras.containsKey(AuthenticationActivity.EXTRA_USE_BROWSER), is(true));
@@ -985,9 +986,10 @@ public class WebAuthProviderTest {
assertThat(intent, is(notNullValue()));
assertThat(intent, hasComponent(AuthenticationActivity.class.getName()));
assertThat(intent, hasFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP));
- assertThat(intent.getData(), is(notNullValue()));
+ assertThat(intent.getData(), is(nullValue()));
Bundle extras = intentCaptor.getValue().getExtras();
+ assertThat(extras.getParcelable(AuthenticationActivity.EXTRA_AUTHORIZE_URI), is(notNullValue()));
assertThat(extras.containsKey(AuthenticationActivity.EXTRA_CONNECTION_NAME), is(true));
assertThat(extras.getString(AuthenticationActivity.EXTRA_CONNECTION_NAME), is(nullValue()));
assertThat(extras.containsKey(AuthenticationActivity.EXTRA_USE_FULL_SCREEN), is(true));
@@ -1012,9 +1014,10 @@ public class WebAuthProviderTest {
assertThat(intent, is(notNullValue()));
assertThat(intent, hasComponent(AuthenticationActivity.class.getName()));
assertThat(intent, hasFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP));
- assertThat(intent.getData(), is(notNullValue()));
+ assertThat(intent.getData(), is(nullValue()));
Bundle extras = intent.getExtras();
+ assertThat(extras.getParcelable(AuthenticationActivity.EXTRA_AUTHORIZE_URI), is(notNullValue()));
assertThat(extras.containsKey(AuthenticationActivity.EXTRA_CONNECTION_NAME), is(true));
assertThat(extras.getString(AuthenticationActivity.EXTRA_CONNECTION_NAME), is("my-connection"));
assertThat(extras.containsKey(AuthenticationActivity.EXTRA_USE_FULL_SCREEN), is(true));
@@ -1050,7 +1053,7 @@ public class WebAuthProviderTest {
.start(activity, callback, REQUEST_CODE);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
String sentState = uri.getQueryParameter(KEY_STATE);
@@ -1070,7 +1073,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
String sentState = uri.getQueryParameter(KEY_STATE);
@@ -1125,7 +1128,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
String sentState = uri.getQueryParameter(KEY_STATE);
@@ -1164,7 +1167,7 @@ public class WebAuthProviderTest {
.start(activity, callback, REQUEST_CODE);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
String sentState = uri.getQueryParameter(KEY_STATE);
@@ -1192,7 +1195,7 @@ public class WebAuthProviderTest {
.start(activity, callback);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
String sentState = uri.getQueryParameter(KEY_STATE);
@@ -1219,7 +1222,7 @@ public class WebAuthProviderTest {
.start(activity, callback, REQUEST_CODE);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
String sentState = uri.getQueryParameter(KEY_STATE);
@@ -1246,7 +1249,7 @@ public class WebAuthProviderTest {
WebAuthProvider.getInstance().setCurrentTimeInMillis(CURRENT_TIME_MS);
verify(activity).startActivity(intentCaptor.capture());
- Uri uri = intentCaptor.getValue().getData();
+ Uri uri = intentCaptor.getValue().getParcelableExtra(AuthenticationActivity.EXTRA_AUTHORIZE_URI);
assertThat(uri, is(notNullValue()));
String sentState = uri.getQueryParameter(KEY_STATE); | ['auth0/src/test/java/com/auth0/android/provider/WebAuthProviderTest.java', 'auth0/src/test/java/com/auth0/android/provider/AuthenticationActivityTest.java', 'auth0/src/main/java/com/auth0/android/provider/AuthenticationActivity.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 282,870 | 57,389 | 7,479 | 67 | 498 | 92 | 8 | 1 | 3,238 | 244 | 946 | 29 | 0 | 1 | 1970-01-01T00:25:07 | 163 | Kotlin | {'Kotlin': 772321, 'Java': 370150} | MIT License |
1,187 | newrelic/newrelic-java-agent/885/387 | newrelic | newrelic-java-agent | https://github.com/newrelic/newrelic-java-agent/issues/387 | https://github.com/newrelic/newrelic-java-agent/pull/885 | https://github.com/newrelic/newrelic-java-agent/pull/885 | 1 | fixes | HttpURLConnection instrumentation does not mark trace as external | ## Description
When a transaction has an HTTP call using `HttpURLConnection`, the distributed traces for the HTTP call do show as being in the same transaction and not as a remote call.
## Expected Behavior
These HTTP calls show as remotes, like calls that use Apache's HTTP client.
## Steps to Reproduce
Have 2 servers with DT enabled.
From one server, make an HTTP call using `HttpURLConnection` to the other.
Check DT.
## Your Environment
Java 16
Agent 7.2.0-SNAPSHOT
But most likely all other versions are affected. | 79b177bb3c68f470891bec891b9a7b1d5b31f4f3 | 81c521b12b942779140991dd3ce65381896c6227 | https://github.com/newrelic/newrelic-java-agent/compare/79b177bb3c68f470891bec891b9a7b1d5b31f4f3...81c521b12b942779140991dd3ce65381896c6227 | diff --git a/agent-bridge/src/main/java/com/newrelic/agent/bridge/external/ExternalMetrics.java b/agent-bridge/src/main/java/com/newrelic/agent/bridge/external/ExternalMetrics.java
index a1d60832a..a2207c4ef 100644
--- a/agent-bridge/src/main/java/com/newrelic/agent/bridge/external/ExternalMetrics.java
+++ b/agent-bridge/src/main/java/com/newrelic/agent/bridge/external/ExternalMetrics.java
@@ -54,7 +54,7 @@ public class ExternalMetrics {
// transaction segment name always contains operations; metric name may or may not
String operationsPath = fixOperations(operations);
- if(operationsPath == null) {
+ if (operationsPath == null) {
String metricName = MessageFormat.format(METRIC_NAME, host, library);
method.setMetricNameFormatInfo(metricName, metricName, uri);
} else {
@@ -89,7 +89,7 @@ public class ExternalMetrics {
makeExternalComponentMetric(method, hostName, library, includeOperationInMetric, uri, operations);
- if(UNKNOWN_HOST.equals(hostName)) {
+ if (UNKNOWN_HOST.equals(hostName)) {
return; // NR doesn't add rollup metrics for "UnknownHost"
}
diff --git a/functional_test/src/test/java/com/newrelic/agent/instrumentation/pointcuts/net/HttpURLConnectionTest.java b/functional_test/src/test/java/com/newrelic/agent/instrumentation/pointcuts/net/HttpURLConnectionTest.java
index 4f1827810..8b1ad9593 100644
--- a/functional_test/src/test/java/com/newrelic/agent/instrumentation/pointcuts/net/HttpURLConnectionTest.java
+++ b/functional_test/src/test/java/com/newrelic/agent/instrumentation/pointcuts/net/HttpURLConnectionTest.java
@@ -7,8 +7,16 @@
package com.newrelic.agent.instrumentation.pointcuts.net;
-import static java.text.MessageFormat.format;
-import static org.junit.Assert.assertEquals;
+import com.google.common.collect.Sets;
+import com.newrelic.agent.AgentHelper;
+import com.newrelic.agent.TransactionDataList;
+import com.newrelic.agent.metric.MetricName;
+import com.newrelic.agent.service.ServiceFactory;
+import com.newrelic.api.agent.Trace;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
@@ -23,16 +31,8 @@ import java.net.URLConnection;
import java.util.Map;
import java.util.Set;
-import com.google.common.collect.Sets;
-import com.newrelic.agent.AgentHelper;
-import com.newrelic.agent.TransactionDataList;
-import com.newrelic.agent.metric.MetricName;
-import com.newrelic.agent.service.ServiceFactory;
-import com.newrelic.api.agent.Trace;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import static java.text.MessageFormat.format;
+import static org.junit.Assert.assertEquals;
public class HttpURLConnectionTest {
@@ -489,43 +489,68 @@ public class HttpURLConnectionTest {
int scopedNetworkIOCount, int unscopedNetworkIOCount) {
Set<String> metrics = AgentHelper.getMetrics();
+ String httpURLConnectionMetric = "External/{0}/HttpURLConnection";
+ String httpURLConnectionGetInputStreamMetric = "External/{0}/HttpURLConnection/getInputStream";
+ String httpURLConnectionGetResponseCodeMetric = "External/{0}/HttpURLConnection/getResponseCode";
+ String externalHostAllMetric = "External/{0}/all";
+ String externalAllMetric = "External/all";
+ String externalAllOtherMetric = "External/allOther";
+
if (scopedHttpUrlCount > 0 || unscopedHttpUrlCount > 0) {
- Assert.assertTrue(metrics.toString(), metrics.contains(format("External/{0}/HttpURLConnection", url)));
+ Assert.assertTrue(metrics.toString(),
+ metrics.contains(format(httpURLConnectionMetric, url)) ||
+ metrics.contains(format(httpURLConnectionGetInputStreamMetric, url)) ||
+ metrics.contains(format(httpURLConnectionGetResponseCodeMetric, url)));
} else {
- Assert.assertFalse(metrics.toString(), metrics.contains(format("External/{0}/HttpURLConnection", url)));
+ Assert.assertFalse(metrics.toString(),
+ metrics.contains(format(httpURLConnectionMetric, url)) ||
+ metrics.contains(format(httpURLConnectionGetInputStreamMetric, url)) ||
+ metrics.contains(format(httpURLConnectionGetResponseCodeMetric, url)));
}
if (scopedNetworkIOCount > 0 || unscopedNetworkIOCount > 0) {
- Assert.assertTrue(metrics.toString(), metrics.contains(format("External/{0}/all", url)));
- Assert.assertTrue(metrics.toString(), metrics.contains("External/all"));
- Assert.assertTrue(metrics.toString(), metrics.contains("External/allOther"));
+ Assert.assertTrue(metrics.toString(), metrics.contains(format(externalHostAllMetric, url)));
+ Assert.assertTrue(metrics.toString(), metrics.contains(externalAllMetric));
+ Assert.assertTrue(metrics.toString(), metrics.contains(externalAllOtherMetric));
} else {
- Assert.assertFalse(metrics.toString(), metrics.contains(format("External/{0}/all", url)));
- Assert.assertFalse(metrics.toString(), metrics.contains("External/all"));
- Assert.assertFalse(metrics.toString(), metrics.contains("External/allOther"));
+ Assert.assertFalse(metrics.toString(), metrics.contains(format(externalHostAllMetric, url)));
+ Assert.assertFalse(metrics.toString(), metrics.contains(externalAllMetric));
+ Assert.assertFalse(metrics.toString(), metrics.contains(externalAllOtherMetric));
}
Map<String, Integer> scopedMetrics = getMetricCounts(
- MetricName.create(format("External/{0}/HttpURLConnection", url), scope),
- MetricName.create(format("External/{0}/all", url), scope),
- MetricName.create("External/all", scope),
- MetricName.create("External/allOther", scope));
+ MetricName.create(format(httpURLConnectionMetric, url), scope),
+ MetricName.create(format(httpURLConnectionGetInputStreamMetric, url), scope),
+ MetricName.create(format(httpURLConnectionGetResponseCodeMetric, url), scope),
+ MetricName.create(format(externalHostAllMetric, url), scope),
+ MetricName.create(externalAllMetric, scope),
+ MetricName.create(externalAllOtherMetric, scope));
Map<String, Integer> unscopedMetrics = getMetricCounts(
- MetricName.create(format("External/{0}/HttpURLConnection", url)),
- MetricName.create(format("External/{0}/all", url)),
- MetricName.create("External/all"),
- MetricName.create("External/allOther"));
-
- assertEquals(scopedHttpUrlCount, (int) scopedMetrics.get(format("External/{0}/HttpURLConnection", url)));
- assertEquals(scopedNetworkIOCount, (int) scopedMetrics.get(format("External/{0}/all", url)));
- assertEquals(scopedNetworkIOCount, (int) scopedMetrics.get("External/all"));
- assertEquals(scopedNetworkIOCount, (int) scopedMetrics.get("External/allOther"));
-
- assertEquals(unscopedHttpUrlCount, (int) unscopedMetrics.get(format("External/{0}/HttpURLConnection", url)));
- assertEquals(unscopedNetworkIOCount, (int) unscopedMetrics.get(format("External/{0}/all", url)));
- assertEquals(unscopedNetworkIOCount, (int) unscopedMetrics.get("External/all"));
- assertEquals(unscopedNetworkIOCount, (int) unscopedMetrics.get("External/allOther"));
+ MetricName.create(format(httpURLConnectionMetric, url)),
+ MetricName.create(format(httpURLConnectionGetInputStreamMetric, url)),
+ MetricName.create(format(httpURLConnectionGetResponseCodeMetric, url)),
+ MetricName.create(format(externalHostAllMetric, url)),
+ MetricName.create(externalAllMetric),
+ MetricName.create(externalAllOtherMetric));
+
+ int actualHttpURLConnectionScopedMetricCount = scopedMetrics.get(format(httpURLConnectionMetric, url)) +
+ scopedMetrics.get(format(httpURLConnectionGetInputStreamMetric, url)) +
+ scopedMetrics.get(format(httpURLConnectionGetResponseCodeMetric, url));
+
+ int actualHttpURLConnectionUnscopedMetricCount = unscopedMetrics.get(format(httpURLConnectionMetric, url)) +
+ unscopedMetrics.get(format(httpURLConnectionGetInputStreamMetric, url)) +
+ unscopedMetrics.get(format(httpURLConnectionGetResponseCodeMetric, url));
+
+ assertEquals(scopedHttpUrlCount, actualHttpURLConnectionScopedMetricCount);
+ assertEquals(scopedNetworkIOCount, (int) scopedMetrics.get(format(externalHostAllMetric, url)));
+ assertEquals(scopedNetworkIOCount, (int) scopedMetrics.get(externalAllMetric));
+ assertEquals(scopedNetworkIOCount, (int) scopedMetrics.get(externalAllOtherMetric));
+
+ assertEquals(unscopedHttpUrlCount, actualHttpURLConnectionUnscopedMetricCount);
+ assertEquals(unscopedNetworkIOCount, (int) unscopedMetrics.get(format(externalHostAllMetric, url)));
+ assertEquals(unscopedNetworkIOCount, (int) unscopedMetrics.get(externalAllMetric));
+ assertEquals(unscopedNetworkIOCount, (int) unscopedMetrics.get(externalAllOtherMetric));
}
private Map<String, Integer> getMetricCounts(MetricName... responseTimeMetricNames) {
diff --git a/functional_test/src/test/java/test/newrelic/test/agent/HttpCommonsTest.java b/functional_test/src/test/java/test/newrelic/test/agent/HttpCommonsTest.java
index f63fed034..b60341294 100644
--- a/functional_test/src/test/java/test/newrelic/test/agent/HttpCommonsTest.java
+++ b/functional_test/src/test/java/test/newrelic/test/agent/HttpCommonsTest.java
@@ -65,13 +65,13 @@ public class HttpCommonsTest {
httpURLConnectionTx();
Set<String> metrics = AgentHelper.getMetrics();
- assertTrue(metrics.toString(), metrics.contains("External/" + HOST + "/HttpURLConnection"));
+ assertTrue(metrics.toString(), metrics.contains("External/" + HOST + "/HttpURLConnection/getResponseCode"));
Map<String, Integer> metricCounts = getMetricCounts(
- MetricName.create("External/" + HOST + "/HttpURLConnection",
+ MetricName.create("External/" + HOST + "/HttpURLConnection/getResponseCode",
"OtherTransaction/Custom/test.newrelic.test.agent.HttpCommonsTest/httpURLConnectionTx"));
- assertEquals(1, (int) metricCounts.get("External/" + HOST + "/HttpURLConnection"));
+ assertEquals(1, (int) metricCounts.get("External/" + HOST + "/HttpURLConnection/getResponseCode"));
}
@Trace(dispatcher = true)
diff --git a/instrumentation/httpurlconnection/src/main/java/com/nr/agent/instrumentation/httpurlconnection/MetricState.java b/instrumentation/httpurlconnection/src/main/java/com/nr/agent/instrumentation/httpurlconnection/MetricState.java
index 08330214f..bc68e2353 100644
--- a/instrumentation/httpurlconnection/src/main/java/com/nr/agent/instrumentation/httpurlconnection/MetricState.java
+++ b/instrumentation/httpurlconnection/src/main/java/com/nr/agent/instrumentation/httpurlconnection/MetricState.java
@@ -12,11 +12,13 @@ import com.newrelic.agent.bridge.TracedMethod;
import com.newrelic.agent.bridge.Transaction;
import com.newrelic.agent.bridge.external.ExternalMetrics;
import com.newrelic.agent.bridge.external.URISupport;
+import com.newrelic.api.agent.HttpParameters;
import java.net.HttpURLConnection;
+import java.net.URI;
public class MetricState {
-
+ private static final String LIBRARY = "HttpURLConnection";
private boolean metricsRecorded;
private boolean recordedANetworkCall;
@@ -25,8 +27,9 @@ public class MetricState {
Transaction tx = AgentBridge.getAgent().getTransaction(false);
if (!isConnected && method.isMetricProducer() && tx != null) {
// This method doesn't have any network I/O so we are explicitly not recording external rollup metrics
- makeMetric(connection, method, operation);
- tx.getCrossProcessState().processOutboundRequestHeaders(new OutboundWrapper(connection), method);
+ makeNonRollupExternalMetric(connection, method, operation);
+ // Add CAT/Distributed tracing headers to this outbound request
+ method.addOutboundRequestHeaders(new OutboundWrapper(connection));
}
}
@@ -35,11 +38,12 @@ public class MetricState {
if (method.isMetricProducer() && tx != null) {
if (!recordedANetworkCall) {
this.recordedANetworkCall = true;
- makeMetric(connection, method, "getInputStream");
+ makeNonRollupExternalMetric(connection, method, "getInputStream");
}
if (!isConnected) {
- tx.getCrossProcessState().processOutboundRequestHeaders(new OutboundWrapper(connection), method);
+ // Add CAT/Distributed tracing headers to this outbound request
+ method.addOutboundRequestHeaders(new OutboundWrapper(connection));
}
}
}
@@ -48,27 +52,46 @@ public class MetricState {
Transaction tx = AgentBridge.getAgent().getTransaction(false);
if (method.isMetricProducer() && tx != null && !recordedANetworkCall) {
this.recordedANetworkCall = true;
- makeMetric(connection, method, "getResponseCode");
+ makeNonRollupExternalMetric(connection, method, "getResponseCode");
}
}
- public void getInboundPostamble(HttpURLConnection connection, TracedMethod method) {
+ public void getInboundPostamble(HttpURLConnection connection, int responseCode, String responseMessage, String requestMethod, TracedMethod method) {
Transaction tx = AgentBridge.getAgent().getTransaction(false);
if (method.isMetricProducer() && !metricsRecorded && tx != null) {
this.metricsRecorded = true;
+ // This conversion is necessary as it strips query parameters from the URI
String uri = URISupport.getURI(connection.getURL());
InboundWrapper inboundWrapper = new InboundWrapper(connection);
- tx.getCrossProcessState()
- .processInboundResponseHeaders(inboundWrapper, method, connection.getURL().getHost(), uri, true);
+
+ // Add CAT/Distributed tracing headers to this outbound request
+ method.addOutboundRequestHeaders(new OutboundWrapper(connection));
+
+ // This will result in External rollup metrics being generated
+ method.reportAsExternal(HttpParameters
+ .library(LIBRARY)
+ .uri(URI.create(uri))
+ .procedure(requestMethod)
+ .inboundHeaders(inboundWrapper)
+ .status(responseCode, responseMessage)
+ .build());
}
}
- private void makeMetric(HttpURLConnection connection, TracedMethod method, String operation) {
+ /**
+ * Sets external metric name (i.e. External/{HOST}/HttpURLConnection).
+ * This does not create rollup metrics such as External/all, External/allWeb, External/allOther, External/{HOST}/all
+ *
+ * @param connection HttpURLConnection instance
+ * @param method TracedMethod instance
+ * @param operation String representation of operation
+ */
+ private void makeNonRollupExternalMetric(HttpURLConnection connection, TracedMethod method, String operation) {
String uri = URISupport.getURI(connection.getURL());
ExternalMetrics.makeExternalComponentMetric(
method,
connection.getURL().getHost(),
- "HttpURLConnection",
+ LIBRARY,
false,
uri,
operation);
diff --git a/instrumentation/httpurlconnection/src/main/java/java/net/HttpURLConnection.java b/instrumentation/httpurlconnection/src/main/java/java/net/HttpURLConnection.java
index 53dd026e8..72a1a34eb 100644
--- a/instrumentation/httpurlconnection/src/main/java/java/net/HttpURLConnection.java
+++ b/instrumentation/httpurlconnection/src/main/java/java/net/HttpURLConnection.java
@@ -42,14 +42,12 @@ public abstract class HttpURLConnection extends URLConnection {
@Trace(leaf = true)
public void connect() throws IOException {
lazyGetMetricState().nonNetworkPreamble(connected, this, "connect");
-
Weaver.callOriginal();
}
@Trace(leaf = true)
public synchronized OutputStream getOutputStream() throws IOException {
lazyGetMetricState().nonNetworkPreamble(connected, this, "getOutputStream");
-
return Weaver.callOriginal();
}
@@ -71,8 +69,7 @@ public abstract class HttpURLConnection extends URLConnection {
throw e;
}
- metricState.getInboundPostamble(this, method);
-
+ metricState.getInboundPostamble(this, 0, null, "getInputStream", method);
return inputStream;
}
@@ -94,8 +91,7 @@ public abstract class HttpURLConnection extends URLConnection {
throw e;
}
- metricState.getInboundPostamble(this, method);
-
+ metricState.getInboundPostamble(this, responseCodeValue, null, "getResponseCode", method);
return responseCodeValue;
}
diff --git a/instrumentation/httpurlconnection/src/test/java/com/nr/agent/instrumentation/httpurlconnection/MetricStateResponseCodeTest.java b/instrumentation/httpurlconnection/src/test/java/com/nr/agent/instrumentation/httpurlconnection/MetricStateResponseCodeTest.java
index 0c73a0303..1939c342e 100644
--- a/instrumentation/httpurlconnection/src/test/java/com/nr/agent/instrumentation/httpurlconnection/MetricStateResponseCodeTest.java
+++ b/instrumentation/httpurlconnection/src/test/java/com/nr/agent/instrumentation/httpurlconnection/MetricStateResponseCodeTest.java
@@ -8,18 +8,14 @@
package com.nr.agent.instrumentation.httpurlconnection;
import com.newrelic.agent.bridge.AgentBridge;
-import com.newrelic.agent.introspec.HttpTestServer;
import com.newrelic.agent.introspec.InstrumentationTestConfig;
import com.newrelic.agent.introspec.InstrumentationTestRunner;
import com.newrelic.agent.introspec.Introspector;
import com.newrelic.agent.introspec.TraceSegment;
import com.newrelic.agent.introspec.TransactionEvent;
import com.newrelic.agent.introspec.TransactionTrace;
-import com.newrelic.agent.introspec.internal.HttpServerLocator;
import com.newrelic.agent.introspec.internal.HttpServerRule;
import com.newrelic.api.agent.Trace;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -67,8 +63,8 @@ public class MetricStateResponseCodeTest {
String transactionName = fetchTransactionName(introspector, "callGetResponseCode");
// We only have one call to this external metric.
- assertTrue(introspector.getMetricsForTransaction(transactionName).containsKey("External/localhost/HttpURLConnection"));
- assertEquals(1, introspector.getMetricsForTransaction(transactionName).get("External/localhost/HttpURLConnection").getCallCount());
+ assertTrue(introspector.getMetricsForTransaction(transactionName).containsKey("External/localhost/HttpURLConnection/getResponseCode"));
+ assertEquals(1, introspector.getMetricsForTransaction(transactionName).get("External/localhost/HttpURLConnection/getResponseCode").getCallCount());
// The number of segments is equal to the number of calls to getResponseCode.
TransactionTrace trace = introspector.getTransactionTracesForTransaction(transactionName).iterator().next();
@@ -94,8 +90,8 @@ public class MetricStateResponseCodeTest {
// Only one external call.
String transactionName = fetchTransactionName(introspector, "callGetResponseCodeThenGetInputStream");
- assertTrue(introspector.getMetricsForTransaction(transactionName).containsKey("External/localhost/HttpURLConnection"));
- assertEquals(1, introspector.getMetricsForTransaction(transactionName).get("External/localhost/HttpURLConnection").getCallCount());
+ assertTrue(introspector.getMetricsForTransaction(transactionName).containsKey("External/localhost/HttpURLConnection/getResponseCode"));
+ assertEquals(1, introspector.getMetricsForTransaction(transactionName).get("External/localhost/HttpURLConnection/getResponseCode").getCallCount());
// Two child segments within the transaction.
TransactionTrace trace = introspector.getTransactionTracesForTransaction(transactionName).iterator().next();
@@ -125,8 +121,8 @@ public class MetricStateResponseCodeTest {
// Only one external call.
String transactionName = fetchTransactionName(introspector, "callGetInputStreamThenResponseCode");
- assertTrue(introspector.getMetricsForTransaction(transactionName).containsKey("External/localhost/HttpURLConnection"));
- assertEquals(1, introspector.getMetricsForTransaction(transactionName).get("External/localhost/HttpURLConnection").getCallCount());
+ assertTrue(introspector.getMetricsForTransaction(transactionName).containsKey("External/localhost/HttpURLConnection/getInputStream"));
+ assertEquals(1, introspector.getMetricsForTransaction(transactionName).get("External/localhost/HttpURLConnection/getInputStream").getCallCount());
// Two child segments within the transaction.
TransactionTrace trace = introspector.getTransactionTracesForTransaction(transactionName).iterator().next();
@@ -204,14 +200,12 @@ public class MetricStateResponseCodeTest {
@Trace(leaf = true)
private void simulatedInstrumentedGetResponseCodeMethod(HttpURLConnection conn, MetricState target) {
target.getResponseCodePreamble(conn, AgentBridge.getAgent().getTracedMethod());
-
- target.getInboundPostamble(conn, AgentBridge.getAgent().getTracedMethod());
+ target.getInboundPostamble(conn, 0, null, "getResponseCode", AgentBridge.getAgent().getTracedMethod());
}
@Trace(leaf = true)
private void simulatedInstrumentedGetInputStreamMethod(boolean isConnected, HttpURLConnection conn, MetricState target) {
target.getInputStreamPreamble(isConnected, conn, AgentBridge.getAgent().getTracedMethod());
-
- target.getInboundPostamble(conn, AgentBridge.getAgent().getTracedMethod());
+ target.getInboundPostamble(conn, 0, null, "getInputStream", AgentBridge.getAgent().getTracedMethod());
}
}
diff --git a/newrelic-api/src/main/java/com/newrelic/api/agent/TracedMethod.java b/newrelic-api/src/main/java/com/newrelic/api/agent/TracedMethod.java
index d5207ee0e..a9006a61c 100644
--- a/newrelic-api/src/main/java/com/newrelic/api/agent/TracedMethod.java
+++ b/newrelic-api/src/main/java/com/newrelic/api/agent/TracedMethod.java
@@ -70,7 +70,8 @@ public interface TracedMethod extends AttributeHolder {
* determines if the external call is HTTP or JMS.
* @since 3.36.0
* @deprecated Instead, use the Distributed Tracing API {@link Transaction#insertDistributedTraceHeaders(Headers)} to create a
- * distributed tracing payload
+ * distributed tracing payload. However, note that the <code>insertDistributedTraceHeaders</code> API only adds distributed tracing
+ * headers and does not add legacy CAT headers. If CAT must be supported then instead use this deprecated API.
*/
@Deprecated
void addOutboundRequestHeaders(OutboundHeaders outboundHeaders); | ['newrelic-api/src/main/java/com/newrelic/api/agent/TracedMethod.java', 'functional_test/src/test/java/com/newrelic/agent/instrumentation/pointcuts/net/HttpURLConnectionTest.java', 'instrumentation/httpurlconnection/src/main/java/java/net/HttpURLConnection.java', 'agent-bridge/src/main/java/com/newrelic/agent/bridge/external/ExternalMetrics.java', 'functional_test/src/test/java/test/newrelic/test/agent/HttpCommonsTest.java', 'instrumentation/httpurlconnection/src/test/java/com/nr/agent/instrumentation/httpurlconnection/MetricStateResponseCodeTest.java', 'instrumentation/httpurlconnection/src/main/java/com/nr/agent/instrumentation/httpurlconnection/MetricState.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 7,303,697 | 1,496,563 | 204,070 | 2,433 | 3,584 | 668 | 60 | 4 | 536 | 87 | 120 | 15 | 0 | 0 | 1970-01-01T00:27:35 | 163 | Java | {'Java': 16381608, 'Scala': 728478, 'HTML': 62037, 'Kotlin': 21562, 'Shell': 9932, 'Groovy': 5230, 'Dockerfile': 519} | Apache License 2.0 |
825 | auth0/auth0.android/325/324 | auth0 | auth0.android | https://github.com/auth0/Auth0.Android/issues/324 | https://github.com/auth0/Auth0.Android/pull/325 | https://github.com/auth0/Auth0.Android/pull/325 | 1 | fix | Credentials lost after update | ### Description
We just released a new version of our app (upgrading to Android X) and it seems like every user has lost their credentials:
> A change on the Lock Screen security settings have deemed the encryption keys invalid and have been recreated. Any previously stored content is now lost. Please, try saving the credentials again.
It's possible this is our fault, but the cause seems very opaque to us. Is it possible that the error message is catching other types of error as well?
https://github.com/auth0/Auth0.Android/blob/dc19c45c01fd5a5d7d023755dc96432ff63ee284/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.java#L170-L178
### Reproduction
- Follow examples for `SecureCredentialsManager`
- Update app (unclear what changes cause this problem)
Thanks
Adam
| 4134c71abddcfca477f11d4903f12b5ab46de936 | 05cdbbfabb643f8f4dd71c9e784cdfd630e03ba2 | https://github.com/auth0/auth0.android/compare/4134c71abddcfca477f11d4903f12b5ab46de936...05cdbbfabb643f8f4dd71c9e784cdfd630e03ba2 | diff --git a/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.java b/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.java
index 2fde37d..3b2bbf9 100644
--- a/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.java
+++ b/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.java
@@ -41,7 +41,9 @@ public class SecureCredentialsManager {
private static final String KEY_CREDENTIALS = "com.auth0.credentials";
private static final String KEY_EXPIRES_AT = "com.auth0.credentials_expires_at";
private static final String KEY_CAN_REFRESH = "com.auth0.credentials_can_refresh";
- private static final String KEY_ALIAS = "com.auth0.key";
+ private static final String KEY_CRYPTO_ALIAS = "com.auth0.manager_key_alias";
+ @VisibleForTesting
+ static final String KEY_ALIAS = "com.auth0.key";
private final AuthenticationAPIClient apiClient;
private final Storage storage;
@@ -165,6 +167,7 @@ public class SecureCredentialsManager {
storage.store(KEY_CREDENTIALS, encryptedEncoded);
storage.store(KEY_EXPIRES_AT, expiresAt);
storage.store(KEY_CAN_REFRESH, canRefresh);
+ storage.store(KEY_CRYPTO_ALIAS, KEY_ALIAS);
} catch (IncompatibleDeviceException e) {
throw new CredentialsManagerException(String.format("This device is not compatible with the %s class.", SecureCredentialsManager.class.getSimpleName()), e);
} catch (CryptoException e) {
@@ -211,6 +214,7 @@ public class SecureCredentialsManager {
storage.remove(KEY_CREDENTIALS);
storage.remove(KEY_EXPIRES_AT);
storage.remove(KEY_CAN_REFRESH);
+ storage.remove(KEY_CRYPTO_ALIAS);
Log.d(TAG, "Credentials were just removed from the storage");
}
@@ -223,9 +227,10 @@ public class SecureCredentialsManager {
String encryptedEncoded = storage.retrieveString(KEY_CREDENTIALS);
Long expiresAt = storage.retrieveLong(KEY_EXPIRES_AT);
Boolean canRefresh = storage.retrieveBoolean(KEY_CAN_REFRESH);
- return !(isEmpty(encryptedEncoded) ||
- expiresAt == null ||
- expiresAt <= getCurrentTimeInMillis() && (canRefresh == null || !canRefresh));
+ String keyAliasUsed = storage.retrieveString(KEY_CRYPTO_ALIAS);
+ return KEY_ALIAS.equals(keyAliasUsed) &&
+ !(isEmpty(encryptedEncoded) || expiresAt == null ||
+ expiresAt <= getCurrentTimeInMillis() && (canRefresh == null || !canRefresh));
}
private void continueGetCredentials(final BaseCallback<Credentials, CredentialsManagerException> callback) {
diff --git a/auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.java b/auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.java
index cc68457..389b71e 100644
--- a/auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.java
+++ b/auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.java
@@ -128,6 +128,7 @@ public class SecureCredentialsManagerTest {
verify(storage).store(eq("com.auth0.credentials"), stringCaptor.capture());
verify(storage).store("com.auth0.credentials_expires_at", sharedExpirationTime);
verify(storage).store("com.auth0.credentials_can_refresh", true);
+ verify(storage).store("com.auth0.manager_key_alias", SecureCredentialsManager.KEY_ALIAS);
verifyNoMoreInteractions(storage);
final String encodedJson = stringCaptor.getValue();
assertThat(encodedJson, is(notNullValue()));
@@ -155,6 +156,7 @@ public class SecureCredentialsManagerTest {
verify(storage).store(eq("com.auth0.credentials"), stringCaptor.capture());
verify(storage).store("com.auth0.credentials_expires_at", accessTokenExpirationTime);
verify(storage).store("com.auth0.credentials_can_refresh", true);
+ verify(storage).store("com.auth0.manager_key_alias", SecureCredentialsManager.KEY_ALIAS);
verifyNoMoreInteractions(storage);
final String encodedJson = stringCaptor.getValue();
assertThat(encodedJson, is(notNullValue()));
@@ -183,6 +185,7 @@ public class SecureCredentialsManagerTest {
verify(storage).store(eq("com.auth0.credentials"), stringCaptor.capture());
verify(storage).store("com.auth0.credentials_expires_at", idTokenExpirationTime);
verify(storage).store("com.auth0.credentials_can_refresh", true);
+ verify(storage).store("com.auth0.manager_key_alias", SecureCredentialsManager.KEY_ALIAS);
verifyNoMoreInteractions(storage);
final String encodedJson = stringCaptor.getValue();
assertThat(encodedJson, is(notNullValue()));
@@ -210,6 +213,7 @@ public class SecureCredentialsManagerTest {
verify(storage).store(eq("com.auth0.credentials"), stringCaptor.capture());
verify(storage).store("com.auth0.credentials_expires_at", expirationTime);
verify(storage).store("com.auth0.credentials_can_refresh", false);
+ verify(storage).store("com.auth0.manager_key_alias", SecureCredentialsManager.KEY_ALIAS);
verifyNoMoreInteractions(storage);
final String encodedJson = stringCaptor.getValue();
assertThat(encodedJson, is(notNullValue()));
@@ -573,6 +577,7 @@ public class SecureCredentialsManagerTest {
verify(storage).remove("com.auth0.credentials");
verify(storage).remove("com.auth0.credentials_expires_at");
verify(storage).remove("com.auth0.credentials_can_refresh");
+ verify(storage).remove("com.auth0.manager_key_alias");
verifyNoMoreInteractions(storage);
}
@@ -586,6 +591,7 @@ public class SecureCredentialsManagerTest {
when(storage.retrieveLong("com.auth0.credentials_expires_at")).thenReturn(expirationTime);
when(storage.retrieveBoolean("com.auth0.credentials_can_refresh")).thenReturn(false);
when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"id_token\\":\\"idToken\\"}");
+ when(storage.retrieveString("com.auth0.manager_key_alias")).thenReturn(SecureCredentialsManager.KEY_ALIAS);
assertThat(manager.hasValidCredentials(), is(true));
when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"access_token\\":\\"accessToken\\"}");
@@ -598,6 +604,7 @@ public class SecureCredentialsManagerTest {
when(storage.retrieveLong("com.auth0.credentials_expires_at")).thenReturn(expirationTime);
when(storage.retrieveBoolean("com.auth0.credentials_can_refresh")).thenReturn(false);
when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"id_token\\":\\"idToken\\"}");
+ when(storage.retrieveString("com.auth0.manager_key_alias")).thenReturn(SecureCredentialsManager.KEY_ALIAS);
assertThat(manager.hasValidCredentials(), is(false));
when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"access_token\\":\\"accessToken\\"}");
@@ -610,6 +617,7 @@ public class SecureCredentialsManagerTest {
when(storage.retrieveLong("com.auth0.credentials_expires_at")).thenReturn(expirationTime);
when(storage.retrieveBoolean("com.auth0.credentials_can_refresh")).thenReturn(true);
when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"id_token\\":\\"idToken\\", \\"refresh_token\\":\\"refreshToken\\"}");
+ when(storage.retrieveString("com.auth0.manager_key_alias")).thenReturn(SecureCredentialsManager.KEY_ALIAS);
assertThat(manager.hasValidCredentials(), is(true));
when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"access_token\\":\\"accessToken\\", \\"refresh_token\\":\\"refreshToken\\"}");
@@ -619,10 +627,37 @@ public class SecureCredentialsManagerTest {
@Test
public void shouldNotHaveCredentialsWhenAccessTokenAndIdTokenAreMissing() {
when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"token_type\\":\\"type\\", \\"refresh_token\\":\\"refreshToken\\"}");
+ when(storage.retrieveString("com.auth0.manager_key_alias")).thenReturn(SecureCredentialsManager.KEY_ALIAS);
assertFalse(manager.hasValidCredentials());
}
+ @Test
+ public void shouldNotHaveCredentialsWhenTheAliasUsedHasNotBeenMigratedYet() {
+ long expirationTime = CredentialsMock.CURRENT_TIME_MS + 123456L * 1000;
+ when(storage.retrieveLong("com.auth0.credentials_expires_at")).thenReturn(expirationTime);
+ when(storage.retrieveBoolean("com.auth0.credentials_can_refresh")).thenReturn(false);
+ when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"id_token\\":\\"idToken\\"}");
+ when(storage.retrieveString("com.auth0.manager_key_alias")).thenReturn("old_alias");
+ assertThat(manager.hasValidCredentials(), is(false));
+
+ when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"access_token\\":\\"accessToken\\"}");
+ assertThat(manager.hasValidCredentials(), is(false));
+ }
+
+ @Test
+ public void shouldNotHaveCredentialsWhenTheAliasUsedHasNotBeenSetYet() {
+ long expirationTime = CredentialsMock.CURRENT_TIME_MS + 123456L * 1000;
+ when(storage.retrieveLong("com.auth0.credentials_expires_at")).thenReturn(expirationTime);
+ when(storage.retrieveBoolean("com.auth0.credentials_can_refresh")).thenReturn(false);
+ when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"id_token\\":\\"idToken\\"}");
+ when(storage.retrieveString("com.auth0.manager_key_alias")).thenReturn(null);
+ assertThat(manager.hasValidCredentials(), is(false));
+
+ when(storage.retrieveString("com.auth0.credentials")).thenReturn("{\\"access_token\\":\\"accessToken\\"}");
+ assertThat(manager.hasValidCredentials(), is(false));
+ }
+
/*
* Authentication tests
*/
@@ -860,6 +895,7 @@ public class SecureCredentialsManagerTest {
when(storage.retrieveString("com.auth0.credentials")).thenReturn(encoded);
when(storage.retrieveLong("com.auth0.credentials_expires_at")).thenReturn(willExpireAt != null ? willExpireAt.getTime() : null);
when(storage.retrieveBoolean("com.auth0.credentials_can_refresh")).thenReturn(hasRefreshToken);
+ when(storage.retrieveString("com.auth0.manager_key_alias")).thenReturn(SecureCredentialsManager.KEY_ALIAS);
return storedJson;
}
| ['auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.java', 'auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 394,971 | 79,680 | 10,138 | 88 | 799 | 160 | 13 | 1 | 834 | 105 | 184 | 18 | 1 | 0 | 1970-01-01T00:26:36 | 163 | Kotlin | {'Kotlin': 772321, 'Java': 370150} | MIT License |
1,176 | consensys/tessera/582/576 | consensys | tessera | https://github.com/Consensys/tessera/issues/576 | https://github.com/Consensys/tessera/pull/582 | https://github.com/Consensys/tessera/pull/582 | 1 | fixes | AddPeer API accept duplicated url | tessera version: 0.7.3
I test `addPeer` API by below command:
```
curl -XPUT http://localhost:9002/config/peers -d '{"url":"http://localhost:9001"}' -H 'content-type:application/json'
curl -XPUT http://localhost:9002/config/peers -d '{"url":"http://localhost:9001"}' -H 'content-type:application/json'
curl -XPUT http://localhost:9002/config/peers -d '{"url":"http://localhost:9001"}' -H 'content-type:application/json'
```
then get peers by:
```
curl http://localhost:9002/config/peers
[{"type":"peer","url":"http://localhost:9000"},{"type":"peer","url":"http://localhost:9001"},{"type":"peer","url":"http://localhost:9001"},{"type":"peer","url":"http://localhost:9001"},{"type":"peer","url":"http://localhost:9001"},{"type":"peer","url":"http://localhost:9001"},{"type":"peer","url":"http://localhost:9001"},{"type":"peer","url":"http://localhost:9001"}]
```
I got lots of duplicated url in peers list, I think we should keep only one of these duplicated url. | 518f2a583865f24b21cb0d414200feff36bb7f63 | 70d2728aa64745202d1a82994dfae99e21d204fb | https://github.com/consensys/tessera/compare/518f2a583865f24b21cb0d414200feff36bb7f63...70d2728aa64745202d1a82994dfae99e21d204fb | diff --git a/jaxrs-service/src/main/java/com/quorum/tessera/p2p/ConfigResource.java b/jaxrs-service/src/main/java/com/quorum/tessera/p2p/ConfigResource.java
index b4f4dcb91..142c5782b 100644
--- a/jaxrs-service/src/main/java/com/quorum/tessera/p2p/ConfigResource.java
+++ b/jaxrs-service/src/main/java/com/quorum/tessera/p2p/ConfigResource.java
@@ -12,11 +12,13 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
-import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.ws.rs.core.GenericEntity;
+import static java.util.Collections.emptySet;
+import static java.util.Collections.singleton;
+
@Path("/config")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@@ -26,33 +28,38 @@ public class ConfigResource {
private final PartyInfoService partyInfoService;
- public ConfigResource(ConfigService configService,
- PartyInfoService partyInfoService) {
+ public ConfigResource(final ConfigService configService, final PartyInfoService partyInfoService) {
this.configService = Objects.requireNonNull(configService);
this.partyInfoService = Objects.requireNonNull(partyInfoService);
}
-
-
@PUT
@Path("/peers")
public Response addPeer(@Valid final Peer peer) {
- this.configService.addPeer(peer.getUrl());
+ final boolean existing = configService.getPeers().contains(peer);
- partyInfoService.updatePartyInfo(
- new PartyInfo(peer.getUrl(),Collections.EMPTY_SET,
- Collections.singleton(new Party(peer.getUrl()))));
-
- //TODO: this seems a bit presumptuous, search for the peer instead?
- final int index = this.configService.getPeers().size() - 1;
+ if (!existing) {
+ this.configService.addPeer(peer.getUrl());
+
+ this.partyInfoService.updatePartyInfo(
+ new PartyInfo(peer.getUrl(), emptySet(), singleton(new Party(peer.getUrl())))
+ );
+ }
+
+ final int index = this.configService.getPeers().indexOf(peer);
final URI uri = UriBuilder.fromPath("config")
.path("peers")
.path(String.valueOf(index))
.build();
- return Response.created(uri).build();
+ if (!existing) {
+ return Response.created(uri).build();
+ } else {
+ return Response.ok().location(uri).build();
+ }
+
}
@GET
diff --git a/jaxrs-service/src/test/java/com/quorum/tessera/p2p/ConfigResourceTest.java b/jaxrs-service/src/test/java/com/quorum/tessera/p2p/ConfigResourceTest.java
index 68767a5c7..a4ba46337 100644
--- a/jaxrs-service/src/test/java/com/quorum/tessera/p2p/ConfigResourceTest.java
+++ b/jaxrs-service/src/test/java/com/quorum/tessera/p2p/ConfigResourceTest.java
@@ -4,22 +4,22 @@ import com.quorum.tessera.config.Peer;
import com.quorum.tessera.core.config.ConfigService;
import com.quorum.tessera.node.PartyInfoService;
import com.quorum.tessera.node.model.PartyInfo;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.core.Response;
-import static org.assertj.core.api.Assertions.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.Mockito;
+
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.List;
+
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
-import org.mockito.Mockito;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.*;
public class ConfigResourceTest {
@@ -43,32 +43,61 @@ public class ConfigResourceTest {
}
@Test
- public void addPeerIsSucessful() {
+ public void addPeerIsSuccessful() {
+
+ final Peer peer = new Peer("junit");
+ final List<Peer> peers = new ArrayList<>();
- List<Peer> peers = new ArrayList<>();
- Mockito.doAnswer((inv) -> {
+ Mockito.doAnswer(inv -> {
peers.add(new Peer(inv.getArgument(0)));
return null;
}).when(configService).addPeer(anyString());
when(configService.getPeers()).thenReturn(peers);
- Peer peer = new Peer("junit");
+ final Response response = configResource.addPeer(peer);
- Response response = configResource.addPeer(peer);
assertThat(response.getStatus()).isEqualTo(201);
assertThat(response.getLocation().toString()).isEqualTo("config/peers/0");
assertThat(peers).containsExactly(peer);
+
verify(configService).addPeer(peer.getUrl());
- verify(configService).getPeers();
+ verify(configService, times(2)).getPeers();
verify(partyInfoService).updatePartyInfo(any(PartyInfo.class));
}
@Test
- public void getPeerIsSucessful() {
- Peer peer = new Peer("getPeerIsSucessfulUrl");
- when(configService.getPeers()).thenReturn(Arrays.asList(peer));
+ public void addExistingPeerIsSuccessful() {
- Response response = configResource.getPeer(0);
+ final Peer peer = new Peer("junit");
+ final List<Peer> peers = new ArrayList<>();
+
+ Mockito.doAnswer(inv -> {
+ peers.add(new Peer(inv.getArgument(0)));
+ return null;
+ }).when(configService).addPeer(anyString());
+ when(configService.getPeers()).thenReturn(peers);
+
+ final Response responseOne = configResource.addPeer(peer);
+ assertThat(responseOne.getStatus()).isEqualTo(201);
+ assertThat(responseOne.getLocation().toString()).isEqualTo("config/peers/0");
+ assertThat(peers).containsExactly(peer);
+
+ final Response responseTwo = configResource.addPeer(peer);
+ assertThat(responseTwo.getStatus()).isEqualTo(200);
+ assertThat(responseTwo.getLocation().toString()).isEqualTo("config/peers/0");
+ assertThat(peers).containsExactly(peer);
+
+ verify(configService).addPeer(peer.getUrl());
+ verify(configService, times(4)).getPeers();
+ verify(partyInfoService).updatePartyInfo(any(PartyInfo.class));
+ }
+
+ @Test
+ public void getPeerIsSuccessful() {
+ final Peer peer = new Peer("getPeerIsSucessfulUrl");
+ when(configService.getPeers()).thenReturn(singletonList(peer));
+
+ final Response response = configResource.getPeer(0);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getEntity()).isEqualTo(peer);
@@ -78,22 +107,23 @@ public class ConfigResourceTest {
@Test
public void getPeerNotFound() {
- Peer peer = new Peer("getPeerNoptFound");
- when(configService.getPeers()).thenReturn(Arrays.asList(peer));
-
- try {
- configResource.getPeer(2);
- failBecauseExceptionWasNotThrown(NotFoundException.class);
- } catch (NotFoundException ex) {
- verify(configService).getPeers();
- }
+ final Peer peer = new Peer("getPeerNoptFound");
+ when(configService.getPeers()).thenReturn(singletonList(peer));
+
+ final Throwable throwable = catchThrowable(() -> this.configResource.getPeer(2));
+
+ assertThat(throwable).isInstanceOf(NotFoundException.class);
+
+ verify(configService).getPeers();
}
@Test
public void getPeers() {
- Peer peer = new Peer("somepeer");
- when(configService.getPeers()).thenReturn(Arrays.asList(peer));
- Response response = configResource.getPeers();
+ final Peer peer = new Peer("somepeer");
+ when(configService.getPeers()).thenReturn(singletonList(peer));
+
+ final Response response = configResource.getPeers();
+
assertThat(response.getStatus()).isEqualTo(200);
List<Peer> results = (List<Peer>) response.getEntity(); | ['jaxrs-service/src/main/java/com/quorum/tessera/p2p/ConfigResource.java', 'jaxrs-service/src/test/java/com/quorum/tessera/p2p/ConfigResourceTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 562,380 | 112,855 | 17,718 | 328 | 1,362 | 248 | 33 | 1 | 979 | 62 | 285 | 16 | 15 | 2 | 1970-01-01T00:25:46 | 162 | Java | {'Java': 3402794, 'Gherkin': 11338, 'Shell': 6831, 'Dockerfile': 5224, 'XSLT': 3932, 'JavaScript': 3693, 'Groovy': 1175, 'HCL': 257} | Apache License 2.0 |
1,174 | consensys/tessera/843/842 | consensys | tessera | https://github.com/Consensys/tessera/issues/842 | https://github.com/Consensys/tessera/pull/843 | https://github.com/Consensys/tessera/pull/843 | 1 | fixes | Fatal node sync call stops subsequent calls | When the PartyInfo poller makes requests to other nodes there are two classes of exceptions that can occur, general connection issues and then other, more serious issues.
A simple connection issue gets logged and passed over, as this is expected to happen from time to time, and all other exception types were presumed to be ephemeral and eventually resolve. We throw this error back up the call stack to handle later.
This means that when this error occurs, all other parties we wanted to sync with after the current do not happen (as the exception stops the loop). Sometimes, the error will never resolve, which effectively stops the node fully syncing with the network.
Any error, whether it is a general connection issue or something more serious, should not stop the processing of other calls. | 6693bbd07ae0b312f23a321683f5b1cf11da692d | f733123b814638962127b686ba2169774ff9b017 | https://github.com/consensys/tessera/compare/6693bbd07ae0b312f23a321683f5b1cf11da692d...f733123b814638962127b686ba2169774ff9b017 | diff --git a/tessera-core/src/main/java/com/quorum/tessera/threading/TesseraScheduledExecutor.java b/tessera-core/src/main/java/com/quorum/tessera/threading/TesseraScheduledExecutor.java
index 9bfc5579d..b46039041 100644
--- a/tessera-core/src/main/java/com/quorum/tessera/threading/TesseraScheduledExecutor.java
+++ b/tessera-core/src/main/java/com/quorum/tessera/threading/TesseraScheduledExecutor.java
@@ -10,10 +10,9 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
- * Schedules a continuous running task as an alternative to
- * a {@link Thread} running a {@code while(true)} loop
+ * Schedules a continuous running task as an alternative to a {@link Thread} running a {@code while(true)} loop
*
- * Also allows delays if required between each execution of the loop
+ * <p>Also allows delays if required between each execution of the loop
*/
public class TesseraScheduledExecutor {
@@ -24,13 +23,11 @@ public class TesseraScheduledExecutor {
private final Runnable action;
private final long rate;
-
+
private final long initialDelay;
- public TesseraScheduledExecutor(final ScheduledExecutorService executor,
- final Runnable action,
- final long rate,
- final long delay) {
+ public TesseraScheduledExecutor(
+ final ScheduledExecutorService executor, final Runnable action, final long rate, final long delay) {
this.executor = Objects.requireNonNull(executor);
this.action = Objects.requireNonNull(action);
this.rate = rate;
@@ -38,21 +35,26 @@ public class TesseraScheduledExecutor {
}
/**
- * Starts the submitted task and schedules it to run every given time frame
- * Catches any Throwable and logs it so that the scheduling doesn't break
+ * Starts the submitted task and schedules it to run every given time frame. Catches any Throwable and logs it so
+ * that the scheduling doesn't break
*/
@PostConstruct
public void start() {
LOGGER.info("Starting {}", this.action.getClass().getSimpleName());
- final Runnable exceptionSafeRunnable = () -> {
- try {
- this.action.run();
- } catch (final Throwable ex) {
- LOGGER.error("Error when executing action {}", action.getClass().getSimpleName());
- LOGGER.error("Error when executing action", ex);
- }
- };
+ final Runnable exceptionSafeRunnable =
+ () -> {
+ try {
+ LOGGER.debug("{} has started running", getClass().getSimpleName());
+
+ this.action.run();
+ } catch (final Throwable ex) {
+ LOGGER.error("Error when executing action {}", action.getClass().getSimpleName());
+ LOGGER.error("Error when executing action", ex);
+ } finally {
+ LOGGER.debug("{} has finished running", getClass().getSimpleName());
+ }
+ };
this.executor.scheduleWithFixedDelay(exceptionSafeRunnable, initialDelay, rate, TimeUnit.MILLISECONDS);
@@ -60,8 +62,8 @@ public class TesseraScheduledExecutor {
}
/**
- * Stops any more executions of the submitted task from running
- * Does not cancel the currently running task, which may be blocking
+ * Stops any more executions of the submitted task from running. Does not cancel the currently running task, which
+ * may be blocking
*/
@PreDestroy
public void stop() {
@@ -71,5 +73,4 @@ public class TesseraScheduledExecutor {
LOGGER.info("Stopped {}", this.action.getClass().getSimpleName());
}
-
}
diff --git a/tessera-partyinfo/src/main/java/com/quorum/tessera/partyinfo/PartyInfoPoller.java b/tessera-partyinfo/src/main/java/com/quorum/tessera/partyinfo/PartyInfoPoller.java
index 14787ec66..35f45250e 100644
--- a/tessera-partyinfo/src/main/java/com/quorum/tessera/partyinfo/PartyInfoPoller.java
+++ b/tessera-partyinfo/src/main/java/com/quorum/tessera/partyinfo/PartyInfoPoller.java
@@ -5,11 +5,10 @@ import com.quorum.tessera.partyinfo.model.PartyInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.net.ConnectException;
import java.util.Objects;
/**
- * Polls every so often to all known nodes for any new discoverable nodes This keeps all nodes up-to date and
+ * Polls every so often to all known nodes for any new discoverable nodes. This keeps all nodes up-to date and
* discoverable by other nodes
*/
public class PartyInfoPoller implements Runnable {
@@ -22,7 +21,7 @@ public class PartyInfoPoller implements Runnable {
private final P2pClient p2pClient;
- public PartyInfoPoller(PartyInfoService partyInfoService, P2pClient p2pClient) {
+ public PartyInfoPoller(final PartyInfoService partyInfoService, final P2pClient p2pClient) {
this(partyInfoService, PartyInfoParser.create(), p2pClient);
}
@@ -47,18 +46,15 @@ public class PartyInfoPoller implements Runnable {
*/
@Override
public void run() {
- LOGGER.debug("Polling {}", getClass().getSimpleName());
-
final PartyInfo partyInfo = partyInfoService.getPartyInfo();
-
final byte[] encodedPartyInfo = partyInfoParser.to(partyInfo);
+ final String ourUrl = partyInfo.getUrl();
+
partyInfo.getParties().stream()
- .filter(party -> !party.getUrl().equals(partyInfo.getUrl()))
.map(Party::getUrl)
+ .filter(url -> !ourUrl.equals(url))
.forEach(url -> pollSingleParty(url, encodedPartyInfo));
-
- LOGGER.debug("Polled {}. PartyInfo : {}", getClass().getSimpleName(), partyInfo);
}
/**
@@ -68,19 +64,11 @@ public class PartyInfoPoller implements Runnable {
* @param encodedPartyInfo the encoded current party information
*/
private void pollSingleParty(final String url, final byte[] encodedPartyInfo) {
-
try {
p2pClient.sendPartyInfo(url, encodedPartyInfo);
} catch (final Exception ex) {
-
- if (ConnectException.class.isInstance(ex.getCause())) {
- LOGGER.warn("Server error {} when connecting to {}", ex.getMessage(), url);
- LOGGER.debug(null, ex);
- } else {
- LOGGER.error("Error {} while executing poller for {}. ", ex.getMessage(), url);
- LOGGER.debug(null, ex);
- throw ex;
- }
+ LOGGER.warn("Error {} when connecting to {}", ex.getMessage(), url);
+ LOGGER.debug(null, ex);
}
}
}
diff --git a/tessera-partyinfo/src/test/java/com/quorum/tessera/partyinfo/PartyInfoPollerTest.java b/tessera-partyinfo/src/test/java/com/quorum/tessera/partyinfo/PartyInfoPollerTest.java
index 65d244e1c..484573b5e 100644
--- a/tessera-partyinfo/src/test/java/com/quorum/tessera/partyinfo/PartyInfoPollerTest.java
+++ b/tessera-partyinfo/src/test/java/com/quorum/tessera/partyinfo/PartyInfoPollerTest.java
@@ -6,7 +6,9 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import java.net.ConnectException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
@@ -20,6 +22,8 @@ public class PartyInfoPollerTest {
private static final String TARGET_URL = "http://bogus.com:9878/";
+ private static final String TARGET_URL_2 = "http://otherwebsite.com:9878/";
+
private static final byte[] DATA = "BOGUS".getBytes();
private PartyInfoService partyInfoService;
@@ -35,6 +39,9 @@ public class PartyInfoPollerTest {
this.partyInfoService = mock(PartyInfoService.class);
this.partyInfoParser = mock(PartyInfoParser.class);
this.p2pClient = mock(P2pClient.class);
+
+ when(partyInfoParser.to(any(PartyInfo.class))).thenReturn(DATA);
+
this.partyInfoPoller = new PartyInfoPoller(partyInfoService, partyInfoParser, p2pClient);
}
@@ -45,109 +52,43 @@ public class PartyInfoPollerTest {
@Test
public void run() {
-
- doReturn(true).when(p2pClient).sendPartyInfo(TARGET_URL, DATA);
-
final PartyInfo partyInfo = new PartyInfo(OWN_URL, emptySet(), singleton(new Party(TARGET_URL)));
doReturn(partyInfo).when(partyInfoService).getPartyInfo();
-
- doReturn(DATA).when(partyInfoParser).to(partyInfo);
-
- final PartyInfo updatedPartyInfo = new PartyInfo(OWN_URL, emptySet(), singleton(new Party(TARGET_URL)));
- doReturn(updatedPartyInfo).when(partyInfoParser).from(DATA);
+ doReturn(true).when(p2pClient).sendPartyInfo(TARGET_URL, DATA);
partyInfoPoller.run();
verify(partyInfoService).getPartyInfo();
-
verify(partyInfoParser).to(partyInfo);
-
verify(p2pClient).sendPartyInfo(TARGET_URL, DATA);
}
@Test
public void testWhenURLIsOwn() {
-
- doReturn(true).when(p2pClient).sendPartyInfo(OWN_URL, DATA);
-
final PartyInfo partyInfo = new PartyInfo(OWN_URL, emptySet(), singleton(new Party(OWN_URL)));
doReturn(partyInfo).when(partyInfoService).getPartyInfo();
doReturn(DATA).when(partyInfoParser).to(partyInfo);
-
- final PartyInfo updatedPartyInfo = mock(PartyInfo.class);
- doReturn(updatedPartyInfo).when(partyInfoParser).from(DATA);
-
- partyInfoPoller.run();
-
- verify(partyInfoParser).to(partyInfo);
- verify(partyInfoService).getPartyInfo();
- }
-
- @Test
- public void testWhenPostFails() {
-
- doReturn(false).when(p2pClient).sendPartyInfo(TARGET_URL, DATA);
-
- final PartyInfo partyInfo = new PartyInfo(OWN_URL, emptySet(), singleton(new Party(TARGET_URL)));
-
- doReturn(partyInfo).when(partyInfoService).getPartyInfo();
- doReturn(DATA).when(partyInfoParser).to(partyInfo);
-
- final PartyInfo updatedPartyInfo = mock(PartyInfo.class);
- doReturn(updatedPartyInfo).when(partyInfoParser).from(DATA);
+ doReturn(true).when(p2pClient).sendPartyInfo(OWN_URL, DATA);
partyInfoPoller.run();
- verify(partyInfoParser, never()).from(DATA);
verify(partyInfoParser).to(partyInfo);
verify(partyInfoService).getPartyInfo();
- verify(p2pClient).sendPartyInfo(TARGET_URL, DATA);
}
@Test
- public void runThrowsException() {
-
- final PartyInfo partyInfo = new PartyInfo(OWN_URL, emptySet(), singleton(new Party(TARGET_URL)));
-
+ public void exceptionThrowByPostDoesntBubble() {
+ final Set<Party> parties = new HashSet<>(Arrays.asList(new Party(TARGET_URL), new Party(TARGET_URL_2)));
+ final PartyInfo partyInfo = new PartyInfo(OWN_URL, emptySet(), parties);
doReturn(partyInfo).when(partyInfoService).getPartyInfo();
- doReturn(DATA).when(partyInfoParser).to(partyInfo);
-
- PartyInfo updatedPartyInfo = mock(PartyInfo.class);
- doReturn(updatedPartyInfo).when(partyInfoParser).from(DATA);
-
doThrow(UnsupportedOperationException.class).when(p2pClient).sendPartyInfo(TARGET_URL, DATA);
final Throwable throwable = catchThrowable(partyInfoPoller::run);
- assertThat(throwable).isInstanceOf(UnsupportedOperationException.class);
-
- verify(p2pClient).sendPartyInfo(TARGET_URL, DATA);
-
- verify(partyInfoService).getPartyInfo();
- verify(partyInfoService, never()).updatePartyInfo(updatedPartyInfo);
- verify(partyInfoParser, never()).from(DATA);
- verify(partyInfoParser).to(partyInfo);
- }
-
- @Test
- public void runThrowsConnectionExceptionAndDoesNotThrow() {
-
- final PartyInfo partyInfo = new PartyInfo(OWN_URL, emptySet(), singleton(new Party(TARGET_URL)));
-
- doReturn(partyInfo).when(partyInfoService).getPartyInfo();
- doReturn(DATA).when(partyInfoParser).to(partyInfo);
-
- final PartyInfo updatedPartyInfo = mock(PartyInfo.class);
- doReturn(updatedPartyInfo).when(partyInfoParser).from(DATA);
-
- final RuntimeException connectionException = new RuntimeException(new ConnectException("OUCH"));
- doThrow(connectionException).when(p2pClient).sendPartyInfo(TARGET_URL, DATA);
-
- partyInfoPoller.run();
+ assertThat(throwable).isNull();
verify(p2pClient).sendPartyInfo(TARGET_URL, DATA);
-
+ verify(p2pClient).sendPartyInfo(TARGET_URL_2, DATA);
verify(partyInfoService).getPartyInfo();
- verify(partyInfoParser, never()).from(DATA);
verify(partyInfoParser).to(partyInfo);
}
| ['tessera-partyinfo/src/main/java/com/quorum/tessera/partyinfo/PartyInfoPoller.java', 'tessera-core/src/main/java/com/quorum/tessera/threading/TesseraScheduledExecutor.java', 'tessera-partyinfo/src/test/java/com/quorum/tessera/partyinfo/PartyInfoPollerTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 747,754 | 148,303 | 23,202 | 416 | 3,697 | 672 | 69 | 2 | 807 | 135 | 154 | 7 | 0 | 0 | 1970-01-01T00:26:04 | 162 | Java | {'Java': 3402794, 'Gherkin': 11338, 'Shell': 6831, 'Dockerfile': 5224, 'XSLT': 3932, 'JavaScript': 3693, 'Groovy': 1175, 'HCL': 257} | Apache License 2.0 |
1,173 | consensys/tessera/896/895 | consensys | tessera | https://github.com/Consensys/tessera/issues/895 | https://github.com/Consensys/tessera/pull/896 | https://github.com/Consensys/tessera/pull/896 | 1 | fixes | Cannot send raw transactions with no other private participants | When sending a raw transaction with no recipients, the transaction failed to be retrieved. This is caused by the fact we have no recipient public key to decrypt with.
For regular transactions, we add ourselves as a recipient for exactly this case, and the same should be done for raw transactions. | 07066da23f0575ce5d88e013856173af1de61830 | 7456134bf0ffb75679c3cbc735d876cd302d0d3e | https://github.com/consensys/tessera/compare/07066da23f0575ce5d88e013856173af1de61830...7456134bf0ffb75679c3cbc735d876cd302d0d3e | diff --git a/tessera-core/src/main/java/com/quorum/tessera/transaction/TransactionManagerImpl.java b/tessera-core/src/main/java/com/quorum/tessera/transaction/TransactionManagerImpl.java
index 73008b79b..ca2eb294f 100644
--- a/tessera-core/src/main/java/com/quorum/tessera/transaction/TransactionManagerImpl.java
+++ b/tessera-core/src/main/java/com/quorum/tessera/transaction/TransactionManagerImpl.java
@@ -72,7 +72,7 @@ public class TransactionManagerImpl implements TransactionManager {
}
/*
- Only sue for tests
+ Only use for tests
*/
public TransactionManagerImpl(
Base64Decoder base64Decoder,
@@ -149,7 +149,7 @@ public class TransactionManagerImpl implements TransactionManager {
@Override
@Transactional
- public SendResponse sendSignedTransaction(SendSignedRequest sendRequest) {
+ public SendResponse sendSignedTransaction(final SendSignedRequest sendRequest) {
final byte[][] recipients =
Stream.of(sendRequest)
@@ -162,7 +162,7 @@ public class TransactionManagerImpl implements TransactionManager {
recipientList.addAll(enclave.getForwardingKeys());
- MessageHash messageHash = new MessageHash(sendRequest.getHash());
+ final MessageHash messageHash = new MessageHash(sendRequest.getHash());
EncryptedRawTransaction encryptedRawTransaction =
encryptedRawTransactionDAO
@@ -172,6 +172,8 @@ public class TransactionManagerImpl implements TransactionManager {
new TransactionNotFoundException(
"Raw Transaction with hash " + messageHash + " was not found"));
+ recipientList.add(PublicKey.from(encryptedRawTransaction.getSender()));
+
final EncodedPayload payload =
enclave.encryptPayload(encryptedRawTransaction.toRawTransaction(), recipientList);
diff --git a/tessera-core/src/test/java/com/quorum/tessera/transaction/TransactionManagerTest.java b/tessera-core/src/test/java/com/quorum/tessera/transaction/TransactionManagerTest.java
index 82708bf9c..4dab10e18 100644
--- a/tessera-core/src/test/java/com/quorum/tessera/transaction/TransactionManagerTest.java
+++ b/tessera-core/src/test/java/com/quorum/tessera/transaction/TransactionManagerTest.java
@@ -151,10 +151,12 @@ public class TransactionManagerTest {
verify(enclave).encryptPayload(any(RawTransaction.class), any());
verify(payloadEncoder).encode(payload);
- verify(payloadEncoder).forRecipient(any(EncodedPayload.class), any(PublicKey.class));
+ verify(payloadEncoder).forRecipient(any(EncodedPayload.class), eq(PublicKey.from("SENDER".getBytes())));
+ verify(payloadEncoder).forRecipient(any(EncodedPayload.class), eq(PublicKey.from("RECEIVER".getBytes())));
verify(encryptedTransactionDAO).save(any(EncryptedTransaction.class));
verify(encryptedRawTransactionDAO).retrieveByHash(any(MessageHash.class));
- verify(partyInfoService).publishPayload(any(EncodedPayload.class), any(PublicKey.class));
+ verify(partyInfoService).publishPayload(any(EncodedPayload.class), eq(PublicKey.from("SENDER".getBytes())));
+ verify(partyInfoService).publishPayload(any(EncodedPayload.class), eq(PublicKey.from("RECEIVER".getBytes())));
verify(enclave).getForwardingKeys();
}
diff --git a/tessera-jaxrs/thirdparty-jaxrs/src/main/java/com/quorum/tessera/thirdparty/RawTransactionResource.java b/tessera-jaxrs/thirdparty-jaxrs/src/main/java/com/quorum/tessera/thirdparty/RawTransactionResource.java
index b8a86a7cb..c7032b975 100644
--- a/tessera-jaxrs/thirdparty-jaxrs/src/main/java/com/quorum/tessera/thirdparty/RawTransactionResource.java
+++ b/tessera-jaxrs/thirdparty-jaxrs/src/main/java/com/quorum/tessera/thirdparty/RawTransactionResource.java
@@ -1,6 +1,7 @@
package com.quorum.tessera.thirdparty;
-import com.quorum.tessera.api.model.*;
+import com.quorum.tessera.api.model.StoreRawRequest;
+import com.quorum.tessera.api.model.StoreRawResponse;
import com.quorum.tessera.core.api.ServiceFactory;
import com.quorum.tessera.transaction.TransactionManager;
import io.swagger.annotations.ApiOperation;
@@ -12,12 +13,14 @@ import org.slf4j.LoggerFactory;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
-import javax.ws.rs.*;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
import java.util.Objects;
-import static javax.ws.rs.core.MediaType.*;
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
/** Provides endpoints for dealing with raw transactions */
@Path("/")
@@ -25,13 +28,15 @@ public class RawTransactionResource {
private static final Logger LOGGER = LoggerFactory.getLogger(RawTransactionResource.class);
+ public static final String ENDPOINT_STORE_RAW = "storeraw";
+
private final TransactionManager delegate;
public RawTransactionResource() {
this(ServiceFactory.create().transactionManager());
}
- public RawTransactionResource(TransactionManager delegate) {
+ public RawTransactionResource(final TransactionManager delegate) {
this.delegate = Objects.requireNonNull(delegate);
}
@@ -41,15 +46,13 @@ public class RawTransactionResource {
@ApiResponse(code = 400, message = "For unknown sender")
})
@POST
- @Path("storeraw")
+ @Path(ENDPOINT_STORE_RAW)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response store(
- @ApiParam(name = "storeRawRequest", required = true) @NotNull @Valid
- final StoreRawRequest storeRawRequest) {
-
- final StoreRawResponse response = delegate.store(storeRawRequest);
+ @ApiParam(name = "storeRawRequest", required = true) @NotNull @Valid final StoreRawRequest request) {
+ final StoreRawResponse response = delegate.store(request);
- return Response.status(Status.OK).type(APPLICATION_JSON).entity(response).build();
+ return Response.ok().type(APPLICATION_JSON).entity(response).build();
}
}
diff --git a/tessera-jaxrs/thirdparty-jaxrs/src/test/java/com/quorum/tessera/thirdparty/RawTransactionResourceTest.java b/tessera-jaxrs/thirdparty-jaxrs/src/test/java/com/quorum/tessera/thirdparty/RawTransactionResourceTest.java
index 4ff1488f3..47a0b645c 100644
--- a/tessera-jaxrs/thirdparty-jaxrs/src/test/java/com/quorum/tessera/thirdparty/RawTransactionResourceTest.java
+++ b/tessera-jaxrs/thirdparty-jaxrs/src/test/java/com/quorum/tessera/thirdparty/RawTransactionResourceTest.java
@@ -1,6 +1,5 @@
package com.quorum.tessera.thirdparty;
-import com.quorum.tessera.thirdparty.RawTransactionResource;
import com.quorum.tessera.api.model.StoreRawRequest;
import com.quorum.tessera.transaction.TransactionManager;
import org.junit.After;
@@ -10,7 +9,6 @@ import org.junit.Test;
import javax.ws.rs.core.Response;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.*;
public class RawTransactionResourceTest {
@@ -21,8 +19,9 @@ public class RawTransactionResourceTest {
@Before
public void onSetup() {
- transactionManager = mock(TransactionManager.class);
- transactionResource = new RawTransactionResource(transactionManager);
+ this.transactionManager = mock(TransactionManager.class);
+
+ this.transactionResource = new RawTransactionResource(transactionManager);
}
@After
@@ -32,12 +31,12 @@ public class RawTransactionResourceTest {
@Test
public void store() {
- StoreRawRequest storeRawRequest = new StoreRawRequest();
+ final StoreRawRequest storeRawRequest = new StoreRawRequest();
storeRawRequest.setPayload("PAYLOAD".getBytes());
- Response result = transactionResource.store(storeRawRequest);
- assertThat(result.getStatus()).isEqualTo(200);
+ final Response result = transactionResource.store(storeRawRequest);
- verify(transactionManager).store(same(storeRawRequest));
+ assertThat(result.getStatus()).isEqualTo(200);
+ verify(transactionManager).store(storeRawRequest);
}
} | ['tessera-jaxrs/thirdparty-jaxrs/src/main/java/com/quorum/tessera/thirdparty/RawTransactionResource.java', 'tessera-core/src/main/java/com/quorum/tessera/transaction/TransactionManagerImpl.java', 'tessera-core/src/test/java/com/quorum/tessera/transaction/TransactionManagerTest.java', 'tessera-jaxrs/thirdparty-jaxrs/src/test/java/com/quorum/tessera/thirdparty/RawTransactionResourceTest.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 758,752 | 150,619 | 23,427 | 423 | 1,717 | 346 | 33 | 2 | 300 | 51 | 57 | 3 | 0 | 0 | 1970-01-01T00:26:10 | 162 | Java | {'Java': 3402794, 'Gherkin': 11338, 'Shell': 6831, 'Dockerfile': 5224, 'XSLT': 3932, 'JavaScript': 3693, 'Groovy': 1175, 'HCL': 257} | Apache License 2.0 |
1,171 | consensys/tessera/1179/1178 | consensys | tessera | https://github.com/Consensys/tessera/issues/1178 | https://github.com/Consensys/tessera/pull/1179 | https://github.com/Consensys/tessera/pull/1179 | 1 | fixes | Tessera Peer Discovery - Exclude 'Self' as active 'configured peer list' in Partystore | When a node has intermittent connection drop from a network it will drop all connection to the network and repopulates 'Partystore' from configured peer list to reestablish connection. But if 'self' url is also in the configured peer list, it will be fooled to believe it is connected to at least 1 active peer list and will not establish connection back to the network. This change is to exclude 'self' as active configured peer. | f5e3c20dbc18ad02098e71373debc525bbb7bb5b | 66013acf54f6dc125b9018e52b2a89fbad5eac53 | https://github.com/consensys/tessera/compare/f5e3c20dbc18ad02098e71373debc525bbb7bb5b...66013acf54f6dc125b9018e52b2a89fbad5eac53 | diff --git a/tessera-jaxrs/sync-jaxrs/src/main/java/com/quorum/tessera/p2p/partyinfo/PartyStore.java b/tessera-jaxrs/sync-jaxrs/src/main/java/com/quorum/tessera/p2p/partyinfo/PartyStore.java
index f51bb93f7..8c0971a39 100644
--- a/tessera-jaxrs/sync-jaxrs/src/main/java/com/quorum/tessera/p2p/partyinfo/PartyStore.java
+++ b/tessera-jaxrs/sync-jaxrs/src/main/java/com/quorum/tessera/p2p/partyinfo/PartyStore.java
@@ -6,6 +6,7 @@ import com.quorum.tessera.discovery.NodeUri;
import java.net.URI;
import java.util.ServiceLoader;
import java.util.Set;
+import java.util.stream.Collectors;
/*
* Support legacy collation of all parties to be added to
@@ -18,12 +19,17 @@ public interface PartyStore {
final Set<URI> parties = getParties();
- if (parties.isEmpty()
- || !runtimeContext.getPeers().stream()
+ final URI ownUri = NodeUri.create(runtimeContext.getP2pServerUri()).asURI();
+
+ final Set<URI> peerList =
+ runtimeContext.getPeers().stream()
.map(NodeUri::create)
.map(NodeUri::asURI)
- .anyMatch(parties::contains)) {
- runtimeContext.getPeers().forEach(this::store);
+ .filter(p -> !p.equals(ownUri))
+ .collect(Collectors.toUnmodifiableSet());
+
+ if (parties.isEmpty() || !peerList.stream().anyMatch(parties::contains)) {
+ peerList.forEach(this::store);
}
}
diff --git a/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/MockRuntimeContextFactory.java b/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/MockRuntimeContextFactory.java
index 45b3682e4..04d2ed4db 100644
--- a/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/MockRuntimeContextFactory.java
+++ b/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/MockRuntimeContextFactory.java
@@ -5,22 +5,13 @@ import com.quorum.tessera.context.ContextHolder;
import com.quorum.tessera.context.RuntimeContext;
import com.quorum.tessera.context.RuntimeContextFactory;
-import java.net.URI;
-import java.util.List;
import java.util.Optional;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
public class MockRuntimeContextFactory implements RuntimeContextFactory<Config>, ContextHolder {
static ThreadLocal<RuntimeContext> runtimeContextThreadLocal =
- ThreadLocal.withInitial(
- () -> {
- RuntimeContext mockContext = mock(RuntimeContext.class);
- when(mockContext.getP2pServerUri()).thenReturn(URI.create("http://own.com/"));
- when(mockContext.getPeers()).thenReturn(List.of(URI.create("http://peer.com/")));
- return mockContext;
- });
+ ThreadLocal.withInitial(() -> mock(RuntimeContext.class));
@Override
public void setContext(RuntimeContext runtimeContext) {
diff --git a/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/P2PRestAppTest.java b/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/P2PRestAppTest.java
index 842329d05..0a340c1e1 100644
--- a/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/P2PRestAppTest.java
+++ b/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/P2PRestAppTest.java
@@ -19,7 +19,9 @@ import org.junit.Test;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Application;
+import java.net.URI;
import java.util.HashSet;
+import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
@@ -44,6 +46,8 @@ public class P2PRestAppTest {
Client client = mock(Client.class);
when(runtimeContext.getP2pClient()).thenReturn(client);
when(runtimeContext.isRemoteKeyValidation()).thenReturn(true);
+ when(runtimeContext.getP2pServerUri()).thenReturn(URI.create("http://own.com/"));
+ when(runtimeContext.getPeers()).thenReturn(List.of(URI.create("http://peer.com/")));
MockServiceLocator serviceLocator = (MockServiceLocator) ServiceLocator.create();
serviceLocator.setServices(services);
@@ -77,7 +81,10 @@ public class P2PRestAppTest {
o ->
assertThat(o)
.isInstanceOfAny(
- PartyInfoResource.class, IPWhitelistFilter.class, UpCheckResource.class, TransactionResource.class));
+ PartyInfoResource.class,
+ IPWhitelistFilter.class,
+ UpCheckResource.class,
+ TransactionResource.class));
}
@Test
@@ -90,7 +97,10 @@ public class P2PRestAppTest {
o ->
assertThat(o)
.isInstanceOfAny(
- PartyInfoResource.class, IPWhitelistFilter.class, UpCheckResource.class, RecoveryResource.class));
+ PartyInfoResource.class,
+ IPWhitelistFilter.class,
+ UpCheckResource.class,
+ RecoveryResource.class));
}
@Test
diff --git a/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/partyinfo/PartyStoreFactoryTest.java b/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/partyinfo/PartyStoreFactoryTest.java
index c7036caa1..232fd1b98 100644
--- a/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/partyinfo/PartyStoreFactoryTest.java
+++ b/tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/partyinfo/PartyStoreFactoryTest.java
@@ -1,9 +1,9 @@
package com.quorum.tessera.p2p.partyinfo;
+import com.quorum.tessera.config.Config;
import com.quorum.tessera.context.RuntimeContext;
-import com.quorum.tessera.p2p.partyinfo.PartyStore;
-import com.quorum.tessera.p2p.partyinfo.PartyStoreFactory;
-import com.quorum.tessera.p2p.partyinfo.SimplePartyStore;
+import com.quorum.tessera.context.RuntimeContextFactory;
+import com.quorum.tessera.discovery.NodeUri;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -22,10 +22,15 @@ public class PartyStoreFactoryTest {
private PartyStore partyStore;
+ static final RuntimeContext runtimeContext = RuntimeContextFactory.newFactory().create(mock(Config.class));
+
@Before
public void beforeTest() {
partyStore = mock(PartyStore.class);
partyStoreFactory = new PartyStoreFactory(partyStore);
+
+ when(runtimeContext.getP2pServerUri()).thenReturn(URI.create("http://own.com/"));
+ when(runtimeContext.getPeers()).thenReturn(List.of(URI.create("http://peer.com/")));
}
@After
@@ -60,7 +65,21 @@ public class PartyStoreFactoryTest {
partyStoreFactory.loadFromConfigIfEmpty();
verify(partyStore).getParties();
- verify(partyStore).store(RuntimeContext.getInstance().getPeers().get(0));
+ verify(partyStore).store(runtimeContext.getPeers().get(0));
+ }
+
+ @Test
+ public void whenPeerListContainsSelf() {
+
+ when(runtimeContext.getPeers())
+ .thenReturn(List.of(URI.create("http://peer.com/"), URI.create("http://own.com/")));
+
+ when(partyStore.getParties()).thenReturn(Set.of(URI.create("http://own.com/")));
+
+ partyStoreFactory.loadFromConfigIfEmpty();
+
+ verify(partyStore).getParties();
+ verify(partyStore).store(NodeUri.create("http://peer.com/").asURI());
}
@Test
@@ -70,7 +89,7 @@ public class PartyStoreFactoryTest {
partyStoreFactory.loadFromConfigIfEmpty();
verify(partyStore).getParties();
- verify(partyStore).store(RuntimeContext.getInstance().getPeers().get(0));
+ verify(partyStore).store(runtimeContext.getPeers().get(0));
}
@Test
@@ -87,13 +106,12 @@ public class PartyStoreFactoryTest {
when(partyStore.getParties()).thenReturn(Set.of(URI.create("http://peer.com/")));
- when(RuntimeContext.getInstance().getPeers()).thenReturn(List.of(URI.create("http://peer.com")));
+ when(runtimeContext.getPeers()).thenReturn(List.of(URI.create("http://peer.com")));
partyStoreFactory.loadFromConfigIfEmpty();
verify(partyStore).getParties();
verify(partyStore, times(0)).store(any());
-
}
@Test | ['tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/partyinfo/PartyStoreFactoryTest.java', 'tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/MockRuntimeContextFactory.java', 'tessera-jaxrs/sync-jaxrs/src/test/java/com/quorum/tessera/p2p/P2PRestAppTest.java', 'tessera-jaxrs/sync-jaxrs/src/main/java/com/quorum/tessera/p2p/partyinfo/PartyStore.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 1,004,470 | 195,002 | 30,134 | 537 | 670 | 135 | 14 | 1 | 430 | 74 | 89 | 1 | 0 | 0 | 1970-01-01T00:26:44 | 162 | Java | {'Java': 3402794, 'Gherkin': 11338, 'Shell': 6831, 'Dockerfile': 5224, 'XSLT': 3932, 'JavaScript': 3693, 'Groovy': 1175, 'HCL': 257} | Apache License 2.0 |
9,300 | mercedes-benz/sechub/2015/2014 | mercedes-benz | sechub | https://github.com/mercedes-benz/sechub/issues/2014 | https://github.com/mercedes-benz/sechub/pull/2015 | https://github.com/mercedes-benz/sechub/pull/2015 | 1 | closes | Code call hierarchy not shown for scans of type `secretScan` | ## Situation
Code call hierarchy not shown for scans of type `secretScan` - in JSON and also in HTML reports
## Wanted
In both reports the information shall be available | 12bd02b6d11e9cc5b6db82f27ffbbfa9942e62d6 | 3b5bf071b0375c872c88f75a1642a6ac2f5b5620 | https://github.com/mercedes-benz/sechub/compare/12bd02b6d11e9cc5b6db82f27ffbbfa9942e62d6...3b5bf071b0375c872c88f75a1642a6ac2f5b5620 | diff --git a/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AssertReport.java b/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AssertReport.java
index 1873078e8..cfe1fa0ee 100644
--- a/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AssertReport.java
+++ b/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AssertReport.java
@@ -207,6 +207,14 @@ public class AssertReport {
return this;
}
+ public AssertFinding hasNoCweId() {
+ if (finding.getCweId() != null) {
+ dump();
+ autoDumper.execute(() -> fail("CWE id found inside finding:" + finding.getCweId()));
+ }
+ return this;
+ }
+
public AssertCodeCall codeCall(int level) {
int currentLevel = 0;
SecHubCodeCallStack code = finding.getCode();
diff --git a/sechub-integrationtest/src/test/java/com/mercedesbenz/sechub/integrationtest/scenario20/PDSSecretScanJobScenario20IntTest.java b/sechub-integrationtest/src/test/java/com/mercedesbenz/sechub/integrationtest/scenario20/PDSSecretScanJobScenario20IntTest.java
index 3848c4c2f..e21bbd835 100644
--- a/sechub-integrationtest/src/test/java/com/mercedesbenz/sechub/integrationtest/scenario20/PDSSecretScanJobScenario20IntTest.java
+++ b/sechub-integrationtest/src/test/java/com/mercedesbenz/sechub/integrationtest/scenario20/PDSSecretScanJobScenario20IntTest.java
@@ -21,6 +21,7 @@ import com.mercedesbenz.sechub.integrationtest.api.TestProject;
import com.mercedesbenz.sechub.integrationtest.internal.IntegrationTestFileSupport;
public class PDSSecretScanJobScenario20IntTest {
+
public static final String PATH = "pds/secretscan/upload/zipfile_contains_inttest_secretscan_with_gitleaks_sample_sarif.json.zip";
@Rule
@@ -53,8 +54,15 @@ public class PDSSecretScanJobScenario20IntTest {
hasTrafficLight(GREEN).
hasFindings(6).
finding(0).
- hasScanType(ScanType.SECRET_SCAN).
- hasDescription("generic-api-key has detected secret for file UnSAFE_Bank/Backend/docker-compose.yml.");
+ hasScanType(ScanType.SECRET_SCAN).
+ hasDescription("generic-api-key has detected secret for file UnSAFE_Bank/Backend/docker-compose.yml.").
+ codeCall(0).
+ hasColumn(14).
+ hasLine(12).
+ hasSource("531486b2bf646636a6a1bba61e78ec4a4a54efbd").
+ hasLocation("UnSAFE_Bank/Backend/docker-compose.yml").
+ andFinding().
+ hasNoCweId();// the results are from gitleaks product, which does not include CWE information
/* @formatter:on */
}
}
diff --git a/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java b/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java
index 1dced2477..4469ef40e 100644
--- a/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java
+++ b/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java
@@ -109,6 +109,7 @@ public class SerecoProductResultTransformer implements ReportProductResultTransf
}
switch (scanType) {
case CODE_SCAN:
+ case SECRET_SCAN:
finding.setCode(convert(vulnerability.getCode()));
break;
case INFRA_SCAN:
diff --git a/sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformerTest.java b/sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformerTest.java
index f51377402..817801522 100644
--- a/sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformerTest.java
+++ b/sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformerTest.java
@@ -50,6 +50,42 @@ public class SerecoProductResultTransformerTest {
AssertSecHubResult.assertSecHubResult(result.getResult()).hasFindings(1);
}
+ @Test
+ public void one_vulnerability_as_secret_in_meta_results_in_one_finding() throws Exception {
+ /* prepare */
+ String converted = createMetaDataWithOneVulnerabilityAsSecretFound();
+
+ /* execute */
+ ReportTransformationResult result = transformerToTest.transform(createProductResult(converted));
+
+ /* test */
+ SecHubResult sechubResult = result.getResult();
+ for (SecHubFinding finding : sechubResult.getFindings()) {
+ assertEquals(ScanType.SECRET_SCAN, finding.getType());
+ }
+
+ AssertSecHubResult.assertSecHubResult(sechubResult).hasFindings(1);
+ SecHubFinding finding1 = sechubResult.getFindings().get(0);
+ assertEquals(Integer.valueOf(4711), finding1.getCweId());
+
+ SecHubCodeCallStack code1 = finding1.getCode();
+ assertNotNull(code1);
+ assertEquals(Integer.valueOf(1), code1.getLine());
+ assertEquals(Integer.valueOf(2), code1.getColumn());
+ assertEquals("Location1", code1.getLocation());
+ assertEquals("source1", code1.getSource());
+ assertEquals("relevantPart1", code1.getRelevantPart());
+
+ SecHubCodeCallStack code2 = code1.getCalls();
+ assertNotNull(code2);
+ assertEquals(Integer.valueOf(3), code2.getLine());
+ assertEquals(Integer.valueOf(4), code2.getColumn());
+ assertEquals("Location2", code2.getLocation());
+ assertEquals("source2", code2.getSource());
+ assertEquals("relevantPart2", code2.getRelevantPart());
+
+ }
+
@Test
public void one_vulnerability_as_code_in_meta_results_in_one_finding() throws Exception {
/* prepare */
@@ -66,6 +102,7 @@ public class SerecoProductResultTransformerTest {
AssertSecHubResult.assertSecHubResult(sechubResult).hasFindings(1);
SecHubFinding finding1 = sechubResult.getFindings().get(0);
+ assertEquals(Integer.valueOf(4711), finding1.getCweId());
SecHubCodeCallStack code1 = finding1.getCode();
assertNotNull(code1);
@@ -195,13 +232,21 @@ public class SerecoProductResultTransformerTest {
}
private String createMetaDataWithOneVulnerabilityAsCodeFound() {
+ return createMetaDataWithOneVulnerability(ScanType.CODE_SCAN);
+ }
+
+ private String createMetaDataWithOneVulnerabilityAsSecretFound() {
+ return createMetaDataWithOneVulnerability(ScanType.SECRET_SCAN);
+ }
+
+ private String createMetaDataWithOneVulnerability(ScanType scanType) {
SerecoMetaData data = new SerecoMetaData();
List<SerecoVulnerability> vulnerabilities = data.getVulnerabilities();
SerecoVulnerability v1 = new SerecoVulnerability();
v1.setSeverity(SerecoSeverity.MEDIUM);
v1.setType("type1");
- v1.setScanType(ScanType.CODE_SCAN);
+ v1.setScanType(scanType);
SerecoCodeCallStackElement serecoCode1 = new SerecoCodeCallStackElement();
serecoCode1.setLine(1);
@@ -223,6 +268,7 @@ public class SerecoProductResultTransformerTest {
SerecoClassification cl = v1.getClassification();
cl.setCapec("capec1");
+ cl.setCwe("4711");
vulnerabilities.add(v1);
| ['sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformerTest.java', 'sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AssertReport.java', 'sechub-integrationtest/src/test/java/com/mercedesbenz/sechub/integrationtest/scenario20/PDSSecretScanJobScenario20IntTest.java', 'sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 3,638,634 | 752,614 | 104,284 | 1,603 | 30 | 5 | 1 | 1 | 174 | 30 | 36 | 5 | 0 | 0 | 1970-01-01T00:27:58 | 159 | Java | {'Java': 7354269, 'Shell': 285620, 'Go': 207604, 'Dockerfile': 58303, 'HTML': 27680, 'TypeScript': 17921, 'Groovy': 8898, 'CSS': 7405, 'Python': 7341, 'C': 748, 'Assembly': 401, 'Batchfile': 391, 'JavaScript': 312, 'Visual Basic .NET': 178, 'Ada': 169, 'Erlang': 140, 'OpenEdge ABL': 139, 'Fortran': 138, 'ABAP': 134, 'Ruby': 103, 'OCaml': 100, 'Scheme': 92, 'Tcl': 77} | MIT License |
358 | opencb/opencga/128/107 | opencb | opencga | https://github.com/opencb/opencga/issues/107 | https://github.com/opencb/opencga/pull/128 | https://github.com/opencb/opencga/pull/128 | 1 | fixes | Index from FileWSServer does not work properly | When we launch this WS the system stores the VCF into the DB but the annotation tool is not launched. We have the data but we do not have the annotations.
Then, when we use the Fetch WS we get a Null Pointer Exception.
``````
java.lang.NullPointerException
org.opencb.datastore.core.QueryResult.<init>(QueryResult.java:58)
org.opencb.opencga.storage.mongodb.variant.MongoDBStudyConfigurationManager.getStudyConfiguration(MongoDBStudyConfigurationManager.java:94)
org.opencb.opencga.storage.mongodb.variant.DBObjectToSamplesConverter.convertToDataModelType(DBObjectToSamplesConverter.java:135)
org.opencb.opencga.storage.mongodb.variant.DBObjectToVariantSourceEntryConverter.convertToDataModelType(DBObjectToVariantSourceEntryConverter.java:114)
org.opencb.opencga.storage.mongodb.variant.DBObjectToVariantConverter.convertToDataModelType(DBObjectToVariantConverter.java:133)
org.opencb.opencga.storage.mongodb.variant.DBObjectToVariantConverter.convertToDataModelType(DBObjectToVariantConverter.java:35)
org.opencb.datastore.mongodb.MongoDBCollection._find(MongoDBCollection.java:209)
org.opencb.datastore.mongodb.MongoDBCollection.find(MongoDBCollection.java:144)
org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.getAllVariants(VariantMongoDBAdaptor.java:117)
org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.getAllVariantsByRegionList(VariantMongoDBAdaptor.java:183)
org.opencb.opencga.server.FileWSServer.fetch(FileWSServer.java:789)
sun.reflect.GeneratedMethodAccessor67.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.process(Errors.java:267)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1030)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)```
``````
| a9364d48969e2965a7931d65f390f632da89e34a | 93740ba5547a116560b5d6f0c3ca69f223d028c5 | https://github.com/opencb/opencga/compare/a9364d48969e2965a7931d65f390f632da89e34a...93740ba5547a116560b5d6f0c3ca69f223d028c5 | diff --git a/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsCalculator.java b/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsCalculator.java
index 554f61d11e..6eb3f396a2 100644
--- a/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsCalculator.java
+++ b/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsCalculator.java
@@ -78,7 +78,7 @@ public class VariantStatisticsCalculator {
List<VariantStatsWrapper> variantStatsWrappers = new ArrayList<>(variants.size());
for (Variant variant : variants) {
- VariantSourceEntry file = variant.getSourceEntry(studyId, fileId);
+ VariantSourceEntry file = variant.getSourceEntry(fileId, studyId);
if (file == null) {
skippedFiles++;
continue;
diff --git a/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsManager.java b/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsManager.java
index 8a06ee0d48..69c69f657b 100644
--- a/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsManager.java
+++ b/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsManager.java
@@ -32,7 +32,6 @@ import org.opencb.opencga.storage.core.StudyConfiguration;
import org.opencb.opencga.storage.core.runner.StringDataWriter;
import org.opencb.opencga.storage.core.variant.VariantStorageManager;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor;
-import org.opencb.opencga.storage.core.variant.adaptors.VariantDBIterator;
import org.opencb.opencga.storage.core.variant.io.VariantDBReader;
import org.opencb.opencga.storage.core.variant.io.json.VariantStatsJsonMixin;
import org.slf4j.Logger;
@@ -51,7 +50,6 @@ import java.util.zip.GZIPOutputStream;
*/
public class VariantStatisticsManager {
- public static final String BATCH_SIZE = "batchSize";
private String VARIANT_STATS_SUFFIX = ".variants.stats.json.gz";
private String SOURCE_STATS_SUFFIX = ".source.stats.json.gz";
private final JsonFactory jsonFactory;
@@ -90,7 +88,7 @@ public class VariantStatisticsManager {
ObjectWriter sourceWriter = jsonObjectMapper.writerFor(VariantSourceStats.class);
/** Variables for statistics **/
- int batchSize = options.getInt(BATCH_SIZE, 1000); // future optimization, threads, etc
+ int batchSize = options.getInt(VariantStorageManager.BATCH_SIZE, 1000); // future optimization, threads, etc
boolean overwrite = options.getBoolean(VariantStorageManager.OVERWRITE_STATS, false);
List<Variant> variantBatch = new ArrayList<>(batchSize);
int retrievedVariants = 0;
@@ -199,18 +197,29 @@ public class VariantStatisticsManager {
int numTasks = 6;
int batchSize = 100; // future optimization, threads, etc
boolean overwrite = false;
+ String fileId;
if(options != null) { //Parse query options
- batchSize = options.getInt(BATCH_SIZE, batchSize);
+ batchSize = options.getInt(VariantStorageManager.BATCH_SIZE, batchSize);
+ numTasks = options.getInt(VariantStorageManager.LOAD_THREADS, numTasks);
overwrite = options.getBoolean(VariantStorageManager.OVERWRITE_STATS, overwrite);
+ fileId = options.getString(VariantStorageManager.FILE_ID);
+ } else {
+ logger.error("missing required fileId in QueryOptions");
+ throw new Exception("createStats: need a fileId to calculate stats from.");
}
-// reader, tasks and writer
+ VariantSourceStats variantSourceStats = new VariantSourceStats(fileId, Integer.toString(studyConfiguration.getStudyId()));
+
+
+ // reader, tasks and writer
VariantDBReader reader = new VariantDBReader(studyConfiguration, variantDBAdaptor, options);
List<ParallelTaskRunner.Task<Variant, String>> tasks = new ArrayList<>(numTasks);
for (int i = 0; i < numTasks; i++) {
- tasks.add(new VariantStatsWrapperTask(overwrite, samples, studyConfiguration, options.getString(VariantStorageManager.FILE_ID)));
+ tasks.add(new VariantStatsWrapperTask(overwrite, samples, studyConfiguration, fileId, variantSourceStats));
}
- StringDataWriter writer = new StringDataWriter(Paths.get(output.getPath() + VARIANT_STATS_SUFFIX));
+ Path variantStatsPath = Paths.get(output.getPath() + VARIANT_STATS_SUFFIX);
+ logger.info("will write stats to {}", variantStatsPath);
+ StringDataWriter writer = new StringDataWriter(variantStatsPath);
// runner
ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numTasks, batchSize, numTasks*2, false);
@@ -220,7 +229,14 @@ public class VariantStatisticsManager {
long start = System.currentTimeMillis();
runner.run();
logger.info("finishing stats creation, time: {}ms", System.currentTimeMillis() - start);
-
+
+ // source stats
+ Path fileSourcePath = Paths.get(output.getPath() + SOURCE_STATS_SUFFIX);
+ OutputStream outputSourceStream = getOutputStream(fileSourcePath, options);
+ ObjectWriter sourceWriter = jsonObjectMapper.writerFor(VariantSourceStats.class);
+ outputSourceStream.write(sourceWriter.writeValueAsBytes(variantSourceStats));
+ outputSourceStream.close();
+
return output;
}
@@ -232,32 +248,47 @@ public class VariantStatisticsManager {
private String fileId;
private ObjectMapper jsonObjectMapper;
private ObjectWriter variantsWriter;
+ private VariantSourceStats variantSourceStats;
- public VariantStatsWrapperTask(boolean overwrite, Map<String, Set<String>> samples, StudyConfiguration studyConfiguration, String fileId) {
+ public VariantStatsWrapperTask(boolean overwrite, Map<String, Set<String>> samples,
+ StudyConfiguration studyConfiguration, String fileId,
+ VariantSourceStats variantSourceStats) {
this.overwrite = overwrite;
this.samples = samples;
this.studyConfiguration = studyConfiguration;
this.fileId = fileId;
jsonObjectMapper = new ObjectMapper(new JsonFactory());
variantsWriter = jsonObjectMapper.writerFor(VariantStatsWrapper.class);
+ this.variantSourceStats = variantSourceStats;
}
@Override
public List<String> apply(List<Variant> variants) {
List<String> strings = new ArrayList<>(variants.size());
-
+ boolean defaultCohortAbsent = false;
+
VariantStatisticsCalculator variantStatisticsCalculator = new VariantStatisticsCalculator(overwrite);
List<VariantStatsWrapper> variantStatsWrappers = variantStatisticsCalculator.calculateBatch(variants, studyConfiguration.getStudyId()+"", fileId, samples);
-
+
long start = System.currentTimeMillis();
for (VariantStatsWrapper variantStatsWrapper : variantStatsWrappers) {
try {
strings.add(variantsWriter.writeValueAsString(variantStatsWrapper));
+ if (variantStatsWrapper.getCohortStats().get(VariantSourceEntry.DEFAULT_COHORT) == null) {
+ defaultCohortAbsent = true;
+ }
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
+ // we don't want to overwrite file stats regarding all samples with stats about a subset of samples. Maybe if we change VariantSource.stats to a map with every subset...
+ if (!defaultCohortAbsent) {
+ synchronized (variantSourceStats) {
+ variantSourceStats.updateFileStats(variants);
+ variantSourceStats.updateSampleStats(variants, null); // TODO test
+ }
+ }
logger.debug("another batch of {} elements calculated. time: {}ms", strings.size(), System.currentTimeMillis() - start);
if (variants.size() != 0) {
logger.info("stats created up to position {}:{}", variants.get(variants.size()-1).getChromosome(), variants.get(variants.size()-1).getStart());
@@ -292,7 +323,7 @@ public class VariantStatisticsManager {
/** Initialize Json parse **/
JsonParser parser = jsonFactory.createParser(variantInputStream);
- int batchSize = options.getInt(BATCH_SIZE, 1000);
+ int batchSize = options.getInt(VariantStorageManager.BATCH_SIZE, 1000);
ArrayList<VariantStatsWrapper> statsBatch = new ArrayList<>(batchSize);
int writes = 0;
int variantsNumber = 0; | ['opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsCalculator.java', 'opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/stats/VariantStatisticsManager.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,736,683 | 569,381 | 71,119 | 278 | 3,652 | 669 | 57 | 2 | 3,813 | 84 | 867 | 44 | 0 | 2 | 1970-01-01T00:23:52 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
9,301 | mercedes-benz/sechub/1908/1907 | mercedes-benz | sechub | https://github.com/mercedes-benz/sechub/issues/1907 | https://github.com/mercedes-benz/sechub/pull/1908 | https://github.com/mercedes-benz/sechub/pull/1908 | 1 | closes | Fix develop branch | With #1887 the GH action build workflow broke due to a misspelled variable. This shall be fixed here. | 9d624d6bf3cb50f2c3cb4270193b034f604f7638 | 07cdf3d8f71f548f123587ca490e59ccf20a454d | https://github.com/mercedes-benz/sechub/compare/9d624d6bf3cb50f2c3cb4270193b034f604f7638...07cdf3d8f71f548f123587ca490e59ccf20a454d | diff --git a/sechub-notification/src/main/java/com/mercedesbenz/sechub/domain/notification/user/NewApiTokenRequestedUserNotificationService.java b/sechub-notification/src/main/java/com/mercedesbenz/sechub/domain/notification/user/NewApiTokenRequestedUserNotificationService.java
index 992773fb0..54d1ef4d5 100644
--- a/sechub-notification/src/main/java/com/mercedesbenz/sechub/domain/notification/user/NewApiTokenRequestedUserNotificationService.java
+++ b/sechub-notification/src/main/java/com/mercedesbenz/sechub/domain/notification/user/NewApiTokenRequestedUserNotificationService.java
@@ -29,7 +29,7 @@ public class NewApiTokenRequestedUserNotificationService {
String link = userMessage.getLinkWithOneTimeToken();
NewApiTokenRequestedUserNotificationServiceHelper serviceHelper = new NewApiTokenRequestedUserNotificationServiceHelper(Clock.systemDefaultZone());
- String tokenExpirationDateTime = serviceHelper.getApiTokenExpireDate();
+ String tokenExpireDateTime = serviceHelper.getApiTokenExpireDate();
StringBuilder emailContent = new StringBuilder();
emailContent.append("You requested a new API token. The token was created for you and expires at "); | ['sechub-notification/src/main/java/com/mercedesbenz/sechub/domain/notification/user/NewApiTokenRequestedUserNotificationService.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,476,594 | 718,588 | 99,935 | 1,539 | 157 | 31 | 2 | 1 | 101 | 18 | 24 | 1 | 0 | 0 | 1970-01-01T00:27:55 | 159 | Java | {'Java': 7354269, 'Shell': 285620, 'Go': 207604, 'Dockerfile': 58303, 'HTML': 27680, 'TypeScript': 17921, 'Groovy': 8898, 'CSS': 7405, 'Python': 7341, 'C': 748, 'Assembly': 401, 'Batchfile': 391, 'JavaScript': 312, 'Visual Basic .NET': 178, 'Ada': 169, 'Erlang': 140, 'OpenEdge ABL': 139, 'Fortran': 138, 'ABAP': 134, 'Ruby': 103, 'OCaml': 100, 'Scheme': 92, 'Tcl': 77} | MIT License |
9,302 | mercedes-benz/sechub/1809/1808 | mercedes-benz | sechub | https://github.com/mercedes-benz/sechub/issues/1808 | https://github.com/mercedes-benz/sechub/pull/1809 | https://github.com/mercedes-benz/sechub/pull/1809 | 1 | closes | HTML report downloaded in browser shows no trafficlight or any other style information | ## Situation
While testing #1807 I became aware, that the HTML report does no longer show any style information and looks very ugly when directly downloaded from server (e.g. when using DAUI and downloading a report directly via HTTPS with Browser)
When storing the file locally and showing it inside the browser everything works fine!
## Wanted
HTML report shall have styling gain
## Analyze
With #1672 we have set a CSP - maybe this was the reason.
## Solution
Setup CSP definition inside `AbstractAllowSecHubAPISecurityConfiguration.java` in a way where the HTML report can be downloaded and shown directly from server.
| a34e59612e8059395eff3ce6411f7e7badeda20a | 59e5183a9b11fac58f4a9818b1ce07ae76b65df5 | https://github.com/mercedes-benz/sechub/compare/a34e59612e8059395eff3ce6411f7e7badeda20a...59e5183a9b11fac58f4a9818b1ce07ae76b65df5 | diff --git a/sechub-shared-kernel/src/main/java/com/mercedesbenz/sechub/sharedkernel/configuration/AbstractAllowSecHubAPISecurityConfiguration.java b/sechub-shared-kernel/src/main/java/com/mercedesbenz/sechub/sharedkernel/configuration/AbstractAllowSecHubAPISecurityConfiguration.java
index 0a0a6f42b..1c71f6bdf 100644
--- a/sechub-shared-kernel/src/main/java/com/mercedesbenz/sechub/sharedkernel/configuration/AbstractAllowSecHubAPISecurityConfiguration.java
+++ b/sechub-shared-kernel/src/main/java/com/mercedesbenz/sechub/sharedkernel/configuration/AbstractAllowSecHubAPISecurityConfiguration.java
@@ -67,7 +67,7 @@ public abstract class AbstractAllowSecHubAPISecurityConfiguration extends WebSec
httpBasic()./* no login screen, just basic auth */
and().
headers().
- contentSecurityPolicy("default-src 'none'");
+ contentSecurityPolicy("default-src 'none'; style-src 'unsafe-inline'");
/* @formatter:on */
} | ['sechub-shared-kernel/src/main/java/com/mercedesbenz/sechub/sharedkernel/configuration/AbstractAllowSecHubAPISecurityConfiguration.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,437,801 | 710,586 | 98,907 | 1,518 | 126 | 27 | 2 | 1 | 638 | 100 | 130 | 13 | 0 | 0 | 1970-01-01T00:27:50 | 159 | Java | {'Java': 7354269, 'Shell': 285620, 'Go': 207604, 'Dockerfile': 58303, 'HTML': 27680, 'TypeScript': 17921, 'Groovy': 8898, 'CSS': 7405, 'Python': 7341, 'C': 748, 'Assembly': 401, 'Batchfile': 391, 'JavaScript': 312, 'Visual Basic .NET': 178, 'Ada': 169, 'Erlang': 140, 'OpenEdge ABL': 139, 'Fortran': 138, 'ABAP': 134, 'Ruby': 103, 'OCaml': 100, 'Scheme': 92, 'Tcl': 77} | MIT License |
9,309 | mercedes-benz/sechub/727/714 | mercedes-benz | sechub | https://github.com/mercedes-benz/sechub/issues/714 | https://github.com/mercedes-benz/sechub/pull/727 | https://github.com/mercedes-benz/sechub/pull/727 | 1 | closes | Optimistic Locks on multiple PDS - members leads to duplicated Job execution | ##### Note
- The origin problem is described here: the occurrence of optimistic lock entries.
- This was more or less only annoying
- After anlaysing the mentioned problem source it became clear that on a clusters this also did execute the JOBS multiple times (see comment below with title "Critical bug detected")
## Problem
When PDS is using PostgreSQL as database, then Optimistic Lock problems occur. It does not matter if the cluster consists of only a single instance or more than one instance. The more instances the PDS cluster has, the more likely it becomes for the optimistic lock problem to occur.
## Analysis
### 1 PDS:
~~~
pds-gosec_1 | 2021-07-13 08:55:05.950 INFO 8 --- [0.0-8444-exec-2] c.d.s.pds.job.PDSFileUploadJobService : Upload file sourcecode.zip for job b135466c-f2bd-434a-a900-10ffcb84c903 to storage
pds-gosec_1 | 2021-07-13 08:55:05.951 INFO 8 --- [0.0-8444-exec-2] c.d.s.s.s.spring.SharedVolumeJobStorage : job:b135466c-f2bd-434a-a900-10ffcb84c903: storing sourcecode.zip in path pds/GOSEC_CLUSTER
pds-gosec_1 | 2021-07-13 08:55:05.953 INFO 8 --- [0.0-8444-exec-2] c.d.s.s.s.spring.SharedVolumeJobStorage : job:b135466c-f2bd-434a-a900-10ffcb84c903: storing sourcecode.zip.checksum in path pds/GOSEC_CLUSTER
loadbalancer_1 | 172.20.0.1 - admin [13/Jul/2021:08:55:05 +0000] "POST /api/job/b135466c-f2bd-434a-a900-10ffcb84c903/upload/sourcecode.zip HTTP/1.1" 200 25 "-" "curl/7.58.0"
pds-gosec_1 | 2021-07-13 08:55:06.138 INFO 8 --- [0.0-8444-exec-1] c.d.s.pds.job.PDSJobTransactionService : Mark job b135466c-f2bd-434a-a900-10ffcb84c903 as ready to start
loadbalancer_1 | 172.20.0.1 - admin [13/Jul/2021:08:55:06 +0000] "PUT /api/job/b135466c-f2bd-434a-a900-10ffcb84c903/mark-ready-to-start HTTP/1.1" 200 0 "-" "curl/7.58.0"
loadbalancer_1 | 172.20.0.1 - admin [13/Jul/2021:08:55:06 +0000] "GET /api/job/b135466c-f2bd-434a-a900-10ffcb84c903/status HTTP/1.1" 200 165 "-" "curl/7.58.0"
pds-gosec_1 | 2021-07-13 08:55:06.583 INFO 8 --- [pool-2-thread-1] c.d.s.p.execution.PDSExecutionCallable : Prepare execution of job b135466c-f2bd-434a-a900-10ffcb84c903
pds-gosec_1 | 2021-07-13 08:55:06.601 INFO 8 --- [pool-2-thread-1] c.d.sechub.pds.job.PDSWorkspaceService : Unzipped 2 files to /workspace/workspace/b135466c-f2bd-434a-a900-10ffcb84c903/upload/unzipped/sourcecode
pds-gosec_1 | 2021-07-13 08:55:06.602 INFO 8 --- [pool-2-thread-1] c.d.s.p.execution.PDSExecutionCallable : Start launcher script for job b135466c-f2bd-434a-a900-10ffcb84c903
pds-gosec_1 | 2021-07-13 08:55:06.603 ERROR 8 --- [ scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
pds-gosec_1 |
pds-gosec_1 | org.springframework.orm.ObjectOptimisticLockingFailureException: Object of class [com.daimler.sechub.pds.job.PDSJob] with identifier [b135466c-f2bd-434a-a900-10ffcb84c903]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.daimler.sechub.pds.job.PDSJob#b135466c-f2bd-434a-a900-10ffcb84c903]
pds-gosec_1 | at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:315)
pds-gosec_1 | at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
pds-gosec_1 | at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:566)
…
pds-gosec_1 | Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.daimler.sechub.pds.job.PDSJob#b135466c-f2bd-434a-a900-10ffcb84c903]
~~~
The exception occurs after starting the execution script and before the job is done.
### 2 PDS
~~~
ds-gosec_1 | 2021-07-13 08:49:11.955 INFO 7 --- [0.0-8444-exec-1] c.d.s.pds.job.PDSFileUploadJobService : Upload file sourcecode.zip for job 07411f09-ed0c-4d24-804d-b900f801e7a7 to storage
pds-gosec_1 | 2021-07-13 08:49:11.957 INFO 7 --- [0.0-8444-exec-1] c.d.s.s.s.spring.SharedVolumeJobStorage : job:07411f09-ed0c-4d24-804d-b900f801e7a7: storing sourcecode.zip in path pds/GOSEC_CLUSTER
pds-gosec_1 | 2021-07-13 08:49:11.959 INFO 7 --- [0.0-8444-exec-1] c.d.s.s.s.spring.SharedVolumeJobStorage : job:07411f09-ed0c-4d24-804d-b900f801e7a7: storing sourcecode.zip.checksum in path pds/GOSEC_CLUSTER
loadbalancer_1 | 172.20.0.1 - admin [13/Jul/2021:08:49:11 +0000] "POST /api/job/07411f09-ed0c-4d24-804d-b900f801e7a7/upload/sourcecode.zip HTTP/1.1" 200 0 "-" "curl/7.58.0"
pds-gosec_1 | 2021-07-13 08:49:12.162 INFO 7 --- [0.0-8444-exec-5] c.d.s.pds.job.PDSJobTransactionService : Mark job 07411f09-ed0c-4d24-804d-b900f801e7a7 as ready to start
loadbalancer_1 | 172.20.0.1 - admin [13/Jul/2021:08:49:12 +0000] "PUT /api/job/07411f09-ed0c-4d24-804d-b900f801e7a7/mark-ready-to-start HTTP/1.1" 200 0 "-" "curl/7.58.0"
pds-gosec_2 | 2021-07-13 08:49:12.201 INFO 8 --- [pool-2-thread-2] c.d.s.p.execution.PDSExecutionCallable : Prepare execution of job 07411f09-ed0c-4d24-804d-b900f801e7a7
pds-gosec_2 | 2021-07-13 08:49:12.213 ERROR 8 --- [ scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
pds-gosec_2 |
pds-gosec_2 | org.springframework.orm.ObjectOptimisticLockingFailureException: Object of class [com.daimler.sechub.pds.job.PDSJob] with identifier [07411f09-ed0c-4d24-804d-b900f801e7a7]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.daimler.sechub.pds.job.PDSJob#07411f09-ed0c-4d24-804d-b900f801e7a7]
…
pds-gosec_2 | Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.daimler.sechub.pds.job.PDSJob#07411f09-ed0c-4d24-804d-b900f801e7a7]
~~~
The issue occurs after starting the execution script and before the job is done in `pds-gosec_2`. `pds-gosec_1` handled the file upload.
### 3 PDS
~~~
pds-gosec_2 | 2021-07-13 08:27:32.122 INFO 10 --- [0.0-8444-exec-9] c.d.s.pds.job.PDSFileUploadJobService : Upload file sourcecode.zip for job d40bba6b-f344-4446-846d-067e57df4ed6 to storage
pds-gosec_2 | 2021-07-13 08:27:32.123 INFO 10 --- [0.0-8444-exec-9] c.d.s.s.s.spring.SharedVolumeJobStorage : job:d40bba6b-f344-4446-846d-067e57df4ed6: storing sourcecode.zip in path pds/GOSEC_CLUSTER
pds-gosec_2 | 2021-07-13 08:27:32.123 INFO 10 --- [0.0-8444-exec-9] c.d.s.s.s.spring.SharedVolumeJobStorage : job:d40bba6b-f344-4446-846d-067e57df4ed6: storing sourcecode.zip.checksum in path pds/GOSEC_CLUSTER
loadbalancer_1 | 172.20.0.1 - admin [13/Jul/2021:08:27:32 +0000] "POST /api/job/d40bba6b-f344-4446-846d-067e57df4ed6/upload/sourcecode.zip HTTP/1.1" 200 25 "-" "curl/7.58.0"
pds-gosec_2 | 2021-07-13 08:27:32.301 INFO 10 --- [0.0-8444-exec-8] c.d.s.pds.job.PDSJobTransactionService : Mark job d40bba6b-f344-4446-846d-067e57df4ed6 as ready to start
loadbalancer_1 | 172.20.0.1 - admin [13/Jul/2021:08:27:32 +0000] "PUT /api/job/d40bba6b-f344-4446-846d-067e57df4ed6/mark-ready-to-start HTTP/1.1" 200 0 "-" "curl/7.58.0"
loadbalancer_1 | 172.20.0.1 - admin [13/Jul/2021:08:27:32 +0000] "GET /api/job/d40bba6b-f344-4446-846d-067e57df4ed6/status HTTP/1.1" 200 165 "-" "curl/7.58.0"
pds-gosec_1 | 2021-07-13 08:27:32.612 INFO 8 --- [pool-2-thread-3] c.d.s.p.execution.PDSExecutionCallable : Prepare execution of job d40bba6b-f344-4446-846d-067e57df4ed6
pds-gosec_3 | 2021-07-13 08:27:32.618 INFO 7 --- [pool-2-thread-4] c.d.s.p.execution.PDSExecutionCallable : Prepare execution of job d40bba6b-f344-4446-846d-067e57df4ed6
pds-gosec_1 | 2021-07-13 08:27:32.627 INFO 8 --- [pool-2-thread-3] c.d.s.p.execution.PDSExecutionCallable : Had optimistic lock problem on update for job d40bba6b-f344-4446-846d-067e57df4ed6 - do retry nr.1
pds-gosec_1 | 2021-07-13 08:27:32.642 INFO 8 --- [pool-2-thread-3] c.d.s.p.execution.PDSExecutionCallable : Had optimistic lock problem on update for job d40bba6b-f344-4446-846d-067e57df4ed6 - do retry nr.2
pds-gosec_3 | 2021-07-13 08:27:32.640 ERROR 7 --- [ scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
pds-gosec_3 |
pds-gosec_3 | org.springframework.orm.ObjectOptimisticLockingFailureException: Object of class [com.daimler.sechub.pds.job.PDSJob] with identifier [d40bba6b-f344-4446-846d-067e57df4ed6]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.daimler.sechub.pds.job.PDSJob#d40bba6b-f344-4446-846d-067e57df4ed6]
…
pds-gosec_3 | Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.daimler.sechub.pds.job.PDSJob#d40bba6b-f344-4446-846d-067e57df4ed6]
~~~
In this case, both `pds-gosec_1` and `pds-gosec_3` prepare for the job execution. `pds-gosec_1` reports it had an optimistic lock problem, but `pds-gosec_3` throws the actual exception. `pds-gosec_2` handled the file upload.
## Wanted
The PDS should scale up to 100s of instances without having optimistic lock problems.
[optimistic_lock_exception.txt](https://github.com/Daimler/sechub/files/6809885/optimistic_lock_exception.txt)
| d1c303d97e668d71e88f11590f7ba27edb0c7561 | 466401750c1914acf7989e4d9902b340fad9bdfb | https://github.com/mercedes-benz/sechub/compare/d1c303d97e668d71e88f11590f7ba27edb0c7561...466401750c1914acf7989e4d9902b340fad9bdfb | diff --git a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/ExecutionConstants.java b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/ExecutionConstants.java
index c54f3fb56..3ec235a73 100644
--- a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/ExecutionConstants.java
+++ b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/ExecutionConstants.java
@@ -36,6 +36,6 @@ public class ExecutionConstants {
* profiles. This profile contains executors of PDS integration test in version V1, using SARIF - but DOES NOT reuse SecHub storage
*
*/
- public static final String DEFAULT_PROFILE_4_ID = IntegrationTestDefaultProfiles.PROFILE_4_PDS_CODESCAN_SARIF_NO_SECHUB_STORAGE_USED.id;
+ public static final String DEFAULT_PROFILE_4_ID = IntegrationTestDefaultProfiles.PROFILE_4_NO_STORAGE_REUSED__PDS_CODESCAN_SARIF.id;
}
diff --git a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultExecutorConfigurations.java b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultExecutorConfigurations.java
index e058a90ac..dab4c7d92 100644
--- a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultExecutorConfigurations.java
+++ b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultExecutorConfigurations.java
@@ -25,6 +25,16 @@ public class IntegrationTestDefaultExecutorConfigurations {
private static final List<TestExecutorConfig> registeredConfigurations = new ArrayList<>();
+ private enum StorageType{
+ REUSE_SECHUB_DATA(),
+
+ DO_NOT_REUSE_SECHUB_DATA,
+
+ ;
+
+
+ }
+
private static final String INTTEST_NAME_PREFIX = "INTTEST_";
public static final TestExecutorConfig NETSPARKER_V1 = defineNetsparkerConfig();
@@ -37,11 +47,32 @@ public class IntegrationTestDefaultExecutorConfigurations {
public static final String PDS_CODESCAN_VARIANT_D="d";
public static final String PDS_CODESCAN_VARIANT_E="e";
- public static final TestExecutorConfig PDS_V1_CODE_SCAN_A = definePDSScan(PDS_CODESCAN_VARIANT_A,false,PDSIntTestProductIdentifier.PDS_INTTEST_CODESCAN);
- public static final TestExecutorConfig PDS_V1_CODE_SCAN_B = definePDSScan(PDS_CODESCAN_VARIANT_B,true,PDSIntTestProductIdentifier.PDS_INTTEST_CODESCAN);
- public static final TestExecutorConfig PDS_V1_CODE_SCAN_C = definePDSScan(PDS_CODESCAN_VARIANT_C,true,(String)null,true);// no identifier set, will not work...
- public static final TestExecutorConfig PDS_V1_CODE_SCAN_D = definePDSScan(PDS_CODESCAN_VARIANT_D,false,PDSIntTestProductIdentifier.PDS_INTTEST_PRODUCT_CS_SARIF,true);
- public static final TestExecutorConfig PDS_V1_CODE_SCAN_E = definePDSScan(PDS_CODESCAN_VARIANT_E,false,PDSIntTestProductIdentifier.PDS_INTTEST_PRODUCT_CS_SARIF,false);
+ /* @formatter:off */
+ public static final TestExecutorConfig PDS_V1_CODE_SCAN_A = definePDSScan(
+ PDS_CODESCAN_VARIANT_A,false,
+ PDSIntTestProductIdentifier.PDS_INTTEST_CODESCAN,
+ StorageType.REUSE_SECHUB_DATA);
+
+ public static final TestExecutorConfig PDS_V1_CODE_SCAN_B = definePDSScan(
+ PDS_CODESCAN_VARIANT_B,true,
+ PDSIntTestProductIdentifier.PDS_INTTEST_CODESCAN,
+ StorageType.REUSE_SECHUB_DATA);
+
+ public static final TestExecutorConfig PDS_V1_CODE_SCAN_C = definePDSScan(
+ PDS_CODESCAN_VARIANT_C,true,
+ (String)null,
+ StorageType.REUSE_SECHUB_DATA);// no identifier set, will not work...
+
+ public static final TestExecutorConfig PDS_V1_CODE_SCAN_D = definePDSScan(
+ PDS_CODESCAN_VARIANT_D,false,PDSIntTestProductIdentifier.
+ PDS_INTTEST_PRODUCT_CS_SARIF,
+ StorageType.REUSE_SECHUB_DATA);
+
+ public static final TestExecutorConfig PDS_V1_CODE_SCAN_E_DO_NOT_REUSE_SECHUBDATA = definePDSScan(
+ PDS_CODESCAN_VARIANT_E,false,
+ PDSIntTestProductIdentifier.PDS_INTTEST_PRODUCT_CS_SARIF,
+ StorageType.DO_NOT_REUSE_SECHUB_DATA);
+ /* @formatter:on */
public static final String PDS_ENV_VARIABLENAME_TECHUSER_ID="TEST_PDS_TECHUSER_ID";
public static final String PDS_ENV_VARIABLENAME_TECHUSER_APITOKEN="TEST_PDS_TECHUSER_APITOKEN";
@@ -53,17 +84,13 @@ public class IntegrationTestDefaultExecutorConfigurations {
return Collections.unmodifiableList(registeredConfigurations);
}
- private static TestExecutorConfig definePDSScan(String variant, boolean credentialsAsEnvEntries,PDSIntTestProductIdentifier pdsProductIdentifier) {
- return definePDSScan(variant, credentialsAsEnvEntries, pdsProductIdentifier, true);
- }
-
- private static TestExecutorConfig definePDSScan(String variant, boolean credentialsAsEnvEntries,PDSIntTestProductIdentifier pdsProductIdentifier, boolean useSecHubStorage) {
+ private static TestExecutorConfig definePDSScan(String variant, boolean credentialsAsEnvEntries,PDSIntTestProductIdentifier pdsProductIdentifier, StorageType useSecHubStorage) {
String productIdentfieriId=pdsProductIdentifier != null ? pdsProductIdentifier.getId():"not-existing";
return definePDSScan(variant, credentialsAsEnvEntries, productIdentfieriId, useSecHubStorage);
}
- private static TestExecutorConfig definePDSScan(String variant, boolean credentialsAsEnvEntries, String productIdentifierId, boolean useSecHubStorage) {
+ private static TestExecutorConfig definePDSScan(String variant, boolean credentialsAsEnvEntries, String productIdentifierId, StorageType storageType) {
TestExecutorConfig config = createTestEditorConfig();
config.enabled=true;
@@ -79,6 +106,8 @@ public class IntegrationTestDefaultExecutorConfigurations {
config.setup.credentials.user=TestAPI.PDS_TECH_USER.getUserId();
config.setup.credentials.password=TestAPI.PDS_TECH_USER.getApiToken();
}
+ boolean useSecHubStorage = storageType==StorageType.REUSE_SECHUB_DATA;
+
List<TestExecutorSetupJobParam> jobParameters = config.setup.jobParameters;
jobParameters.add(new TestExecutorSetupJobParam("pds.config.productidentifier",productIdentifierId));
jobParameters.add(new TestExecutorSetupJobParam("pds.config.use.sechub.storage", Boolean.valueOf(useSecHubStorage).toString()));
diff --git a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultProfiles.java b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultProfiles.java
index eda7a45eb..2416d2ba9 100644
--- a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultProfiles.java
+++ b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultProfiles.java
@@ -6,7 +6,7 @@ public class IntegrationTestDefaultProfiles {
public static final DoNotChangeTestExecutionProfile PROFILE_2_PDS_CODESCAN = defineProfile2();
public static final DoNotChangeTestExecutionProfile PROFILE_3_PDS_CODESCAN_SARIF = defineProfile3();
- public static final DoNotChangeTestExecutionProfile PROFILE_4_PDS_CODESCAN_SARIF_NO_SECHUB_STORAGE_USED = defineProfile4();
+ public static final DoNotChangeTestExecutionProfile PROFILE_4_NO_STORAGE_REUSED__PDS_CODESCAN_SARIF = defineProfile4();
private static final DoNotChangeTestExecutionProfile[] ALL_PROFILES = new DoNotChangeTestExecutionProfile[] {
@@ -16,7 +16,7 @@ public class IntegrationTestDefaultProfiles {
PROFILE_3_PDS_CODESCAN_SARIF,
- PROFILE_4_PDS_CODESCAN_SARIF_NO_SECHUB_STORAGE_USED
+ PROFILE_4_NO_STORAGE_REUSED__PDS_CODESCAN_SARIF
};
@@ -57,7 +57,7 @@ public class IntegrationTestDefaultProfiles {
private static DoNotChangeTestExecutionProfile defineProfile4() {
DoNotChangeTestExecutionProfile profile = new DoNotChangeTestExecutionProfile();
- profile.initialConfigurationsWithoutUUID.add(IntegrationTestDefaultExecutorConfigurations.PDS_V1_CODE_SCAN_E);
+ profile.initialConfigurationsWithoutUUID.add(IntegrationTestDefaultExecutorConfigurations.PDS_V1_CODE_SCAN_E_DO_NOT_REUSE_SECHUBDATA);
profile.id = "inttest-default-profile4-sarif"; // not more than 30 chars per profile id, so we use this
profile.description="Same as profile 3, but executor config does not reuse sechub storage!";
profile.enabled = true;
diff --git a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/ScenarioInitializer.java b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/ScenarioInitializer.java
index 8064f07e4..f7629a08e 100644
--- a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/ScenarioInitializer.java
+++ b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/ScenarioInitializer.java
@@ -64,7 +64,7 @@ public class ScenarioInitializer {
}
public ScenarioInitializer ensureDefaultExecutionProfile_4_PDS_codescan_sarif_no_sechub_storage_used() {
- return ensureDefaultExecutionProfile(IntegrationTestDefaultProfiles.PROFILE_4_PDS_CODESCAN_SARIF_NO_SECHUB_STORAGE_USED);
+ return ensureDefaultExecutionProfile(IntegrationTestDefaultProfiles.PROFILE_4_NO_STORAGE_REUSED__PDS_CODESCAN_SARIF);
}
private ScenarioInitializer ensureDefaultExecutionProfile(DoNotChangeTestExecutionProfile profile) {
diff --git a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario5/Scenario5.java b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario5/Scenario5.java
index 008bd33de..5823819d7 100644
--- a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario5/Scenario5.java
+++ b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario5/Scenario5.java
@@ -8,11 +8,11 @@ import com.daimler.sechub.integrationtest.internal.CleanScenario;
import com.daimler.sechub.integrationtest.internal.PDSTestScenario;
/**
- * <b><u>Scenario5 - the PDS integrationtest standard scenario</u></b><br>
+ * <b><u>Scenario5 - the PDS integration test standard scenario. Scenario9 (REUSE SECHUB DATA enabled!)</u></b><br>
*
* In this scenario following is automatically initialized at start (old data
* removed as well): <br> <br>
- * a) <b> PDS integrationtest configuration is done automatically!</b>
+ * a) <b> PDS integration test configuration is done automatically!</b>
* All configurations from
* 'sechub-integrationtest/src/main/resources/pds-config-integrationtest.json' will be
* configured automatically!<br><br>
diff --git a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario6/Scenario6.java b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario6/Scenario6.java
index 4b60c6002..526c0d820 100644
--- a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario6/Scenario6.java
+++ b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario6/Scenario6.java
@@ -6,7 +6,7 @@ import com.daimler.sechub.integrationtest.internal.PDSTestScenario;
import com.daimler.sechub.integrationtest.internal.StaticTestScenario;
/**
- * <b><u>Scenario6 - the PDS ONLY integration test scenario</u></b><br>
+ * <b><u>Scenario6 - the PDS ONLY integration test scenario (no special sechub storage setings necessary)</u></b><br>
*
* In this scenario no sechub server instance is necessary. No special
* preparations are done.
diff --git a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario9/Scenario9.java b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario9/Scenario9.java
index 707db8b09..4d4b7c471 100644
--- a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario9/Scenario9.java
+++ b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario9/Scenario9.java
@@ -8,11 +8,11 @@ import com.daimler.sechub.integrationtest.internal.CleanScenario;
import com.daimler.sechub.integrationtest.internal.PDSTestScenario;
/**
- * <b><u>Scenario9 - the PDS integrationtest SARIF scenario (REUSE SECHUB DATA enabled!)</u></b><br>
+ * <b><u>Scenario9 - the PDS integration test SARIF scenario (REUSE SECHUB DATA enabled!)</u></b><br>
*
* In this scenario following is automatically initialized at start (old data
* removed as well): <br> <br>
- * a) <b> PDS integrationtest configuration is done automatically!</b>
+ * a) <b> PDS integration test configuration is done automatically!</b>
* All configurations from
* 'sechub-integrationtest/src/main/resources/pds-config-integrationtest.json' will be
* configured automatically!<br><br>
diff --git a/sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario5/PDSCodeScanJobScenario5IntTest.java b/sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario5/PDSCodeScanJobScenario5IntTest.java
index d9b6f9a92..7f96ef47a 100644
--- a/sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario5/PDSCodeScanJobScenario5IntTest.java
+++ b/sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario5/PDSCodeScanJobScenario5IntTest.java
@@ -39,7 +39,7 @@ public class PDSCodeScanJobScenario5IntTest {
@SuppressWarnings("deprecation") // we use assertSecHubReport here - old implementation okay here
@Test
- public void a_user_can_start_a_pds_scan_job_and_gets_result_containing_expected_findings_and_also_dynamic_parts() {
+ public void pds_reuse_sechub_data__a_user_can_start_a_pds_scan_job_and_gets_result_containing_expected_findings_and_also_dynamic_parts() {
/* @formatter:off */
/* prepare */
diff --git a/sechub-pds/src/main/java/com/daimler/sechub/pds/batch/PDSBatchTriggerService.java b/sechub-pds/src/main/java/com/daimler/sechub/pds/batch/PDSBatchTriggerService.java
index 66b51a037..84d1c01f9 100644
--- a/sechub-pds/src/main/java/com/daimler/sechub/pds/batch/PDSBatchTriggerService.java
+++ b/sechub-pds/src/main/java/com/daimler/sechub/pds/batch/PDSBatchTriggerService.java
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: MIT
package com.daimler.sechub.pds.batch;
-import java.util.Optional;
+import java.util.Random;
+import java.util.UUID;
import javax.annotation.PostConstruct;
@@ -9,15 +10,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
+import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
import com.daimler.sechub.pds.PDSMustBeDocumented;
import com.daimler.sechub.pds.execution.PDSExecutionService;
-import com.daimler.sechub.pds.job.PDSJob;
import com.daimler.sechub.pds.job.PDSJobRepository;
-import com.daimler.sechub.pds.job.PDSJobStatusState;
+import com.daimler.sechub.pds.job.PDSJobTransactionService;
@Service
public class PDSBatchTriggerService {
@@ -35,17 +35,20 @@ public class PDSBatchTriggerService {
@Autowired
PDSJobRepository repository;
- @PDSMustBeDocumented(value="initial delay for next job trigger in milliseconds",scope="scheduler")
+ @Autowired
+ PDSJobTransactionService jobTransactionService;
+
+ @PDSMustBeDocumented(value = "initial delay for next job trigger in milliseconds", scope = "scheduler")
@Value("${sechub.pds.config.trigger.nextjob.initialdelay:" + DEFAULT_INITIAL_DELAY_MILLIS + "}")
private String infoInitialDelay; // here only for logging - used in scheduler annotation as well!
- @PDSMustBeDocumented(value="delay for next job trigger in milliseconds",scope="scheduler")
+ @PDSMustBeDocumented(value = "delay for next job trigger in milliseconds", scope = "scheduler")
@Value("${sechub.pds.config.trigger.nextjob.delay:" + DEFAULT_FIXED_DELAY_MILLIS + "}")
private String infoFixedDelay; // here only for logging - used in scheduler annotation as well!
- @PDSMustBeDocumented(value="Set scheduler enabled state",scope="scheduler")
- @Value("${sechub.pds.config.scheduling.enable:"+DEFAULT_SCHEDULING_ENABLED+"}")
- boolean schedulingEnabled=DEFAULT_SCHEDULING_ENABLED;
+ @PDSMustBeDocumented(value = "Set scheduler enabled state", scope = "scheduler")
+ @Value("${sechub.pds.config.scheduling.enable:" + DEFAULT_SCHEDULING_ENABLED + "}")
+ boolean schedulingEnabled = DEFAULT_SCHEDULING_ENABLED;
@PostConstruct
protected void postConstruct() {
@@ -56,7 +59,6 @@ public class PDSBatchTriggerService {
// default 10 seconds delay and 5 seconds initial
@Scheduled(initialDelayString = "${sechub.pds.config.trigger.nextjob.initialdelay:" + DEFAULT_INITIAL_DELAY_MILLIS
+ "}", fixedDelayString = "${sechub.pds.config.trigger.nextjob.delay:" + DEFAULT_FIXED_DELAY_MILLIS + "}")
- @Transactional
public void triggerExecutionOfNextJob() {
if (!schedulingEnabled) {
LOG.trace("Trigger execution of next job canceled, because scheduling disabled.");
@@ -67,21 +69,44 @@ public class PDSBatchTriggerService {
LOG.debug("Execution service is not able to execute next job, so cancel here");
return;
}
- /* query does auto increment version here! */
- Optional<PDSJob> nextJob = repository.findNextJobToExecute();
- if (!nextJob.isPresent()) {
- LOG.trace("No next job present");
- return;
- }
- PDSJob pdsJob = nextJob.get();
- pdsJob.setState(PDSJobStatusState.QUEUED);
-
/*
- * next is done async - so on leave of this methods PDS job version will be
- * updated + state set to queue, so no other POD will process this job again
+ * find next job and mark it as already queued - so no other PDS instance does
+ * try to process it
*/
- executionService.addToExecutionQueueAsynchron(pdsJob.getUUID());
+ UUID uuid = null;
+
+ boolean fetchedNextJob = false;
+ while (!fetchedNextJob) {
+
+ try {
+ uuid = jobTransactionService.findNextJobToExecuteAndMarkAsQueued();
+
+ fetchedNextJob = true;
+
+ } catch (ObjectOptimisticLockingFailureException e) {
+ /*
+ * This can happen when PDS instances are started at same time, so the check for
+ * next jobs can lead to race condiitons - and optmistic locks will occurre
+ * here.
+ *
+ * To avoid this to happen again, we wait a random time here. So next call on
+ * this machine should normally not collide again.
+ */
+ Random random = new Random();
+ int millis = random.ints(50, 3000).findFirst().getAsInt();
+ LOG.info("Next job was already handled by another cluster member - will wait {} milliseconds and retry.", millis);
+ try {
+ Thread.sleep(millis);
+ } catch (InterruptedException e1) {
+ Thread.currentThread().interrupt();
+ }
+ LOG.info("Wait done - try again");
+ }
+ }
+ if (uuid == null) {
+ return;
+ }
+ executionService.addToExecutionQueueAsynchron(uuid);
}
-
}
\\ No newline at end of file
diff --git a/sechub-pds/src/main/java/com/daimler/sechub/pds/execution/PDSExecutionCallable.java b/sechub-pds/src/main/java/com/daimler/sechub/pds/execution/PDSExecutionCallable.java
index bb5053b98..6a0d5be0b 100644
--- a/sechub-pds/src/main/java/com/daimler/sechub/pds/execution/PDSExecutionCallable.java
+++ b/sechub-pds/src/main/java/com/daimler/sechub/pds/execution/PDSExecutionCallable.java
@@ -16,7 +16,6 @@ import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.orm.ObjectOptimisticLockingFailureException;
import com.daimler.sechub.pds.PDSJSONConverterException;
import com.daimler.sechub.pds.job.PDSJobConfiguration;
@@ -35,7 +34,6 @@ import com.daimler.sechub.pds.usecase.UseCaseUserCancelsJob;
class PDSExecutionCallable implements Callable<PDSExecutionResult> {
private static final Logger LOG = LoggerFactory.getLogger(PDSExecutionCallable.class);
- private static final int MAXIMUM_RETRIES_ON_OPTIMISTIC_LOCKS = 2;
private PDSJobTransactionService jobTransactionService;
private Process process;
@@ -64,7 +62,7 @@ class PDSExecutionCallable implements Callable<PDSExecutionResult> {
PDSExecutionResult result = new PDSExecutionResult();
PDSJobConfiguration config = null;
try {
- updateWithRetriesOnOptimisticLocks(UpdateState.RUNNING);
+ jobTransactionService.markJobAsRunningInOwnTransaction(jobUUID);
String configJSON = jobTransactionService.getJobConfiguration(jobUUID);
@@ -103,32 +101,6 @@ class PDSExecutionCallable implements Callable<PDSExecutionResult> {
return result;
}
- private enum UpdateState {
- RUNNING,
- }
-
- private void updateWithRetriesOnOptimisticLocks(UpdateState state) {
-
- int retries = 0;
- while (true) {
- try {
- if (state == UpdateState.RUNNING) {
- jobTransactionService.markJobAsRunningInOwnTransaction(jobUUID);
- }
- break;
-
- } catch (ObjectOptimisticLockingFailureException e) {
-
- /* we just retry - to avoid any optimistic locks */
- if (retries > MAXIMUM_RETRIES_ON_OPTIMISTIC_LOCKS) {
- throw new IllegalStateException("Still having optimistic lock problems - event after " + retries + " retries", e);
- }
- retries++;
- LOG.info("Had optimistic lock problem on update for job {} - do retry nr.{}", jobUUID, retries);
- }
- }
- }
-
private void waitForProcessEndAndGetResultByFiles(PDSExecutionResult result, UUID jobUUID, PDSJobConfiguration config, long minutesToWaitForResult)
throws InterruptedException, IOException {
LOG.debug("Wait for process of job with uuid:{}, will wait {} minutes for result from product with id:{}", jobUUID, minutesToWaitForResult,
diff --git a/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryCustom.java b/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryCustom.java
index d99686249..50a2d4a90 100644
--- a/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryCustom.java
+++ b/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryCustom.java
@@ -5,10 +5,6 @@ import java.util.Optional;
public interface PDSJobRepositoryCustom {
- /**
- * @return next executable job as optional - check if present or not is
- * necessary
- */
Optional<PDSJob> findNextJobToExecute();
long countJobsOfServerInState(String serverId, PDSJobStatusState state);
diff --git a/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryImpl.java b/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryImpl.java
index 3ff1d2882..da457cbbc 100644
--- a/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryImpl.java
+++ b/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryImpl.java
@@ -46,7 +46,7 @@ public class PDSJobRepositoryImpl implements PDSJobRepositoryCustom {
query.setParameter(PROPERTY_STATE, READY_TO_START);
query.setMaxResults(1);
// we use OPTIMISTIC_FORCE_INCREMENT write lock - so only one POD will be able
- // to execute next job...
+ // to execute next job... (it's just a fuse, it should not happen)
// see https://www.baeldung.com/jpa-pessimistic-locking
query.setLockMode(LockModeType.OPTIMISTIC_FORCE_INCREMENT);
diff --git a/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobTransactionService.java b/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobTransactionService.java
index 0936b5f83..e5ca1620b 100644
--- a/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobTransactionService.java
+++ b/sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobTransactionService.java
@@ -5,6 +5,7 @@ import static com.daimler.sechub.pds.job.PDSJobAssert.*;
import static com.daimler.sechub.pds.util.PDSAssert.*;
import java.time.LocalDateTime;
+import java.util.Optional;
import java.util.UUID;
import javax.annotation.security.RolesAllowed;
@@ -28,10 +29,13 @@ public class PDSJobTransactionService {
PDSJobRepository repository;
public PDSJobTransactionService() {
- //
}
- /* mark as running - no matter of state before */
+ /**
+ * Mark job as ready to start - state before allowed: only CREATED
+ *
+ * @param jobUUID
+ */
@RolesAllowed({ PDSRoleConstants.ROLE_USER, PDSRoleConstants.ROLE_SUPERADMIN })
public void markReadyToStartInOwnTransaction(UUID jobUUID) {
LOG.info("Mark job {} as ready to start", jobUUID);
@@ -39,18 +43,18 @@ public class PDSJobTransactionService {
}
/**
- * Marks job as running - no matter which state before
+ * Mark job as running - no matter which state before
*
- * @param uuid
+ * @param jobUUID
*/
- public void markJobAsRunningInOwnTransaction(UUID uuid) {
- updateJobInOwnTransaction(uuid, null, LocalDateTime.now(), null, PDSJobStatusState.RUNNING, PDSJobStatusState.values());
+ public void markJobAsRunningInOwnTransaction(UUID jobUUID) {
+ updateJobInOwnTransaction(jobUUID, null, LocalDateTime.now(), null, PDSJobStatusState.RUNNING, PDSJobStatusState.values());
}
private void updateJobInOwnTransaction(UUID jobUUID, String result, LocalDateTime started, LocalDateTime ended, PDSJobStatusState newState,
PDSJobStatusState... acceptedStatesBefore) {
notNull(jobUUID, "job uuid may not be null!");
-
+
PDSJob job = assertJobFound(jobUUID, repository);
if (started != null) {
job.setStarted(started);
@@ -66,7 +70,29 @@ public class PDSJobTransactionService {
LOG.debug("Updated job in own transaction - pds job uuid={}, state={}", job.getUUID(), job.getState());
}
+ /**
+ * Read job configuration in own transaction
+ *
+ * @param jobUUID
+ * @return job configuration, will fail when job is not found
+ */
public String getJobConfiguration(UUID jobUUID) {
return assertJobFound(jobUUID, repository).getJsonConfiguration();
}
+
+ /**
+ * Resolves next job to execute. If found the job will be marked as queued
+ *
+ * @return uuid or <code>null</code> if no job found to put in queue.
+ */
+ public UUID findNextJobToExecuteAndMarkAsQueued() {
+
+ Optional<PDSJob> nextJob = repository.findNextJobToExecute();
+ if (!nextJob.isPresent()) {
+ return null;
+ }
+ PDSJob pdsJob = nextJob.get();
+ pdsJob.setState(PDSJobStatusState.QUEUED);
+ return pdsJob.getUUID();
+ }
}
diff --git a/sechub-pds/src/test/java/com/daimler/sechub/pds/batch/PDSBatchTriggerServiceTest.java b/sechub-pds/src/test/java/com/daimler/sechub/pds/batch/PDSBatchTriggerServiceTest.java
index 59ab34aa1..81f9ee5aa 100644
--- a/sechub-pds/src/test/java/com/daimler/sechub/pds/batch/PDSBatchTriggerServiceTest.java
+++ b/sechub-pds/src/test/java/com/daimler/sechub/pds/batch/PDSBatchTriggerServiceTest.java
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
package com.daimler.sechub.pds.batch;
-import static org.junit.Assert.*;
+import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.util.Optional;
@@ -13,91 +13,83 @@ import org.junit.Test;
import com.daimler.sechub.pds.execution.PDSExecutionService;
import com.daimler.sechub.pds.job.PDSJob;
import com.daimler.sechub.pds.job.PDSJobRepository;
-import com.daimler.sechub.pds.job.PDSJobStatusState;
+import com.daimler.sechub.pds.job.PDSJobTransactionService;
public class PDSBatchTriggerServiceTest {
private PDSBatchTriggerService serviceToTest;
private PDSExecutionService executionService;
private PDSJobRepository repository;
+ private PDSJobTransactionService jobTransactionService;
+ private UUID nextJobUUID;
+ private PDSJob job;
@Before
public void before() throws Exception {
+ nextJobUUID = UUID.randomUUID();
+ job = mock(PDSJob.class);
+ when(job.getUUID()).thenReturn(nextJobUUID);
+
executionService = mock(PDSExecutionService.class);
repository = mock(PDSJobRepository.class);
+ jobTransactionService = mock(PDSJobTransactionService.class);
+ when(jobTransactionService.findNextJobToExecuteAndMarkAsQueued()).thenReturn(nextJobUUID);
serviceToTest = new PDSBatchTriggerService();
serviceToTest.executionService = executionService;
serviceToTest.repository = repository;
+ serviceToTest.jobTransactionService = jobTransactionService;
}
@Test
- public void a_job_found_for_next_execution_is_changed_to_state_QUEUED() {
+ public void a_job_found_for_next_execution_executor_service_called() {
/* prepare */
- PDSJob job = new PDSJob();
- job.setState(PDSJobStatusState.READY_TO_START);
-
when(repository.findNextJobToExecute()).thenReturn(Optional.of(job));
- /* check precondition */
- assertEquals(PDSJobStatusState.READY_TO_START, job.getState());
-
/* execute */
serviceToTest.triggerExecutionOfNextJob();
/* test */
- assertEquals(PDSJobStatusState.QUEUED, job.getState());
+ verify(executionService).addToExecutionQueueAsynchron(nextJobUUID);
}
-
+
@Test
- public void a_job_found_for_next_execution_but_scheduling_disabled_job_is_not_changed() {
+ public void a_job_found_for_next_execution_jobtransaction_service_is_called() {
/* prepare */
- serviceToTest.schedulingEnabled=false;
- PDSJob job = new PDSJob();
- job.setState(PDSJobStatusState.READY_TO_START);
-
when(repository.findNextJobToExecute()).thenReturn(Optional.of(job));
- /* check precondition */
- assertEquals(PDSJobStatusState.READY_TO_START, job.getState());
-
/* execute */
serviceToTest.triggerExecutionOfNextJob();
/* test */
- assertEquals(PDSJobStatusState.READY_TO_START, job.getState());
+ verify(jobTransactionService).findNextJobToExecuteAndMarkAsQueued();
}
-
+
@Test
- public void a_job_found_for_next_execution_but_scheduling_disabled_executor_service_not_called() {
+ public void a_job_found_for_next_execution_but_scheduling_disabled_executor_service_is_NOT_called() {
/* prepare */
- serviceToTest.schedulingEnabled=false;
- UUID uuid = UUID.randomUUID();
- PDSJob job = mock(PDSJob.class);
- when(job.getUUID()).thenReturn(uuid);
+ serviceToTest.schedulingEnabled = false;
when(repository.findNextJobToExecute()).thenReturn(Optional.of(job));
-
+
/* execute */
serviceToTest.triggerExecutionOfNextJob();
-
+
/* test */
- verify(executionService,never()).addToExecutionQueueAsynchron(uuid);
+ verify(executionService, never()).addToExecutionQueueAsynchron(any());
}
-
+
@Test
- public void a_job_found_for_next_execution_executor_service_called() {
+ public void a_job_found_for_next_execution_but_scheduling_disabled_jobtransaction_service_is_NOT_called() {
/* prepare */
- UUID uuid = UUID.randomUUID();
- PDSJob job = mock(PDSJob.class);
- when(job.getUUID()).thenReturn(uuid);
+ serviceToTest.schedulingEnabled = false;
when(repository.findNextJobToExecute()).thenReturn(Optional.of(job));
-
+
/* execute */
serviceToTest.triggerExecutionOfNextJob();
-
+
/* test */
- verify(executionService).addToExecutionQueueAsynchron(uuid);
+ verify(jobTransactionService, never()).findNextJobToExecuteAndMarkAsQueued();
}
} | ['sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario5/Scenario5.java', 'sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/ScenarioInitializer.java', 'sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryImpl.java', 'sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultExecutorConfigurations.java', 'sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobRepositoryCustom.java', 'sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario6/Scenario6.java', 'sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/scenario9/Scenario9.java', 'sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/ExecutionConstants.java', 'sechub-pds/src/main/java/com/daimler/sechub/pds/job/PDSJobTransactionService.java', 'sechub-pds/src/main/java/com/daimler/sechub/pds/execution/PDSExecutionCallable.java', 'sechub-pds/src/test/java/com/daimler/sechub/pds/batch/PDSBatchTriggerServiceTest.java', 'sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario5/PDSCodeScanJobScenario5IntTest.java', 'sechub-pds/src/main/java/com/daimler/sechub/pds/batch/PDSBatchTriggerService.java', 'sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestDefaultProfiles.java'] | {'.java': 14} | 14 | 14 | 0 | 0 | 14 | 2,435,934 | 518,771 | 74,308 | 1,169 | 6,367 | 1,360 | 147 | 5 | 9,693 | 882 | 3,588 | 84 | 1 | 0 | 1970-01-01T00:27:06 | 159 | Java | {'Java': 7354269, 'Shell': 285620, 'Go': 207604, 'Dockerfile': 58303, 'HTML': 27680, 'TypeScript': 17921, 'Groovy': 8898, 'CSS': 7405, 'Python': 7341, 'C': 748, 'Assembly': 401, 'Batchfile': 391, 'JavaScript': 312, 'Visual Basic .NET': 178, 'Ada': 169, 'Erlang': 140, 'OpenEdge ABL': 139, 'Fortran': 138, 'ABAP': 134, 'Ruby': 103, 'OCaml': 100, 'Scheme': 92, 'Tcl': 77} | MIT License |
9,308 | mercedes-benz/sechub/866/864 | mercedes-benz | sechub | https://github.com/mercedes-benz/sechub/issues/864 | https://github.com/mercedes-benz/sechub/pull/866 | https://github.com/mercedes-benz/sechub/pull/866 | 1 | closes | SecHub report results do not contain job UUID | ## Situation
With release `v0.27.0-server` the reports did not conain a job uuid any longer.
This is critical for sechub client interactive false-positive handling were the Job UUID of an report is used - and will fail because not existing.
## Wanted
When user fetches reports the Job UUID must be in report again
## Solution
Problem lays inside `SerecoProductResultTransformer.java` where after the refactoring the job UUID was not set.
This must be fixed.
Also `ScanSecHubReport` shall have an fallback for reports that were currently already transformed without job uuid inside.
| f874525cc3b01eda12d74934fd79782b25b370c6 | 5810a49ce9dd6895502d71765886164430270aa3 | https://github.com/mercedes-benz/sechub/compare/f874525cc3b01eda12d74934fd79782b25b370c6...5810a49ce9dd6895502d71765886164430270aa3 | diff --git a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/AssertReport.java b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/AssertReport.java
index b5e6ac84e..f7237c685 100644
--- a/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/AssertReport.java
+++ b/sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/AssertReport.java
@@ -235,11 +235,15 @@ public class AssertReport {
assertNotNull(findings);
return findings;
}
-
- public AssertReport hasJobUUID(String uuidAsString) {
- assertEquals(UUID.fromString(uuidAsString), report.getJobUUID());
+
+ public AssertReport hasJobUUID(UUID uuid) {
+ assertEquals(uuid, report.getJobUUID());
return this;
}
+
+ public AssertReport hasJobUUID(String uuidAsString) {
+ return hasJobUUID(UUID.fromString(uuidAsString));
+ }
public AssertReport dump() {
LOG.info("-----------------------------------------------------------");
diff --git a/sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario10/PDSCodeScanSarifJobScenario10IntTest.java b/sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario10/PDSCodeScanSarifJobScenario10IntTest.java
index ddb83f8f8..8ee2d60ed 100644
--- a/sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario10/PDSCodeScanSarifJobScenario10IntTest.java
+++ b/sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario10/PDSCodeScanSarifJobScenario10IntTest.java
@@ -66,6 +66,7 @@ public class PDSCodeScanSarifJobScenario10IntTest {
assertReport(report).
hasStatus(SecHubStatus.SUCCESS).
hasMessages(0).
+ hasJobUUID(jobUUID).
hasTrafficLight(RED).
finding(0).
hasSeverity(Severity.HIGH).
diff --git a/sechub-scan-product-sereco/src/main/java/com/daimler/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java b/sechub-scan-product-sereco/src/main/java/com/daimler/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java
index 28c9e8ba6..d23cb466a 100644
--- a/sechub-scan-product-sereco/src/main/java/com/daimler/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java
+++ b/sechub-scan-product-sereco/src/main/java/com/daimler/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java
@@ -56,6 +56,7 @@ public class SerecoProductResultTransformer implements ReportProductResultTransf
ReportTransformationResult transformerResult = new ReportTransformationResult();
transformerResult.setReportVersion(SecHubReportVersion.VERSION_1_0.getVersionAsString());
+ transformerResult.setJobUUID(sechubJobUUID);
List<SecHubFinding> findings = transformerResult.getResult().getFindings();
diff --git a/sechub-scan/src/main/java/com/daimler/sechub/domain/scan/report/ScanSecHubReport.java b/sechub-scan/src/main/java/com/daimler/sechub/domain/scan/report/ScanSecHubReport.java
index 53882039f..db3ed5278 100644
--- a/sechub-scan/src/main/java/com/daimler/sechub/domain/scan/report/ScanSecHubReport.java
+++ b/sechub-scan/src/main/java/com/daimler/sechub/domain/scan/report/ScanSecHubReport.java
@@ -59,6 +59,11 @@ public class ScanSecHubReport implements SecHubReportData, JSONable<ScanSecHubRe
if (ScanReportResultType.MODEL.equals(resultType)) {
try {
model = SecHubReportModel.fromJSONString(report.getResult());
+ if (model.getJobUUID() == null) {
+ // Fallback for problems when model did not contain job uuid - see https://github.com/Daimler/sechub/issues/864
+ LOG.warn("Job uuid not found inside report result JSON, will set Job UUID from entity data");
+ model.setJobUUID(report.getSecHubJobUUID());
+ }
} catch (JSONConverterException e) {
LOG.error("FATAL PROBLEM! Failed to create sechub result by model for job:{}", report.getSecHubJobUUID(), e);
diff --git a/sechub-scan/src/test/java/com/daimler/sechub/domain/scan/report/ScanSecHubReportTest.java b/sechub-scan/src/test/java/com/daimler/sechub/domain/scan/report/ScanSecHubReportTest.java
index e35ace13f..6c9bac7aa 100644
--- a/sechub-scan/src/test/java/com/daimler/sechub/domain/scan/report/ScanSecHubReportTest.java
+++ b/sechub-scan/src/test/java/com/daimler/sechub/domain/scan/report/ScanSecHubReportTest.java
@@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.util.List;
+import java.util.UUID;
import org.junit.jupiter.api.Test;
@@ -18,6 +19,8 @@ import com.daimler.sechub.commons.model.Severity;
import com.daimler.sechub.commons.model.TrafficLight;
import com.daimler.sechub.domain.scan.ScanDomainTestFileSupport;
+import static org.mockito.Mockito.*;
+
class ScanSecHubReportTest {
@Test
@@ -115,6 +118,52 @@ class ScanSecHubReportTest {
assertEquals(TrafficLight.GREEN, reportToTest.getTrafficLight());
}
+ @Test
+ void report_by_model_sets_jobUUID_from_scanreport_when_not_inside_model() {
+
+ /* prepare */
+ UUID uuid = UUID.randomUUID();
+
+ ScanReport report = mock(ScanReport.class);
+ when(report.getResultType()).thenReturn(ScanReportResultType.MODEL);
+ when(report.getSecHubJobUUID()).thenReturn(uuid);
+
+ SecHubReportModel model = new SecHubReportModel();
+
+ String jsonResult = model.toJSON();
+ when(report.getResult()).thenReturn(jsonResult);
+
+ /* execute */
+ ScanSecHubReport createdReport = new ScanSecHubReport(report);
+
+ /* test */
+ assertEquals(uuid, createdReport.getJobUUID());
+ }
+
+ @Test
+ void report_by_model_has_jobUUID_from_model_when_there_not_null() {
+
+ /* prepare */
+ UUID uuid1 = UUID.randomUUID();
+ UUID uuid2 = UUID.randomUUID();
+
+ ScanReport report = mock(ScanReport.class);
+ when(report.getResultType()).thenReturn(ScanReportResultType.MODEL);
+ when(report.getSecHubJobUUID()).thenReturn(uuid1);
+
+ SecHubReportModel model = new SecHubReportModel();
+ model.setJobUUID(uuid2);
+
+ String jsonResult = model.toJSON();
+ when(report.getResult()).thenReturn(jsonResult);
+
+ /* execute */
+ ScanSecHubReport createdReport = new ScanSecHubReport(report);
+
+ /* test */
+ assertEquals(uuid2, createdReport.getJobUUID());
+ }
+
@Test
void report_by_model_sets_version_to_version_from_model() {
| ['sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/api/AssertReport.java', 'sechub-scan-product-sereco/src/main/java/com/daimler/sechub/domain/scan/product/sereco/SerecoProductResultTransformer.java', 'sechub-integrationtest/src/test/java/com/daimler/sechub/integrationtest/scenario10/PDSCodeScanSarifJobScenario10IntTest.java', 'sechub-scan/src/test/java/com/daimler/sechub/domain/scan/report/ScanSecHubReportTest.java', 'sechub-scan/src/main/java/com/daimler/sechub/domain/scan/report/ScanSecHubReport.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 2,583,770 | 548,549 | 78,306 | 1,218 | 437 | 88 | 6 | 2 | 604 | 91 | 130 | 15 | 0 | 0 | 1970-01-01T00:27:15 | 159 | Java | {'Java': 7354269, 'Shell': 285620, 'Go': 207604, 'Dockerfile': 58303, 'HTML': 27680, 'TypeScript': 17921, 'Groovy': 8898, 'CSS': 7405, 'Python': 7341, 'C': 748, 'Assembly': 401, 'Batchfile': 391, 'JavaScript': 312, 'Visual Basic .NET': 178, 'Ada': 169, 'Erlang': 140, 'OpenEdge ABL': 139, 'Fortran': 138, 'ABAP': 134, 'Ruby': 103, 'OCaml': 100, 'Scheme': 92, 'Tcl': 77} | MIT License |
357 | opencb/opencga/130/108 | opencb | opencga | https://github.com/opencb/opencga/issues/108 | https://github.com/opencb/opencga/pull/130 | https://github.com/opencb/opencga/pull/130 | 1 | fixes | Ensure that indices are created in mongo | It's not clear if we are creating indices consistently in all branches and in all the collections that need them.
For example, in 0.5 currently there are no indices in `variants` collection.
| fc85135196bf86e1c781b3a1fb9dbd353c752585 | c0f672a15365660ff3c7aa7344012514c8a1adcf | https://github.com/opencb/opencga/compare/fc85135196bf86e1c781b3a1fb9dbd353c752585...c0f672a15365660ff3c7aa7344012514c8a1adcf | diff --git a/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java b/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java
index 5504f07c64..8604fd22fc 100644
--- a/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java
+++ b/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java
@@ -461,21 +461,21 @@ public class VariantMongoDBWriter extends VariantDBWriter {
logger.info("POST");
writeSourceSummary(source);
- DBObject empty = new BasicDBObject(); // are we sure a null won't raise nullptrException? it doesn't seem to be checks anywhere
- variantMongoCollection.createIndex(new BasicDBObject("_at.chunkIds", 1), empty);
- variantMongoCollection.createIndex(new BasicDBObject("annot.xrefs.id", 1), empty);
- variantMongoCollection.createIndex(new BasicDBObject("annot.ct.so", 1), empty);
- variantMongoCollection.createIndex(new BasicDBObject(DBObjectToVariantConverter.IDS_FIELD, 1), empty);
- variantMongoCollection.createIndex(new BasicDBObject(DBObjectToVariantConverter.CHROMOSOME_FIELD, 1), empty);
+ DBObject onBackground = new BasicDBObject("background", true);
+ variantMongoCollection.createIndex(new BasicDBObject("_at.chunkIds", 1), onBackground);
+ variantMongoCollection.createIndex(new BasicDBObject("annot.xrefs.id", 1), onBackground);
+ variantMongoCollection.createIndex(new BasicDBObject("annot.ct.so", 1), onBackground);
+ variantMongoCollection.createIndex(new BasicDBObject(DBObjectToVariantConverter.IDS_FIELD, 1), onBackground);
+ variantMongoCollection.createIndex(new BasicDBObject(DBObjectToVariantConverter.CHROMOSOME_FIELD, 1), onBackground);
variantMongoCollection.createIndex(
new BasicDBObject(DBObjectToVariantConverter.FILES_FIELD + "." + DBObjectToVariantSourceEntryConverter.STUDYID_FIELD, 1)
- .append(DBObjectToVariantConverter.FILES_FIELD + "." + DBObjectToVariantSourceEntryConverter.FILEID_FIELD, 1), empty);
- variantMongoCollection.createIndex(new BasicDBObject("st.maf", 1), empty);
- variantMongoCollection.createIndex(new BasicDBObject("st.mgf", 1), empty);
+ .append(DBObjectToVariantConverter.FILES_FIELD + "." + DBObjectToVariantSourceEntryConverter.FILEID_FIELD, 1), onBackground);
+ variantMongoCollection.createIndex(new BasicDBObject("st.maf", 1), onBackground);
+ variantMongoCollection.createIndex(new BasicDBObject("st.mgf", 1), onBackground);
variantMongoCollection.createIndex(
new BasicDBObject(DBObjectToVariantConverter.CHROMOSOME_FIELD, 1)
.append(DBObjectToVariantConverter.START_FIELD, 1)
- .append(DBObjectToVariantConverter.END_FIELD, 1), empty);
+ .append(DBObjectToVariantConverter.END_FIELD, 1), onBackground);
logger.debug("sent order to create indices");
logger.debug("checkExistsTime " + checkExistsTime / 1000000.0 + "ms "); | ['opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,640,582 | 548,562 | 68,771 | 260 | 2,067 | 432 | 20 | 1 | 192 | 32 | 41 | 4 | 0 | 0 | 1970-01-01T00:23:52 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
356 | opencb/opencga/529/528 | opencb | opencga | https://github.com/opencb/opencga/issues/528 | https://github.com/opencb/opencga/pull/529 | https://github.com/opencb/opencga/pull/529 | 1 | fix | OpenCGA fails to parse NC_007605 contigs. | Our samples contain Human herpesvirus 4 complete wild type genome (NC_007605) [1] for QC purpose. OpenCGA fails to parse gVCF files with it. Exception [2] is below and pull request will follow.
[1] https://www.ncbi.nlm.nih.gov/nuccore/82503188
[2]
```
Caused by: org.opencb.opencga.storage.core.exceptions.StorageEngineException: Error while Transforming file /path/to/g.vcf.gz into /path/to/g.vcf.gz.variants.proto.gz
at org.opencb.opencga.storage.hadoop.variant.AbstractHadoopVariantStoragePipeline.processProto(AbstractHadoopVariantStoragePipeline.java:267)
at org.opencb.opencga.storage.core.variant.VariantStoragePipeline.transform(VariantStoragePipeline.java:422)
at org.opencb.opencga.storage.core.StorageEngine.transformFile(StorageEngine.java:144)
... 10 more
Caused by: java.lang.IllegalStateException: Block ID is not valid - exected 2 blocks separaed by `_`; value `NC_007605_000000000000`
at org.opencb.opencga.storage.hadoop.variant.GenomeHelper.splitBlockId(GenomeHelper.java:231)
at org.opencb.opencga.storage.hadoop.variant.archive.VariantHbaseTransformTask.lambda$orderKeys$2(VariantHbaseTransformTask.java:154)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.LinkedList$LLSpliterator.forEachRemaining(LinkedList.java:1235)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at org.opencb.opencga.storage.hadoop.variant.archive.VariantHbaseTransformTask.orderKeys(VariantHbaseTransformTask.java:155)
at org.opencb.opencga.storage.hadoop.variant.archive.VariantHbaseTransformTask.checkSlices(VariantHbaseTransformTask.java:123)
at org.opencb.opencga.storage.hadoop.variant.archive.VariantHbaseTransformTask.encodeVariants(VariantHbaseTransformTask.java:92)
at org.opencb.opencga.storage.hadoop.variant.archive.VariantHbaseTransformTask.apply(VariantHbaseTransformTask.java:85)
at org.opencb.opencga.storage.hadoop.variant.AbstractHadoopVariantStoragePipeline.processProto(AbstractHadoopVariantStoragePipeline.java:237)
``` | 6f14d3aba69bd85b723b6805ea967ae0a6cb3e9c | 079fe277faecc7bca762571fb68d39ec19bc7138 | https://github.com/opencb/opencga/compare/6f14d3aba69bd85b723b6805ea967ae0a6cb3e9c...079fe277faecc7bca762571fb68d39ec19bc7138 | diff --git a/opencga-storage/opencga-storage-hadoop/opencga-storage-hadoop-core/src/main/java/org/opencb/opencga/storage/hadoop/variant/GenomeHelper.java b/opencga-storage/opencga-storage-hadoop/opencga-storage-hadoop-core/src/main/java/org/opencb/opencga/storage/hadoop/variant/GenomeHelper.java
index 590d34469b..116c37cf97 100644
--- a/opencga-storage/opencga-storage-hadoop/opencga-storage-hadoop-core/src/main/java/org/opencb/opencga/storage/hadoop/variant/GenomeHelper.java
+++ b/opencga-storage/opencga-storage-hadoop/opencga-storage-hadoop-core/src/main/java/org/opencb/opencga/storage/hadoop/variant/GenomeHelper.java
@@ -227,11 +227,23 @@ public class GenomeHelper implements AutoCloseable {
public String[] splitBlockId(String blockId) {
char sep = getSeparator();
String[] split = StringUtils.splitPreserveAllTokens(blockId, sep);
- if (split.length != 2) {
- throw new IllegalStateException(String.format("Block ID is not valid - exected 2 blocks separaed by `%s`; value `%s`", sep,
- blockId));
+
+ if (split.length < 2) {
+ throw new IllegalStateException(
+ String.format("Block ID is not valid - expected 2 or more blocks separated by `%s`; value `%s`", sep, blockId));
}
- return split;
+
+ // Should parse contigs with separator in names, e.g. NC_007605
+ StringBuilder contig = new StringBuilder();
+ for (int i = 0; i < split.length - 1; i++) {
+ contig.append(split[i]);
+ if (i < split.length - 2) {
+ contig.append(String.valueOf(sep));
+ }
+ }
+
+ String[] res = {contig.toString(), split[split.length - 1]};
+ return res;
}
/* *************** | ['opencga-storage/opencga-storage-hadoop/opencga-storage-hadoop-core/src/main/java/org/opencb/opencga/storage/hadoop/variant/GenomeHelper.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 6,278,997 | 1,275,042 | 147,678 | 594 | 873 | 198 | 20 | 1 | 2,358 | 101 | 557 | 29 | 1 | 1 | 1970-01-01T00:24:47 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
359 | opencb/opencga/121/111 | opencb | opencga | https://github.com/opencb/opencga/issues/111 | https://github.com/opencb/opencga/pull/121 | https://github.com/opencb/opencga/pull/121 | 1 | resolves | VepVariantAnnotator hangs when an exception occurs | If the VEP file used as input is not found, the following exceptions are displayed: http://pastebin.com/cAMW0vQh, but the application is not aborted, it just hangs.
| 93c4c3b6c21e0d1b344c0b5e83407d5b2e60e829 | 711b2dc91403a75b36266ad7c839ac15f05126ad | https://github.com/opencb/opencga/compare/93c4c3b6c21e0d1b344c0b5e83407d5b2e60e829...711b2dc91403a75b36266ad7c839ac15f05126ad | diff --git a/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/annotation/VepVariantAnnotator.java b/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/annotation/VepVariantAnnotator.java
index 7f5219313d..c917599c06 100644
--- a/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/annotation/VepVariantAnnotator.java
+++ b/opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/annotation/VepVariantAnnotator.java
@@ -22,6 +22,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
+import static org.opencb.opencga.lib.common.ExceptionUtils.getExceptionString;
+
/**
* Created by fjlopez on 10/04/15.
*/
@@ -93,7 +95,19 @@ public class VepVariantAnnotator implements VariantAnnotator {
vepFormatReader.post();
vepFormatReader.close();
} catch (InterruptedException e) {
- e.printStackTrace();
+ logger.error(getExceptionString(e));
+ } catch (Exception e) {
+ logger.error(getExceptionString(e));
+ logger.error("Thread ends UNEXPECTEDLY due to an exception raising.");
+ try {
+ for (int i = 0; i < numConsumers; i++) { //Add a lastElement marker. Consumers will stop reading when read this element.
+ queue.put(lastElement);
+ }
+ logger.debug("Consumers were notified to finish.");
+ } catch (InterruptedException ie) {
+ logger.error("Another exception occurred when finishing.");
+ logger.error(getExceptionString(e));
+ }
}
}
});
@@ -119,7 +133,10 @@ public class VepVariantAnnotator implements VariantAnnotator {
}
logger.debug("thread finished updating annotations");
} catch (InterruptedException e) {
- e.printStackTrace();
+ logger.error(getExceptionString(e));
+ } catch (Exception e) {
+ logger.error(getExceptionString(e));
+ logger.error("Thread ends UNEXPECTEDLY due to exception raising.");
}
}
});
@@ -130,7 +147,11 @@ public class VepVariantAnnotator implements VariantAnnotator {
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error("annotation interrupted");
- e.printStackTrace();
+ logger.error(getExceptionString(e));
+ } catch (Exception e) {
+ logger.error(getExceptionString(e));
+ logger.error("Thread executor ends UNEXPECTEDLY due to exception raising.");
+ executor.shutdown();
}
/** Join | ['opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/annotation/VepVariantAnnotator.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,646,783 | 549,926 | 68,909 | 261 | 1,531 | 234 | 27 | 1 | 165 | 25 | 42 | 2 | 1 | 0 | 1970-01-01T00:23:51 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
364 | opencb/opencga/74/69 | opencb | opencga | https://github.com/opencb/opencga/issues/69 | https://github.com/opencb/opencga/pull/74 | https://github.com/opencb/opencga/pull/74 | 1 | resolves | OpenCGA main command line sets too many Storage arguments | The following opencga-storage arguments should not be set by the main OpenCGA command line:
- include-genotypes
- compress-genotypes
- include-stats
| 53f064e16e1b0481ed6762993cff17f85bd932bd | ff6b57ba12a05bf7fc104d172a2b96859253acfe | https://github.com/opencb/opencga/compare/53f064e16e1b0481ed6762993cff17f85bd932bd...ff6b57ba12a05bf7fc104d172a2b96859253acfe | diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/storage/AnalysisFileIndexer.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/storage/AnalysisFileIndexer.java
index e0ab3801c3..f90a1bd147 100644
--- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/storage/AnalysisFileIndexer.java
+++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/storage/AnalysisFileIndexer.java
@@ -285,9 +285,6 @@ public class AnalysisFileIndexer {
.append(" --database ").append(dbName)
.append(" --input ").append(catalogManager.getFileUri(file))
.append(" --outdir ").append(outDirUri)
- .append(" --include-genotypes ")
- .append(" --compress-genotypes ")
- .append(" --include-stats ")
// .append(" --sample-ids ").append(sampleIdsString)
// .append(" --credentials ")
; | ['opencga-analysis/src/main/java/org/opencb/opencga/analysis/storage/AnalysisFileIndexer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,622,126 | 544,952 | 68,411 | 259 | 158 | 26 | 3 | 1 | 149 | 20 | 34 | 5 | 0 | 0 | 1970-01-01T00:23:49 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
9,303 | mercedes-benz/sechub/1785/1780 | mercedes-benz | sechub | https://github.com/mercedes-benz/sechub/issues/1780 | https://github.com/mercedes-benz/sechub/pull/1785 | https://github.com/mercedes-benz/sechub/pull/1785 | 1 | closes | Fix problem of failing FileUploadSizeScenario2IntTest on S3 storage | ## Situation
In integration test `FileUploadSizeScenario2IntTest` the test method `when_binaries_tarfile_exceeds_NOT_max_bin_file_size_file_is_uploaded` fails on S3 usage.
The problematic part is here:
```java
assertEquals("Fetched file size not as expected for " + data.fileNameAtServerSide + " !", realFileSizeInBytes, fetchedSize);
```
The problem happens only on S3 usage, not when we use a network share volume.
It happens on build servers and also on local machines.
### Wanted
Find a solution... | c12429348c718cdf050c9be143bc38b7a2f38dba | 14c9b31d9e656ed6cb81d5f0322b5a1bcb7924bd | https://github.com/mercedes-benz/sechub/compare/c12429348c718cdf050c9be143bc38b7a2f38dba...14c9b31d9e656ed6cb81d5f0322b5a1bcb7924bd | diff --git a/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AsUser.java b/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AsUser.java
index 28cd47c47..0d638bc56 100644
--- a/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AsUser.java
+++ b/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AsUser.java
@@ -740,19 +740,18 @@ public class AsUser {
}
}
- public File downloadAsTempFileFromURL(String url, UUID jobUUID) {
- String fileName = "sechub-file-redownload-" + jobUUID.toString();
- String fileEnding = ".zip";
- return downloadAsTempFileFromURL(url, jobUUID, fileName, fileEnding);
+ public File downloadAsTempFileFromURL(String url, UUID jobUUID, String fileName) {
+ String prefix = "sechub-file-redownload-" + jobUUID.toString();
+ return downloadAsTempFileFromURL(url, jobUUID, prefix, fileName);
}
- public File downloadAsTempFileFromURL(String url, UUID jobUUID, String fileName, String fileEnding) {
+ public File downloadAsTempFileFromURL(String url, UUID jobUUID, String prefix, String fileEnding) {
// Optional Accept header
RequestCallback requestCallback = request -> request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
ResponseExtractor<File> responseExtractor = response -> {
- Path path = TestUtil.createTempFileInBuildFolder(fileName, fileEnding);
+ Path path = TestUtil.createTempFileInBuildFolder(prefix, fileEnding);
Files.copy(response.getBody(), path, StandardCopyOption.REPLACE_EXISTING);
if (TestUtil.isDeletingTempFiles()) {
path.toFile().deleteOnExit();
diff --git a/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/TestAPI.java b/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/TestAPI.java
index c7712b235..9c6536aa3 100644
--- a/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/TestAPI.java
+++ b/sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/TestAPI.java
@@ -695,7 +695,7 @@ public class TestAPI {
SecHubTestURLBuilder urlBuilder = IntegrationTestContext.get().getUrlBuilder();
String url = urlBuilder.buildGetFileUpload(project.getProjectId(), jobUUID.toString(), fileName);
try {
- File file = as(ANONYMOUS).downloadAsTempFileFromURL(url, jobUUID);
+ File file = as(ANONYMOUS).downloadAsTempFileFromURL(url, jobUUID, fileName);
return file;
} catch (HttpStatusCodeException e) {
if (HttpStatus.NOT_FOUND.equals(e.getStatusCode())) {
diff --git a/sechub-server-core/src/main/java/com/mercedesbenz/sechub/server/core/IntegrationTestServerRestController.java b/sechub-server-core/src/main/java/com/mercedesbenz/sechub/server/core/IntegrationTestServerRestController.java
index a8c2fd5b8..6750eff5b 100644
--- a/sechub-server-core/src/main/java/com/mercedesbenz/sechub/server/core/IntegrationTestServerRestController.java
+++ b/sechub-server-core/src/main/java/com/mercedesbenz/sechub/server/core/IntegrationTestServerRestController.java
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: MIT
package com.mercedesbenz.sechub.server.core;
-import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@@ -14,7 +13,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Profile;
-import org.springframework.core.io.ByteArrayResource;
+import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -202,6 +201,7 @@ public class IntegrationTestServerRestController {
return ResponseEntity.notFound().build();
}
LOG.info("Integration test server: getJobStorage for {} {}", logSanitizer.sanitize(projectId, 30), jobUUID);
+
JobStorage storage = storageService.getJobStorage(projectId, jobUUID);
if (!storage.isExisting(fileName)) {
throw new NotFoundException("file not uploaded:" + fileName);
@@ -214,13 +214,9 @@ public class IntegrationTestServerRestController {
headers.add("Expires", "0");
/* @formatter:off */
- byte[] bytes = new byte[inputStream.available()];
- new DataInputStream(inputStream).readFully(bytes);
- ByteArrayResource resource = new ByteArrayResource(bytes);
-
+ InputStreamResource resource = new InputStreamResource(inputStream);
return ResponseEntity.ok()
.headers(headers)
- .contentLength(resource.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
/* @formatter:on */ | ['sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/AsUser.java', 'sechub-server-core/src/main/java/com/mercedesbenz/sechub/server/core/IntegrationTestServerRestController.java', 'sechub-integrationtest/src/main/java/com/mercedesbenz/sechub/integrationtest/api/TestAPI.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,405,276 | 703,875 | 98,000 | 1,505 | 435 | 73 | 10 | 1 | 518 | 66 | 119 | 13 | 0 | 1 | 1970-01-01T00:27:49 | 159 | Java | {'Java': 7354269, 'Shell': 285620, 'Go': 207604, 'Dockerfile': 58303, 'HTML': 27680, 'TypeScript': 17921, 'Groovy': 8898, 'CSS': 7405, 'Python': 7341, 'C': 748, 'Assembly': 401, 'Batchfile': 391, 'JavaScript': 312, 'Visual Basic .NET': 178, 'Ada': 169, 'Erlang': 140, 'OpenEdge ABL': 139, 'Fortran': 138, 'ABAP': 134, 'Ruby': 103, 'OCaml': 100, 'Scheme': 92, 'Tcl': 77} | MIT License |
9,305 | mercedes-benz/sechub/1644/1643 | mercedes-benz | sechub | https://github.com/mercedes-benz/sechub/issues/1643 | https://github.com/mercedes-benz/sechub/pull/1644 | https://github.com/mercedes-benz/sechub/pull/1644 | 1 | closes | Improve SerecoSourceRelevantPartResolver to avoid NPE inside Sereco | ### Situation
The relevant part resolver inside Sereco can fail when doing the regular expression matching when the source is null.
### Wanted
No NPE when source is null
### Solution
Inside `SerecoSourceRelevantPartResolver.java` we check for `null` and return an empty string as a fallback result.
https://github.com/mercedes-benz/sechub/blob/1deb8b6aba4e1a5d891f1b1e8cfb25fdf2a3198a/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolver.java#L13-L16
```java
public String toRelevantPart(String source) {
String result = P.matcher(source).replaceAll("");
return result.toLowerCase();
}
```
### Details
```java
Caused by: java.lang.NullPointerException: null
at java.base/java.util.regex.Matcher.getTextLength(Unknown Source)
at java.base/java.util.regex.Matcher.reset(Unknown Source)
at java.base/java.util.regex.Matcher.<init>(Unknown Source)
at java.base/java.util.regex.Pattern.matcher(Unknown Source)
at com.mercedesbenz.sechub.domain.scan.product.sereco.SerecoSourceRelevantPartResolver.toRelevantPart(SerecoSourceRelevantPartResolver.java:14)
at com.mercedesbenz.sechub.domain.scan.product.sereco.SerecoFalsePositiveCodeScanStrategy.createRelevantReplacment(SerecoFalsePositiveCodeScanStrategy.java:153)
at com.mercedesbenz.sechub.domain.scan.product.sereco.SerecoFalsePositiveCodeScanStrategy.isFalsePositive(SerecoFalsePositiveCodeScanStrategy.java:120)
at com.mercedesbenz.sechub.domain.scan.product.sereco.SerecoFalsePositiveFinder.isFound(SerecoFalsePositiveFinder.java:37)
at com.mercedesbenz.sechub.domain.scan.product.sereco.SerecoFalsePositiveMarker.isFalsePositive(SerecoFalsePositiveMarker.java:91)
at com.mercedesbenz.sechub.domain.scan.product.sereco.SerecoFalsePositiveMarker.handleVulnereability(SerecoFalsePositiveMarker.java:68)
at com.mercedesbenz.sechub.domain.scan.product.sereco.SerecoFalsePositiveMarker.markFalsePositives(SerecoFalsePositiveMarker.java:61)
at com.mercedesbenz.sechub.domain.scan.product.sereco.SerecoProductResultTransformer.transform(SerecoProductResultTransformer.java:68)
at com.mercedesbenz.sechub.domain.scan.SecHubReportProductTransformerService.createResult(SecHubReportProductTransformerService.java:75)
at com.mercedesbenz.sechub.domain.scan.SecHubReportProductTransformerService.createResult(SecHubReportProductTransformerService.java:53)
at com.mercedesbenz.sechub.domain.scan.report.CreateScanReportService.createReport(CreateScanReportService.java:79)
``` | e63c92044d315d2602f82a39ab25b43e99f2b493 | dc61fdfd6a5516ee0cf012a396152dd1d7d59117 | https://github.com/mercedes-benz/sechub/compare/e63c92044d315d2602f82a39ab25b43e99f2b493...dc61fdfd6a5516ee0cf012a396152dd1d7d59117 | diff --git a/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolver.java b/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolver.java
index 0b92a107d..1599733c8 100644
--- a/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolver.java
+++ b/sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolver.java
@@ -11,6 +11,9 @@ public class SerecoSourceRelevantPartResolver {
private static final Pattern P = Pattern.compile("\\\\s");
public String toRelevantPart(String source) {
+ if (source == null) {
+ return "";
+ }
String result = P.matcher(source).replaceAll("");
return result.toLowerCase();
}
diff --git a/sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolverTest.java b/sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolverTest.java
index 5116790dc..14e324d70 100644
--- a/sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolverTest.java
+++ b/sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolverTest.java
@@ -1,22 +1,22 @@
// SPDX-License-Identifier: MIT
package com.mercedesbenz.sechub.domain.scan.product.sereco;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class SerecoSourceRelevantPartResolverTest {
private SerecoSourceRelevantPartResolver resolverToTest;
- @Before
- public void before() throws Exception {
+ @BeforeEach
+ void beforeEach() throws Exception {
resolverToTest = new SerecoSourceRelevantPartResolver();
}
@Test
- public void shrink_whitespaces() {
+ void shrink_whitespaces() {
assertEquals("iwillbeshrinked", resolverToTest.toRelevantPart("i will be shrinked"));
assertEquals("iwillbeshrinked", resolverToTest.toRelevantPart("i will be shrinked"));
assertEquals("iwillbeshrinked", resolverToTest.toRelevantPart("i will beshrinked"));
@@ -25,10 +25,20 @@ public class SerecoSourceRelevantPartResolverTest {
}
@Test
- public void lowercased() {
+ void lowercased() {
assertEquals("lowered", resolverToTest.toRelevantPart("loWEREd"));
assertEquals("lowered", resolverToTest.toRelevantPart("LOWERED"));
assertEquals("lowered", resolverToTest.toRelevantPart("lowered"));
}
+ @Test
+ void null_source_returns_empty_string() {
+ assertEquals("", resolverToTest.toRelevantPart(null));
+ }
+
+ @Test
+ void empty_source_returns_empty_string() {
+ assertEquals("", resolverToTest.toRelevantPart(""));
+ }
+
} | ['sechub-scan-product-sereco/src/test/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolverTest.java', 'sechub-scan-product-sereco/src/main/java/com/mercedesbenz/sechub/domain/scan/product/sereco/SerecoSourceRelevantPartResolver.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,318,687 | 686,724 | 95,831 | 1,479 | 65 | 13 | 3 | 1 | 2,628 | 103 | 626 | 37 | 1 | 2 | 1970-01-01T00:27:43 | 159 | Java | {'Java': 7354269, 'Shell': 285620, 'Go': 207604, 'Dockerfile': 58303, 'HTML': 27680, 'TypeScript': 17921, 'Groovy': 8898, 'CSS': 7405, 'Python': 7341, 'C': 748, 'Assembly': 401, 'Batchfile': 391, 'JavaScript': 312, 'Visual Basic .NET': 178, 'Ada': 169, 'Erlang': 140, 'OpenEdge ABL': 139, 'Fortran': 138, 'ABAP': 134, 'Ruby': 103, 'OCaml': 100, 'Scheme': 92, 'Tcl': 77} | MIT License |
360 | opencb/opencga/112/108 | opencb | opencga | https://github.com/opencb/opencga/issues/108 | https://github.com/opencb/opencga/pull/112 | https://github.com/opencb/opencga/pull/112 | 1 | resolves | Ensure that indices are created in mongo | It's not clear if we are creating indices consistently in all branches and in all the collections that need them.
For example, in 0.5 currently there are no indices in `variants` collection.
| d54cd38bcf0645c61178d6d083bbf56954c94609 | 6054188d422240d717c2dd03b71982562d97f73c | https://github.com/opencb/opencga/compare/d54cd38bcf0645c61178d6d083bbf56954c94609...6054188d422240d717c2dd03b71982562d97f73c | diff --git a/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java b/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java
index 2d99b9223d..5504f07c64 100644
--- a/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java
+++ b/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java
@@ -460,6 +460,24 @@ public class VariantMongoDBWriter extends VariantDBWriter {
}
logger.info("POST");
writeSourceSummary(source);
+
+ DBObject empty = new BasicDBObject(); // are we sure a null won't raise nullptrException? it doesn't seem to be checks anywhere
+ variantMongoCollection.createIndex(new BasicDBObject("_at.chunkIds", 1), empty);
+ variantMongoCollection.createIndex(new BasicDBObject("annot.xrefs.id", 1), empty);
+ variantMongoCollection.createIndex(new BasicDBObject("annot.ct.so", 1), empty);
+ variantMongoCollection.createIndex(new BasicDBObject(DBObjectToVariantConverter.IDS_FIELD, 1), empty);
+ variantMongoCollection.createIndex(new BasicDBObject(DBObjectToVariantConverter.CHROMOSOME_FIELD, 1), empty);
+ variantMongoCollection.createIndex(
+ new BasicDBObject(DBObjectToVariantConverter.FILES_FIELD + "." + DBObjectToVariantSourceEntryConverter.STUDYID_FIELD, 1)
+ .append(DBObjectToVariantConverter.FILES_FIELD + "." + DBObjectToVariantSourceEntryConverter.FILEID_FIELD, 1), empty);
+ variantMongoCollection.createIndex(new BasicDBObject("st.maf", 1), empty);
+ variantMongoCollection.createIndex(new BasicDBObject("st.mgf", 1), empty);
+ variantMongoCollection.createIndex(
+ new BasicDBObject(DBObjectToVariantConverter.CHROMOSOME_FIELD, 1)
+ .append(DBObjectToVariantConverter.START_FIELD, 1)
+ .append(DBObjectToVariantConverter.END_FIELD, 1), empty);
+ logger.debug("sent order to create indices");
+
logger.debug("checkExistsTime " + checkExistsTime / 1000000.0 + "ms ");
logger.debug("checkExistsDBTime " + checkExistsDBTime / 1000000.0 + "ms ");
logger.debug("bulkTime " + bulkTime / 1000000.0 + "ms "); | ['opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/VariantMongoDBWriter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,638,413 | 548,122 | 68,737 | 260 | 1,481 | 307 | 18 | 1 | 192 | 32 | 41 | 4 | 0 | 0 | 1970-01-01T00:23:51 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
9,306 | mercedes-benz/sechub/1619/1615 | mercedes-benz | sechub | https://github.com/mercedes-benz/sechub/issues/1615 | https://github.com/mercedes-benz/sechub/pull/1619 | https://github.com/mercedes-benz/sechub/pull/1619 | 1 | closes | OWASP ZAP Wrapper OpenApi Scanning exits because missing condition | ### Situation
During the implementation of the open api scanning there was a misunterstanding regarding the data section part on my side. I thought the ENV variable:
`PDS_JOB_EXTRACTED_SOURCES_FOLDER` on PDS side will only be set if there are sources extracted to the PDS. I relied on this condition, but this is not enough.
### Solution
Check if the data section was found, otherwise assume no API definition was uploaded. | bfd344fde3d47fbb87a6bfe7bf935a9ecc78e108 | 0cc45c7ae425ad1e98bc01bd0b82688b348bd7be | https://github.com/mercedes-benz/sechub/compare/bfd344fde3d47fbb87a6bfe7bf935a9ecc78e108...0cc45c7ae425ad1e98bc01bd0b82688b348bd7be | diff --git a/sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProvider.java b/sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProvider.java
index 15ef0fde2..d77d6184b 100644
--- a/sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProvider.java
+++ b/sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProvider.java
@@ -5,12 +5,16 @@ import java.io.File;
import java.nio.file.Path;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.mercedesbenz.sechub.commons.model.SecHubScanConfiguration;
import com.mercedesbenz.sechub.commons.model.SecHubSourceDataConfiguration;
import com.mercedesbenz.sechub.owaspzapwrapper.cli.ZapWrapperExitCode;
import com.mercedesbenz.sechub.owaspzapwrapper.cli.ZapWrapperRuntimeException;
public class ApiDefinitionFileProvider {
+ private static final Logger LOG = LoggerFactory.getLogger(ApiDefinitionFileProvider.class);
/**
*
@@ -21,19 +25,22 @@ public class ApiDefinitionFileProvider {
*
* @param extractedSourcesFolderPath
* @param sechubConfig
- * @return Path to API definition file
+ * @return Path to API definition file or <code>null</code> if parameters are
+ * null or no data section is found
*/
public Path fetchApiDefinitionFile(String extractedSourcesFolderPath, SecHubScanConfiguration sechubConfig) {
if (extractedSourcesFolderPath == null) {
- throw new ZapWrapperRuntimeException("Sources folder must not be null!", ZapWrapperExitCode.EXECUTION_FAILED);
+ LOG.info("Extracted sources folder path env variable was not set.");
+ return null;
}
if (sechubConfig == null) {
- throw new ZapWrapperRuntimeException("SecHub scan config must not be null!", ZapWrapperExitCode.EXECUTION_FAILED);
+ LOG.info("SecHub scan configuration was not set.");
+ return null;
}
if (!sechubConfig.getData().isPresent()) {
- throw new ZapWrapperRuntimeException("Data section should not be empty since a sources folder was found.",
- ZapWrapperExitCode.SECHUB_CONFIGURATION_INVALID);
+ LOG.info("No data section was found. Continuing without searching for API definition.");
+ return null;
}
List<SecHubSourceDataConfiguration> sourceData = sechubConfig.getData().get().getSources();
diff --git a/sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/OwaspZapScanConfigurationFactory.java b/sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/OwaspZapScanConfigurationFactory.java
index c28b4180d..902a967fc 100644
--- a/sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/OwaspZapScanConfigurationFactory.java
+++ b/sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/OwaspZapScanConfigurationFactory.java
@@ -184,12 +184,9 @@ public class OwaspZapScanConfigurationFactory {
}
private Path createPathToApiDefinitionFileOrNull(SecHubScanConfiguration sechubScanConfig) {
- // use the extracted sources folder path if sources where uploaded and extracted
- // on the PDS
+ // use the extracted sources folder path, where all text files are uploaded and
+ // extracted
String extractedSourcesFolderPath = environmentVariableReader.readAsString(EnvironmentVariableConstants.PDS_JOB_EXTRACTED_SOURCES_FOLDER);
- if (extractedSourcesFolderPath == null) {
- return null;
- }
return apiDefinitionFileProvider.fetchApiDefinitionFile(extractedSourcesFolderPath, sechubScanConfig);
}
}
diff --git a/sechub-wrapper-owasp-zap/src/test/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProviderTest.java b/sechub-wrapper-owasp-zap/src/test/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProviderTest.java
index 8e1a880a9..b47a42595 100644
--- a/sechub-wrapper-owasp-zap/src/test/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProviderTest.java
+++ b/sechub-wrapper-owasp-zap/src/test/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProviderTest.java
@@ -22,38 +22,35 @@ class ApiDefinitionFileProviderTest {
private ApiDefinitionFileProvider providerToTest = new ApiDefinitionFileProvider();;
@Test
- void sources_folder_is_null_results_in_must_exit_exception() {
- /* execute + test */
- ZapWrapperRuntimeException exception = assertThrows(ZapWrapperRuntimeException.class,
- () -> providerToTest.fetchApiDefinitionFile(null, new SecHubScanConfiguration()));
+ void sources_folder_is_null_results_in_null_as_api_file_path() {
+ /* execute */
+ Path result = providerToTest.fetchApiDefinitionFile(null, new SecHubScanConfiguration());
- assertEquals("Sources folder must not be null!", exception.getMessage());
- assertEquals(ZapWrapperExitCode.EXECUTION_FAILED, exception.getExitCode());
+ /* test */
+ assertEquals(null, result);
}
@Test
- void sechub_scan_config_is_null_results_in_must_exit_exception() {
- /* execute + test */
- ZapWrapperRuntimeException exception = assertThrows(ZapWrapperRuntimeException.class,
- () -> providerToTest.fetchApiDefinitionFile("/example/path/to/extracted/sources", null));
+ void sechub_scan_config_is_null_results_in_null_as_api_file_path() {
+ /* execute */
+ Path result = providerToTest.fetchApiDefinitionFile("/example/path/to/extracted/sources", null);
- assertEquals("SecHub scan config must not be null!", exception.getMessage());
- assertEquals(ZapWrapperExitCode.EXECUTION_FAILED, exception.getExitCode());
+ /* test */
+ assertEquals(null, result);
}
@Test
- void missing_data_section_part_results_in_zap_wrapper_runtime_exception() {
+ void missing_data_section_part_results_in_null_as_api_file_path() {
/* prepare */
String sechubScanConfigJSON = "{\\"apiVersion\\":\\"1.0\\","
+ "\\"webScan\\":{\\"uri\\":\\"https://localhost:8443\\",\\"api\\":{\\"type\\":\\"openApi\\",\\"use\\":[\\"open-api-file-reference\\"]}}}";
SecHubScanConfiguration sechubScanConfiguration = SecHubScanConfiguration.createFromJSON(sechubScanConfigJSON);
- /* execute + test */
- ZapWrapperRuntimeException exception = assertThrows(ZapWrapperRuntimeException.class,
- () -> providerToTest.fetchApiDefinitionFile("/example/path/to/extracted/sources", sechubScanConfiguration));
+ /* execute */
+ Path result = providerToTest.fetchApiDefinitionFile("/example/path/to/extracted/sources", sechubScanConfiguration);
- assertEquals("Data section should not be empty since a sources folder was found.", exception.getMessage());
- assertEquals(ZapWrapperExitCode.SECHUB_CONFIGURATION_INVALID, exception.getExitCode());
+ /* test */
+ assertEquals(null, result);
}
@ParameterizedTest | ['sechub-wrapper-owasp-zap/src/test/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProviderTest.java', 'sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/OwaspZapScanConfigurationFactory.java', 'sechub-wrapper-owasp-zap/src/main/java/com/mercedesbenz/sechub/owaspzapwrapper/config/ApiDefinitionFileProvider.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 3,318,687 | 686,724 | 95,831 | 1,479 | 1,414 | 266 | 24 | 2 | 429 | 69 | 92 | 6 | 0 | 0 | 1970-01-01T00:27:42 | 159 | Java | {'Java': 7354269, 'Shell': 285620, 'Go': 207604, 'Dockerfile': 58303, 'HTML': 27680, 'TypeScript': 17921, 'Groovy': 8898, 'CSS': 7405, 'Python': 7341, 'C': 748, 'Assembly': 401, 'Batchfile': 391, 'JavaScript': 312, 'Visual Basic .NET': 178, 'Ada': 169, 'Erlang': 140, 'OpenEdge ABL': 139, 'Fortran': 138, 'ABAP': 134, 'Ruby': 103, 'OCaml': 100, 'Scheme': 92, 'Tcl': 77} | MIT License |
361 | opencb/opencga/109/93 | opencb | opencga | https://github.com/opencb/opencga/issues/93 | https://github.com/opencb/opencga/pull/109 | https://github.com/opencb/opencga/pull/109 | 1 | fixes | Job status is not cleaned up when aborted | If a job fails under normal conditions (a managed exception) the status of the involved files is properly handled. But when a job queue manager aborts it for reasons such as too much memory usage, then this status is not cleaned and must be corrected by hand (or forced to be ignored in a re-run).
One solution would be to use Runtime.getRuntime().addShutdownHook(...) from the Java API, although it would be necessary to analyse how this will affect the current CLI structure (unless we find a generic way to deal with status recovery).
| d54cd38bcf0645c61178d6d083bbf56954c94609 | 816666a76dcbfc60c7ffed9eab11e912f47f1642 | https://github.com/opencb/opencga/compare/d54cd38bcf0645c61178d6d083bbf56954c94609...816666a76dcbfc60c7ffed9eab11e912f47f1642 | diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/AnalysisJobExecuter.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/AnalysisJobExecuter.java
index 494e22d360..9537714af9 100644
--- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/AnalysisJobExecuter.java
+++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/AnalysisJobExecuter.java
@@ -16,9 +16,12 @@ import org.opencb.opencga.analysis.beans.Option;
import org.opencb.opencga.lib.common.StringUtils;
import org.opencb.opencga.lib.common.TimeUtils;
import org.opencb.opencga.lib.exec.Command;
+import org.opencb.opencga.lib.exec.RunnableProcess;
import org.opencb.opencga.lib.exec.SingleProcess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import sun.misc.Signal;
+import sun.misc.SignalHandler;
import java.io.IOException;
import java.io.InputStream;
@@ -206,10 +209,10 @@ public class AnalysisJobExecuter {
randomString, temporalOutDirUri, commandLine, false, false, false, new HashMap<String, Object>());
}
- public static QueryResult<Job> createJob(CatalogManager catalogManager, int studyId, String jobName, String toolName, String description,
- File outDir, List<Integer> inputFiles, String sessionId,
+ public static QueryResult<Job> createJob(final CatalogManager catalogManager, int studyId, String jobName, String toolName, String description,
+ File outDir, List<Integer> inputFiles, final String sessionId,
String randomString, URI temporalOutDirUri, String commandLine,
- boolean execute, boolean simulate, boolean recordOutput, Map<String, Object> resourceManagerAttributes)
+ boolean execute, boolean simulate, final boolean recordOutput, Map<String, Object> resourceManagerAttributes)
throws AnalysisExecutionException, CatalogException {
logger.debug("Creating job {}: simulate {}, execute {}, recordOutput {}", jobName, simulate, execute, recordOutput);
long start = System.currentTimeMillis();
@@ -234,11 +237,37 @@ public class AnalysisJobExecuter {
logger.info("Executing job {}({})", jobQueryResult.first().getName(), jobQueryResult.first().getId());
logger.debug("Executing commandLine {}", jobQueryResult.first().getCommandLine());
- Command com = new Command(commandLine);
+ final Command com = new Command(commandLine);
+ final int jobId = jobQueryResult.first().getId();
+ Thread hook = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ logger.info("Running ShutdownHook. Job {id: " + jobId + "} has being aborted.");
+ com.setStatus(RunnableProcess.Status.KILLED);
+ com.setExitValue(-2);
+ catalogManager.modifyJob(jobId, new ObjectMap("resourceManagerAttributes", new ObjectMap("executionInfo", com)), sessionId);
+ if (recordOutput) {
+ // Record Output.
+ // Internally, change status to PROCESSING_OUTPUT and then to READY
+ AnalysisOutputRecorder outputRecorder = new AnalysisOutputRecorder(catalogManager, sessionId);
+ outputRecorder.recordJobOutput(catalogManager.getJob(jobId, null, sessionId).first());
+ catalogManager.modifyJob(jobId, new ObjectMap("status", Job.Status.ERROR), sessionId);
+ } else {
+ // Change status to DONE
+ catalogManager.modifyJob(jobId, new ObjectMap("status", Job.Status.DONE), sessionId);
+ }
+ } catch (CatalogException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ Runtime.getRuntime().addShutdownHook(hook);
// SingleProcess sp = new SingleProcess(com);
// sp.getRunnableProcess().run();
// sp.runSync();
com.run();
+ Runtime.getRuntime().removeShutdownHook(hook);
catalogManager.modifyJob(jobQueryResult.first().getId(), new ObjectMap("resourceManagerAttributes", new ObjectMap("executionInfo", com)), sessionId);
@@ -247,6 +276,9 @@ public class AnalysisJobExecuter {
// Internally, change status to PROCESSING_OUTPUT and then to READY
AnalysisOutputRecorder outputRecorder = new AnalysisOutputRecorder(catalogManager, sessionId);
outputRecorder.recordJobOutput(jobQueryResult.first());
+ if (com.getExitValue() != 0) {
+ catalogManager.modifyJob(jobId, new ObjectMap("status", Job.Status.ERROR), sessionId);
+ }
} else {
// Change status to DONE
catalogManager.modifyJob(jobQueryResult.first().getId(), new ObjectMap("status", Job.Status.DONE), sessionId); | ['opencga-analysis/src/main/java/org/opencb/opencga/analysis/AnalysisJobExecuter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,638,413 | 548,122 | 68,737 | 260 | 2,964 | 471 | 40 | 1 | 539 | 92 | 109 | 4 | 0 | 0 | 1970-01-01T00:23:51 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
363 | opencb/opencga/79/51 | opencb | opencga | https://github.com/opencb/opencga/issues/51 | https://github.com/opencb/opencga/pull/79 | https://github.com/opencb/opencga/pull/79 | 1 | resolves | tag names in vcf header with dots | DBObjectToVariantSourceConverter complains when a vcf has a line in the header like:
```
##source_20120715.1=...
```
because mongo doesn't allow dots in field names, so they are not loaded. Maybe it's interesting adding a char mapping in the converter.
| 804790e9e3cef9b5ba6923420da43e3e95ba0a6e | 1cc6e9d5eb2bfd951a0bd6d77e8a5bd37c455e0e | https://github.com/opencb/opencga/compare/804790e9e3cef9b5ba6923420da43e3e95ba0a6e...1cc6e9d5eb2bfd951a0bd6d77e8a5bd37c455e0e | diff --git a/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverter.java b/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverter.java
index 539e8d83bf..a71627772b 100644
--- a/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverter.java
+++ b/opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverter.java
@@ -57,7 +57,7 @@ public class DBObjectToVariantSourceConverter implements ComplexTypeConverter<Va
if (object.containsField(SAMPLES_FIELD)) {
Map<String, Integer> samplesPosition = new HashMap<>();
for (Map.Entry<String, Integer> entry : ((Map<String, Integer>) object.get(SAMPLES_FIELD)).entrySet()) {
- samplesPosition.put(entry.getKey().replace(CHARACTER_TO_REPLACE_DOTS, ','), entry.getValue());
+ samplesPosition.put(entry.getKey().replace(CHARACTER_TO_REPLACE_DOTS, '.'), entry.getValue());
}
source.setSamplesPosition(samplesPosition);
}
@@ -87,7 +87,7 @@ public class DBObjectToVariantSourceConverter implements ComplexTypeConverter<Va
// Metadata
BasicDBObject metadata = (BasicDBObject) object.get(METADATA_FIELD);
for (Map.Entry<String, Object> o : metadata.entrySet()) {
- source.addMetadata(o.getKey(), o.getValue());
+ source.addMetadata(o.getKey().replace(CHARACTER_TO_REPLACE_DOTS, '.'), o.getValue());
}
return source;
@@ -141,17 +141,16 @@ public class DBObjectToVariantSourceConverter implements ComplexTypeConverter<Va
for (Map.Entry<String, Object> metaEntry : meta.entrySet()) {
if (metaEntry.getKey().equals("variantFileHeader")) {
metadataMongo.append(HEADER_FIELD, metaEntry.getValue());
- } else if (!metaEntry.getKey().contains(".")) {
+ } else {
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer();
+ String key = metaEntry.getKey().replace('.', CHARACTER_TO_REPLACE_DOTS);
try {
- metadataMongo.append(metaEntry.getKey(), JSON.parse(writer.writeValueAsString(metaEntry.getValue())));
+ metadataMongo.append(key, JSON.parse(writer.writeValueAsString(metaEntry.getValue())));
} catch (JsonProcessingException e) {
logger.log(Level.WARNING, "Metadata key {0} could not be parsed in json", metaEntry.getKey());
logger.log(Level.INFO, "{}", e.toString());
}
- } else {
- logger.log(Level.WARNING, "Metadata key {0} could not be inserted", metaEntry.getKey());
}
}
studyMongo = studyMongo.append(METADATA_FIELD, metadataMongo);
diff --git a/opencga-storage/opencga-storage-mongodb/src/test/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverterTest.java b/opencga-storage/opencga-storage-mongodb/src/test/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverterTest.java
index d364e2fa37..1a11f36e70 100644
--- a/opencga-storage/opencga-storage-mongodb/src/test/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverterTest.java
+++ b/opencga-storage/opencga-storage-mongodb/src/test/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverterTest.java
@@ -9,6 +9,7 @@ import org.junit.BeforeClass;
import org.junit.Test;
import org.opencb.biodata.formats.variant.vcf4.VcfFormatHeader;
import org.opencb.biodata.models.variant.VariantSource;
+import org.opencb.biodata.models.variant.VariantStudy;
import org.opencb.biodata.models.variant.stats.VariantGlobalStats;
/**
@@ -30,14 +31,16 @@ public class DBObjectToVariantSourceConverterTest {
source.getSamplesPosition().put("NA002", 2);
source.getSamplesPosition().put("NA003", 3);
source.addMetadata("header", "##fileformat=v4.1");
- source.addMetadata("FORMAT", new VcfFormatHeader("id", "1", "Integer", "description"));
+ source.addMetadata("FORMAT.A", new VcfFormatHeader("id", "1", "Integer", "description"));
VariantGlobalStats global = new VariantGlobalStats(10, 4, 7, 3, 0, 9, 4, 4, -1, 20.5f, null);
source.setStats(global);
+ source.setType(VariantStudy.StudyType.CASE_CONTROL);
mongoSource = new BasicDBObject(DBObjectToVariantSourceConverter.FILENAME_FIELD, source.getFileName())
.append(DBObjectToVariantSourceConverter.FILEID_FIELD, source.getFileId())
.append(DBObjectToVariantSourceConverter.STUDYNAME_FIELD, source.getStudyName())
.append(DBObjectToVariantSourceConverter.STUDYID_FIELD, source.getStudyId())
+ .append(DBObjectToVariantSourceConverter.STUDYTYPE_FIELD, source.getType())
.append(DBObjectToVariantSourceConverter.DATE_FIELD, Calendar.getInstance().getTime())
.append(DBObjectToVariantSourceConverter.SAMPLES_FIELD, new BasicDBObject()
.append("NA000" + DBObjectToVariantSourceConverter.CHARACTER_TO_REPLACE_DOTS + "A", 0)
@@ -61,13 +64,13 @@ public class DBObjectToVariantSourceConverterTest {
// TODO Save pedigree information
// Metadata
- Map<String, Object> meta = source.getMetadata();
- DBObject metadataMongo = new BasicDBObject(DBObjectToVariantSourceConverter.HEADER_FIELD, source.getMetadata().get("header"));
+ DBObject metadataMongo = new BasicDBObject(DBObjectToVariantSourceConverter.HEADER_FIELD, source.getMetadata().get("header"))
+ .append("FORMAT" + DBObjectToVariantSourceConverter.CHARACTER_TO_REPLACE_DOTS + "A", source.getMetadata().get("FORMAT.A"));
mongoSource = mongoSource.append(DBObjectToVariantSourceConverter.METADATA_FIELD, metadataMongo);
}
@Test
- public void testConvertToDataModelType() {
+ public void testConvertToStorageType() {
DBObjectToVariantSourceConverter converter = new DBObjectToVariantSourceConverter();
DBObject converted = converter.convertToStorageType(source);
@@ -94,13 +97,24 @@ public class DBObjectToVariantSourceConverterTest {
DBObject convertedMetadata = (DBObject) converted.get(DBObjectToVariantSourceConverter.METADATA_FIELD);
DBObject expectedMetadata = (DBObject) converted.get(DBObjectToVariantSourceConverter.METADATA_FIELD);
assertEquals(expectedMetadata.get(DBObjectToVariantSourceConverter.HEADER_FIELD), convertedMetadata.get(DBObjectToVariantSourceConverter.HEADER_FIELD));
+ assertEquals(expectedMetadata.get("FORMAT" + DBObjectToVariantSourceConverter.CHARACTER_TO_REPLACE_DOTS + "A"), convertedMetadata.get("FORMAT" + DBObjectToVariantSourceConverter.CHARACTER_TO_REPLACE_DOTS + "A"));
}
@Test
- public void testConvertToStorageType() {
+ public void testConvertToDataModelType() {
DBObjectToVariantSourceConverter converter = new DBObjectToVariantSourceConverter();
VariantSource converted = converter.convertToDataModelType(mongoSource);
- assertEquals(source, converted);
+
+ assertEquals(source.getFileName(), converted.getFileName());
+ assertEquals(source.getFileId(), converted.getFileId());
+ assertEquals(source.getStudyName(), converted.getStudyName());
+ assertEquals(source.getStudyId(), converted.getStudyId());
+ assertEquals(source.getType(), converted.getType());
+ assertEquals(source.getSamplesPosition(), converted.getSamplesPosition());
+
+ assertEquals(source.getStats(), converted.getStats());
+ assertEquals(source.getMetadata(), converted.getMetadata());
+ assertEquals(source.getPedigree(), converted.getPedigree());
}
} | ['opencga-storage/opencga-storage-mongodb/src/test/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverterTest.java', 'opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToVariantSourceConverter.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,624,665 | 545,471 | 68,458 | 259 | 916 | 165 | 11 | 1 | 256 | 38 | 61 | 8 | 0 | 1 | 1970-01-01T00:23:49 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
362 | opencb/opencga/82/71 | opencb | opencga | https://github.com/opencb/opencga/issues/71 | https://github.com/opencb/opencga/pull/82 | https://github.com/opencb/opencga/pull/82 | 1 | resolves | Error calling opencga/rest/users/demo/info with lastActivity query parameter | When calling this ws with lastActivity parameter an error is returned:
"User { id: \\"demo\\" } not found."
``` json
{"warning":"","error":"","queryOptions":{"metadata":true,"exclude":["password","sessions"]},"response":[{"id":"","time":0,"dbTime":-1,"numResults":-1,"numTotalResults":-1,"warningMsg":"","errorMsg":"User { id: \\"demo\\" } not found.","resultType":"","result":[]}]}
```
And a CatalogDBException is printed in the server log:
org.opencb.opencga.catalog.db.CatalogDBException: User { id: "demo" } not found.
| 0006c49c8141bf10a5884cb493fd65a2f3ef89d9 | ca665080e691a22e25ace64d20fb8c9359e1961e | https://github.com/opencb/opencga/compare/0006c49c8141bf10a5884cb493fd65a2f3ef89d9...ca665080e691a22e25ace64d20fb8c9359e1961e | diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/CatalogMongoDBAdaptor.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/CatalogMongoDBAdaptor.java
index fa29164b67..cb73744769 100644
--- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/CatalogMongoDBAdaptor.java
+++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/CatalogMongoDBAdaptor.java
@@ -347,17 +347,17 @@ public class CatalogMongoDBAdaptor extends CatalogDBAdaptor {
@Override
public QueryResult<User> getUser(String userId, QueryOptions options, String lastActivity) throws CatalogDBException {
long startTime = startQuery();
+ if (!userExists(userId)) {
+ throw CatalogDBException.idNotFound("User", userId);
+ }
DBObject query = new BasicDBObject("id", userId);
query.put("lastActivity", new BasicDBObject("$ne", lastActivity));
QueryResult<DBObject> result = userCollection.find(query, options);
User user = parseUser(result);
- if(user == null){
- throw CatalogDBException.idNotFound("User", userId);
- }
- joinFields(user, options);
- if(user.getLastActivity() != null && user.getLastActivity().equals(lastActivity)) { // TODO explain
- return endQuery("Get user", startTime);
+ if(user == null) {
+ return endQuery("Get user", startTime); // user exists but no different lastActivity was found: return empty result
} else {
+ joinFields(user, options);
return endQuery("Get user", startTime, Arrays.asList(user));
}
}
diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/CatalogManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/CatalogManagerTest.java
index c42d620c58..7619c8511a 100644
--- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/CatalogManagerTest.java
+++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/CatalogManagerTest.java
@@ -139,7 +139,7 @@ public class CatalogManagerTest extends GenericTest {
try {
catalogManager.getUser("user", null, sessionIdUser2);
fail();
- } catch (CatalogDBException e) {
+ } catch (CatalogException e) {
System.out.println(e);
}
}
@@ -193,7 +193,7 @@ public class CatalogManagerTest extends GenericTest {
try {
catalogManager.modifyUser("user", params, sessionIdUser2);
fail("Expected exception");
- } catch (CatalogDBException e){
+ } catch (CatalogException e){
System.out.println(e);
}
| ['opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/CatalogMongoDBAdaptor.java', 'opencga-catalog/src/test/java/org/opencb/opencga/catalog/CatalogManagerTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,634,663 | 547,575 | 68,825 | 262 | 611 | 120 | 12 | 1 | 525 | 45 | 134 | 14 | 0 | 1 | 1970-01-01T00:23:49 | 159 | Java | {'Java': 19466288, 'Jupyter Notebook': 6290799, 'JavaScript': 629614, 'Python': 598047, 'R': 479859, 'Shell': 137088, 'CSS': 95683, 'Dockerfile': 14459, 'Mustache': 9851, 'Makefile': 3567, 'Smarty': 2215, 'HTML': 1001} | Apache License 2.0 |
857 | wso2/micro-integrator/1302/1301 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1301 | https://github.com/wso2/micro-integrator/pull/1302 | https://github.com/wso2/micro-integrator/pull/1302 | 1 | fixes | Message Processors are scheduled in paused stated when hot deployed. | **Description:**
$subject.
**Steps**
- Deploy a MP in MI.
- Delete the file and add it again.
- It will be scheduled and be in paused state. | 32aa3da3d9c6f4bde5dbca111303353b0f365ca2 | 5d83bf8336331a5c528c5f91b7dd048420f872cf | https://github.com/wso2/micro-integrator/compare/32aa3da3d9c6f4bde5dbca111303353b0f365ca2...5d83bf8336331a5c528c5f91b7dd048420f872cf | diff --git a/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/FileBasedTaskRepository.java b/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/FileBasedTaskRepository.java
index b07a858b3..506bded48 100644
--- a/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/FileBasedTaskRepository.java
+++ b/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/FileBasedTaskRepository.java
@@ -258,6 +258,7 @@ public class FileBasedTaskRepository implements TaskRepository {
if (metaFile.exists()) {
if (metaFile.delete()) {
deleteSuccess = true;
+ taskMetaPropMap.remove(getSystemDependentPath(resourcePath + taskName));
} else {
log.error("Error occurred while deleting task. Unable to delete: " + getSystemDependentPath(
resourcePath + tasksPath + "/_meta_" + taskName)); | ['components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/FileBasedTaskRepository.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,014,923 | 1,786,346 | 227,076 | 1,273 | 93 | 17 | 1 | 1 | 149 | 27 | 38 | 8 | 0 | 0 | 1970-01-01T00:26:25 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
848 | wso2/micro-integrator/1705/1700 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1700 | https://github.com/wso2/micro-integrator/pull/1705 | https://github.com/wso2/micro-integrator/pull/1705 | 1 | fixes | When the Message Processor gets deactivated due to an issue, it keeps deactivated state even after restarting the server. | **Description:**
After redeploying a carbon application / restarted the server, the Message Processor goes to a Paused state.
If the Message Processor gets deactivated due to some issue (as an example, the endpoint not existing), even if the car file is redeployed and the server is restarted, the message processor is in the PAUSED state.
```
[2020-06-17 17:22:23,953] INFO {ScheduledMessageProcessor} - Started message processor. [Processor1].
[2020-06-17 17:22:23,953] INFO {AbstractQuartzTaskManager} - Task paused: [ESB_TASK][MSMP_Processor1_0]
[2020-06-17 17:22:23,954] INFO {ScheduledMessageProcessor} - Successfully deactivated the message processor [Processor1]
```
In /mi-home/registry/governance/repository/components/org.apache.synapse.message.processor/Processor1.properties file,
**MESSAGE_PROCESSOR_STATE=PAUSED**
Tested pack: https://wso2.org/jenkins/job/products/job/micro-integrator/lastSuccessfulBuild/artifact/distribution/target/wso2mi-1.2.0-SNAPSHOT.zip
[JMSMessageStoreCompositeApplication_1.0.0.car.zip](https://github.com/wso2/micro-integrator/files/4792291/JMSMessageStoreCompositeApplication_1.0.0.car.zip)
| a29ead51eb85887e69c8b8e75fe953977598d5a9 | 0a4a85d803b5836f0386f441b8304952a52c7bd6 | https://github.com/wso2/micro-integrator/compare/a29ead51eb85887e69c8b8e75fe953977598d5a9...0a4a85d803b5836f0386f441b8304952a52c7bd6 | diff --git a/components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java b/components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java
index 5b85cfa69..14b843a0a 100644
--- a/components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java
+++ b/components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java
@@ -618,14 +618,19 @@ public class MicroIntegratorRegistry extends AbstractRegistry {
*/
private void removeResource(String key) {
try {
- File resource = new File(new URI(resolveRegistryURI(key)));
+ String resourcePath = resolveRegistryURI(key);
+ File resource = new File(new URI(resourcePath));
if (resource.exists()) {
if (resource.isFile()) {
deleteFile(resource);
+ // the properties also need to be removed when removing the resource
+ File resourceProperties = new File(new URI(resourcePath + PROPERTY_EXTENTION));
+ if (resourceProperties.exists()) {
+ deleteFile(resourceProperties);
+ }
} else if (resource.isDirectory()) {
deleteDirectory(resource);
}
-
} else {
handleException("Parent folder: " + key + " does not exists.");
} | ['components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,122,849 | 1,807,442 | 229,637 | 1,297 | 523 | 80 | 9 | 1 | 1,160 | 93 | 308 | 17 | 2 | 1 | 1970-01-01T00:26:32 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
856 | wso2/micro-integrator/1380/1071 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1071 | https://github.com/wso2/micro-integrator/pull/1380 | https://github.com/wso2/micro-integrator/pull/1380 | 1 | fixes | Message Processor state is not saved properly in MI registry | **Description:**
The Activate parameter we configure in synapse configurations is only helpful for the message processor to deploy for the very first time. Once it is deployed, the message processor's state is preserved in the registry [1]. The current state is assigned to the property MESSAGE_PROCESSOR_STATE and saved in the registry (<MI-HOME>/registry/governance/repository/components/org.apache.synapse.message.processor).
In MI the state of the message processor is not properly stored as a property. It should be stored as key-value pair as shown below,
`MESSAGE_PROCESSOR_STATE=PAUSED`
but the value is stored without the property name.
**Steps to reproduce:**
1. Configure JMS transport for Active MQ by following the documentation [2]
2. Configure JMS Message Store, Scheduled Message Forwarding processor and the Proxy service by following the doc [3]
3. Invoke the Proxy Service
[1] https://github.com/wso2/wso2-synapse/blob/2a1064286a31d2efa458b31da4d518e1f60b6df1/modules/core/src/main/java/org/apache/synapse/message/processor/impl/ScheduledMessageProcessor.java#L564
[2] https://ei.docs.wso2.com/en/latest/micro-integrator/setup/brokers/configure-with-ActiveMQ/
[3] https://ei.docs.wso2.com/en/latest/micro-integrator/use-cases/examples/jms_examples/guaranteed-delivery-with-failover/
| ca3409646204b84ea3e79030df3e4b1e8b50f96a | bf5ab53019e15af90f10bbc6975f8712078e9151 | https://github.com/wso2/micro-integrator/compare/ca3409646204b84ea3e79030df3e4b1e8b50f96a...bf5ab53019e15af90f10bbc6975f8712078e9151 | diff --git a/components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java b/components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java
index 8f879f8d2..62e0ea968 100644
--- a/components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java
+++ b/components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java
@@ -23,6 +23,7 @@ import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.impl.llom.OMDocumentImpl;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseException;
@@ -55,6 +56,7 @@ import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import static org.wso2.micro.integrator.registry.MicroIntegratorRegistryConstants.DEFAULT_MEDIA_TYPE;
+import static org.wso2.micro.integrator.registry.MicroIntegratorRegistryConstants.PROPERTY_EXTENTION;
import static org.wso2.micro.integrator.registry.MicroIntegratorRegistryConstants.URL_SEPARATOR;
public class MicroIntegratorRegistry extends AbstractRegistry {
@@ -510,21 +512,31 @@ public class MicroIntegratorRegistry extends AbstractRegistry {
if (isDirectory && !targetPath.endsWith(URL_SEPARATOR)) {
targetPath += URL_SEPARATOR;
}
-
String parent = getParentPath(targetPath, isDirectory);
- String fileName = getResourceName(targetPath);
-
- Properties metadata = new Properties();
- if (mediaType != null) {
- metadata.setProperty(METADATA_KEY_MEDIA_TYPE, mediaType);
- }
-
try {
- writeToFile(new URI(parent), fileName, content, metadata);
+ if (isDirectory) {
+ if (!new File(parent).exists() && !new File(parent).mkdirs()) {
+ handleException("Unable to create directory: " + parent);
+ }
+ if (StringUtils.isNotEmpty(propertyName)) {
+ writeToFile(new URI(parent), PROPERTY_EXTENTION, propertyName + "=" + content, null);
+ }
+ } else {
+ String fileName = getResourceName(targetPath);
+ if (StringUtils.isEmpty(propertyName)) {
+ Properties metadata = new Properties();
+ if (mediaType != null) {
+ metadata.setProperty(METADATA_KEY_MEDIA_TYPE, mediaType);
+ }
+ writeToFile(new URI(parent), fileName, content, metadata);
+ } else {
+ writeToFile(new URI(parent), fileName, "", null);
+ writeToFile(new URI(parent), fileName + PROPERTY_EXTENTION, propertyName + "=" + content, null);
+ }
+ }
} catch (Exception e) {
handleException("Error when adding a new resource", e);
}
-
} else {
log.warn("Creating new resource in remote registry is NOT SUPPORTED. Unable to create: " + path);
}
@@ -765,8 +777,9 @@ public class MicroIntegratorRegistry extends AbstractRegistry {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(newFile))) {
writer.write(content);
writer.flush();
- writeMetadata(parent, newFileName, metadata);
-
+ if (metadata != null) {
+ writeMetadata(parent, newFileName, metadata);
+ }
if (log.isDebugEnabled()) {
log.debug("Successfully content written to file : " + parentName + URL_SEPARATOR + newFileName);
}
diff --git a/integration/mediation-tests/tests-platform/tests-coordination/src/test/java/org/wso2/micro/integrator/message/processor/MessageProcessorTests.java b/integration/mediation-tests/tests-platform/tests-coordination/src/test/java/org/wso2/micro/integrator/message/processor/MessageProcessorTests.java
index a5c74d38a..1e08bc358 100644
--- a/integration/mediation-tests/tests-platform/tests-coordination/src/test/java/org/wso2/micro/integrator/message/processor/MessageProcessorTests.java
+++ b/integration/mediation-tests/tests-platform/tests-coordination/src/test/java/org/wso2/micro/integrator/message/processor/MessageProcessorTests.java
@@ -231,9 +231,7 @@ public class MessageProcessorTests extends ESBIntegrationTest {
}
}
- @Test(dependsOnMethods = { "testMpActivationViaPassiveNode" },
- // due to https://github.com/wso2/micro-integrator/issues/1071
- enabled = false)
+ @Test(dependsOnMethods = { "testMpActivationViaPassiveNode" })
void testMpStateUponRedeployment() throws Exception {
logManager.clearAll(); | ['components/mediation/registry/org.wso2.micro.integrator.registry/src/main/java/org/wso2/micro/integrator/registry/MicroIntegratorRegistry.java', 'integration/mediation-tests/tests-platform/tests-coordination/src/test/java/org/wso2/micro/integrator/message/processor/MessageProcessorTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,065,629 | 1,796,261 | 228,368 | 1,284 | 1,812 | 287 | 37 | 1 | 1,323 | 131 | 312 | 17 | 3 | 0 | 1970-01-01T00:26:26 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
855 | wso2/micro-integrator/1422/1060 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1060 | https://github.com/wso2/micro-integrator/pull/1422 | https://github.com/wso2/micro-integrator/pull/1422 | 1 | fixes | Error thrown when securevault.sh is run | **Description:**
The following exception is thrown when securevault.sh is run as described in https://ei.docs.wso2.com/en/latest/micro-integrator/develop/creating-artifacts/encrypting-synapse-passwords/#encrypting-passwords-for-synapse-configurations
```
writing to: /home/user/temp/wso2mi-1.1.0/registry/config/repository/components/secure-vault/secure-vault.properties
org.wso2.micro.integrator.security.vault.SecureVaultException: Error loading properties from a file at : /home/user/temp/wso2mi-1.1.0/registry/config/repository/components/secure-vault/secure-vault.properties Error : /home/user/temp/wso2mi-1.1.0/registry/config/repository/components/secure-vault/secure-vault.properties (No such file or directory)
at org.wso2.micro.integrator.security.vault.utils.Utils.writeKeyToFile(Utils.java:83)
at org.wso2.micro.integrator.security.vault.VaultTool.main(VaultTool.java:69)
Caused by: java.io.FileNotFoundException: /home/user/temp/wso2mi-1.1.0/registry/config/repository/components/secure-vault/secure-vault.properties (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.wso2.micro.integrator.security.vault.utils.Utils.writeKeyToFile(Utils.java:68)
... 1 more
``` | eb5b754d40972ee360e5b8d34948d852cd1b2eb8 | da1e778ff594b555779c504cf29ab7b5bdad5776 | https://github.com/wso2/micro-integrator/compare/eb5b754d40972ee360e5b8d34948d852cd1b2eb8...da1e778ff594b555779c504cf29ab7b5bdad5776 | diff --git a/components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/vault/utils/Utils.java b/components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/vault/utils/Utils.java
index 6136ed394..15a2ac781 100644
--- a/components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/vault/utils/Utils.java
+++ b/components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/vault/utils/Utils.java
@@ -65,6 +65,13 @@ public class Utils {
throw new SecureVaultException(msg);
}
} else {
+ if (!file.exists()) {
+ try {
+ file.createNewFile();
+ } catch (IOException e) {
+ throw new SecureVaultException("Error while creating " + filePath);
+ }
+ }
try (FileInputStream fileInputStream = new FileInputStream(file)) {
keys.load(fileInputStream);
if (keys.containsKey(alias)) { | ['components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/vault/utils/Utils.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,066,653 | 1,796,432 | 228,386 | 1,284 | 266 | 41 | 7 | 1 | 1,344 | 62 | 328 | 14 | 1 | 1 | 1970-01-01T00:26:27 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
854 | wso2/micro-integrator/1432/1431 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1431 | https://github.com/wso2/micro-integrator/pull/1432 | https://github.com/wso2/micro-integrator/pull/1432 | 1 | fixes | Nodes with duplicate Ids are allowed to join cluster. | **Description:**
When two nodes have same node-id , they are still allowed to join the cluster with a warn log. | 607ee76566fb06c5ca50a1a78d05b10760d0a0ba | fac2e904c901412f0345e7401400adf1db19e4b5 | https://github.com/wso2/micro-integrator/compare/607ee76566fb06c5ca50a1a78d05b10760d0a0ba...fac2e904c901412f0345e7401400adf1db19e4b5 | diff --git a/components/org.wso2.micro.integrator.coordination/src/main/java/org/wso2/micro/integrator/coordination/RDBMSCoordinationStrategy.java b/components/org.wso2.micro.integrator.coordination/src/main/java/org/wso2/micro/integrator/coordination/RDBMSCoordinationStrategy.java
index 6119670e3..0c3e54ede 100644
--- a/components/org.wso2.micro.integrator.coordination/src/main/java/org/wso2/micro/integrator/coordination/RDBMSCoordinationStrategy.java
+++ b/components/org.wso2.micro.integrator.coordination/src/main/java/org/wso2/micro/integrator/coordination/RDBMSCoordinationStrategy.java
@@ -230,10 +230,8 @@ public class RDBMSCoordinationStrategy implements CoordinationStrategy {
}
if (isNodeExist) {
- log.warn("Node with ID " + localNodeId + " in group " + localGroupId +
- " already exists.");
- stillCoordinator = communicationBusContext.
- updateCoordinatorHeartbeat(localNodeId, localGroupId, System.currentTimeMillis());
+ throw new ClusterCoordinationException(
+ "Node with ID " + localNodeId + " in group " + localGroupId + " already exists.");
}
isCoordinatorTasksRunning = true; | ['components/org.wso2.micro.integrator.coordination/src/main/java/org/wso2/micro/integrator/coordination/RDBMSCoordinationStrategy.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,067,861 | 1,796,675 | 228,415 | 1,284 | 519 | 77 | 6 | 1 | 112 | 20 | 25 | 2 | 0 | 0 | 1970-01-01T00:26:27 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
853 | wso2/micro-integrator/1479/1476 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1476 | https://github.com/wso2/micro-integrator/pull/1479 | https://github.com/wso2/micro-integrator/pull/1479 | 1 | fix | JMS Topic subscription is not removed when node looses connection to the cluster. | **Description:**
When using JMS inbound endpoint in a clustered scenario, the JMS topic subscription is not removed when the connection to the cluster is lost. Ideally the subscription should be removed as we are stopping the underlying running task and need to be re established when the task is resumed again. | 429254dfb02ce67b088a042544a66903e243b4c6 | c5b53c7db3f8964c8e68ceeb63eed31662806ac4 | https://github.com/wso2/micro-integrator/compare/429254dfb02ce67b088a042544a66903e243b4c6...c5b53c7db3f8964c8e68ceeb63eed31662806ac4 | diff --git a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/jms/JMSTask.java b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/jms/JMSTask.java
index 18520cc59..ec2bf6262 100644
--- a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/jms/JMSTask.java
+++ b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/jms/JMSTask.java
@@ -63,13 +63,15 @@ public class JMSTask extends InboundTask implements LocalTaskActionListener {
/**
* {@inheritDoc}
* <p>
- * Destroys the JMS task upon deletion of the local task.
+ * Destroys the JMS task upon removal of the local task.
*
* @param taskName the name of the task that was deleted
*/
@Override
- public void notifyLocalTaskDeletion(String taskName) {
+ public void notifyLocalTaskRemoval(String taskName) {
destroy();
- logger.debug("Destroyed JMS task due to deletion of task: " + taskName);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Destroyed JMS task due to deletion of task: " + taskName);
+ }
}
}
diff --git a/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/AbstractQuartzTaskManager.java b/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/AbstractQuartzTaskManager.java
index 19e6af510..69281ced6 100644
--- a/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/AbstractQuartzTaskManager.java
+++ b/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/AbstractQuartzTaskManager.java
@@ -145,7 +145,7 @@ public abstract class AbstractQuartzTaskManager implements TaskManager {
//notify the listeners of the task deletion
LocalTaskActionListener listener = localTaskActionListeners.get(taskName);
if (null != listener) {
- listener.notifyLocalTaskDeletion(taskName);
+ listener.notifyLocalTaskRemoval(taskName);
}
}
} catch (SchedulerException e) {
@@ -159,6 +159,11 @@ public abstract class AbstractQuartzTaskManager implements TaskManager {
String taskGroup = this.getTenantTaskGroup();
try {
this.getScheduler().pauseJob(new JobKey(taskName, taskGroup));
+ //notify the listeners of the task pause
+ LocalTaskActionListener listener = localTaskActionListeners.get(taskName);
+ if (null != listener) {
+ listener.notifyLocalTaskRemoval(taskName);
+ }
log.info("Task paused: [" + this.getTaskType() + "][" + taskName + "]");
} catch (SchedulerException e) {
throw new TaskException("Error in pausing task with name: " + taskName, TaskException.Code.UNKNOWN, e);
diff --git a/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/LocalTaskActionListener.java b/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/LocalTaskActionListener.java
index e55ac9e30..04e8e8e77 100644
--- a/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/LocalTaskActionListener.java
+++ b/components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/LocalTaskActionListener.java
@@ -27,9 +27,9 @@ import org.wso2.micro.integrator.ntask.core.TaskManager;
public interface LocalTaskActionListener {
/**
- * Method to notify when a local task is deleted.
+ * Method to notify when a local task is removed, it can be due to pause or delete.
*
* @param taskName
*/
- void notifyLocalTaskDeletion(String taskName);
+ void notifyLocalTaskRemoval(String taskName);
} | ['components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/AbstractQuartzTaskManager.java', 'components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/jms/JMSTask.java', 'components/mediation/tasks/org.wso2.micro.integrator.ntask.core/src/main/java/org/wso2/micro/integrator/ntask/core/impl/LocalTaskActionListener.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 9,083,361 | 1,799,831 | 228,820 | 1,286 | 1,090 | 223 | 19 | 3 | 313 | 51 | 60 | 2 | 0 | 0 | 1970-01-01T00:26:27 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
852 | wso2/micro-integrator/1481/1477 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1477 | https://github.com/wso2/micro-integrator/pull/1481 | https://github.com/wso2/micro-integrator/pull/1481 | 1 | fixes | RabbitMq Inbound Ep message consumption is not paused when the underlying task is stopped. | **Description:**
When a node looses connection to the cluster, the rabbit mq inbound task is paused, however the inbound endpoint continues to receive the message and not paused. This need to be fixed. | ca55da26c8b32ffd2701d957f087cb5a7eefd71b | c7332eb422243ed75e0902ad0633edab6d193323 | https://github.com/wso2/micro-integrator/compare/ca55da26c8b32ffd2701d957f087cb5a7eefd71b...c7332eb422243ed75e0902ad0633edab6d193323 | diff --git a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/InboundOneTimeTriggerRequestProcessor.java b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/InboundOneTimeTriggerRequestProcessor.java
index f1625fb80..a630468b9 100644
--- a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/InboundOneTimeTriggerRequestProcessor.java
+++ b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/InboundOneTimeTriggerRequestProcessor.java
@@ -24,8 +24,10 @@ import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.inbound.InboundRequestProcessor;
import org.apache.synapse.startup.quartz.StartUpController;
import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskManager;
import org.wso2.carbon.inbound.endpoint.persistence.InboundEndpointsDataStore;
-
+import org.wso2.carbon.inbound.endpoint.protocol.rabbitmq.RabbitMQTask;
+import org.wso2.micro.integrator.mediation.ntask.NTaskTaskManager;
import static org.wso2.carbon.inbound.endpoint.common.Constants.SUPER_TENANT_DOMAIN_NAME;
@@ -76,6 +78,14 @@ public abstract class InboundOneTimeTriggerRequestProcessor implements InboundRe
startUpController = new StartUpController();
startUpController.setTaskDescription(taskDescription);
startUpController.init(synapseEnvironment);
+ // registering a listener to identify task removal or deletions.
+ if (task instanceof RabbitMQTask) {
+ TaskManager taskManagerImpl = synapseEnvironment.getTaskManager().getTaskManagerImpl();
+ if (taskManagerImpl instanceof NTaskTaskManager) {
+ ((NTaskTaskManager) taskManagerImpl).registerListener((RabbitMQTask) task,
+ taskDescription.getName());
+ }
+ }
} catch (Exception e) {
log.error("Error starting the inbound endpoint " + name + ". Unable to schedule the task. " + e
.getLocalizedMessage(), e);
diff --git a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/OneTimeTriggerInboundTask.java b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/OneTimeTriggerInboundTask.java
index 2893e36f4..5f4555043 100644
--- a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/OneTimeTriggerInboundTask.java
+++ b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/OneTimeTriggerInboundTask.java
@@ -30,6 +30,8 @@ public abstract class OneTimeTriggerInboundTask implements org.apache.synapse.ta
private static final Log logger = LogFactory.getLog(InboundTask.class.getName());
private boolean isOneTimeTriggered = false;
private OneTimeTriggerAbstractCallback callback;
+ // boolean used to identify the re-trigger of the task.
+ private boolean reTrigger = false;
public void execute() {
//this check is there to synchronize task cycle round hit and connection lost reconnection
@@ -38,15 +40,11 @@ public abstract class OneTimeTriggerInboundTask implements org.apache.synapse.ta
if (callback != null && callback.isCallbackSuspended()) {
callback.releaseCallbackSuspension();
}
-
- if (!isOneTimeTriggered) {
+ if (!isOneTimeTriggered || reTrigger) {
isOneTimeTriggered = true;
- if (logger.isDebugEnabled()) {
- logger.debug("Common One time trigger Inbound Task executing.");
- }
+ reTrigger = false;
+ logger.debug("Common One time trigger Inbound Task executing.");
taskExecute();
- } else {
- return;
}
}
@@ -58,5 +56,10 @@ public abstract class OneTimeTriggerInboundTask implements org.apache.synapse.ta
return callback;
}
+ protected void setReTrigger() {
+ logger.debug("Enabling re-trigger.");
+ this.reTrigger = true;
+ }
+
protected abstract void taskExecute();
}
diff --git a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQTask.java b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQTask.java
index 9300153c1..65d0044a5 100644
--- a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQTask.java
+++ b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQTask.java
@@ -22,8 +22,9 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.core.SynapseEnvironment;
import org.wso2.carbon.inbound.endpoint.common.OneTimeTriggerInboundTask;
+import org.wso2.micro.integrator.ntask.core.impl.LocalTaskActionListener;
-public class RabbitMQTask extends OneTimeTriggerInboundTask {
+public class RabbitMQTask extends OneTimeTriggerInboundTask implements LocalTaskActionListener {
private static final Log log = LogFactory.getLog(RabbitMQTask.class.getName());
@@ -46,4 +47,10 @@ public class RabbitMQTask extends OneTimeTriggerInboundTask {
public void destroy() {
log.debug("Destroying.");
}
+
+ @Override
+ public void notifyLocalTaskRemoval(String taskName) {
+ setReTrigger();
+ rabbitMQConnectionConsumer.requestShutdown();
+ }
} | ['components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/InboundOneTimeTriggerRequestProcessor.java', 'components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQTask.java', 'components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/common/OneTimeTriggerInboundTask.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 9,083,693 | 1,799,894 | 228,827 | 1,286 | 1,752 | 327 | 38 | 3 | 202 | 33 | 41 | 2 | 0 | 0 | 1970-01-01T00:26:27 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
860 | wso2/micro-integrator/981/977 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/977 | https://github.com/wso2/micro-integrator/pull/981 | https://github.com/wso2/micro-integrator/pull/981 | 1 | fix | Can not deploy main and fault sequence | **Description:**
When trying to deploy main and fault sequence using Capp in mi at the first run it does not get deployed. | 3d279eb3fd315d05721e0c7a069842f8649525eb | b0b3e750ea25760f4dcfe6284770699b1e918b74 | https://github.com/wso2/micro-integrator/compare/3d279eb3fd315d05721e0c7a069842f8649525eb...b0b3e750ea25760f4dcfe6284770699b1e918b74 | diff --git a/components/org.wso2.micro.integrator.initializer/src/main/java/org/wso2/micro/integrator/initializer/deployment/synapse/deployer/SynapseAppDeployer.java b/components/org.wso2.micro.integrator.initializer/src/main/java/org/wso2/micro/integrator/initializer/deployment/synapse/deployer/SynapseAppDeployer.java
index f2f64874e..1855eb089 100644
--- a/components/org.wso2.micro.integrator.initializer/src/main/java/org/wso2/micro/integrator/initializer/deployment/synapse/deployer/SynapseAppDeployer.java
+++ b/components/org.wso2.micro.integrator.initializer/src/main/java/org/wso2/micro/integrator/initializer/deployment/synapse/deployer/SynapseAppDeployer.java
@@ -783,7 +783,7 @@ public class SynapseAppDeployer implements AppDeploymentHandler {
* @return whether main or fault sequence is handled
*/
private boolean handleMainFaultSeqDeployment(Artifact artifact,
- AxisConfiguration axisConfig) {
+ AxisConfiguration axisConfig, Deployer deployer) throws DeploymentException {
String fileName = artifact.getFiles().get(0).getName();
String artifactPath = artifact.getExtractedPath() + File.separator + fileName;
@@ -795,9 +795,24 @@ public class SynapseAppDeployer implements AppDeploymentHandler {
String mainXMLPath = getMainXmlPath(axisConfig);
log.info("Copying main sequence to " + mainXMLPath);
FileUtils.copyFile(new File(artifactPath), new File(mainXMLPath));
+ deployer.deploy(new DeploymentFileData(new File(mainXMLPath), deployer));
artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_DEPLOYED);
+ } catch (DeploymentException e) {
+ artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_FAILED);
+ throw e;
} catch (IOException e) {
log.error("Error copying main.xml to sequence directory", e);
+ } catch (Throwable throwable) {
+ artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_FAILED);
+ // Since there can be different deployers, they can throw any error.
+ // So need to handle unhandled exception has occurred during deployement. Hence catch all and
+ // wrap it with DeployementException and throw it
+ throw new DeploymentException(throwable);
+ } finally {
+ //clear the log appender once deployment is finished to avoid appending the
+ //same log to other classes.
+ setCustomLogContent(deployer, null);
+ CustomLogSetter.getInstance().clearThreadLocalContent();
}
} else if (fileName.matches(FAULT_SEQ_REGEX) || fileName.matches(SynapseAppDeployerConstants.FAULT_SEQ_FILE)) {
isMainOrFault = true;
@@ -805,9 +820,24 @@ public class SynapseAppDeployer implements AppDeploymentHandler {
String faultXMLPath = getFaultXmlPath(axisConfig);
log.info("Copying fault sequence to " + faultXMLPath);
FileUtils.copyFile(new File(artifactPath), new File(faultXMLPath));
+ deployer.deploy(new DeploymentFileData(new File(faultXMLPath), deployer));
artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_DEPLOYED);
+ } catch (DeploymentException e) {
+ artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_FAILED);
+ throw e;
} catch (IOException e) {
log.error("Error copying main.xml to sequence directory", e);
+ } catch (Throwable throwable) {
+ artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_FAILED);
+ // Since there can be different deployers, they can throw any error.
+ // So need to handle unhandled exception has occurred during deployement. Hence catch all and
+ // wrap it with DeployementException and throw it
+ throw new DeploymentException(throwable);
+ } finally {
+ //clear the log appender once deployment is finished to avoid appending the
+ //same log to other classes.
+ setCustomLogContent(deployer, null);
+ CustomLogSetter.getInstance().clearThreadLocalContent();
}
}
return isMainOrFault;
@@ -1045,7 +1075,7 @@ public class SynapseAppDeployer implements AppDeploymentHandler {
File artifactInRepo = new File(artifactDir + File.separator + fileName);
if (SynapseAppDeployerConstants.SEQUENCE_TYPE.equals(artifact.getType()) &&
- handleMainFaultSeqDeployment(artifact, axisConfig)) {
+ handleMainFaultSeqDeployment(artifact, axisConfig, deployer)) {
} else if (artifactInRepo.exists()) {
log.warn("Artifact " + fileName + " already found in " + artifactInRepo.getAbsolutePath() +
". Ignoring CAPP's artifact"); | ['components/org.wso2.micro.integrator.initializer/src/main/java/org/wso2/micro/integrator/initializer/deployment/synapse/deployer/SynapseAppDeployer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 8,822,370 | 1,747,918 | 222,478 | 1,243 | 2,402 | 406 | 34 | 1 | 125 | 22 | 28 | 2 | 0 | 0 | 1970-01-01T00:26:10 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
851 | wso2/micro-integrator/1576/1575 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1575 | https://github.com/wso2/micro-integrator/pull/1576 | https://github.com/wso2/micro-integrator/pull/1576 | 1 | fixes | HTTP Inbound endpoint creates new inbound worker thread pool for each request | **Description:**
HTTP Inboundendpoint creates a new inbound worker thread pool for each request.
The thread pool needs to be initialized once and then the threads should be taken from the pool for every consequent request.
**Affected Product Version:**
MI 1.1.0
**Steps to reproduce:**
1. Deploy the InboundWorkerTest.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<inboundEndpoint xmlns="http://ws.apache.org/ns/synapse"
name="InboundWorkerTest"
sequence="TestInboundSequence"
onError="InboundFault"
protocol="http"
suspend="false">
<parameters>
<parameter name="inbound.http.port">9600</parameter>
<parameter name="inbound.worker.pool.size.core">2</parameter>
<parameter name="inbound.worker.pool.size.max">5</parameter>
<parameter name="inbound.worker.thread.keep.alive.sec">60</parameter>
<parameter name="inbound.worker.pool.queue.length">1</parameter>
<parameter name="inbound.thread.group.id">PassThroughinboundworkerthreadgroup</parameter>
<parameter name="inbound.thread.id">thread_id</parameter>
</parameters>
</inboundEndpoint>
```
2. Deploy the TestInboundSequence.xml
<?xml version="1.0" encoding="UTF-8"?>
```
<sequence xmlns="http://ws.apache.org/ns/synapse" name="TestInboundSequence">
<log level="custom">
<property name="Thread logger" value="********************"/>
</log>
<log level="custom">
<property name="Thread logger Before" value="********************"/>
</log>
<script language="js">java.lang.Thread.sleep(60000);</script>
<log level="custom">
<property name="Thread logger After" value="********************"/>
</log>
<respond/>
</sequence>
```
3. Invoke the inbound with below curl command
`curl http://localhost:9600/InboundWorkerTest`
It will take around 60s to respond back since we have blocked the inboundworker thread with thread sleep using script mediator.
4. If we send another ten requests within 60s after the first request MI will accept all the request, We cannot accept that behavior since we have configured the inbound worker thread poll as below.
```
<parameter name="inbound.worker.pool.size.core">2</parameter>
<parameter name="inbound.worker.pool.size.max">5</parameter>
<parameter name="inbound.worker.pool.queue.length">1</parameter>
```
Theoretically, it should accept only 6 requests (5 + 1 in queue) within the 60s | 67a6d37acbb7c51ed4b866bdba072670398bec2a | 72105ef297f0ccc0d12c27b3c43fe06b377205e8 | https://github.com/wso2/micro-integrator/compare/67a6d37acbb7c51ed4b866bdba072670398bec2a...72105ef297f0ccc0d12c27b3c43fe06b377205e8 | diff --git a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/http/InboundHttpSourceHandler.java b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/http/InboundHttpSourceHandler.java
index 8ebf041e5..dc8e90000 100644
--- a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/http/InboundHttpSourceHandler.java
+++ b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/http/InboundHttpSourceHandler.java
@@ -79,20 +79,21 @@ public class InboundHttpSourceHandler extends SourceHandler {
Pattern dispatchPattern = null;
- WorkerPoolConfiguration workerPoolConfiguration = HTTPEndpointManager.getInstance()
- .getWorkerPoolConfiguration(SUPER_TENANT_DOMAIN_NAME, port);
- if (workerPoolConfiguration != null) {
- workerPool = sourceConfiguration.getWorkerPool(workerPoolConfiguration.getWorkerPoolCoreSize(),
- workerPoolConfiguration.getWorkerPoolSizeMax(),
- workerPoolConfiguration
- .getWorkerPoolThreadKeepAliveSec(),
- workerPoolConfiguration.getWorkerPoolQueuLength(),
- workerPoolConfiguration.getThreadGroupID(),
- workerPoolConfiguration.getThreadID());
- }
-
+ // Need to initialize workerPool only once
if (workerPool == null) {
- workerPool = sourceConfiguration.getWorkerPool();
+ WorkerPoolConfiguration workerPoolConfiguration = HTTPEndpointManager.getInstance()
+ .getWorkerPoolConfiguration(SUPER_TENANT_DOMAIN_NAME, port);
+ if (workerPoolConfiguration != null) {
+ workerPool = sourceConfiguration.getWorkerPool(workerPoolConfiguration.getWorkerPoolCoreSize(),
+ workerPoolConfiguration.getWorkerPoolSizeMax(),
+ workerPoolConfiguration
+ .getWorkerPoolThreadKeepAliveSec(),
+ workerPoolConfiguration.getWorkerPoolQueuLength(),
+ workerPoolConfiguration.getThreadGroupID(),
+ workerPoolConfiguration.getThreadID());
+ } else {
+ workerPool = sourceConfiguration.getWorkerPool();
+ }
}
Object correlationId = conn.getContext().getAttribute(PassThroughConstants.CORRELATION_ID);
@@ -121,5 +122,4 @@ public class InboundHttpSourceHandler extends SourceHandler {
sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
}
}
-
} | ['components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/http/InboundHttpSourceHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,171,233 | 1,816,664 | 230,994 | 1,307 | 2,021 | 262 | 28 | 1 | 2,503 | 204 | 580 | 56 | 3 | 3 | 1970-01-01T00:26:30 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
849 | wso2/micro-integrator/1645/1594 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1594 | https://github.com/wso2/micro-integrator/pull/1645 | https://github.com/wso2/micro-integrator/pull/1645 | 1 | fix | NumberFormatException occurs when invoking the Management API resource for transaction count | **Description:**
The following NumberFormatException is printed in logs when invoking the following Management API resource for transaction count.
`curl -X GET "https://localhost:9164/management/transactions" -H "accept: application/json" -H "Authorization: Bearer %AccessToken%"`
```
[2020-05-28 14:28:41,203] ERROR {RequestCountResource} - Invalid input. Cannot parse the input 'null' as an Integer: java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at org.wso2.micro.integrator.management.apis.RequestCountResource.tryParseInt(RequestCountResource.java:127)
at org.wso2.micro.integrator.management.apis.RequestCountResource.invoke(RequestCountResource.java:68)
at org.wso2.micro.integrator.management.apis.ApiResourceAdapter.invoke(ApiResourceAdapter.java:55)
at org.wso2.carbon.inbound.endpoint.internal.http.api.InternalAPIDispatcher.dispatch(InternalAPIDispatcher.java:86)
at org.wso2.carbon.inbound.endpoint.protocol.http.InboundHttpServerWorker.run(InboundHttpServerWorker.java:109)
at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
```
**Affected Product Version:**
MI-1.2.0 alpha
**OS, DB, other environment details and versions:**
N/A
**Steps to reproduce:**
- enable the transaction counter component and management API (on port 9164) in the MI server
- Invoke `curl -X GET "https://hostname:9164/management/transactions" -H "accept: application/json" -H "Authorization: Bearer %AccessToken%"`
| 46552f7b3374ef2916c32c219fcd6ea8c0850765 | 9c272b1c40de3950105936d4ab4b5b151735c7ac | https://github.com/wso2/micro-integrator/compare/46552f7b3374ef2916c32c219fcd6ea8c0850765...9c272b1c40de3950105936d4ab4b5b151735c7ac | diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/RequestCountResource.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/RequestCountResource.java
index 106e73213..dccf3dd8a 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/RequestCountResource.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/RequestCountResource.java
@@ -61,21 +61,33 @@ public class RequestCountResource implements MiApiResource {
public boolean invoke(MessageContext synCtx,
org.apache.axis2.context.MessageContext axis2MessageContext,
SynapseConfiguration synapseConfiguration) {
+ String errorMessage;
String yearParameter = Utils.getQueryParameter(synCtx, "year");
String monthParameter = Utils.getQueryParameter(synCtx, "month");
- if (tryParseInt(yearParameter) != null && tryParseInt(monthParameter) != null) {
- if (!StringUtils.isEmpty(yearParameter) && !StringUtils.isEmpty(monthParameter)) {
- return takeRequestCountOfTheMonth(axis2MessageContext, Integer.parseInt(yearParameter),
- Integer.parseInt(monthParameter));
- }
- } else if (StringUtils.isEmpty(yearParameter) && StringUtils.isEmpty(monthParameter)) {
+ if (StringUtils.isEmpty(yearParameter) && StringUtils.isEmpty(monthParameter)) {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
return takeRequestCountOfTheMonth(axis2MessageContext, localDate.getYear(), localDate.getMonthValue());
+ } else if (StringUtils.isEmpty(yearParameter) || StringUtils.isEmpty(monthParameter)) {
+ errorMessage = "Either both \\"year\\" and \\"month\\" arguments or none should be specified.";
+ } else {
+ Integer year = tryParseInt(yearParameter);
+ Integer month = tryParseInt(monthParameter);
+
+ if (null != year && null != month) {
+ return takeRequestCountOfTheMonth(axis2MessageContext, year, month);
+ } else if (null == year && null == month){
+ errorMessage = "Invalid inputs for arguments \\"year\\" and \\"month\\".";
+ } else if (null == year){
+ errorMessage = "Invalid input for argument \\"year\\".";
+ } else {
+ errorMessage = "Invalid input for argument \\"month\\".";
+ }
}
- JSONObject response = Utils.createJsonError("Input parameters are not valid", axis2MessageContext, BAD_REQUEST);
+
+ JSONObject response = Utils.createJsonError(errorMessage, axis2MessageContext, BAD_REQUEST);
Utils.setJsonPayLoad(axis2MessageContext, response);
return true;
} | ['components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/RequestCountResource.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,108,978 | 1,804,747 | 229,321 | 1,296 | 1,671 | 299 | 26 | 1 | 1,869 | 115 | 429 | 30 | 2 | 1 | 1970-01-01T00:26:31 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
858 | wso2/micro-integrator/1180/1165 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1165 | https://github.com/wso2/micro-integrator/pull/1180 | https://github.com/wso2/micro-integrator/pull/1180 | 1 | fixes | [Management API] Cannot retrieve the list of available endpoints using management api | **Description:**
The following exception occurs when trying to retrieve the list of available endpoints using management api by invoking [1].
```
[2020-02-21 15:18:31,254] ERROR {org.wso2.carbon.inbound.endpoint.protocol.http.InboundHttpServerWorker} - Exception occurred when running org.wso2.carbon.inbound.endpoint.protocol.http.InboundHttpServerWorker java.lang.NullPointerException
at org.wso2.micro.integrator.management.apis.EndpointResource.populateEndpointList(EndpointResource.java:95)
at org.wso2.micro.integrator.management.apis.EndpointResource.invoke(EndpointResource.java:66)
at org.wso2.carbon.inbound.endpoint.internal.http.api.InternalAPIDispatcher.dispatch(InternalAPIDispatcher.java:86)
at org.wso2.carbon.inbound.endpoint.protocol.http.InboundHttpServerWorker.run(InboundHttpServerWorker.java:109)
at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
```
[1] - `curl -X GET "https://localhost:9164/management/endpoints" -H "accept: application/json" -H "Authorization: Bearer TOKEN" -k -i` | 7b7a0411fd48a56894c33b1e888e8ead46611a49 | b9224d8b9f2e96bf4a89aff961f5d370ff653fe4 | https://github.com/wso2/micro-integrator/compare/7b7a0411fd48a56894c33b1e888e8ead46611a49...b9224d8b9f2e96bf4a89aff961f5d370ff653fe4 | diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/EndpointResource.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/EndpointResource.java
index d6b28b175..54ae8399b 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/EndpointResource.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/EndpointResource.java
@@ -28,6 +28,7 @@ import org.apache.synapse.endpoints.Endpoint;
import org.json.JSONObject;
import org.wso2.carbon.inbound.endpoint.internal.http.api.APIResource;
+import javax.xml.namespace.QName;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
@@ -91,8 +92,13 @@ public class EndpointResource extends APIResource {
OMElement element = EndpointSerializer.getElementFromEndpoint(ep);
OMElement firstElement = element.getFirstElement();
-
- String type = firstElement.getLocalName();
+ String type;
+ // For template endpoints the endpoint type can not be retrieved from firstElement
+ if (firstElement == null) {
+ type = element.getAttribute(new QName("template")).getLocalName();
+ } else {
+ type = firstElement.getLocalName();
+ }
endpointObject.put(Constants.TYPE, type);
jsonBody.getJSONArray(Constants.LIST).put(endpointObject); | ['components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/EndpointResource.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 8,824,998 | 1,748,795 | 222,582 | 1,243 | 429 | 73 | 10 | 1 | 1,338 | 64 | 311 | 16 | 1 | 1 | 1970-01-01T00:26:22 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
847 | wso2/micro-integrator/1795/1773 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1773 | https://github.com/wso2/micro-integrator/pull/1795 | https://github.com/wso2/micro-integrator/pull/1795 | 1 | fixes | Prometheus API - basic authentication does not work with an external user store | **Steps to reproduce:**
1. Start the Prometheus server with the below configs in the prometheus.yml file.
```
scrape_configs:
- job_name: "esb_stats"
static_configs:
- targets: ['localhost:9201']
metrics_path: "metric-service/metrics"
```
2. Have the following configurations in the deployment.yml with the external user store defined.
```
[internal_apis.file_user_store]
enable = false
[user_store]
class = "org.wso2.micro.integrator.security.user.core.jdbc.JDBCUserStoreManager"
type = "database"
read_only = false
[[datasource]]
id = "WSO2_USER_DB"
url= "jdbc:mysql://localhost:3306/userdb"
username="root"
password="root"
driver="com.mysql.jdbc.Driver"
pool_options.maxActive=50
pool_options.maxWait = 60000
pool_options.testOnBorrow = true
[realm_manager]
data_source = "WSO2_USER_DB"
[prometheus_api]
protocols = "http"
[prometheus_api.basic_security_handler]
enable = true
[prometheus_api.authorization_handler]
enable = true
[[prometheus_api.authorization_handler.resources]]
path = "/metric"
[[management_api.authorization_handler.resources]]
path = "/user"
[management_api.cors]
enabled = true
allowed_origins = "https://localhost:9743,https://wso2.com:9743"
allowed_headers = "Authorization"
```
3. Start the micro integrator.
4. Call the Prometheus API as below.
```
curl http://localhost:9201/metric-service/metrics
```
Getting the following error in the micro integrator logs.
```
[2020-06-30 11:26:49,171] ERROR {InboundHttpServerWorker} - Exception occurred when running org.wso2.carbon.inbound.endpoint.protocol.http.InboundHttpServerWorker java.lang.NullPointerException
at org.wso2.micro.integrator.management.apis.security.handler.SecurityHandlerAdapter.needsHandling(SecurityHandlerAdapter.java:85)
at org.wso2.micro.integrator.management.apis.security.handler.SecurityHandlerAdapter.invoke(SecurityHandlerAdapter.java:119)
at org.wso2.carbon.inbound.endpoint.internal.http.api.InternalAPIDispatcher.dispatch(InternalAPIDispatcher.java:75)
at org.wso2.carbon.inbound.endpoint.protocol.http.InboundHttpServerWorker.run(InboundHttpServerWorker.java:102)
at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
``` | 622c5d1d8c7208f3f2c7a912827f4bc088d700ce | 35c83ceb65c1773e23895aaa023039e14688e87c | https://github.com/wso2/micro-integrator/compare/622c5d1d8c7208f3f2c7a912827f4bc088d700ce...35c83ceb65c1773e23895aaa023039e14688e87c | diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/AuthenticationHandlerAdapter.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/AuthenticationHandlerAdapter.java
index a99fe7c68..63dfb2bdd 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/AuthenticationHandlerAdapter.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/AuthenticationHandlerAdapter.java
@@ -19,21 +19,30 @@
package org.wso2.micro.integrator.management.apis.security.handler;
import org.apache.axis2.transport.http.HTTPConstants;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.wso2.micro.core.util.CarbonException;
import org.wso2.micro.integrator.management.apis.ManagementApiUndefinedException;
+import org.wso2.micro.integrator.security.MicroIntegratorSecurityUtils;
+import org.wso2.micro.integrator.security.user.api.UserStoreException;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
+import static org.wso2.micro.integrator.management.apis.Constants.USERNAME_PROPERTY;
+
/**
* This class provides an abstraction for all security handlers using authentication for management api.
*/
public abstract class AuthenticationHandlerAdapter extends SecurityHandlerAdapter {
+ private static final Log LOG = LogFactory.getLog(AuthenticationHandlerAdapter.class);
+
public AuthenticationHandlerAdapter(String context) throws CarbonException, XMLStreamException, IOException,
ManagementApiUndefinedException {
super(context);
@@ -88,4 +97,72 @@ public abstract class AuthenticationHandlerAdapter extends SecurityHandlerAdapte
*/
protected abstract Boolean authenticate(String authHeaderToken);
+ /**
+ * Processes authentication request with basic auth and carbon user store.
+ *
+ * @param token extracted basic auth token
+ * @return if successfully authenticated
+ */
+ boolean processAuthRequestWithCarbonUserStore(String token) throws UserStoreException {
+
+ String[] userDetails = extractDetails(token);
+ if (userDetails.length == 0) {
+ return false;
+ }
+ boolean isAuthenticated = MicroIntegratorSecurityUtils.getUserStoreManager().authenticate(userDetails[0],
+ userDetails[1]);
+ if (isAuthenticated) {
+ messageContext.setProperty(USERNAME_PROPERTY, userDetails[0]);
+ LOG.info("User " + userDetails[0] + " logged in successfully");
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Processes authentication request with basic auth and in memory user store
+ *
+ * @param token extracted basic auth token
+ * @return boolean if successfully authenticated
+ */
+ boolean processAuthRequestWithFileBasedUserStore(String token) {
+
+ String[] userDetails = extractDetails(token);
+ if (userDetails.length == 0) {
+ return false;
+ }
+ if (!usersList.isEmpty()) {
+ for (String userNameFromStore : usersList.keySet()) {
+ if (userNameFromStore.equals(userDetails[0])) {
+ String passwordFromStore = String.valueOf(usersList.get(userNameFromStore));
+ if (isValid(passwordFromStore) && passwordFromStore.equals(userDetails[1])) {
+ messageContext.setProperty(USERNAME_PROPERTY, userDetails[0]);
+ LOG.info("User " + userDetails[0] + " logged in successfully");
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private String[] extractDetails(String token) {
+
+ String decodedCredentials = new String(new Base64().decode(token.getBytes()));
+ String[] usernamePasswordArray = decodedCredentials.split(":");
+ if (usernamePasswordArray.length != 2) {
+ return new String[] {};
+ }
+ return new String[] { usernamePasswordArray[0], usernamePasswordArray[1] };
+ }
+
+ /**
+ * Checks if a given value is not null and not empty.
+ *
+ * @param value String value
+ */
+ private Boolean isValid(String value) {
+
+ return (Objects.nonNull(value) && !value.isEmpty());
+ }
}
diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/BasicSecurityHandler.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/BasicSecurityHandler.java
index bbe830c79..b7da12d38 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/BasicSecurityHandler.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/BasicSecurityHandler.java
@@ -18,17 +18,15 @@
package org.wso2.micro.integrator.management.apis.security.handler;
-import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.MessageContext;
import org.wso2.micro.core.util.CarbonException;
import org.wso2.micro.integrator.management.apis.ManagementApiUndefinedException;
+import org.wso2.micro.integrator.security.user.api.UserStoreException;
-import javax.xml.stream.XMLStreamException;
import java.io.IOException;
-import java.util.Objects;
-
-import static org.wso2.micro.integrator.management.apis.Constants.USERNAME_PROPERTY;
+import javax.xml.stream.XMLStreamException;
/**
* This class extends the AuthenticationHandlerAdapter to create a basic security handler with a user store defined in
@@ -55,38 +53,26 @@ public class BasicSecurityHandler extends AuthenticationHandlerAdapter {
this.name = name;
}
+ @Override
+ public Boolean invoke(MessageContext messageContext) {
+ this.messageContext = messageContext;
+ return super.invoke(messageContext);
+ }
+
@Override
protected Boolean authenticate(String authHeaderToken) {
- LOG.debug("Handling authentication");
- String decodedCredentials = new String(new Base64().decode(authHeaderToken.getBytes()));
- String[] usernamePasswordArray = decodedCredentials.split(":");
- // Avoid possible array index out of bound errors
- if (usernamePasswordArray.length != 2) {
- return false;
- }
- String userNameFromHeader = usernamePasswordArray[0];
- String passwordFromHeader = usernamePasswordArray[1];
- if (!usersList.isEmpty()) {
- for (String userNameFromStore : usersList.keySet()) {
- if (userNameFromStore.equals(userNameFromHeader)) {
- String passwordFromStore = String.valueOf(usersList.get(userNameFromStore));
- if (isValid(passwordFromStore) && passwordFromStore.equals(passwordFromHeader)) {
- messageContext.setProperty(USERNAME_PROPERTY, userNameFromHeader);
- return true;
- }
- }
+
+ LOG.debug("Handling authentication with BasicSecurityHandler");
+ if (useCarbonUserStore) {
+ try {
+ return processAuthRequestWithCarbonUserStore(authHeaderToken);
+ } catch (UserStoreException e) {
+ LOG.error("Error while authenticating with carbon user store", e);
+ return false;
}
+ } else {
+ return processAuthRequestWithFileBasedUserStore(authHeaderToken);
}
-
- return false;
}
- /**
- * Checks if a given value is not null and not empty.
- *
- * @param value String value
- */
- private Boolean isValid(String value) {
- return (Objects.nonNull(value) && !value.isEmpty());
- }
}
diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/JWTTokenSecurityHandler.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/JWTTokenSecurityHandler.java
index 26fdfffd5..448fb2898 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/JWTTokenSecurityHandler.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/JWTTokenSecurityHandler.java
@@ -17,19 +17,16 @@
*/
package org.wso2.micro.integrator.management.apis.security.handler;
-import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.wso2.micro.core.util.CarbonException;
import org.wso2.micro.integrator.management.apis.Constants;
import org.wso2.micro.integrator.management.apis.ManagementApiUndefinedException;
-import org.wso2.micro.integrator.security.MicroIntegratorSecurityUtils;
import org.wso2.micro.integrator.security.user.api.UserStoreException;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
-import java.util.Objects;
import static org.wso2.micro.integrator.management.apis.Constants.USERNAME_PROPERTY;
@@ -70,13 +67,13 @@ public class JWTTokenSecurityHandler extends AuthenticationHandlerAdapter {
if (useCarbonUserStore) {
//Uses carbon user store
try {
- return processLoginRequestWithCarbonUserStore(authHeaderToken);
+ return processAuthRequestWithCarbonUserStore(authHeaderToken);
} catch (UserStoreException e) {
LOG.error("Error while authenticating with carbon user store", e);
}
} else {
//Uses in memory user store
- return processLoginRequestInMemoryUserStore(authHeaderToken);
+ return processAuthRequestWithFileBasedUserStore(authHeaderToken);
}
} else {
//Other resources apart from /login should be authenticated from JWT based auth
@@ -91,70 +88,4 @@ public class JWTTokenSecurityHandler extends AuthenticationHandlerAdapter {
return false;
}
- /**
- * Checks if a given value is not null and not empty.
- *
- * @param value String value
- */
- private Boolean isValid(String value) {
-
- return (Objects.nonNull(value) && !value.isEmpty());
- }
-
- /**
- * Processes /login request if the JWTToken Security Handler is engaged. Since /login is
- * basic auth
- *
- * @param token extracted basic auth token
- * @return boolean if successfully authenticated
- */
- private boolean processLoginRequestInMemoryUserStore(String token) {
-
- String decodedCredentials = new String(new Base64().decode(token.getBytes()));
- String[] usernamePasswordArray = decodedCredentials.split(":");
- if (usernamePasswordArray.length != 2) {
- return false;
- }
- String username = usernamePasswordArray[0];
- String password = usernamePasswordArray[1];
- if (!usersList.isEmpty()) {
- for (String userNameFromStore : usersList.keySet()) {
- if (userNameFromStore.equals(username)) {
- String passwordFromStore = String.valueOf(usersList.get(userNameFromStore));
- if (isValid(passwordFromStore) && passwordFromStore.equals(password)) {
- messageContext.setProperty(USERNAME_PROPERTY, username);
- LOG.info("User " + username + " logged in successfully");
- return true;
- }
- }
- }
- }
- return false;
- }
-
- /**
- * Processes /login request if the JWTToken Security Handler is engaged. Since /login is
- * basic auth
- *
- * @param token extracted basic auth token
- * @return if successfully authenticated
- */
- private boolean processLoginRequestWithCarbonUserStore(String token) throws UserStoreException {
-
- String decodedCredentials = new String(new Base64().decode(token.getBytes()));
- String[] usernamePasswordArray = decodedCredentials.split(":");
- if (usernamePasswordArray.length != 2) {
- return false;
- }
- String username = usernamePasswordArray[0];
- String password = usernamePasswordArray[1];
- boolean isAuthenticated = MicroIntegratorSecurityUtils.getUserStoreManager().authenticate(username,
- password);
- if (isAuthenticated) {
- messageContext.setProperty(USERNAME_PROPERTY, username);
- LOG.info("User " + username + " logged in successfully");
- return true;
- }
- return false;
- }
} | ['components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/BasicSecurityHandler.java', 'components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/JWTTokenSecurityHandler.java', 'components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/security/handler/AuthenticationHandlerAdapter.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 9,220,650 | 1,826,315 | 231,759 | 1,305 | 8,531 | 1,546 | 202 | 3 | 2,502 | 162 | 587 | 73 | 2 | 4 | 1970-01-01T00:26:34 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
846 | wso2/micro-integrator/1851/1837 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1837 | https://github.com/wso2/micro-integrator/pull/1851 | https://github.com/wso2/micro-integrator/pull/1851 | 1 | fixes | Incorrect url is returned for an API with version | **Description:**
The URL returned for an API with a version using the MI CLI is incorrect.
**Example API configuration:**
```
<?xml version="1.0" encoding="UTF-8"?>
<api context="/HelloWorld" name="HelloWorld" version="2.0.0" version-type="url" xmlns="http://ws.apache.org/ns/synapse">
<resource methods="GET">
<inSequence>
<payloadFactory media-type="json">
<format>{"Hello":"World"}</format>
<args/>
</payloadFactory>
<respond/>
</inSequence>
<outSequence/>
<faultSequence/>
</resource>
</api>
```
**Expected:**
http://localhost:8290/HelloWorld/2.0.0
**Returned:**
http://localhost:8290/HelloWorld
**Suggested Labels:**
<!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels-->
**Suggested Assignees:**
<!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
**Affected Product Version:**
WSO2 MI 1.2.0-beta
**OS, DB, other environment details and versions:**
**Steps to reproduce:**
**Related Issues:**
<!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> | 1f5559689f039aff2a38ede2df0ca746f689bdd2 | 74a9b6da9fde9178c6a0e4e76edda171c47a4365 | https://github.com/wso2/micro-integrator/compare/1f5559689f039aff2a38ede2df0ca746f689bdd2...74a9b6da9fde9178c6a0e4e76edda171c47a4365 | diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java
index c36517cb2..ea660ecdb 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java
@@ -47,6 +47,7 @@ import java.util.Set;
public class ApiResource extends APIResource {
private static final String API_NAME = "apiName";
+ private String serverContext = ""; // base server url
public ApiResource(String urlTemplate) {
super(urlTemplate);
@@ -107,15 +108,9 @@ public class ApiResource extends APIResource {
Collection<API> apis = configuration.getAPIs();
JSONObject jsonBody = Utils.createJSONList(apis.size());
-
- String serverUrl = getServerContext(axis2MessageContext.getConfigurationContext().getAxisConfiguration());
-
for (API api: apis) {
-
JSONObject apiObject = new JSONObject();
-
- String apiUrl = serverUrl.equals("err") ? api.getContext() : serverUrl + api.getContext();
-
+ String apiUrl = getApiUrl(api, messageContext);
apiObject.put(Constants.NAME, api.getName());
apiObject.put(Constants.URL, apiUrl);
apiObject.put(Constants.TRACING,
@@ -156,13 +151,7 @@ public class ApiResource extends APIResource {
JSONObject apiObject = new JSONObject();
apiObject.put(Constants.NAME, api.getName());
-
- org.apache.axis2.context.MessageContext axis2MessageContext =
- ((Axis2MessageContext) messageContext).getAxis2MessageContext();
-
- String serverUrl = getServerContext(axis2MessageContext.getConfigurationContext().getAxisConfiguration());
- String apiUrl = serverUrl.equals("err") ? api.getContext() : serverUrl + api.getContext();
-
+ String apiUrl = getApiUrl(api, messageContext);
apiObject.put(Constants.URL, apiUrl);
String version = api.getVersion().equals("") ? "N/A" : api.getVersion();
@@ -208,8 +197,22 @@ public class ApiResource extends APIResource {
return apiObject;
}
+ private String getApiUrl(API api, MessageContext msgCtx) {
+
+ org.apache.axis2.context.MessageContext axisMsgCtx = ((Axis2MessageContext) msgCtx).getAxis2MessageContext();
+ String serverUrl = getServerContext(axisMsgCtx.getConfigurationContext().getAxisConfiguration());
+ String versionUrl = "";
+ if (!api.getVersion().isEmpty()) {
+ versionUrl = "/" + api.getVersion();
+ }
+ return serverUrl.equals("err") ? api.getContext() : serverUrl + api.getContext() + versionUrl;
+ }
+
private String getServerContext(AxisConfiguration configuration) {
+ if (!serverContext.isEmpty()) {
+ return serverContext;
+ }
String portValue;
String protocol;
@@ -238,19 +241,18 @@ public class ApiResource extends APIResource {
host = "localhost";
}
}
-
- String serverContext;
-
+ String url;
try {
int port = Integer.parseInt(portValue);
if (("http".equals(protocol) && port == 80) || ("https".equals(protocol) && port == 443)) {
port = -1;
}
URL serverURL = new URL(protocol, host, port, "");
- serverContext = serverURL.toExternalForm();
+ url = serverURL.toExternalForm();
} catch (MalformedURLException e) {
- serverContext = "err";
+ url = "err";
}
- return serverContext;
+ this.serverContext = url;
+ return url;
}
} | ['components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,244,216 | 1,831,025 | 232,419 | 1,312 | 1,721 | 333 | 42 | 1 | 1,511 | 155 | 346 | 43 | 3 | 1 | 1970-01-01T00:26:34 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
840 | wso2/micro-integrator/2649/2648 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/2648 | https://github.com/wso2/micro-integrator/pull/2649 | https://github.com/wso2/micro-integrator/pull/2649 | 1 | fixes | Cannot create a new super admin user | **Description:**
When we use a JDBC user store and try to add a superuser using the following config, the newly created user will be a non-admin user if there is a super admin user already present in the user store. But if we try the same in EI 660, it will create a new super admin user.
```toml
[super_admin]
username = "admin2"
password = "admin2"
admin_role = "admin"
create_admin_account = true
```
**Steps to reproduce:**
1. Configure a [JDBC user store](https://apim.docs.wso2.com/en/latest/install-and-setup/setup/mi-setup/user_stores/setting_up_a_userstore/)
2. Start the MI pack without adding the `super_admin` element to the toml. This will create a super admin user as `admin`.
3. Add the above `super_admin` element to the toml and restart the server.
4. If you login to the dashboard and check, the newly created super admin user `admin2` will be a non admin user.
5. If we check the user store database, it doesn't have the admin role assigned to the new user `admin2`. | a59eb9b199e47e6d1e22579aba70ffc94b7e77be | 186c6fe55afee4efe407ae917cecb2228c3d2eed | https://github.com/wso2/micro-integrator/compare/a59eb9b199e47e6d1e22579aba70ffc94b7e77be...186c6fe55afee4efe407ae917cecb2228c3d2eed | diff --git a/components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/user/core/common/AbstractUserStoreManager.java b/components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/user/core/common/AbstractUserStoreManager.java
index 6e56da6d1..d581b18e4 100644
--- a/components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/user/core/common/AbstractUserStoreManager.java
+++ b/components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/user/core/common/AbstractUserStoreManager.java
@@ -5921,7 +5921,7 @@ public abstract class AbstractUserStoreManager implements UserStoreManager, Pagi
} else if (addAdmin) {
try {
this.doAddUser(adminUserName, realmConfig.getAdminPassword(),
- null, null, null, false);
+ new String[]{adminRoleName}, null, null, false);
} catch (Exception e) {
String message = "Admin user has not been created. " +
"Error occurs while creating Admin user in primary user store."; | ['components/org.wso2.micro.integrator.security/src/main/java/org/wso2/micro/integrator/security/user/core/common/AbstractUserStoreManager.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 10,215,536 | 2,025,142 | 257,085 | 1,478 | 132 | 23 | 2 | 1 | 1,003 | 158 | 250 | 17 | 1 | 1 | 1970-01-01T00:27:27 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
841 | wso2/micro-integrator/2628/2625 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/2625 | https://github.com/wso2/micro-integrator/pull/2628 | https://github.com/wso2/micro-integrator/pull/2628 | 1 | fixes | [Management API] NPE when calling CApp resource without Accept header | **Description:**
When we try to retrieve information about a capp, MI will throw an NPE if we haven't defined the `Accept` header in the request. To fix this we need to have a null check at [[1](https://github.com/wso2/micro-integrator/blob/master/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/CarbonAppResource.java#L116)].
**Steps to reproduce:**
1. Deploy some capp
2. Call the Management API without Accept header
```
curl -X GET "https://localhost:9164/management/applications?carbonAppName=HelloCApp" -H "Authorization: Bearer TOKEN" -k
```
| 1b9bbda77891c9f00ddfd31294f2f895fb6e791c | d3a8a25c0edc2785001c74ff1b6ae4e797269273 | https://github.com/wso2/micro-integrator/compare/1b9bbda77891c9f00ddfd31294f2f895fb6e791c...d3a8a25c0edc2785001c74ff1b6ae4e797269273 | diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/CarbonAppResource.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/CarbonAppResource.java
index a17f6e934..f8de287d6 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/CarbonAppResource.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/CarbonAppResource.java
@@ -113,7 +113,7 @@ public class CarbonAppResource extends APIResource {
if (Objects.nonNull(param)) {
String acceptHeader = (String) SecurityUtils.getHeaders(axis2MessageContext)
.get(HTTPConstants.HEADER_ACCEPT);
- if (acceptHeader.equalsIgnoreCase(Constants.MEDIA_TYPE_APPLICATION_OCTET_STREAM)) {
+ if (Constants.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(acceptHeader)) {
populateFileContent(messageContext, param);
} else {
populateCarbonAppData(messageContext, param); | ['components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/CarbonAppResource.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 10,215,513 | 2,025,133 | 257,085 | 1,478 | 199 | 33 | 2 | 1 | 659 | 63 | 167 | 11 | 2 | 1 | 1970-01-01T00:27:26 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
842 | wso2/micro-integrator/2489/2430 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/2430 | https://github.com/wso2/micro-integrator/pull/2489 | https://github.com/wso2/micro-integrator/pull/2489 | 1 | fixes | Metric Handler causes OOM issues. | **Description:**
Under heavy load (in cases where APIs with query parameters), the metrics publishing leads to OOM issues. Suspected cause for this having the invocation URL in labels, which causes more and more metrics to be created each time the path param changes. This leads to issues when formatting the metrics in https://github.com/wso2/micro-integrator/blob/9f7ceb0cc800e7df7d0ba6102a6ab26e2c9fc52a/components/mediation/data-publishers/org.wso2.micro.integrator.observability/src/main/java/org/wso2/micro/integrator/observability/metric/publisher/MetricFormatter.java#L57
This OOM issue needs to addresses either by ignoring path params of the invocation URL or removing the invocation URL.
We need to limit the number of metrics created and make sure this doesn't fail under heavy load.
| 0cbc20d6a8bf45cefcd04d9db54dbe1e97d8413a | 369402745b1a943e630420a0c366245c019f3751 | https://github.com/wso2/micro-integrator/compare/0cbc20d6a8bf45cefcd04d9db54dbe1e97d8413a...369402745b1a943e630420a0c366245c019f3751 | diff --git a/components/mediation/data-publishers/org.wso2.micro.integrator.observability/src/main/java/org/wso2/micro/integrator/observability/metric/handler/MetricHandler.java b/components/mediation/data-publishers/org.wso2.micro.integrator.observability/src/main/java/org/wso2/micro/integrator/observability/metric/handler/MetricHandler.java
index d5853ef54..dcd3f3479 100644
--- a/components/mediation/data-publishers/org.wso2.micro.integrator.observability/src/main/java/org/wso2/micro/integrator/observability/metric/handler/MetricHandler.java
+++ b/components/mediation/data-publishers/org.wso2.micro.integrator.observability/src/main/java/org/wso2/micro/integrator/observability/metric/handler/MetricHandler.java
@@ -133,12 +133,19 @@ public class MetricHandler extends AbstractExtendedSynapseHandler {
if ((serviceInvokePort != internalHttpApiPort) && (null !=
axis2MessageContext.getProperty(MetricConstants.SERVICE_PREFIX))) {
- String context = axis2MessageContext.getProperty(MetricConstants.TRANSPORT_IN_URL).
+ String url = axis2MessageContext.getProperty(MetricConstants.TRANSPORT_IN_URL).
toString();
- String apiInvocationUrl = axis2MessageContext.getProperty(MetricConstants.SERVICE_PREFIX).
- toString() + context.replaceFirst(DELIMITER, EMPTY);
- String apiName = getApiName(context, synCtx);
+ String apiName = getApiName(url, synCtx);
if (apiName != null) {
+ String context = "";
+ if (synCtx.getConfiguration() != null) {
+ API api = synCtx.getConfiguration().getAPI(apiName);
+ if (api != null) {
+ context = api.getContext();
+ }
+ }
+ String apiInvocationUrl = axis2MessageContext.getProperty(MetricConstants.SERVICE_PREFIX).
+ toString() + context.replaceFirst(DELIMITER, EMPTY);
incrementAPICount(apiName, apiInvocationUrl);
startTimers(synCtx, apiName, SynapseConstants.FAIL_SAFE_MODE_API, apiInvocationUrl);
} | ['components/mediation/data-publishers/org.wso2.micro.integrator.observability/src/main/java/org/wso2/micro/integrator/observability/metric/handler/MetricHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,811,564 | 1,942,294 | 246,419 | 1,399 | 1,032 | 171 | 15 | 1 | 802 | 91 | 187 | 6 | 1 | 0 | 1970-01-01T00:27:14 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
843 | wso2/micro-integrator/2452/2438 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/2438 | https://github.com/wso2/micro-integrator/pull/2452 | https://github.com/wso2/micro-integrator/pull/2452 | 1 | fix | Issues in Management APIs | **Description:**
1. The transport values in data-services are missing GET data-services from the management api.
2. The sequence name is missing in response form GET sequence from the management api
3. If there is a de-active proxy service, an AxisFault is thrown when retrieving data-services
4. Missing fields such as default values in endpoint configurations
**Suggested Labels:**
<!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels-->
**Suggested Assignees:**
<!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
**Affected Product Version:**
**OS, DB, other environment details and versions:**
**Steps to reproduce:**
**Data-services**
1. Deploy a data service with transports.
`<data name="Accout_dataservice" serviceNamespace="http://ws.wso2.org/dataservice" serviceGroup="" transports="http https local">`
2. The values for transport property is getting missed at the response of the Management API as below.
`<data name=\\"Accout_dataservice\\" serviceNamespace=\\"http://ws.wso2.org/dataservice\\" description=\\"\\" enableBatchRequests=\\"false\\" enableBoxcarring=\\"false\\" disableLegacyBoxcarringMode=\\"false\\" transports=\\"\\">`
3. Deploy a proxy and deactivate the proxy service. (You can use MI dashboard). An AxisFault is thrown when retrieving data-services.
**Sequences**
1. Create a sequnces and deploy.
2. Invoke the get sequence request using the management api. The name of the sequence is missing in the configuration.
**Related Issues:**
<!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> | 3135abf8fa714b2294d6bcb03ec7238fab760a75 | ff2dd64cfd4203b4f019b229e7e9ef9ca1d3cb87 | https://github.com/wso2/micro-integrator/compare/3135abf8fa714b2294d6bcb03ec7238fab760a75...ff2dd64cfd4203b4f019b229e7e9ef9ca1d3cb87 | diff --git a/components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DBUtils.java b/components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DBUtils.java
index a214dc1c8..3982a7ed6 100644
--- a/components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DBUtils.java
+++ b/components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DBUtils.java
@@ -439,11 +439,20 @@ public class DBUtils {
Map<String, AxisService> map = axisConfiguration.getServices();
Set<String> set = map.keySet();
for (String serviceName : set) {
- AxisService axisService = axisConfiguration.getService(serviceName);
- Parameter parameter = axisService.getParameter(DBConstants.AXIS2_SERVICE_TYPE);
- if (parameter != null) {
- if (DBConstants.DB_SERVICE_TYPE.equals(parameter.getValue().toString())) {
- serviceList.add(serviceName);
+ try {
+ AxisService axisService = axisConfiguration.getService(serviceName);
+ Parameter parameter = axisService.getParameter(DBConstants.AXIS2_SERVICE_TYPE);
+ if (parameter != null) {
+ if (DBConstants.DB_SERVICE_TYPE.equals(parameter.getValue().toString())) {
+ serviceList.add(serviceName);
+ }
+ }
+ } catch (AxisFault axisFault) {
+ if (axisFault.getMessage().contains("inactive")) {
+ log.debug("Ignoring axisFault due to inactive service.");
+ } else {
+ log.error("Error occurred while populating service " + serviceName + " : "
+ + axisFault.getMessage(), axisFault);
}
}
}
diff --git a/components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DataServiceFactory.java b/components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DataServiceFactory.java
index 429848a2d..d232ff1dd 100644
--- a/components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DataServiceFactory.java
+++ b/components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DataServiceFactory.java
@@ -41,6 +41,7 @@ import org.wso2.securevault.SecurityConstants;
import javax.xml.namespace.QName;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
@@ -146,6 +147,13 @@ public class DataServiceFactory {
/* set disable legacy boxcarring mode */
dataService.setDisableLegacyBoxcarringMode(disableLegacyBoxcarringMode);
+ /* set transports */
+ String transports = dbsElement.getAttributeValue(new QName(DBSFields.TRANSPORTS));
+ if (transports != null && !transports.isEmpty()) {
+ List<String> transportsList = Arrays.asList(transports.split("\\\\s"));
+ dataService.setTransports(transportsList);
+ }
+
/* add the password manager */
Iterator<OMElement> passwordMngrItr = dbsElement.getChildrenWithName(
new QName(SecurityConstants.PASSWORD_MANAGER_SIMPLE));
diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/SequenceResource.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/SequenceResource.java
index 9d7547ba8..1b018bd70 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/SequenceResource.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/SequenceResource.java
@@ -175,7 +175,7 @@ public class SequenceResource extends APIResource {
}
sequenceObject.put("mediators", mediatorTypes);
sequenceObject.put(Constants.SYNAPSE_CONFIGURATION,
- new SequenceMediatorSerializer().serializeAnonymousSequence(null, sequenceMediator));
+ new SequenceMediatorSerializer().serializeSpecificMediator(sequenceMediator));
return sequenceObject;
} | ['components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DataServiceFactory.java', 'components/data/data-services/org.wso2.micro.integrator.dataservices.core/src/main/java/org/wso2/micro/integrator/dataservices/core/DBUtils.java', 'components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/SequenceResource.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 9,799,755 | 1,940,152 | 246,178 | 1,398 | 1,756 | 286 | 29 | 3 | 1,950 | 248 | 411 | 35 | 2 | 0 | 1970-01-01T00:27:12 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
844 | wso2/micro-integrator/2377/2376 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/2376 | https://github.com/wso2/micro-integrator/pull/2377 | https://github.com/wso2/micro-integrator/pull/2377 | 1 | fixes | RabbitMQ Exchage declaration fails when there is already an exchange with extra paramters | **Description:**
$subject
**Affected Product Version:**
MI-1.2.0
**Steps to reproduce:**
1. Configure RabbitMQ AMQP with Micro Integrator.
2. Add the following configurations to deployment.toml file.
```toml
[transport.rabbitmq]
sender_enable = true
listener_enable = true
[[transport.rabbitmq.sender]]
name = "AMQPConnectionFactory"
parameter.port = 5673
parameter.username = "guest"
parameter.password = "guest"
[[transport.rabbitmq.listener]]
name = "AMQPConnectionFactory"
parameter.hostname = "localhost"
parameter.port = 5673
parameter.username = "guest"
parameter.password = "guest"
parameter.retry_interval = "10"
parameter.retry_count = 5
```
4. Create a exchange with an alternate-exchange property.
3. Use the proxy RabbitProxy.xml to publish messages to the queue.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="RabbitProxy"
transports="http https"
startOnLoad="true">
<description/>
<target>
<inSequence>
<property name="OUT_ONLY" value="true" scope="default" type="STRING"/>
<log level="custom" category="INFO">
<property name="this log is" value="***proxy invoked***"/>
</log>
<call>
<endpoint>
<address uri="rabbitmq:/?rabbitmq.server.host.name=localhost&rabbitmq.server.user.name=guest&rabbitmq.server.password=guest&rabbitmq.server.port=5672&rabbitmq.queue.name=testQ&rabbitmq.exchange.autodeclare=false&rabbitmq.queue.autodeclare=false&rabbitmq.exchange.name=hasi&rabbitmq.connection.factory=CachedRabbitMQConnectionFactory&rabbitmq.queue.route.key=testK"/>
</endpoint>
</call>
<respond/>
</inSequence>
</target>
</proxy>
```
| 86823dc84e7d5648e5ed68d45bfb6d27ab8ae075 | fa195ac306a96bee1de1257b3a70f1c97cb72838 | https://github.com/wso2/micro-integrator/compare/86823dc84e7d5648e5ed68d45bfb6d27ab8ae075...fa195ac306a96bee1de1257b3a70f1c97cb72838 | diff --git a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQConsumer.java b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQConsumer.java
index de858dfdf..757f58b0e 100644
--- a/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQConsumer.java
+++ b/components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQConsumer.java
@@ -95,7 +95,20 @@ public class RabbitMQConsumer implements Consumer {
// declaring queue, exchange and binding
queueName = rabbitMQProperties.get(RabbitMQConstants.QUEUE_NAME);
String exchangeName = rabbitMQProperties.get(RabbitMQConstants.EXCHANGE_NAME);
- RabbitMQUtils.declareQueuesExchangesAndBindings(channel, queueName, exchangeName, rabbitMQProperties);
+
+ try {
+ RabbitMQUtils.declareQueue(channel, queueName, rabbitMQProperties);
+ } catch (IOException ex) {
+ channel = RabbitMQUtils.checkAndIgnoreInEquivalentParamException(connection, ex,
+ org.apache.axis2.transport.rabbitmq.RabbitMQConstants.QUEUE, queueName);
+ }
+ try {
+ RabbitMQUtils.declareExchange(channel, exchangeName, rabbitMQProperties);
+ } catch (IOException ex) {
+ channel = RabbitMQUtils.checkAndIgnoreInEquivalentParamException(connection, ex,
+ org.apache.axis2.transport.rabbitmq.RabbitMQConstants.EXCHANGE, exchangeName);
+ }
+ RabbitMQUtils.bindQueueToExchange(channel, queueName, exchangeName, rabbitMQProperties);
// get max dead-lettered count
maxDeadLetteredCount = | ['components/mediation/inbound-endpoints/org.wso2.micro.integrator.inbound.endpoint/src/main/java/org/wso2/carbon/inbound/endpoint/protocol/rabbitmq/RabbitMQConsumer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,763,961 | 1,933,508 | 245,459 | 1,396 | 885 | 172 | 15 | 1 | 1,861 | 126 | 431 | 59 | 1 | 2 | 1970-01-01T00:27:09 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
845 | wso2/micro-integrator/1928/1927 | wso2 | micro-integrator | https://github.com/wso2/micro-integrator/issues/1927 | https://github.com/wso2/micro-integrator/pull/1928 | https://github.com/wso2/micro-integrator/pull/1928 | 1 | fixes | API - When the version-type of the synapse API is context, the url shown in dashboard does not work | **Description:**
When the following API is deployed the URL shown in the Dashboard is `http://localhost:8290/v2/pet/1.0.5/findByStatus`. But the working URL is `http://localhost:8290/v2/pet/findByStatus`.
```
<?xml version="1.0" encoding="UTF-8"?>
<api context="/v2" name="Swagger Petstore" publishSwagger="/_system/governance/swagger_files/petStore.json" version="1.0.5" version-type="context" xmlns="http://ws.apache.org/ns/synapse">
<resource methods="POST" uri-template="/pet/{petId}/uploadImage">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.petId')" name="petId" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="POST" url-mapping="/pet">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="PUT" url-mapping="/pet">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="GET" url-mapping="/pet/findByStatus">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="GET" url-mapping="/pet/findByTags">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="GET" uri-template="/pet/{petId}">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.petId')" name="petId" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="POST" uri-template="/pet/{petId}">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.petId')" name="petId" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="DELETE" uri-template="/pet/{petId}">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.petId')" name="petId" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="POST" url-mapping="/store/order">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="GET" uri-template="/store/order/{orderId}">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.orderId')" name="orderId" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="DELETE" uri-template="/store/order/{orderId}">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.orderId')" name="orderId" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="GET" url-mapping="/store/inventory">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="POST" url-mapping="/user/createWithArray">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="POST" url-mapping="/user/createWithList">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="GET" uri-template="/user/{username}">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.username')" name="username" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="PUT" uri-template="/user/{username}">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.username')" name="username" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="DELETE" uri-template="/user/{username}">
<inSequence>
<!--This is generated API skeleton.-->
<property expression="get-property('uri.var.username')" name="username" scope="default" type="STRING"/>
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="GET" url-mapping="/user/login">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="GET" url-mapping="/user/logout">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
<resource methods="POST" url-mapping="/user">
<inSequence>
<!--This is generated API skeleton.-->
<!--Business Logic Goes Here-->
<payloadFactory media-type="json">
<format>{"Response" : "Sample Response"}</format>
<args/>
</payloadFactory>
<loopback/>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
</api>
```
**Steps to reproduce:**
1. Create a Synapse API importing the following swagger definition.
[petStore.zip](https://github.com/wso2/micro-integrator/files/4986905/petStore.zip)
2. Deploy it.
3. In the Dashboard, the URL will be shown as this `http://localhost:8290/v2/pet/1.0.5/findByStatus`.
4. But the working URL is `http://localhost:8290/v2/pet/findByStatus`. | b025e32b3218bb94828d31ca778228e4a20f6110 | 77094efb54a22ed3771331d5595aa1bbcdcb48f5 | https://github.com/wso2/micro-integrator/compare/b025e32b3218bb94828d31ca778228e4a20f6110...77094efb54a22ed3771331d5595aa1bbcdcb48f5 | diff --git a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java
index a91067a34..ce8cffcae 100644
--- a/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java
+++ b/components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java
@@ -53,6 +53,7 @@ public class ApiResource extends APIResource {
private static Log LOG = LogFactory.getLog(ApiResource.class);
private static final String API_NAME = "apiName";
+ private static final String URL_VERSION_TYPE = "url";
private String serverContext = ""; // base server url
public ApiResource(String urlTemplate) {
@@ -215,7 +216,7 @@ public class ApiResource extends APIResource {
org.apache.axis2.context.MessageContext axisMsgCtx = ((Axis2MessageContext) msgCtx).getAxis2MessageContext();
String serverUrl = getServerContext(axisMsgCtx.getConfigurationContext().getAxisConfiguration());
String versionUrl = "";
- if (!api.getVersion().isEmpty()) {
+ if (URL_VERSION_TYPE.equals(api.getVersionStrategy().getVersionType()) && !api.getVersion().isEmpty()) {
versionUrl = "/" + api.getVersion();
}
return serverUrl.equals("err") ? api.getContext() : serverUrl + api.getContext() + versionUrl; | ['components/org.wso2.micro.integrator.extensions/org.wso2.micro.integrator.management.apis/src/main/java/org/wso2/micro/integrator/management/apis/ApiResource.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,269,204 | 1,836,078 | 233,053 | 1,315 | 216 | 44 | 3 | 1 | 12,106 | 676 | 2,490 | 325 | 6 | 1 | 1970-01-01T00:26:35 | 154 | Java | {'Java': 16580512, 'Shell': 271199, 'Jinja': 131746, 'XSLT': 77329, 'Batchfile': 49378, 'JavaScript': 46701, 'PLSQL': 37765, 'Ballerina': 22977, 'SQLPL': 17882, 'Ruby': 17030, 'TSQL': 15030, 'Dockerfile': 7861, 'XQuery': 2384, 'HTML': 609} | Apache License 2.0 |
720 | finos/waltz/4287/4286 | finos | waltz | https://github.com/finos/waltz/issues/4286 | https://github.com/finos/waltz/pull/4287 | https://github.com/finos/waltz/pull/4287 | 1 | fix | Revert Maria Union fix | bringing in way too much on app-selector with groups (and probably elsewhere) | ba73fb04f74ebe170e3c4020ccb5dcac271375f4 | 77eb9291dd53160d6d696ac2108ac7540ba78fe1 | https://github.com/finos/waltz/compare/ba73fb04f74ebe170e3c4020ccb5dcac271375f4...77eb9291dd53160d6d696ac2108ac7540ba78fe1 | diff --git a/waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationDao.java b/waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationDao.java
index d629081c3..778c85b8a 100644
--- a/waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationDao.java
+++ b/waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationDao.java
@@ -231,8 +231,7 @@ public class ApplicationDao {
public List<Application> findByAppIdSelector(Select<Record1<Long>> selector) {
- return dsl
- .selectFrom(APPLICATION)
+ return dsl.selectFrom(APPLICATION)
.where(APPLICATION.ID.in(selector))
.fetch(TO_DOMAIN_MAPPER);
}
diff --git a/waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationIdSelectorFactory.java b/waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationIdSelectorFactory.java
index 3d3c7a4b6..75b5ed492 100644
--- a/waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationIdSelectorFactory.java
+++ b/waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationIdSelectorFactory.java
@@ -81,10 +81,14 @@ public class ApplicationIdSelectorFactory implements Function<ApplicationIdSelec
return mkForAppGroup(options);
case APPLICATION:
return mkForApplication(options);
+ case CHANGE_INITIATIVE:
+ return mkForEntityRelationship(options);
case DATA_TYPE:
return mkForDataType(options);
case FLOW_DIAGRAM:
return mkForFlowDiagram(options);
+ case LICENCE:
+ return mkForEntityRelationship(options);
case MEASURABLE:
return mkForMeasurable(options);
case SCENARIO:
@@ -97,9 +101,6 @@ public class ApplicationIdSelectorFactory implements Function<ApplicationIdSelec
return mkForPerson(options);
case SOFTWARE:
return mkForSoftwarePackage(options);
- case CHANGE_INITIATIVE: // drop thru
- case LICENCE:
- return mkForEntityRelationship(options);
default:
throw new IllegalArgumentException("Cannot create selector for entity kind: " + ref.kind());
}
@@ -172,10 +173,8 @@ public class ApplicationIdSelectorFactory implements Function<ApplicationIdSelec
.and(logicalFlow.ENTITY_LIFECYCLE_STATUS.ne(REMOVED.name())))
.and(applicationConditions);
- // UNION like this to support maria (see #4267)
- return DSL
- .select(DSL.field("id", Long.class))
- .from(sourceAppIds.unionAll(targetAppIds));
+ return sourceAppIds
+ .union(targetAppIds);
}
@@ -238,10 +237,9 @@ public class ApplicationIdSelectorFactory implements Function<ApplicationIdSelec
.and(ENTITY_RELATIONSHIP.ID_A.eq(options.entityReference().id()))
.and(applicationConditions);
- // UNION like this to support maria (see #4267)
- return DSL
- .select(DSL.field("id", Long.class))
- .from(appToEntity.unionAll(entityToApp));
+
+ return appToEntity
+ .union(entityToApp);
}
@@ -292,15 +290,10 @@ public class ApplicationIdSelectorFactory implements Function<ApplicationIdSelec
.from(APPLICATION_GROUP_ENTRY)
.where(APPLICATION_GROUP_ENTRY.GROUP_ID.eq(options.entityReference().id()));
- // UNION like this to support maria (see #4267)
- SelectJoinStep<Record1<Long>> appIds = DSL
- .select(DSL.field("id", Long.class))
- .from(directApps.unionAll(applicationIdsFromAssociatedOrgUnits));
-
return DSL
.select(APPLICATION.ID)
.from(APPLICATION)
- .where(APPLICATION.ID.in(appIds))
+ .where(APPLICATION.ID.in(directApps.unionAll(applicationIdsFromAssociatedOrgUnits)))
.and(applicationConditions);
}
@@ -390,10 +383,10 @@ public class ApplicationIdSelectorFactory implements Function<ApplicationIdSelec
.and(applicationConditions),
LOGICAL_FLOW.TARGET_ENTITY_ID);
- // UNION like this to support maria (see #4267)
return DSL
- .select(DSL.field("id", Long.class))
- .from(sources.unionAll(targets));
+ .selectDistinct(appId)
+ .from(sources)
+ .union(targets);
}
diff --git a/waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeDao.java b/waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeDao.java
index 14203b32d..dd16e95b0 100644
--- a/waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeDao.java
+++ b/waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeDao.java
@@ -111,10 +111,7 @@ public class ChangeInitiativeDao implements FindEntityReferencesByIdSelector {
.where(ENTITY_HIERARCHY.ANCESTOR_ID.in(selector)
.and(ENTITY_HIERARCHY.KIND.eq(EntityKind.CHANGE_INITIATIVE.name())));
- // UNION like this to support maria (see #4267)
- SelectOrderByStep<Record1<Long>> hierarchySelector = DSL
- .select(DSL.field("id", Long.class))
- .from(descendants.unionAll(ancestors));
+ SelectOrderByStep<Record1<Long>> hierarchySelector = descendants.unionAll(ancestors);
return findForSelector(hierarchySelector);
}
diff --git a/waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeIdSelectorFactory.java b/waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeIdSelectorFactory.java
index f045e3df0..ae868c86a 100644
--- a/waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeIdSelectorFactory.java
+++ b/waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeIdSelectorFactory.java
@@ -27,7 +27,6 @@ import com.khartec.waltz.model.IdSelectionOptions;
import org.jooq.Record1;
import org.jooq.Select;
import org.jooq.SelectConditionStep;
-import org.jooq.SelectJoinStep;
import org.jooq.impl.DSL;
import static com.khartec.waltz.data.SelectorUtilities.ensureScopeIsExact;
@@ -131,10 +130,7 @@ public class ChangeInitiativeIdSelectorFactory extends AbstractIdSelectorFactory
.and(ENTITY_RELATIONSHIP.KIND_A.eq(ref.kind().name()))
.and(ENTITY_RELATIONSHIP.ID_A.eq(ref.id()));
- // UNION like this to support maria (see #4267)
- return DSL
- .select(DSL.field("id", Long.class))
- .from(aToB.unionAll(bToA));
+ return aToB.union(bToA);
}
}
diff --git a/waltz-data/src/main/java/com/khartec/waltz/data/entity_hierarchy/AbstractIdSelectorFactory.java b/waltz-data/src/main/java/com/khartec/waltz/data/entity_hierarchy/AbstractIdSelectorFactory.java
index 82c303858..c728205cf 100644
--- a/waltz-data/src/main/java/com/khartec/waltz/data/entity_hierarchy/AbstractIdSelectorFactory.java
+++ b/waltz-data/src/main/java/com/khartec/waltz/data/entity_hierarchy/AbstractIdSelectorFactory.java
@@ -64,15 +64,13 @@ public abstract class AbstractIdSelectorFactory implements IdSelectorFactory {
selector = DSL.select(DSL.val(options.entityReference().id()));
break;
case CHILDREN:
- selector = DSL
- .select(ENTITY_HIERARCHY.ID)
+ selector = DSL.select(ENTITY_HIERARCHY.ID)
.from(ENTITY_HIERARCHY)
.where(ENTITY_HIERARCHY.ANCESTOR_ID.eq(options.entityReference().id()))
.and(ENTITY_HIERARCHY.KIND.eq(entityKind.name()));
break;
case PARENTS:
- selector = DSL
- .select(ENTITY_HIERARCHY.ANCESTOR_ID)
+ selector = DSL.select(ENTITY_HIERARCHY.ANCESTOR_ID)
.from(ENTITY_HIERARCHY)
.where(ENTITY_HIERARCHY.ID.eq(options.entityReference().id()))
.and(ENTITY_HIERARCHY.KIND.eq(entityKind.name()));
diff --git a/waltz-data/src/main/java/com/khartec/waltz/data/licence/LicenceIdSelectorFactory.java b/waltz-data/src/main/java/com/khartec/waltz/data/licence/LicenceIdSelectorFactory.java
index 0595c38e2..f7589e8e7 100644
--- a/waltz-data/src/main/java/com/khartec/waltz/data/licence/LicenceIdSelectorFactory.java
+++ b/waltz-data/src/main/java/com/khartec/waltz/data/licence/LicenceIdSelectorFactory.java
@@ -83,10 +83,8 @@ public class LicenceIdSelectorFactory extends AbstractIdSelectorFactory {
.and(ENTITY_RELATIONSHIP.KIND_A.eq(EntityKind.APPLICATION.name()))
.and(ENTITY_RELATIONSHIP.ID_A.in(appSelector));
- // UNION like this to support maria (see #4267)
- return DSL
- .select(DSL.field("id", Long.class))
- .from(aToB.unionAll(bToA));
+ return aToB.unionAll(bToA);
+
}
@@ -111,9 +109,6 @@ public class LicenceIdSelectorFactory extends AbstractIdSelectorFactory {
.and(ENTITY_RELATIONSHIP.KIND_A.eq(ref.kind().name()))
.and(ENTITY_RELATIONSHIP.ID_A.eq(ref.id()));
- // UNION like this to support maria (see #4267)
- return DSL
- .select(DSL.field("id", Long.class))
- .from(aToB.unionAll(bToA));
+ return aToB.union(bToA);
}
}
diff --git a/waltz-data/src/main/java/com/khartec/waltz/data/measurable/MeasurableIdSelectorFactory.java b/waltz-data/src/main/java/com/khartec/waltz/data/measurable/MeasurableIdSelectorFactory.java
index ea9249d3c..2497fc8bb 100644
--- a/waltz-data/src/main/java/com/khartec/waltz/data/measurable/MeasurableIdSelectorFactory.java
+++ b/waltz-data/src/main/java/com/khartec/waltz/data/measurable/MeasurableIdSelectorFactory.java
@@ -187,10 +187,8 @@ public class MeasurableIdSelectorFactory implements IdSelectorFactory {
.where(FLOW_DIAGRAM_ENTITY.ENTITY_KIND.eq(EntityKind.MEASURABLE.name()))
.and(FLOW_DIAGRAM_ENTITY.DIAGRAM_ID.eq(diagramId));
- // UNION like this to support maria (see #4267)
- return DSL
- .select(DSL.field("id", Long.class))
- .from(viaAppRatings.unionAll(viaDirectRelationship));
+ return viaAppRatings.union(viaDirectRelationship);
+
}
| ['waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeIdSelectorFactory.java', 'waltz-data/src/main/java/com/khartec/waltz/data/measurable/MeasurableIdSelectorFactory.java', 'waltz-data/src/main/java/com/khartec/waltz/data/licence/LicenceIdSelectorFactory.java', 'waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationIdSelectorFactory.java', 'waltz-data/src/main/java/com/khartec/waltz/data/entity_hierarchy/AbstractIdSelectorFactory.java', 'waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeDao.java', 'waltz-data/src/main/java/com/khartec/waltz/data/application/ApplicationDao.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 3,107,973 | 642,181 | 81,478 | 922 | 3,172 | 694 | 70 | 7 | 77 | 12 | 15 | 1 | 0 | 0 | 1970-01-01T00:26:05 | 153 | Java | {'Java': 5787749, 'JavaScript': 2747626, 'HTML': 1447638, 'Svelte': 1041672, 'SCSS': 136037, 'EJS': 6787, 'Shell': 1560, 'FreeMarker': 1496, 'Dockerfile': 1346, 'CSS': 1298} | Apache License 2.0 |
716 | finos/waltz/5889/5865 | finos | waltz | https://github.com/finos/waltz/issues/5865 | https://github.com/finos/waltz/pull/5889 | https://github.com/finos/waltz/pull/5889 | 1 | fix | Grid export: reports of timeout when exporting large numbers of rows | ### Description
Needs further investigation as initial tests seem fine.
### Waltz Version
1.39
| 3c248a23280ed81799fdb6b54c83acb6fa24711e | 2d4f4a15e96d5d07dfc75394253e75b1fb3b4726 | https://github.com/finos/waltz/compare/3c248a23280ed81799fdb6b54c83acb6fa24711e...2d4f4a15e96d5d07dfc75394253e75b1fb3b4726 | diff --git a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/AttestationExtractor.java b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/AttestationExtractor.java
index fd365e32e..d0af431ef 100644
--- a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/AttestationExtractor.java
+++ b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/AttestationExtractor.java
@@ -231,7 +231,7 @@ public class AttestationExtractor extends DirectQueryBasedDataExtractor {
private byte[] mkExcelReport(String reportName,
List<String> columnDefinitions,
Set<ApplicationAttestationInstanceSummary> reportRows) throws IOException {
- SXSSFWorkbook workbook = new SXSSFWorkbook();
+ SXSSFWorkbook workbook = new SXSSFWorkbook(2000);
SXSSFSheet sheet = workbook.createSheet(sanitizeSheetName(reportName));
int colCount = writeExcelHeader(columnDefinitions, sheet);
diff --git a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/CustomDataExtractor.java b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/CustomDataExtractor.java
index c45749812..8fb815c79 100644
--- a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/CustomDataExtractor.java
+++ b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/CustomDataExtractor.java
@@ -73,7 +73,7 @@ public abstract class CustomDataExtractor implements DataExtractor {
private byte[] mkExcelReport(String reportName, List<List<Object>> reportRows, List<String> headers) throws IOException {
- SXSSFWorkbook workbook = new SXSSFWorkbook();
+ SXSSFWorkbook workbook = new SXSSFWorkbook(2000);
SXSSFSheet sheet = workbook.createSheet(sanitizeSheetName(reportName));
int colCount = writeExcelHeader(sheet, headers);
diff --git a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/DirectQueryBasedDataExtractor.java b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/DirectQueryBasedDataExtractor.java
index 589ee5305..629e6daf6 100644
--- a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/DirectQueryBasedDataExtractor.java
+++ b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/DirectQueryBasedDataExtractor.java
@@ -74,7 +74,7 @@ public abstract class DirectQueryBasedDataExtractor implements DataExtractor {
String suggestedFilenameStem,
Response response,
Tuple2<String, Select<?>>... sheetDefinitions) {
- SXSSFWorkbook workbook = new SXSSFWorkbook();
+ SXSSFWorkbook workbook = new SXSSFWorkbook(2000);
for (Tuple2<String, Select<?>> sheetDef : sheetDefinitions) {
time("preparing excel sheet: " + sheetDef.v1, () -> {
@@ -101,7 +101,7 @@ public abstract class DirectQueryBasedDataExtractor implements DataExtractor {
private static Object writeAsExcel(String suggestedFilenameStem,
Select<?> qry,
Response response) throws IOException {
- SXSSFWorkbook workbook = new SXSSFWorkbook();
+ SXSSFWorkbook workbook = new SXSSFWorkbook(2000);
SXSSFSheet sheet = workbook.createSheet(ExtractorUtilities.sanitizeSheetName(suggestedFilenameStem));
writeExcelHeader(qry, sheet);
diff --git a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java
index 2d8d8cfef..222114d0d 100644
--- a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java
+++ b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java
@@ -272,7 +272,7 @@ public class SurveyInstanceExtractor implements DataExtractor {
private byte[] mkExcelReport(String reportName, List<SurveyQuestion> questions, List<List<Object>> reportRows) throws IOException {
- SXSSFWorkbook workbook = new SXSSFWorkbook(4000);
+ SXSSFWorkbook workbook = new SXSSFWorkbook(2000);
SXSSFSheet sheet = workbook.createSheet(sanitizeSheetName(reportName));
int colCount = writeExcelHeader(questions, sheet); | ['waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java', 'waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/CustomDataExtractor.java', 'waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/DirectQueryBasedDataExtractor.java', 'waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/AttestationExtractor.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 4,084,896 | 842,947 | 108,199 | 1,166 | 570 | 108 | 10 | 4 | 109 | 14 | 22 | 10 | 0 | 0 | 1970-01-01T00:27:23 | 153 | Java | {'Java': 5787749, 'JavaScript': 2747626, 'HTML': 1447638, 'Svelte': 1041672, 'SCSS': 136037, 'EJS': 6787, 'Shell': 1560, 'FreeMarker': 1496, 'Dockerfile': 1346, 'CSS': 1298} | Apache License 2.0 |
715 | finos/waltz/5902/5894 | finos | waltz | https://github.com/finos/waltz/issues/5894 | https://github.com/finos/waltz/pull/5902 | https://github.com/finos/waltz/pull/5902 | 1 | fix | Survey export from run view doesn't export NOT_STARTED instances | ### Description
Works for the IN_PROGRESS and COMPLETED/APPROVED exports
### Waltz Version
1.39.1
### Steps to Reproduce
1.
2.
3.
...
### Expected Result
Should export a list of not started survey instances (number indicated in the progress bar)
### Actual Result
Produces an export with no data | 0425f06b7986500d61678a5525ac8639dc0e792c | d019710e393ecad5ac3cb5a2a7352597be2ec1e1 | https://github.com/finos/waltz/compare/0425f06b7986500d61678a5525ac8639dc0e792c...d019710e393ecad5ac3cb5a2a7352597be2ec1e1 | diff --git a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java
index 222114d0d..464692fc6 100644
--- a/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java
+++ b/waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java
@@ -380,13 +380,13 @@ public class SurveyInstanceExtractor implements DataExtractor {
sqr.LIST_RESPONSE_CONCAT)
.select(responseNameField,
responseExtIdField)
- .select(DSL.when(si.ORIGINAL_INSTANCE_ID.isNull(), "Yes").else_("No").as("Latest")) //Could always just return latest instance
+ .select(DSL.when(si.ORIGINAL_INSTANCE_ID.isNull(), "Yes").otherwise("No").as("Latest"))
.select(st.EXTERNAL_ID)
- .from(sqr)
- .innerJoin(sq).on(sqr.QUESTION_ID.eq(sq.ID))
- .innerJoin(si).on(sqr.SURVEY_INSTANCE_ID.eq(si.ID))
- .innerJoin(sr).on(sr.ID.eq(si.SURVEY_RUN_ID))
- .innerJoin(st).on(st.ID.eq(sr.SURVEY_TEMPLATE_ID))
+ .from(st)
+ .innerJoin(sr).on(sr.SURVEY_TEMPLATE_ID.eq(st.ID))
+ .innerJoin(si).on(si.SURVEY_RUN_ID.eq(sr.ID))
+ .innerJoin(sq).on(sq.SURVEY_TEMPLATE_ID.eq(st.ID))
+ .leftJoin(sqr).on(sqr.SURVEY_INSTANCE_ID.eq(si.ID).and(sqr.QUESTION_ID.eq(sq.ID)))
.where(dsl.renderInlined(condition));
Result<Record> results = extractAnswersQuery.fetch(); | ['waltz-web/src/main/java/org/finos/waltz/web/endpoints/extracts/SurveyInstanceExtractor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,086,442 | 843,217 | 108,231 | 1,166 | 865 | 222 | 12 | 1 | 309 | 48 | 73 | 23 | 0 | 0 | 1970-01-01T00:27:24 | 153 | Java | {'Java': 5787749, 'JavaScript': 2747626, 'HTML': 1447638, 'Svelte': 1041672, 'SCSS': 136037, 'EJS': 6787, 'Shell': 1560, 'FreeMarker': 1496, 'Dockerfile': 1346, 'CSS': 1298} | Apache License 2.0 |
1,054 | snowflakedb/snowflake-jdbc/1298/1270 | snowflakedb | snowflake-jdbc | https://github.com/snowflakedb/snowflake-jdbc/issues/1270 | https://github.com/snowflakedb/snowflake-jdbc/pull/1298 | https://github.com/snowflakedb/snowflake-jdbc/pull/1298 | 1 | fixes | SNOW-752403: Enabling Illegal Reflective Access Warnings | <!--
If you need urgent assistance then file the issue using the support process:
https://community.snowflake.com/s/article/How-To-Submit-a-Support-Case-in-Snowflake-Lodge
otherwise continue here.
-->
Please answer these questions before submitting your issue.
In order to accurately debug the issue this information is required. Thanks!
### 1. What version of JDBC driver are you using?
`v3.13.11`
### 2. What operating system and processor architecture are you using?
`Ubuntu 20.04.5 LTS x86_64`
### 3. What version of Java are you using?
`Java 16`
### 4. What did you do?
Currently, the `SnowflakeDriver.disableIllegalReflectiveAccessWarning()` suppresses the `IllegalAccessLogger` . This results in no warnings shown (`WARNING: Illegal reflective access by...` ). Up till JDK 16, there is an option in jvm `illegal-access=permit`.
[Reference](https://docs.oracle.com/javase/9/tools/java.htm#JSWOR624). This option will issue a warning log in the first illegal reflective access, but won't issue a statement after the first occurrence. Adding `snowflake-jdbc` as a dependency would suppress these logs. Now, since JDK 17 has removed the `illegal-access` option, the only way to suppress the exceptions is to use the `add-opens` option ([Reference](https://docs.oracle.com/en/java/javase/18/migrate/migrating-jdk-8-later-jdk-releases.html#GUID-7744EF96-5899-4FB2-B34E-86D49B2E89B6)). In order to upgade to JDK 17, one should know all the packages which should be granted access to internal reflective APIs, so that they can be included in the `add-opens` option. This logger suppression results in no visibility of the application since there will be no warnings.
### 5. What did you expect to see?
This suppression should be removed and instead the jvm option `illegal-access=permit` should be used.
| 4be4b184dd9817e5c25688802a24960e73e7537d | 5886edbac3b636ed16d8aab787bc6bf561f25b2b | https://github.com/snowflakedb/snowflake-jdbc/compare/4be4b184dd9817e5c25688802a24960e73e7537d...5886edbac3b636ed16d8aab787bc6bf561f25b2b | diff --git a/src/main/java/net/snowflake/client/jdbc/SnowflakeDriver.java b/src/main/java/net/snowflake/client/jdbc/SnowflakeDriver.java
index 45d4f5ad..66c60666 100644
--- a/src/main/java/net/snowflake/client/jdbc/SnowflakeDriver.java
+++ b/src/main/java/net/snowflake/client/jdbc/SnowflakeDriver.java
@@ -61,6 +61,10 @@ public class SnowflakeDriver implements Driver {
disableArrowResultFormat = true;
disableArrowResultFormatMessage = t.getLocalizedMessage();
}
+ if ("true"
+ .equals(SnowflakeUtil.systemGetProperty("snowflake.jdbc.enable.illegalAccessWarning"))) {
+ return;
+ }
disableIllegalReflectiveAccessWarning();
}
| ['src/main/java/net/snowflake/client/jdbc/SnowflakeDriver.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,856,971 | 397,262 | 55,607 | 204 | 136 | 30 | 4 | 1 | 1,857 | 237 | 457 | 29 | 3 | 0 | 1970-01-01T00:27:58 | 151 | Java | {'Java': 3678518, 'Shell': 18685, 'Python': 4357, 'Lua': 3489, 'Standard ML': 833} | Apache License 2.0 |
9,870 | eclipse-vertx/vertx-auth/625/619 | eclipse-vertx | vertx-auth | https://github.com/eclipse-vertx/vertx-auth/issues/619 | https://github.com/eclipse-vertx/vertx-auth/pull/625 | https://github.com/eclipse-vertx/vertx-auth/pull/625 | 1 | fixes | WebAuthn : MetadataServiceImpl parseX5c method returns emptyList when x5c is null | ### Version
Which version(s) did you encounter this bug ?
4.3.8
### Context
I encountered an exception which looks suspicious while I tried to verify my Webauthn authenticator using the metadataService.verify() method and when my authenticator attestationStatement (packed) looks like this : `"{"alg":"ES256"}"` leading to `empty chain` error when calling the MetaData.verifyMetadata() method.
```
private static List<X509Certificate> parseX5c(List<String> x5c) throws CertificateException {
=> List<X509Certificate> certChain = new ArrayList<>();
if (x5c == null || x5c.size() == 0) {
=> return certChain;
}
for (String s : x5c) {
certChain.add(JWS.parseX5c(BASE64_DECODER.decode(s)));
}
return certChain;
}
```
```
MetaData.verifyMetadata()
# at this stage the x5c is an empty list
=> if (x5c != null) {
// make a copy before we start
x5c = new ArrayList<>(x5c);
...
}
```
### Steps to reproduce
1. Verify a packed attestation with no x5c
2. Call the metadataService.verify() method
3. Should not throw RuntimeException if MetaDataEntry is empty or OK
### Potential Solution
Do not create an empty list if the x5c is null.
| 67b237b1cdca069c1a8b2d2b1f4f2f15c8e4b113 | b1ee486c1ac9187002e352d7de94187cac4b0f8b | https://github.com/eclipse-vertx/vertx-auth/compare/67b237b1cdca069c1a8b2d2b1f4f2f15c8e4b113...b1ee486c1ac9187002e352d7de94187cac4b0f8b | diff --git a/vertx-auth-webauthn/src/main/java/io/vertx/ext/auth/webauthn/impl/metadata/MetaDataServiceImpl.java b/vertx-auth-webauthn/src/main/java/io/vertx/ext/auth/webauthn/impl/metadata/MetaDataServiceImpl.java
index 86636dfe..a31208f3 100644
--- a/vertx-auth-webauthn/src/main/java/io/vertx/ext/auth/webauthn/impl/metadata/MetaDataServiceImpl.java
+++ b/vertx-auth-webauthn/src/main/java/io/vertx/ext/auth/webauthn/impl/metadata/MetaDataServiceImpl.java
@@ -200,12 +200,12 @@ public class MetaDataServiceImpl implements MetaDataService {
}
private static List<X509Certificate> parseX5c(List<String> x5c) throws CertificateException {
- List<X509Certificate> certChain = new ArrayList<>();
-
if (x5c == null || x5c.size() == 0) {
- return certChain;
+ return null;
}
+ List<X509Certificate> certChain = new ArrayList<>();
+
for (String s : x5c) {
certChain.add(JWS.parseX5c(BASE64_DECODER.decode(s)));
}
diff --git a/vertx-auth-webauthn/src/test/java/io/vertx/ext/auth/webauthn/MetaDataServiceTest.java b/vertx-auth-webauthn/src/test/java/io/vertx/ext/auth/webauthn/MetaDataServiceTest.java
index 36bfe5b9..559dbab5 100644
--- a/vertx-auth-webauthn/src/test/java/io/vertx/ext/auth/webauthn/MetaDataServiceTest.java
+++ b/vertx-auth-webauthn/src/test/java/io/vertx/ext/auth/webauthn/MetaDataServiceTest.java
@@ -29,6 +29,20 @@ public class MetaDataServiceTest {
mds.verify(authenticator);
}
+ @Test
+ public void testVerifyPackedWithEmptyX5C() {
+
+ // defaults
+ MetaDataService mds = new MetaDataServiceImpl(rule.vertx(), new WebAuthnOptions());
+
+ JsonObject packed = new JsonObject(data);
+ packed.getJsonObject("attestationCertificates").remove("x5c");
+
+ Authenticator authenticator = new Authenticator(packed);
+ // doesn't throw
+ mds.verify(authenticator);
+ }
+
@Test
public void testMDS3(TestContext should) {
final Async test = should.async(); | ['vertx-auth-webauthn/src/main/java/io/vertx/ext/auth/webauthn/impl/metadata/MetaDataServiceImpl.java', 'vertx-auth-webauthn/src/test/java/io/vertx/ext/auth/webauthn/MetaDataServiceTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 885,507 | 219,148 | 26,540 | 219 | 164 | 35 | 6 | 1 | 1,262 | 167 | 314 | 46 | 0 | 2 | 1970-01-01T00:27:58 | 146 | Java | {'Java': 1401518, 'JavaScript': 10208} | Apache License 2.0 |
9,869 | eclipse-vertx/vertx-auth/569/567 | eclipse-vertx | vertx-auth | https://github.com/eclipse-vertx/vertx-auth/issues/567 | https://github.com/eclipse-vertx/vertx-auth/pull/569 | https://github.com/eclipse-vertx/vertx-auth/pull/569#issuecomment-1167255878 | 1 | fixes | 4.2.1: NoSuchAlgorithmException: RSA-OAEP no longer a warning | ### Questions
Do not use this issue tracker to ask questions, instead use one of these [channels](https://vertx.io/community/). Questions will likely be closed without notice.
### Version
4.2.1
### Context
I encountered an exception which looks suspicious while ...
### Do you have a reproducer?
JWTUtil.setupJwtAuth();
throws an exception and does not iterate through all algorithms.
### Extra
i am migrating from 3.2.1 to 4.2.1
with 3.2.1 JWTUtil.setupJwtAuth(); did not throw an exception, so setup completed correctly.
to resolve change:
in io.vertx.ext.auth.jwt.impl.JWTAuthProviderImpl
for (JsonObject jwk : jwks) {
//this.jwt.addJWK(new JWK(jwk));
// +++ should be warning not throw an exception
try
{
this.jwt.addJWK(new JWK(jwk));
}
catch (Exception ex)
{
System.out.println("warning: "+ex.getMessage());
}
// +++
}
| 6011b23bdf3ce28b10d8c58009b945158ab83909 | a8df7dd75d60f50371b6090e0fb2cd9c0fa27309 | https://github.com/eclipse-vertx/vertx-auth/compare/6011b23bdf3ce28b10d8c58009b945158ab83909...a8df7dd75d60f50371b6090e0fb2cd9c0fa27309 | diff --git a/vertx-auth-common/src/main/java/io/vertx/ext/auth/impl/asn/ASN1.java b/vertx-auth-common/src/main/java/io/vertx/ext/auth/impl/asn/ASN1.java
index 5c1e8a13..b0b05d48 100644
--- a/vertx-auth-common/src/main/java/io/vertx/ext/auth/impl/asn/ASN1.java
+++ b/vertx-auth-common/src/main/java/io/vertx/ext/auth/impl/asn/ASN1.java
@@ -17,6 +17,7 @@ package io.vertx.ext.auth.impl.asn;
import io.vertx.core.buffer.Buffer;
+import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
@@ -87,6 +88,22 @@ public class ASN1 {
return (byte[]) value.get(index);
}
+ public int integer(int index) {
+ byte[] bytes = binary(index);
+ if (bytes.length > 4) {
+ throw new IllegalArgumentException("integer too long");
+ }
+ int result = 0;
+ for (byte b : bytes) {
+ result = (result << 8) | (b & 0xFF);
+ }
+ return result;
+ }
+
+ public BigInteger bigInteger(int index) {
+ return new BigInteger(binary(index));
+ }
+
public ASN object(int index) {
return (ASN) value.get(index);
}
diff --git a/vertx-auth-jwt/src/main/java/io/vertx/ext/auth/jwt/impl/JWTAuthProviderImpl.java b/vertx-auth-jwt/src/main/java/io/vertx/ext/auth/jwt/impl/JWTAuthProviderImpl.java
index 081b99b0..e7629a49 100644
--- a/vertx-auth-jwt/src/main/java/io/vertx/ext/auth/jwt/impl/JWTAuthProviderImpl.java
+++ b/vertx-auth-jwt/src/main/java/io/vertx/ext/auth/jwt/impl/JWTAuthProviderImpl.java
@@ -22,6 +22,8 @@ import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.FileSystemException;
+import io.vertx.core.impl.logging.Logger;
+import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
@@ -55,6 +57,8 @@ import java.util.List;
*/
public class JWTAuthProviderImpl implements JWTAuth {
+ private static final Logger LOG = LoggerFactory.getLogger(JWTAuthProviderImpl.class);
+
private static final JsonArray EMPTY_ARRAY = new JsonArray();
private final JWT jwt = new JWT();
@@ -112,7 +116,11 @@ public class JWTAuthProviderImpl implements JWTAuth {
if (jwks != null) {
for (JsonObject jwk : jwks) {
- this.jwt.addJWK(new JWK(jwk));
+ try {
+ jwt.addJWK(new JWK(jwk));
+ } catch (Exception e) {
+ LOG.warn("Unsupported JWK", e);
+ }
}
}
diff --git a/vertx-auth-oauth2/src/main/java/io/vertx/ext/auth/oauth2/impl/OAuth2AuthProviderImpl.java b/vertx-auth-oauth2/src/main/java/io/vertx/ext/auth/oauth2/impl/OAuth2AuthProviderImpl.java
index 3b2a2b97..d3db785a 100644
--- a/vertx-auth-oauth2/src/main/java/io/vertx/ext/auth/oauth2/impl/OAuth2AuthProviderImpl.java
+++ b/vertx-auth-oauth2/src/main/java/io/vertx/ext/auth/oauth2/impl/OAuth2AuthProviderImpl.java
@@ -120,8 +120,8 @@ public class OAuth2AuthProviderImpl implements OAuth2Auth, Closeable {
for (Object key : keys) {
try {
jwt.addJWK(new JWK((JsonObject) key));
- } catch (RuntimeException e) {
- LOG.warn("Skipped unsupported JWK: " + e.getMessage());
+ } catch (Exception e) {
+ LOG.warn("Unsupported JWK", e);
}
}
// swap | ['vertx-auth-oauth2/src/main/java/io/vertx/ext/auth/oauth2/impl/OAuth2AuthProviderImpl.java', 'vertx-auth-common/src/main/java/io/vertx/ext/auth/impl/asn/ASN1.java', 'vertx-auth-jwt/src/main/java/io/vertx/ext/auth/jwt/impl/JWTAuthProviderImpl.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 1,036,200 | 240,632 | 31,744 | 273 | 1,020 | 219 | 31 | 3 | 1,061 | 113 | 227 | 52 | 1 | 0 | 1970-01-01T00:27:36 | 146 | Java | {'Java': 1401518, 'JavaScript': 10208} | Apache License 2.0 |
945 | zrips/jobs/215/203 | zrips | jobs | https://github.com/Zrips/Jobs/issues/203 | https://github.com/Zrips/Jobs/pull/215 | https://github.com/Zrips/Jobs/pull/215 | 1 | fixes | MELON not recognized as block for Break or Place | Doesn't look like MELON is being recognized as a proper block type on 1.13.
[Jobs] Job Farmer has an invalid Break type property: MELON! Material must be a block!
[Jobs] Job Farmer has an invalid Place type property: MELON! Material must be a block!
On 1.12 and earlier versions, MELON referred to the melon slice, and MELON_BLOCK was the block. This is no longer the case for 1.13, as it is MELON for the block, and MELON_SLICE for the slice.
| 9dee8c76f8ab5e45a783c149bce801c7f4dd2642 | 96fbc8e19f9cdad1142f57d8f5ce0513bda7dfe3 | https://github.com/zrips/jobs/compare/9dee8c76f8ab5e45a783c149bce801c7f4dd2642...96fbc8e19f9cdad1142f57d8f5ce0513bda7dfe3 | diff --git a/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java b/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
index 9073accc..60b4a211 100644
--- a/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
+++ b/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
@@ -1089,7 +1089,7 @@ public class ItemManager {
MAP(395, 0, 21655, "Empty Map", "EMPTY_MAP"),
MELON(103, 0, 25172, "Melon", "Melon_Block"),
MELON_SEEDS(362, 0, 18340, "Melon Seeds", ""),
- MELON_SLICE(360, 0, 5347, "Melon", "Melon Slice"),
+ MELON_SLICE(360, 0, 5347, "Melon Slice", ""),
MELON_STEM(105, 0, 8247, "Melon Stem", "MELON_STEM"),
MILK_BUCKET(335, 0, 9680, "Milk Bucket", ""),
MINECART(328, 0, 14352, "Minecart", ""),
| ['src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,153,421 | 297,241 | 35,722 | 213 | 102 | 47 | 2 | 1 | 454 | 80 | 129 | 7 | 0 | 0 | 1970-01-01T00:25:34 | 142 | Java | {'Java': 1300453} | Apache License 2.0 |
944 | zrips/jobs/338/337 | zrips | jobs | https://github.com/Zrips/Jobs/issues/337 | https://github.com/Zrips/Jobs/pull/338 | https://github.com/Zrips/Jobs/pull/338 | 1 | fix | Could not register Brewing Stand in v1.12.2 | I join the Brewer job.
and, place and interact to brewer stand.
but, it's did not registerd.
Jobs: 4.9.5
Spigot: 1.12.2 | 3adbf6eebddf7b8ee8921e9071370900aa1d03cd | f3a9346dba2b8d514a94a18247932ba56043db31 | https://github.com/zrips/jobs/compare/3adbf6eebddf7b8ee8921e9071370900aa1d03cd...f3a9346dba2b8d514a94a18247932ba56043db31 | diff --git a/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java b/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
index cd7e44aa..caa0427a 100644
--- a/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
+++ b/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
@@ -671,7 +671,7 @@ public class ItemManager {
BLACK_STAINED_GLASS(95, 15, 13941, "Black Stained Glass"),
BLACK_STAINED_GLASS_PANE(160, 15, 13201, "Black Stained Glass Pane"),
BLACK_TERRACOTTA(159, 15, 26691, "Black Terracotta"),
- BLACK_WALL_BANNER(117, 0, 4919, "Black Banner"),
+ BLACK_WALL_BANNER(177, 0, 4919, "Black Banner"),
BLACK_WOOL(35, 15, 16693, "Black Wool"),
BLAZE_POWDER(377, 0, 18941, "Blaze Powder"),
BLAZE_ROD(369, 0, 8289, "Blaze Rod"),
@@ -689,7 +689,7 @@ public class ItemManager {
BLUE_STAINED_GLASS(95, 11, 7107, "Blue Stained Glass"),
BLUE_STAINED_GLASS_PANE(160, 11, 28484, "Blue Stained Glass Pane"),
BLUE_TERRACOTTA(159, 11, 5236, "Blue Terracotta"),
- BLUE_WALL_BANNER(117, 4, 17757, "Blue Banner"),
+ BLUE_WALL_BANNER(177, 4, 17757, "Blue Banner"),
BLUE_WOOL(35, 11, 15738, "Blue Wool"),
BONE(352, 0, 5686, "Bone"),
BONE_BLOCK(216, 0, 17312, "Bone Block"),
@@ -721,7 +721,7 @@ public class ItemManager {
BROWN_STAINED_GLASS(95, 12, 20945, "Brown Stained Glass"),
BROWN_STAINED_GLASS_PANE(160, 12, 17557, "Brown Stained Glass Pane"),
BROWN_TERRACOTTA(159, 12, 23664, "Brown Terracotta"),
- BROWN_WALL_BANNER(117, 3, 14731, "Brown Banner"),
+ BROWN_WALL_BANNER(177, 3, 14731, "Brown Banner"),
BROWN_WOOL(35, 12, 32638, "Brown Wool"),
BUBBLE_COLUMN(-1, -1, 13758, "Bubble Column"),
BUBBLE_CORAL(-1, -1, 12464, "Bubble Coral"),
@@ -806,7 +806,7 @@ public class ItemManager {
CYAN_STAINED_GLASS(95, 9, 30604, "Cyan Stained Glass"),
CYAN_STAINED_GLASS_PANE(160, 9, 11784, "Cyan Stained Glass Pane"),
CYAN_TERRACOTTA(159, 9, 25940, "Cyan Terracotta"),
- CYAN_WALL_BANNER(117, 6, 10889, "Cyan Banner"),
+ CYAN_WALL_BANNER(177, 6, 10889, "Cyan Banner"),
CYAN_WOOL(35, 9, 12221, "Cyan Wool"),
DAMAGED_ANVIL(145, 2, 10274, "Damaged Anvil"),
DANDELION(37, 0, 30558, "Dandelion", "YELLOW_FLOWER"),
@@ -963,7 +963,7 @@ public class ItemManager {
GRAY_STAINED_GLASS(95, 7, 29979, "Gray Stained Glass"),
GRAY_STAINED_GLASS_PANE(160, 7, 25272, "Gray Stained Glass Pane"),
GRAY_TERRACOTTA(159, 7, 18004, "Gray Terracotta"),
- GRAY_WALL_BANNER(117, 8, 24275, "Gray Banner"),
+ GRAY_WALL_BANNER(177, 8, 24275, "Gray Banner"),
GRAY_WOOL(35, 7, 27209, "Gray Wool"),
GREEN_BANNER(425, 2, 10698, "Green Banner"),
GREEN_BED(355, 13, 13797, "Green Bed"),
@@ -975,7 +975,7 @@ public class ItemManager {
GREEN_STAINED_GLASS(95, 13, 22503, "Green Stained Glass"),
GREEN_STAINED_GLASS_PANE(160, 13, 4767, "Green Stained Glass Pane", "STAINED_GLASS_PANE"),
GREEN_TERRACOTTA(159, 13, 4105, "Green Terracotta"),
- GREEN_WALL_BANNER(117, 2, 15046, "Green Banner"),
+ GREEN_WALL_BANNER(177, 2, 15046, "Green Banner"),
GREEN_WOOL(35, 13, 25085, "Green Wool"),
GUARDIAN_SPAWN_EGG(383, 68, 20113, "Spawn Guardian", "Guardian Spawn Egg"),
GUNPOWDER(289, 0, 29974, "Gunpowder", "SULPHUR"),
@@ -1061,7 +1061,7 @@ public class ItemManager {
LIGHT_BLUE_STAINED_GLASS(95, 3, 17162, "Light Blue Stained Glass"),
LIGHT_BLUE_STAINED_GLASS_PANE(160, 3, 18721, "Light Blue Stained Glass Pane"),
LIGHT_BLUE_TERRACOTTA(159, 3, 31779, "Light Blue Terracotta"),
- LIGHT_BLUE_WALL_BANNER(117, 12, 12011, "Light Blue Banner"),
+ LIGHT_BLUE_WALL_BANNER(177, 12, 12011, "Light Blue Banner"),
LIGHT_BLUE_WOOL(35, 3, 21073, "Light Blue Wool"),
LIGHT_GRAY_BANNER(425, 7, 11417, "Light Gray Banner"),
LIGHT_GRAY_BED(355, 8, 5090, "Light Gray Bed"),
@@ -1074,7 +1074,7 @@ public class ItemManager {
LIGHT_GRAY_STAINED_GLASS(95, 8, 5843, "Light Gray Stained Glass"),
LIGHT_GRAY_STAINED_GLASS_PANE(160, 8, 19008, "Light Gray Stained Glass Pane"),
LIGHT_GRAY_TERRACOTTA(159, 8, 26388, "Light Gray Terracotta"),
- LIGHT_GRAY_WALL_BANNER(117, 7, 31088, "Light Gray Banner"),
+ LIGHT_GRAY_WALL_BANNER(177, 7, 31088, "Light Gray Banner"),
LIGHT_GRAY_WOOL(35, 8, 22936, "Light Gray Wool"),
LIGHT_WEIGHTED_PRESSURE_PLATE(147, 0, 14875, "Light Weighted Pressure Plate", "GOLD_PLATE"),
LILAC(175, 1, 22837, "Lilac"),
@@ -1090,7 +1090,7 @@ public class ItemManager {
LIME_STAINED_GLASS(95, 5, 24266, "Lime Stained Glass"),
LIME_STAINED_GLASS_PANE(160, 5, 10610, "Lime Stained Glass Pane"),
LIME_TERRACOTTA(159, 5, 24013, "Lime Terracotta"),
- LIME_WALL_BANNER(117, 10, 21422, "Lime Banner"),
+ LIME_WALL_BANNER(177, 10, 21422, "Lime Banner"),
LIME_WOOL(35, 5, 10443, "Lime Wool"),
LINGERING_POTION(441, 0, 25857, "Lingering Potion"),
LLAMA_SPAWN_EGG(383, 103, 23640, "Spawn Llama", "Llama Spawn Egg"),
@@ -1105,7 +1105,7 @@ public class ItemManager {
MAGENTA_STAINED_GLASS(95, 2, 26814, "Magenta Stained Glass"),
MAGENTA_STAINED_GLASS_PANE(160, 2, 14082, "Magenta Stained Glass Pane"),
MAGENTA_TERRACOTTA(159, 2, 25900, "Magenta Terracotta"),
- MAGENTA_WALL_BANNER(117, 13, 23291, "Magenta Banner"),
+ MAGENTA_WALL_BANNER(177, 13, 23291, "Magenta Banner"),
MAGENTA_WOOL(35, 2, 11853, "Magenta Wool"),
MAGMA_BLOCK(213, 0, 25927, "Magma Block", "MAGMA"),
MAGMA_CREAM(378, 0, 25097, "Magma Cream"),
@@ -1183,7 +1183,7 @@ public class ItemManager {
ORANGE_STAINED_GLASS_PANE(160, 1, 21089, "Orange Stained Glass Pane"),
ORANGE_TERRACOTTA(159, 1, 18684, "Orange Terracotta"),
ORANGE_TULIP(38, 5, 26038, "Orange Tulip"),
- ORANGE_WALL_BANNER(117, 114, 9936, "Orange Banner"),
+ ORANGE_WALL_BANNER(177, 114, 9936, "Orange Banner"),
ORANGE_WOOL(35, 1, 23957, "Orange Wool"),
OXEYE_DAISY(38, 8, 11709, "Oxeye Daisy"),
PACKED_ICE(174, 0, 28993, "Packed Ice"),
@@ -1207,7 +1207,7 @@ public class ItemManager {
PINK_STAINED_GLASS_PANE(160, 6, 24637, "Pink Stained Glass Pane"),
PINK_TERRACOTTA(159, 6, 23727, "Pink Terracotta"),
PINK_TULIP(38, 7, 27319, "Pink Tulip"),
- PINK_WALL_BANNER(117, 9, 9421, "Pink Banner"),
+ PINK_WALL_BANNER(177, 9, 9421, "Pink Banner"),
PINK_WOOL(35, 6, 7611, "Pink Wool"),
PISTON(33, 0, 21130, "Piston", "PISTON_BASE"),
PISTON_HEAD(34, 0, 30226, "Piston Head", "PISTON_EXTENSION"),
@@ -1319,7 +1319,7 @@ public class ItemManager {
PURPLE_STAINED_GLASS(95, 10, 21845, "Purple Stained Glass"),
PURPLE_STAINED_GLASS_PANE(160, 10, 10948, "Purple Stained Glass Pane"),
PURPLE_TERRACOTTA(159, 10, 10387, "Purple Terracotta"),
- PURPLE_WALL_BANNER(117, 5, 14298, "Purple Banner"),
+ PURPLE_WALL_BANNER(177, 5, 14298, "Purple Banner"),
PURPLE_WOOL(35, 10, 11922, "Purple Wool"),
PURPUR_BLOCK(201, 0, 7538, "Purpur Block"),
PURPUR_PILLAR(202, 0, 26718, "Purpur Pillar"),
@@ -1361,7 +1361,7 @@ public class ItemManager {
RED_STAINED_GLASS_PANE(160, 14, 8630, "Red Stained Glass Pane"),
RED_TERRACOTTA(159, 14, 5086, "Red Terracotta"),
RED_TULIP(38, 4, 16781, "Red Tulip"),
- RED_WALL_BANNER(117, 1, 4378, "Red Banner"),
+ RED_WALL_BANNER(177, 1, 4378, "Red Banner"),
RED_WOOL(35, 14, 11621, "Red Wool"),
REPEATER(356, 0, 28823, "Redstone Repeater"),
REPEATING_COMMAND_BLOCK(-1, -1, 12405, "Repeating Command Block"),
@@ -1555,7 +1555,7 @@ public class ItemManager {
LEGACY_CAKE_BLOCK(92, 0, -1, "Cake Block"),
LEGACY_DIODE_BLOCK_OFF(93, 0, -1, "Diode Block Off"),
LEGACY_DIODE_BLOCK_ON(94, 0, -1, "Diode Block On"),
-// LEGACY_BREWING_STAND(117, -1, -1, "LEGACY_BREWING_STAND", ""),
+ LEGACY_BREWING_STAND(117, 0, -1, "Brewing Stand"),
// LEGACY_CAULDRON(118, 0, -1, "LEGACY_CAULDRON", ""),
// LEGACY_REDSTONE_LAMP_ON(124, -1, -1, "LEGACY_REDSTONE_LAMP_ON", ""),
// LEGACY_WOOD_DOUBLE_STEP(125, -1, -1, "LEGACY_WOOD_DOUBLE_STEP", ""),
diff --git a/src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java b/src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java
index 1aa03592..c9a425e3 100644
--- a/src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java
+++ b/src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java
@@ -1458,7 +1458,7 @@ public class JobsPaymentListener implements Listener {
"[current]", jPlayer.getFurnaceCount(),
"[max]", jPlayer.getMaxFurnacesAllowed() == 0 ? "-" : jPlayer.getMaxFurnacesAllowed()));
}
- } else if (CMIMaterial.get(block).equals(CMIMaterial.BREWING_STAND)) {
+ } else if (CMIMaterial.get(block).equals(CMIMaterial.BREWING_STAND) || CMIMaterial.get(block).equals(CMIMaterial.LEGACY_BREWING_STAND)) {
if (!Jobs.getGCManager().isBrewingStandsReassign())
return;
diff --git a/src/main/java/com/gamingmesh/jobs/stuff/FurnaceBrewingHandling.java b/src/main/java/com/gamingmesh/jobs/stuff/FurnaceBrewingHandling.java
index 2755e7ef..ceab6f01 100644
--- a/src/main/java/com/gamingmesh/jobs/stuff/FurnaceBrewingHandling.java
+++ b/src/main/java/com/gamingmesh/jobs/stuff/FurnaceBrewingHandling.java
@@ -289,7 +289,7 @@ public class FurnaceBrewingHandling {
public static ownershipFeedback registerBrewingStand(Player player, Block block) {
- if (!CMIMaterial.get(block).equals(CMIMaterial.BREWING_STAND))
+ if (!CMIMaterial.get(block).equals(CMIMaterial.BREWING_STAND) && !CMIMaterial.get(block).equals(CMIMaterial.LEGACY_BREWING_STAND))
return ownershipFeedback.invalid;
JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
| ['src/main/java/com/gamingmesh/jobs/stuff/FurnaceBrewingHandling.java', 'src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java', 'src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 1,155,289 | 293,799 | 37,174 | 220 | 2,048 | 763 | 34 | 3 | 125 | 21 | 44 | 6 | 0 | 0 | 1970-01-01T00:25:48 | 142 | Java | {'Java': 1300453} | Apache License 2.0 |
943 | zrips/jobs/346/37 | zrips | jobs | https://github.com/Zrips/Jobs/issues/37 | https://github.com/Zrips/Jobs/pull/346 | https://github.com/Zrips/Jobs/pull/346 | 1 | fix | Jobs db not 'transferring' data to game, and/or retaining all jobs info | After updating to 1.9.4 from 1.8.8, I am getting complaints that 'my jobs are losing levels'. I have updated the plugin to vs. 3.5.1. I have tried using MySQL instead of SQLite, and have tried manually adding levels/xp/points either in-game, or through the MySQL itself. The issue appears to be this: the data is saved correctly in the database (sqlite was what we started with) but it fails to 'remember' ALL of the jobs' data when /jobs stats is run. It only lists up to three (limit is 3 jobs, default) jobs and their levels, and 99% the level is incorrect. I haven't seen any errors print to the console, so I'm not sure where to begin looking to get this resolved. It had been going on since the update to 1.9.4.
Thanks!
| 6753f24876dcb3e8b417cf00ca802ac520d394cf | 82620c0d01cf3871f7588f1e895837a8bc203642 | https://github.com/zrips/jobs/compare/6753f24876dcb3e8b417cf00ca802ac520d394cf...82620c0d01cf3871f7588f1e895837a8bc203642 | diff --git a/src/main/java/com/gamingmesh/jobs/economy/PointsData.java b/src/main/java/com/gamingmesh/jobs/economy/PointsData.java
index c6c8de12..cc871d39 100644
--- a/src/main/java/com/gamingmesh/jobs/economy/PointsData.java
+++ b/src/main/java/com/gamingmesh/jobs/economy/PointsData.java
@@ -3,6 +3,7 @@ package com.gamingmesh.jobs.economy;
import java.util.HashMap;
import java.util.UUID;
+import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.PlayerPoints;
public class PointsData {
@@ -25,11 +26,11 @@ public class PointsData {
}
public void addPlayer(UUID uuid, double points, double total) {
- if (!Pointbase.containsKey(uuid))
- Pointbase.put(uuid, new PlayerPoints(points, total));
+ addPlayer(uuid, new PlayerPoints(points,total));
}
public void addPlayer(UUID uuid, PlayerPoints points) {
+ if (Jobs.getGCManager().MultiServerCompatability()&&Pointbase.containsKey(uuid)) Pointbase.remove(uuid);
if (!Pointbase.containsKey(uuid))
Pointbase.put(uuid, points);
}
| ['src/main/java/com/gamingmesh/jobs/economy/PointsData.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,164,711 | 296,149 | 37,496 | 220 | 298 | 69 | 5 | 1 | 728 | 133 | 189 | 4 | 0 | 0 | 1970-01-01T00:25:49 | 142 | Java | {'Java': 1300453} | Apache License 2.0 |
939 | zrips/jobs/255/254 | zrips | jobs | https://github.com/Zrips/Jobs/issues/254 | https://github.com/Zrips/Jobs/pull/255 | https://github.com/Zrips/Jobs/pull/255#issuecomment-429337396 | 1 | fixes | Carpet block being detected wrongly | using /jobs editjobs if you look at a white carpet and click the "LOOKING AT" button:
https://gyazo.com/6b3e8acc4670a1ad4cd55ac38526b99e
It will say you looked at a `BLACK_CARPET:0` instead of `CARPET:0`
paperspigot 1.12.2
| e05a7f34af4a3ee0c6fabce20679e63e9faccd32 | bccf89cc77a608b4c79ba8319d0a4916d622aadd | https://github.com/zrips/jobs/compare/e05a7f34af4a3ee0c6fabce20679e63e9faccd32...bccf89cc77a608b4c79ba8319d0a4916d622aadd | diff --git a/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java b/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
index f4d3a9c3..4576f157 100644
--- a/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
+++ b/src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java
@@ -676,7 +676,7 @@ public class ItemManager {
BLAZE_SPAWN_EGG(383, 61, 4759, "Spawn Blaze", "Blaze Spawn Egg"),
BLUE_BANNER(245, 4, 18481, "Blue Banner", ""),
BLUE_BED(355, 11, 12714, "Blue Bed", "Blue Bed"),
- BLUE_CARPET(171, 11, 13292, "Blue Carpet", ""),
+ BLUE_CARPET(171, 11, 13292, "Blue Carpet", "CARPET"),
BLUE_CONCRETE(251, 11, 18756, "Blue Concrete", ""),
BLUE_CONCRETE_POWDER(252, 11, 17773, "Blue Concrete Powder", ""),
BLUE_GLAZED_TERRACOTTA(246, 0, 23823, "Blue Glazed Terracotta", ""),
@@ -707,7 +707,7 @@ public class ItemManager {
BRICK_STAIRS(108, 0, 21534, "Brick Stairs", ""),
BROWN_BANNER(425, 3, 11481, "Brown Banner", ""),
BROWN_BED(355, 12, 25624, "Brown Bed", "Brown Bed"),
- BROWN_CARPET(171, 12, 23352, "Brown Carpet", ""),
+ BROWN_CARPET(171, 12, 23352, "Brown Carpet", "CARPET"),
BROWN_CONCRETE(251, 12, 19006, "Brown Concrete", ""),
BROWN_CONCRETE_POWDER(252, 12, 21485, "Brown Concrete Powder", ""),
BROWN_GLAZED_TERRACOTTA(247, 0, 5655, "Brown Glazed Terracotta", ""),
@@ -755,7 +755,7 @@ public class ItemManager {
CHORUS_PLANT(199, 0, 28243, "Chorus Plant", ""),
CLAY(82, 0, 27880, "Clay", "Clay Block"),
CLAY_BALL(337, 0, 24603, "Clay Ball"),
- CLOCK(347, 0, 14980, "Clock", "watch"),
+ CLOCK(347, 0, 14980, "Clock", "WATCH"),
COAL(263, 0, 29067, "Coal", ""),
COAL_BLOCK(173, 0, 27968, "Block of Coal", ""),
COAL_ORE(16, 0, 30965, "Coal Ore", ""),
@@ -793,7 +793,7 @@ public class ItemManager {
CUT_SANDSTONE(-1, -1, 6118, "Cut Sandstone", ""),
CYAN_BANNER(425, 6, 9839, "Cyan Banner", ""),
CYAN_BED(355, 9, 16746, "Cyan Bed", "Cyan Bed"),
- CYAN_CARPET(171, 9, 31495, "Cyan Carpet", ""),
+ CYAN_CARPET(171, 9, 31495, "Cyan Carpet", "CARPET"),
CYAN_CONCRETE(251, 9, 26522, "Cyan Concrete", ""),
CYAN_CONCRETE_POWDER(252, 9, 15734, "Cyan Concrete Powder", ""),
CYAN_DYE(351, 6, 8043, "Cyan Dye", ""),
@@ -863,7 +863,7 @@ public class ItemManager {
DIAMOND_SWORD(276, 0, 27707, "Diamond Sword", ""),
DIORITE(1, 3, 24688, "Diorite", ""),
DIRT(3, 0, 10580, "Dirt", ""),
- DISPENSER(23, 0, 20871, "Dispenser", "DISPENSER"),
+ DISPENSER(23, 0, 20871, "Dispenser", ""),
DOLPHIN_SPAWN_EGG(-1, -1, 20787, "Dolphin Spawn Egg", ""),
DONKEY_SPAWN_EGG(383, 31, 14513, "Spawn Donkey", "Donkey Spawn Egg"),
DRAGON_BREATH(437, 0, 20154, "Dragon's Breath", ""),
@@ -872,7 +872,7 @@ public class ItemManager {
DRAGON_WALL_HEAD(144, 5, 19818, "Dragon Wall Head", ""),
DRIED_KELP(-1, -1, 21042, "Dried Kelp", ""),
DRIED_KELP_BLOCK(-1, -1, 12966, "Dried Kelp Block", ""),
- DROPPER(158, 0, 31273, "Dropper", "DROPPER"),
+ DROPPER(158, 0, 31273, "Dropper", ""),
DROWNED_SPAWN_EGG(-1, -1, 19368, "Drowned Spawn Egg", ""),
EGG(344, 0, 21603, "Egg", ""),
ELDER_GUARDIAN_SPAWN_EGG(383, 4, 11418, "Spawn Elder Guardian", "Elder Guardian Spawn Egg"),
@@ -948,7 +948,7 @@ public class ItemManager {
GRAVEL(13, 0, 7804, "Gravel", "GRAVEL"),
GRAY_BANNER(425, 8, 12053, "Gray Banner", ""),
GRAY_BED(355, 7, 15745, "Gray Bed", "Gray Bed"),
- GRAY_CARPET(171, 7, 26991, "Gray Carpet", ""),
+ GRAY_CARPET(171, 7, 26991, "Gray Carpet", "CARPET"),
GRAY_CONCRETE(251, 7, 13959, "Gray Concrete", ""),
GRAY_CONCRETE_POWDER(252, 7, 13031, "Gray Concrete Powder", ""),
GRAY_DYE(351, 8, 9184, "Gray Dye", ""),
@@ -961,7 +961,7 @@ public class ItemManager {
GRAY_WOOL(35, 7, 27209, "Gray Wool", ""),
GREEN_BANNER(425, 2, 10698, "Green Banner", ""),
GREEN_BED(355, 13, 13797, "Green Bed", "Green Bed"),
- GREEN_CARPET(171, 13, 7780, "Green Carpet", ""),
+ GREEN_CARPET(171, 13, 7780, "Green Carpet", "CARPET"),
GREEN_CONCRETE(251, 13, 17949, "Green Concrete", ""),
GREEN_CONCRETE_POWDER(252, 13, 6904, "Green Concrete Powder", ""),
GREEN_GLAZED_TERRACOTTA(248, 0, 6958, "Green Glazed Terracotta", ""),
@@ -1045,7 +1045,7 @@ public class ItemManager {
LEVER(69, 0, 15319, "Lever", "LEVER"),
LIGHT_BLUE_BANNER(425, 12, 18060, "Light Blue Banner", ""),
LIGHT_BLUE_BED(355, 3, 20957, "Light Blue Bed", "Light Blue Bed"),
- LIGHT_BLUE_CARPET(171, 3, 21194, "Light Blue Carpet", ""),
+ LIGHT_BLUE_CARPET(171, 3, 21194, "Light Blue Carpet", "CARPET"),
LIGHT_BLUE_CONCRETE(251, 3, 29481, "Light Blue Concrete", ""),
LIGHT_BLUE_CONCRETE_POWDER(252, 3, 31206, "Light Blue Concrete Powder", ""),
LIGHT_BLUE_DYE(351, 12, 28738, "Light Blue Dye", ""),
@@ -1058,7 +1058,7 @@ public class ItemManager {
LIGHT_BLUE_WOOL(35, 3, 21073, "Light Blue Wool", ""),
LIGHT_GRAY_BANNER(425, 7, 11417, "Light Gray Banner", ""),
LIGHT_GRAY_BED(355, 8, 5090, "Light Gray Bed", "Light Gray Bed"),
- LIGHT_GRAY_CARPET(171, 8, 11317, "Light Gray Carpet", ""),
+ LIGHT_GRAY_CARPET(171, 8, 11317, "Light Gray Carpet", "CARPET"),
LIGHT_GRAY_CONCRETE(251, 8, 14453, "Light Gray Concrete", ""),
LIGHT_GRAY_CONCRETE_POWDER(252, 8, 21589, "Light Gray Concrete Powder", ""),
LIGHT_GRAY_DYE(351, 7, 27643, "Light Gray Dye", ""),
@@ -1074,7 +1074,7 @@ public class ItemManager {
LILY_PAD(111, 0, 19271, "Lily Pad", "WATER_LILY"),
LIME_BANNER(425, 10, 18887, "Lime Banner", ""),
LIME_BED(355, 5, 27860, "Lime Bed", "Lime Bed"),
- LIME_CARPET(171, 5, 15443, "Lime Carpet", ""),
+ LIME_CARPET(171, 5, 15443, "Lime Carpet", "CARPET"),
LIME_CONCRETE(251, 5, 5863, "Lime Concrete", ""),
LIME_CONCRETE_POWDER(252, 5, 28859, "Lime Concrete Powder", ""),
LIME_DYE(351, 10, 6147, "Lime Dye", ""),
@@ -1089,7 +1089,7 @@ public class ItemManager {
LLAMA_SPAWN_EGG(383, 103, 23640, "Spawn Llama", "Llama Spawn Egg"),
MAGENTA_BANNER(425, 13, 15591, "Magenta Banner", ""),
MAGENTA_BED(355, 2, 20061, "Magenta Bed", "Magenta Bed"),
- MAGENTA_CARPET(171, 2, 6180, "Magenta Carpet", ""),
+ MAGENTA_CARPET(171, 2, 6180, "Magenta Carpet", "CARPET"),
MAGENTA_CONCRETE(251, 2, 20591, "Magenta Concrete", ""),
MAGENTA_CONCRETE_POWDER(252, 2, 8272, "Magenta Concrete Powder", ""),
MAGENTA_DYE(351, 13, 11788, "Magenta Dye", ""),
@@ -1147,14 +1147,14 @@ public class ItemManager {
NETHER_WART_BLOCK(214, 0, 15486, "Nether Wart Block", ""),
NOTE_BLOCK(25, 0, 20979, "Note Block", "NOTE_BLOCK"),
OAK_BOAT(333, 0, 17570, "Boat", "Oak Boat"),
- OAK_BUTTON(143, 0, 13510, "Oak Button", "Wooden_button"),
+ OAK_BUTTON(143, 0, 13510, "Oak Button", "wooden_button"),
OAK_DOOR(324, 0, 20341, "Wooden Door", "Wood Door"),
OAK_FENCE(85, 0, 6442, "Oak Fence", "FENCE"),
OAK_FENCE_GATE(107, 0, 16689, "Oak Fence Gate", "FENCE_GATE"),
OAK_LEAVES(18, 0, 4385, "Oak Leaves", ""),
OAK_LOG(17, 0, 26723, "Oak Log", ""),
OAK_PLANKS(5, 0, 14905, "Oak Wood Plank", "Oak Planks"),
- OAK_PRESSURE_PLATE(72, 0, 20108, "Oak Pressure Plate", "Wooden_Presure_Plate"),
+ OAK_PRESSURE_PLATE(72, 0, 20108, "Oak Pressure Plate", "Wooden_Pressure_Plate"),
OAK_SAPLING(6, 0, 9636, "Oak Sapling", ""),
OAK_SLAB(126, 0, 12002, "Oak Slab", "Wood step"),
OAK_STAIRS(53, 0, 5449, "Oak Stairs", "WOOD_STAIRS"),
@@ -1165,7 +1165,7 @@ public class ItemManager {
OCELOT_SPAWN_EGG(383, 98, 30080, "Spawn Ocelot", "Ocelot Spawn Egg"),
ORANGE_BANNER(425, 14, 4839, "Orange Banner", ""),
ORANGE_BED(355, 1, 11194, "Orange Bed", "Orange Bed"),
- ORANGE_CARPET(171, 1, 24752, "Orange Carpet", ""),
+ ORANGE_CARPET(171, 1, 24752, "Orange Carpet", "CARPET"),
ORANGE_CONCRETE(251, 1, 19914, "Orange Concrete", ""),
ORANGE_CONCRETE_POWDER(252, 1, 30159, "Orange Concrete Powder", ""),
ORANGE_DYE(351, 14, 13866, "Orange Dye", ""),
@@ -1189,7 +1189,7 @@ public class ItemManager {
PIG_SPAWN_EGG(383, 90, 22584, "Spawn Pig", "Pig Spawn Egg"),
PINK_BANNER(425, 9, 19439, "Pink Banner", ""),
PINK_BED(355, 6, 13795, "Pink Bed", "Pink Bed"),
- PINK_CARPET(171, 6, 30186, "Pink Carpet", ""),
+ PINK_CARPET(171, 6, 30186, "Pink Carpet", "CARPET"),
PINK_CONCRETE(251, 6, 5227, "Pink Concrete", ""),
PINK_CONCRETE_POWDER(252, 6, 6421, "Pink Concrete Powder", ""),
PINK_DYE(351, 9, 31151, "Pink Dye", ""),
@@ -1296,7 +1296,7 @@ public class ItemManager {
PUMPKIN_STEM(104, 0, 19021, "Pumpkin Stem", ""),
PURPLE_BANNER(425, 5, 29027, "Purple Banner", ""),
PURPLE_BED(355, 10, 29755, "Purple Bed", "Purple Bed"),
- PURPLE_CARPET(171, 10, 5574, "Purple Carpet", ""),
+ PURPLE_CARPET(171, 10, 5574, "Purple Carpet", "CARPET"),
PURPLE_CONCRETE(251, 10, 20623, "Purple Concrete", ""),
PURPLE_CONCRETE_POWDER(252, 10, 26808, "Purple Concrete Powder", ""),
PURPLE_DYE(351, 5, 6347, "Purple Dye", ""),
@@ -1331,7 +1331,7 @@ public class ItemManager {
REDSTONE_WIRE(55, 0, 25984, "Redstone Dust", ""),
RED_BANNER(425, 1, 26961, "Red Banner", ""),
RED_BED(355, 14, 30910, "Red Bed", "Red Bed"),
- RED_CARPET(171, 14, 5424, "Red Carpet", ""),
+ RED_CARPET(171, 14, 5424, "Red Carpet", "CARPET"),
RED_CONCRETE(251, 14, 8032, "Red Concrete", ""),
RED_CONCRETE_POWDER(252, 14, 13286, "Red Concrete Powder", ""),
RED_GLAZED_TERRACOTTA(249, 0, 24989, "Red Glazed Terracotta", ""),
@@ -1479,7 +1479,7 @@ public class ItemManager {
WHEAT_SEEDS(295, 0, 28742, "Wheat Seeds", "SEEDS"),
WHITE_BANNER(425, 15, 17562, "White Banner", ""),
WHITE_BED(355, 0, 8185, "White Bed", "Bed"),
- WHITE_CARPET(171, 0, 15117, "White Carpet", ""),
+ WHITE_CARPET(171, 0, 15117, "White Carpet", "CARPET"),
WHITE_CONCRETE(251, 0, 6281, "White Concrete", ""),
WHITE_CONCRETE_POWDER(252, 0, 10363, "White Concrete Powder", ""),
WHITE_GLAZED_TERRACOTTA(235, 0, 11326, "White Glazed Terracotta", ""),
@@ -1504,7 +1504,7 @@ public class ItemManager {
WRITTEN_BOOK(387, 0, 24164, "Written Book", ""),
YELLOW_BANNER(425, 11, 30382, "Yellow Banner", ""),
YELLOW_BED(355, 4, 30410, "Yellow Bed", "Yellow Bed"),
- YELLOW_CARPET(171, 4, 18149, "Yellow Carpet", ""),
+ YELLOW_CARPET(171, 4, 18149, "Yellow Carpet", "CARPET"),
YELLOW_CONCRETE(251, 4, 15722, "Yellow Concrete", ""),
YELLOW_CONCRETE_POWDER(252, 4, 10655, "Yellow Concrete Powder", ""),
YELLOW_GLAZED_TERRACOTTA(239, 0, 10914, "Yellow Glazed Terracotta", ""),
| ['src/main/java/com/gamingmesh/jobs/CMILib/ItemManager.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,160,094 | 300,145 | 35,993 | 213 | 2,248 | 931 | 40 | 1 | 232 | 30 | 83 | 7 | 1 | 0 | 1970-01-01T00:25:39 | 142 | Java | {'Java': 1300453} | Apache License 2.0 |
940 | zrips/jobs/1291/1290 | zrips | jobs | https://github.com/Zrips/Jobs/issues/1290 | https://github.com/Zrips/Jobs/pull/1291 | https://github.com/Zrips/Jobs/pull/1291 | 1 | fix | The "jobsr_description_" does not work! | ***Detailed description of the issue:***
`%jobsr_description_(jname/number)% - Returns jobs description` **Does not work!**
---
**Jobs version:** Dev (commit 52547b94a566574cad1e318c2df985b38fc6a8e7)
**Server Type (Spigot/Paper/etc):** Spigot
**Server Version (using `/ver`):** 1.12.2 | 52547b94a566574cad1e318c2df985b38fc6a8e7 | 182367acd100c8dd206a0d7d7594e306d3a777d2 | https://github.com/zrips/jobs/compare/52547b94a566574cad1e318c2df985b38fc6a8e7...182367acd100c8dd206a0d7d7594e306d3a777d2 | diff --git a/src/main/java/com/gamingmesh/jobs/container/Job.java b/src/main/java/com/gamingmesh/jobs/container/Job.java
index 2510203e..da47738f 100644
--- a/src/main/java/com/gamingmesh/jobs/container/Job.java
+++ b/src/main/java/com/gamingmesh/jobs/container/Job.java
@@ -566,7 +566,8 @@ public class Job {
if (fDescription != null) {
this.fDescription.addAll(fDescription);
- }
+ this.description = String.join("\\n",this.fDescription);
+ }
}
public void setMaxLevelCommands(List<String> commands) {
| ['src/main/java/com/gamingmesh/jobs/container/Job.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,060,942 | 258,199 | 33,929 | 207 | 78 | 19 | 3 | 1 | 303 | 28 | 98 | 13 | 0 | 0 | 1970-01-01T00:27:13 | 142 | Java | {'Java': 1300453} | Apache License 2.0 |
942 | zrips/jobs/945/940 | zrips | jobs | https://github.com/Zrips/Jobs/issues/940 | https://github.com/Zrips/Jobs/pull/945 | https://github.com/Zrips/Jobs/pull/945 | 1 | fixes | stripping logs are respected as stripped_*_log block place | ***Description of issue:***
---
When stripping logs by right clicking on it with an axe, Jobs respects it as if it has been placed which results in unwanted payments.
**CONFIG SECTION:**
```
*Extracted from jobConfig.yml*
Jobs:
Gaertner:
Place:
STRIPPED_ACACIA_LOG:
income: -2.49
experience: -2.49
```
-2.49 will be charged if a player right clicks with an axe on acacia log to strip it. (should only happen when *placing* acacia log)
---
**Server Type (Spigot/Paperspigot/etc):**
paperspigot
**Server Version (using `/ver`):**
git-Paper-204 (MC: 1.16.3)
**Relevant plugins (Delete if this isn't needed):**
Jobs version 4.16.2
| c8bb020587776f49ebd7499a141abac7ba7189ae | 8aff873a5b38f4d906bc77c9285fc7d2583d72de | https://github.com/zrips/jobs/compare/c8bb020587776f49ebd7499a141abac7ba7189ae...8aff873a5b38f4d906bc77c9285fc7d2583d72de | diff --git a/src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java b/src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java
index 0c9f5ddc..522291ab 100644
--- a/src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java
+++ b/src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java
@@ -423,6 +423,10 @@ public class JobsPaymentListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
+ // A tool should not trigger a BlockPlaceEvent (fixes stripping logs bug #940)
+ if (CMIMaterial.get(event.getItemInHand().getType()).isTool())
+ return;
+
Block block = event.getBlock();
//disabling plugin in world
| ['src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,389,049 | 364,599 | 44,510 | 247 | 162 | 43 | 4 | 1 | 688 | 91 | 191 | 27 | 0 | 1 | 1970-01-01T00:26:41 | 142 | Java | {'Java': 1300453} | Apache License 2.0 |
430 | wso2/carbon-apimgt/6584/4980 | wso2 | carbon-apimgt | https://github.com/wso2/carbon-apimgt/issues/4980 | https://github.com/wso2/carbon-apimgt/pull/6584 | https://github.com/wso2/carbon-apimgt/pull/6584 | 1 | fixes | Build fail on Windows [APIM 2.2.0][6.x] | **Description:**
The following error occurs when the 6.x branch is being built on a windows machine.
Failed tests:
TenantManagerHostObjectTest.testGetStoreTenantThemesPath:23 expected:<repository[\\deployment\\server\\jaggeryapps\\store\\site\\tenant_themes\\]> but was:<repository[/deployment/server/jaggeryapps/store/site/tenant_themes/]>
**Suggested Labels:**
<!-- Optional comma separated list of suggested labels. Non committers can’t assign labels to issues, so this will help issue creators who are not a committer to suggest possible labels-->
**Suggested Assignees:**
<!--Optional comma separated list of suggested team members who should attend the issue. Non committers can’t assign issues to assignees, so this will help issue creators who are not a committer to suggest possible assignees-->
**Affected Product Version:**
**OS, DB, other environments details and versions:**
**Steps to reproduce:**
**Related Issues:**
<!-- Any related issues such as sub tasks, issues reported in other repositories (e.g component repositories), similar problems, etc. --> | 667c62b97ea03a8722258adcdf9b86a8c7db0868 | a32ad1b675ed1a992c795449d1682db530b1497d | https://github.com/wso2/carbon-apimgt/compare/667c62b97ea03a8722258adcdf9b86a8c7db0868...a32ad1b675ed1a992c795449d1682db530b1497d | diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/impl/ApisApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/impl/ApisApiServiceImpl.java
index 3d0a5a3edc1..d238f521118 100644
--- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/impl/ApisApiServiceImpl.java
+++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/impl/ApisApiServiceImpl.java
@@ -583,10 +583,21 @@ public class ApisApiServiceImpl extends ApisApiService {
String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
apiIdentifier = APIMappingUtil.getAPIIdentifierFromApiIdOrUUID(apiId,
tenantDomain);
+ API api = APIMappingUtil.getAPIFromApiIdOrUUID(apiId, tenantDomain);
APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
String apiResourcePath = APIUtil.getAPIPath(apiIdentifier);
//Getting the api base path out apiResourcePath
apiResourcePath = apiResourcePath.substring(0, apiResourcePath.lastIndexOf("/"));
+ //Getting specified mediation policy
+ Mediation mediation = apiProvider.getApiSpecificMediationPolicy(apiResourcePath,
+ mediationPolicyId);
+ if (mediation != null) {
+ if (isAPIModified(api, mediation)) {
+ apiProvider.updateAPI(api);
+ }
+ } else {
+ RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_POLICY, mediationPolicyId, log);
+ }
boolean deletionStatus = apiProvider.deleteApiSpecificMediationPolicy(apiResourcePath,
mediationPolicyId);
if (deletionStatus) {
@@ -607,6 +618,9 @@ public class ApisApiServiceImpl extends ApisApiService {
mediationPolicyId + "of API " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
+ } catch (FaultGatewaysException e) {
+ String errorMessage = "Error while updating API : " + apiId;
+ RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
@@ -1883,4 +1897,41 @@ public class ApisApiServiceImpl extends ApisApiService {
String errorMessage = e.getMessage();
return errorMessage != null && errorMessage.contains(APIConstants.UN_AUTHORIZED_ERROR_MESSAGE);
}
+
+ /***
+ * To check if the API is modified or not when the given sequence is in API.
+ *
+ * @param api
+ * @param mediation
+ * @return if the API is modified or not
+ */
+ private boolean isAPIModified(API api, Mediation mediation) {
+ if (mediation != null) {
+ String sequenceName;
+ if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equalsIgnoreCase(mediation.getType())) {
+ sequenceName = api.getInSequence();
+ if (isSequenceExistsInAPI(sequenceName, mediation)) {
+ api.setInSequence(null);
+ return true;
+ }
+ } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equalsIgnoreCase(mediation.getType())) {
+ sequenceName = api.getOutSequence();
+ if (isSequenceExistsInAPI(sequenceName, mediation)) {
+ api.setOutSequence(null);
+ return true;
+ }
+ } else {
+ sequenceName = api.getFaultSequence();
+ if (isSequenceExistsInAPI(sequenceName, mediation)) {
+ api.setFaultSequence(null);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean isSequenceExistsInAPI(String sequenceName, Mediation mediation) {
+ return StringUtils.isNotEmpty(sequenceName) && mediation.getName().equals(sequenceName);
+ }
} | ['components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/impl/ApisApiServiceImpl.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,978,750 | 2,008,907 | 239,942 | 1,329 | 2,264 | 417 | 51 | 1 | 1,096 | 126 | 230 | 21 | 0 | 0 | 1970-01-01T00:26:01 | 136 | Java | {'Java': 17505227, 'HTML': 1653332, 'PLSQL': 304432, 'TSQL': 241929, 'SQLPL': 112457, 'Jinja': 102262, 'CSS': 27317, 'Shell': 26899, 'Mustache': 23530, 'JavaScript': 12876, 'Batchfile': 11203} | Apache License 2.0 |
429 | wso2/carbon-apimgt/8413/8411 | wso2 | carbon-apimgt | https://github.com/wso2/carbon-apimgt/issues/8411 | https://github.com/wso2/carbon-apimgt/pull/8413 | https://github.com/wso2/carbon-apimgt/pull/8413 | 1 | fixes | Message Mediation Policies (xml_validator) failing with Global Mediation Extensions with FULL log | ### Description:
Message Mediation Policies (xml_validator) isn't working if Global Mediation Extension with a FULL log mediator added to the synapse folder.
XMLSchemaValidator directly consumes the stream from the pipe. Therefore, if log full is used in global in_sequence or any content-aware mediators, it will try to build the message by consuming the stream from the pipe. Since XMLSchemaValidator consumes the pipe later according to the order of the sequences, the pipe is already empty. This produces the error.
### Steps to reproduce:
1. Copy an [WSO2AM-Ext-In.xml](https://support.wso2.com/jira/secure/attachment/248017/248017_WSO2AM--Ext--In.xml) file to <APIM_HOME>/repository\\deployment\\server\\synapse-configs\\default\\sequences folder.
2. Run APIM
3. Create or edit API by enabling Message Mediation Policies (xml_validator)
4. Subscribe to that API
5. Send a request
### Affected Product Version:
2.6
| 1feec0f17dc9a7b1602ac3cd6407b504344960a4 | cd2e263248421eabdcfcbb1b16229d4e606da1b8 | https://github.com/wso2/carbon-apimgt/compare/1feec0f17dc9a7b1602ac3cd6407b504344960a4...cd2e263248421eabdcfcbb1b16229d4e606da1b8 | diff --git a/components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java b/components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java
index cad3e17f2e1..1953626ce0a 100644
--- a/components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java
+++ b/components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java
@@ -40,6 +40,7 @@ import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.synapse.Mediator;
+import org.apache.synapse.commons.json.JsonUtil;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.RESTConstants;
import org.apache.synapse.transport.nhttp.NhttpConstants;
@@ -78,6 +79,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.security.interfaces.RSAPublicKey;
@@ -399,15 +401,14 @@ public class GatewayUtils {
* @return cloned InputStreams.
* @throws IOException this exception might occurred while cloning the inputStream.
*/
- public static Map<String, InputStream> cloneRequestMessage(org.apache.synapse.MessageContext messageContext)
+ public static Map<String,InputStream> cloneRequestMessage(org.apache.synapse.MessageContext messageContext)
throws IOException {
-
BufferedInputStream bufferedInputStream = null;
- Map<String, InputStream> inputStreamMap = null;
- InputStream inputStreamSchema;
- InputStream inputStreamXml;
- InputStream inputStreamJSON;
- InputStream inputStreamOriginal;
+ Map<String, InputStream> inputStreamMap;
+ InputStream inputStreamSchema = null;
+ InputStream inputStreamXml = null;
+ InputStream inputStreamJSON = null ;
+ InputStream inputStreamOriginal = null;
int requestBufferSize = 1024;
org.apache.axis2.context.MessageContext axis2MC;
Pipe pipe;
@@ -422,24 +423,38 @@ public class GatewayUtils {
if (pipe != null) {
bufferedInputStream = new BufferedInputStream(pipe.getInputStream());
}
+ inputStreamMap = new HashMap<>();
+ String contentType = axis2MC.getProperty(ThreatProtectorConstants.CONTENT_TYPE).toString();
+
if (bufferedInputStream != null) {
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[requestBufferSize];
- int length;
- while ((length = bufferedInputStream.read(buffer)) > -1) {
- byteArrayOutputStream.write(buffer, 0, length);
+ bufferedInputStream.mark(0);
+ if (bufferedInputStream.read() != -1){
+ bufferedInputStream.reset();
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ byte[] buffer = new byte[requestBufferSize];
+ int length;
+ while ((length = bufferedInputStream.read(buffer)) > -1) {
+ byteArrayOutputStream.write(buffer, 0, length);
+ }
+ byteArrayOutputStream.flush();
+ inputStreamSchema = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
+ inputStreamXml = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
+ inputStreamOriginal = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
+ inputStreamJSON = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
+ } else {
+ String payload;
+ if (ThreatProtectorConstants.APPLICATION_JSON.equals(contentType)){
+ inputStreamJSON = JsonUtil.getJsonPayload(axis2MC);
+ } else {
+ payload = axis2MC.getEnvelope().getBody().getFirstElement().toString();
+ inputStreamXml= new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
+ }
}
- byteArrayOutputStream.flush();
- inputStreamMap = new HashMap<>();
- inputStreamSchema = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
- inputStreamXml = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
- inputStreamOriginal = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
- inputStreamJSON = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
- inputStreamMap.put(ThreatProtectorConstants.SCHEMA, inputStreamSchema);
- inputStreamMap.put(ThreatProtectorConstants.XML, inputStreamXml);
- inputStreamMap.put(ThreatProtectorConstants.ORIGINAL, inputStreamOriginal);
- inputStreamMap.put(ThreatProtectorConstants.JSON, inputStreamJSON);
}
+ inputStreamMap.put(ThreatProtectorConstants.SCHEMA, inputStreamSchema);
+ inputStreamMap.put(ThreatProtectorConstants.XML, inputStreamXml);
+ inputStreamMap.put(ThreatProtectorConstants.ORIGINAL, inputStreamOriginal);
+ inputStreamMap.put(ThreatProtectorConstants.JSON, inputStreamJSON);
return inputStreamMap;
}
| ['components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 11,912,399 | 2,396,261 | 284,253 | 1,523 | 3,737 | 577 | 59 | 1 | 942 | 119 | 220 | 19 | 1 | 0 | 1970-01-01T00:26:27 | 136 | Java | {'Java': 17505227, 'HTML': 1653332, 'PLSQL': 304432, 'TSQL': 241929, 'SQLPL': 112457, 'Jinja': 102262, 'CSS': 27317, 'Shell': 26899, 'Mustache': 23530, 'JavaScript': 12876, 'Batchfile': 11203} | Apache License 2.0 |
8,980 | kruize/autotune/710/697 | kruize | autotune | https://github.com/kruize/autotune/issues/697 | https://github.com/kruize/autotune/pull/710 | https://github.com/kruize/autotune/pull/710 | 1 | fixes | Typo with percentile for cpu requests recommendations | The cpu requests generated by algorithm is using 0.9 percentile instead of 90th percentile.
https://github.com/kruize/autotune/blob/0c7043d8cd8dd369265e1c9f0517863c7830815b/src/main/java/com/autotune/analyzer/recommendations/GenerateRecommendation.java#L141 | ef137d417024ac20b55ab75845915ee7cfe6a32e | 5b1adca970f67423309c409e5d36fa527add5d26 | https://github.com/kruize/autotune/compare/ef137d417024ac20b55ab75845915ee7cfe6a32e...5b1adca970f67423309c409e5d36fa527add5d26 | diff --git a/src/main/java/com/autotune/analyzer/recommendations/engine/DurationBasedRecommendationEngine.java b/src/main/java/com/autotune/analyzer/recommendations/engine/DurationBasedRecommendationEngine.java
index b9d492df..ecf1be0f 100644
--- a/src/main/java/com/autotune/analyzer/recommendations/engine/DurationBasedRecommendationEngine.java
+++ b/src/main/java/com/autotune/analyzer/recommendations/engine/DurationBasedRecommendationEngine.java
@@ -123,7 +123,7 @@ public class DurationBasedRecommendationEngine implements KruizeRecommendationEn
if (null != format && !format.isEmpty())
break;
}
- recommendationConfigItem = new RecommendationConfigItem(CommonUtils.percentile(0.9, doubleList), format);
+ recommendationConfigItem = new RecommendationConfigItem(CommonUtils.percentile(98, doubleList), format);
} catch (Exception e) {
LOGGER.error("Not able to get getCPUCapacityRecommendation: " + e.getMessage());
@@ -173,7 +173,7 @@ public class DurationBasedRecommendationEngine implements KruizeRecommendationEn
if (null != format && !format.isEmpty())
break;
}
- recommendationConfigItem = new RecommendationConfigItem(CommonUtils.percentile(0.9, doubleList), format);
+ recommendationConfigItem = new RecommendationConfigItem(CommonUtils.percentile(100, doubleList), format);
} catch (Exception e) {
LOGGER.error("Not able to get getMemoryCapacityRecommendation: " + e.getMessage());
recommendationConfigItem = new RecommendationConfigItem(e.getMessage()); | ['src/main/java/com/autotune/analyzer/recommendations/engine/DurationBasedRecommendationEngine.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,073,903 | 206,981 | 25,362 | 266 | 474 | 88 | 4 | 1 | 260 | 15 | 78 | 3 | 1 | 0 | 1970-01-01T00:28:00 | 133 | Java | {'Java': 1278738, 'Shell': 283720, 'Python': 244636} | Apache License 2.0 |
8,979 | kruize/autotune/713/700 | kruize | autotune | https://github.com/kruize/autotune/issues/700 | https://github.com/kruize/autotune/pull/713 | https://github.com/kruize/autotune/pull/713 | 2 | fixes | Remove resultData from the KruizeObject | Currently we're a getting a redundant result response in the `listExperiments` API. We need to remove the `resultData` object from the JSON and keep the results inside `kubernetes_objects` | ffff426cf44476c14ed2f4609654ff4d6ce3a3a8 | 06ba47028296930697bc1c154428199a65dc08d0 | https://github.com/kruize/autotune/compare/ffff426cf44476c14ed2f4609654ff4d6ce3a3a8...06ba47028296930697bc1c154428199a65dc08d0 | diff --git a/src/main/java/com/autotune/analyzer/experiment/ExperimentInterfaceImpl.java b/src/main/java/com/autotune/analyzer/experiment/ExperimentInterfaceImpl.java
index b22d187c..4da1efb6 100644
--- a/src/main/java/com/autotune/analyzer/experiment/ExperimentInterfaceImpl.java
+++ b/src/main/java/com/autotune/analyzer/experiment/ExperimentInterfaceImpl.java
@@ -66,13 +66,6 @@ public class ExperimentInterfaceImpl implements ExperimentInterface {
(resultData) -> {
resultData.setStatus(AnalyzerConstants.ExperimentStatus.QUEUED);
KruizeObject ko = mainKruizeExperimentMap.get(resultData.getExperiment_name());
- Set<ExperimentResultData> results;
- if (ko.getResultData() == null)
- results = new HashSet<>();
- else
- results = ko.getResultData();
- results.add(resultData);
- ko.setResultData(results);
// creating a temp map to store k8sdata
HashMap<String, K8sObject> k8sObjectHashMap = new HashMap<>();
for (K8sObject k8sObj : ko.getKubernetes_objects())
diff --git a/src/main/java/com/autotune/analyzer/experiment/ExperimentResultValidation.java b/src/main/java/com/autotune/analyzer/experiment/ExperimentResultValidation.java
index f41e2438..76a6ee22 100644
--- a/src/main/java/com/autotune/analyzer/experiment/ExperimentResultValidation.java
+++ b/src/main/java/com/autotune/analyzer/experiment/ExperimentResultValidation.java
@@ -18,11 +18,13 @@ package com.autotune.analyzer.experiment;
import com.autotune.analyzer.utils.AnalyzerErrorConstants;
import com.autotune.analyzer.performanceProfiles.utils.PerformanceProfileUtil;
import com.autotune.common.data.ValidationOutputData;
+import com.autotune.common.data.result.ContainerData;
import com.autotune.common.data.result.ExperimentResultData;
import com.autotune.analyzer.kruizeObject.KruizeObject;
import com.autotune.analyzer.performanceProfiles.PerformanceProfile;
import com.autotune.analyzer.utils.AnalyzerConstants;
import com.autotune.common.data.result.IntervalResults;
+import com.autotune.common.k8sObjects.K8sObject;
import com.autotune.utils.KruizeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -76,8 +78,16 @@ public class ExperimentResultValidation {
}
// check if resultData is present
boolean isExist = false;
- if (null != kruizeObject.getResultData())
- isExist = kruizeObject.getResultData().contains(resultData);
+ for (K8sObject k8sObject : kruizeObject.getKubernetes_objects()) {
+ for (ContainerData containerData : k8sObject.getContainerDataMap().values()) {
+ if (null != containerData.getResults()) {
+ if (null != containerData.getResults().get(resultData.getEndtimestamp())) {
+ isExist = true;
+ break;
+ }
+ }
+ }
+ }
if (isExist) {
errorMsg = errorMsg.concat(String.format("Experiment name : %s already contains result for timestamp : %s", resultData.getExperiment_name(), resultData.getEndtimestamp()));
resultData.setValidationOutputData(new ValidationOutputData(false, errorMsg, HttpServletResponse.SC_CONFLICT));
diff --git a/src/main/java/com/autotune/analyzer/kruizeObject/KruizeObject.java b/src/main/java/com/autotune/analyzer/kruizeObject/KruizeObject.java
index 81fae424..525b36fc 100644
--- a/src/main/java/com/autotune/analyzer/kruizeObject/KruizeObject.java
+++ b/src/main/java/com/autotune/analyzer/kruizeObject/KruizeObject.java
@@ -59,7 +59,6 @@ public final class KruizeObject {
private TrialSettings trial_settings;
private RecommendationSettings recommendation_settings;
private ExperimentUseCaseType experimentUseCaseType;
- private Set<ExperimentResultData> resultData; // TODO: Need to remove this
private ValidationOutputData validationData;
private List<K8sObject> kubernetes_objects;
@@ -203,13 +202,6 @@ public final class KruizeObject {
this.experimentUseCaseType = experimentUseCaseType;
}
- public Set<ExperimentResultData> getResultData() {
- return resultData;
- }
-
- public void setResultData(Set<ExperimentResultData> resultData) {
- this.resultData = resultData;
- }
public ValidationOutputData getValidationData() {
return validationData;
@@ -277,7 +269,6 @@ public final class KruizeObject {
", trial_settings=" + trial_settings +
", recommendation_settings=" + recommendation_settings +
", experimentUseCaseType=" + experimentUseCaseType +
- ", resultData=" + resultData +
", validationData=" + validationData +
", kubernetes_objects=" + kubernetes_objects +
'}'; | ['src/main/java/com/autotune/analyzer/kruizeObject/KruizeObject.java', 'src/main/java/com/autotune/analyzer/experiment/ExperimentResultValidation.java', 'src/main/java/com/autotune/analyzer/experiment/ExperimentInterfaceImpl.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 1,074,174 | 207,040 | 25,362 | 266 | 1,576 | 260 | 30 | 3 | 188 | 28 | 41 | 1 | 0 | 0 | 1970-01-01T00:28:00 | 133 | Java | {'Java': 1278738, 'Shell': 283720, 'Python': 244636} | Apache License 2.0 |
2,086 | smallrye/smallrye-graphql/1006/1005 | smallrye | smallrye-graphql | https://github.com/smallrye/smallrye-graphql/issues/1005 | https://github.com/smallrye/smallrye-graphql/pull/1006 | https://github.com/smallrye/smallrye-graphql/pull/1006 | 1 | fix | Typesafe Client: exception while reading array path index | It throws, e.g., `GraphQlClientException: invalid java.lang.Object value for test.graphql.OrderIT$Api#order.items[0].product.path[2]: 0` | 510fc53b3d44c0fb9920cfff5b5f945eca7db0b2 | d20302d1e693c15ab937ff755728b3efd8fa7369 | https://github.com/smallrye/smallrye-graphql/compare/510fc53b3d44c0fb9920cfff5b5f945eca7db0b2...d20302d1e693c15ab937ff755728b3efd8fa7369 | diff --git a/client/implementation/src/main/java/io/smallrye/graphql/client/typesafe/impl/json/JsonNumberReader.java b/client/implementation/src/main/java/io/smallrye/graphql/client/typesafe/impl/json/JsonNumberReader.java
index 73592ddb..389d6259 100644
--- a/client/implementation/src/main/java/io/smallrye/graphql/client/typesafe/impl/json/JsonNumberReader.java
+++ b/client/implementation/src/main/java/io/smallrye/graphql/client/typesafe/impl/json/JsonNumberReader.java
@@ -41,7 +41,7 @@ class JsonNumberReader extends Reader<JsonNumber> {
return value.doubleValue();
if (BigInteger.class.equals(rawType))
return value.bigIntegerValueExact();
- if (BigDecimal.class.equals(rawType))
+ if (BigDecimal.class.equals(rawType) || Object.class.equals(rawType))
return value.bigDecimalValue();
throw new GraphQLClientValueException(location, value);
diff --git a/client/tck/src/main/java/tck/graphql/typesafe/ErrorBehavior.java b/client/tck/src/main/java/tck/graphql/typesafe/ErrorBehavior.java
index beea0c32..29ee375b 100644
--- a/client/tck/src/main/java/tck/graphql/typesafe/ErrorBehavior.java
+++ b/client/tck/src/main/java/tck/graphql/typesafe/ErrorBehavior.java
@@ -5,10 +5,12 @@ import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.assertj.core.api.BDDAssertions.then;
+import java.math.BigDecimal;
import java.util.List;
import java.util.NoSuchElementException;
import org.eclipse.microprofile.graphql.Name;
+import org.eclipse.microprofile.graphql.NonNull;
import org.junit.jupiter.api.Test;
import io.smallrye.graphql.client.typesafe.api.ErrorOr;
@@ -556,4 +558,65 @@ class ErrorBehavior {
then(error.getPath()).containsExactly("find", "teams");
then(error.getErrorCode()).isEqualTo("team-search-disabled");
}
+
+ interface OrderApi {
+ @SuppressWarnings("UnusedReturnValue")
+ Order order(@NonNull String id);
+ }
+
+ @SuppressWarnings("unused")
+ public static class Order {
+ public String id;
+ public String orderDate;
+ public List<OrderItem> items;
+ }
+
+ public static class OrderItem {
+ @SuppressWarnings("unused")
+ public Product product;
+ }
+
+ public static class Product {
+ @SuppressWarnings("unused")
+ public String id;
+ public String name;
+ }
+
+ @Test
+ void shouldFetchComplexError() {
+ fixture.returns("{\\"errors\\":[" +
+ "{" +
+ "\\"message\\":\\"System error\\"," +
+ "\\"locations\\":[{\\"line\\":1,\\"column\\":84}]," +
+ "\\"path\\":[\\"order\\",\\"items\\",0,\\"product\\"]" +
+ "}" +
+ "]," +
+ "\\"data\\":{" +
+ "\\"order\\":{" +
+ "\\"id\\":\\"o1\\"," +
+ "\\"items\\":[" +
+ "{\\"product\\":null}," +
+ "{\\"product\\":null}" +
+ "]}}}");
+ OrderApi api = fixture.build(OrderApi.class);
+
+ GraphQLClientException throwable = catchThrowableOfType(() -> api.order("o1"), GraphQLClientException.class);
+
+ then(fixture.query())
+ .isEqualTo("query order($id: String!) { order(id: $id) {id orderDate items {product {id name}}} }");
+ then(fixture.variables()).isEqualTo("{'id':'o1'}");
+ then(throwable).hasMessage("errors from service (and we can't apply them to a " + Product.class.getName()
+ + " value for tck.graphql.typesafe.ErrorBehavior$OrderApi#order.items[0].product; see ErrorOr)");
+ then(throwable).hasToString("GraphQlClientException: errors from service (and we can't apply them to a " +
+ Product.class.getName()
+ + " value for tck.graphql.typesafe.ErrorBehavior$OrderApi#order.items[0].product; see ErrorOr)\\n" +
+ "errors:\\n" +
+ "- [order, items, 0, product] System error [(1:84)])");
+ then(throwable.getErrors()).hasSize(1);
+ GraphQLClientError error = throwable.getErrors().get(0);
+ then(error.getMessage()).isEqualTo("System error");
+ then(error.getPath()).containsExactly("order", "items", BigDecimal.ZERO, "product");
+ then(error.getLocations()).containsExactly(new SourceLocation(1, 84, null));
+ then(error.getErrorCode()).isNull();
+ }
} | ['client/implementation/src/main/java/io/smallrye/graphql/client/typesafe/impl/json/JsonNumberReader.java', 'client/tck/src/main/java/tck/graphql/typesafe/ErrorBehavior.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,106,261 | 217,841 | 31,525 | 342 | 2,749 | 571 | 65 | 2 | 136 | 10 | 40 | 1 | 0 | 0 | 1970-01-01T00:27:10 | 132 | Java | {'Java': 2081470, 'JavaScript': 4025, 'Shell': 1757, 'Kotlin': 1745, 'HTML': 1357, 'CSS': 737} | Apache License 2.0 |