id
int64 0
10.2k
| text_id
stringlengths 17
67
| repo_owner
stringclasses 232
values | repo_name
stringclasses 295
values | issue_url
stringlengths 39
89
| pull_url
stringlengths 37
87
| comment_url
stringlengths 37
94
| links_count
int64 1
2
| link_keyword
stringclasses 12
values | issue_title
stringlengths 7
197
| issue_body
stringlengths 45
21.3k
| base_sha
stringlengths 40
40
| head_sha
stringlengths 40
40
| diff_url
stringlengths 120
170
| diff
stringlengths 478
132k
| changed_files
stringlengths 47
2.6k
| changed_files_exts
stringclasses 22
values | changed_files_count
int64 1
22
| java_changed_files_count
int64 1
22
| kt_changed_files_count
int64 0
0
| py_changed_files_count
int64 0
0
| code_changed_files_count
int64 1
22
| repo_symbols_count
int64 32.6k
242M
| repo_tokens_count
int64 6.59k
49.2M
| repo_lines_count
int64 992
6.2M
| repo_files_without_tests_count
int64 12
28.1k
| changed_symbols_count
int64 0
36.1k
| changed_tokens_count
int64 0
6.5k
| changed_lines_count
int64 0
561
| changed_files_without_tests_count
int64 1
17
| issue_symbols_count
int64 45
21.3k
| issue_words_count
int64 2
1.39k
| issue_tokens_count
int64 13
4.47k
| issue_lines_count
int64 1
325
| issue_links_count
int64 0
19
| issue_code_blocks_count
int64 0
31
| pull_create_at
timestamp[s] | stars
int64 10
44.3k
| language
stringclasses 8
values | languages
stringclasses 296
values | license
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,330 | micrometer-metrics/micrometer/3544/3543 | micrometer-metrics | micrometer | https://github.com/micrometer-metrics/micrometer/issues/3543 | https://github.com/micrometer-metrics/micrometer/pull/3544 | https://github.com/micrometer-metrics/micrometer/pull/3544 | 1 | fixes | Fix logic to choose ObservationConvention | There are two issues with the logic that chooses and applies the `ObservationConvention` on the `Observation`s.
1. The logic can choose and apply multiple conventions, also in one case it can mix them together
2. In one case the logic pics the wrong convention
Here's the old and the new decision matrix:
**OLD:**
```
1. custom default no pre-cofigured -> custom
2. custom default pre-cofigured -> custom on top of pre-cofigured
3. no custom default no pre-cofigured -> default
4. no custom default pre-cofigured -> default on top of pre-cofigured (*)
5. custom no default no pre-cofigured -> custom
6. custom no default pre-cofigured -> custom on top of pre-cofigured
7. no custom no default no pre-cofigured -> local
8. no custom no default pre-cofigured -> pre-cofigured
```
_(*): This logic is wrong: 1. they are mixed, 2. pre-cofigured should have choosen_
**NEW:**
```
1. custom default no pre-configured -> custom
2. custom default pre-configured -> custom (not really a valid case, use custom)
3. no custom default no pre-configured -> default
4. no custom default pre-configured -> pre-configured
5. custom no default no pre-configured -> custom (providing default is recommended)
6. custom no default pre-configured -> custom (providing default is recommended)
7. no custom no default no pre-configured -> local names/tags will be used
8. no custom no default pre-configured -> pre-configured
```
cc: @bclozel | 4647bf2813f1fd5da668835e2304864f99ed4c95 | c9dad1f182b85398e74a7fb57a4ec1e61c96d002 | https://github.com/micrometer-metrics/micrometer/compare/4647bf2813f1fd5da668835e2304864f99ed4c95...c9dad1f182b85398e74a7fb57a4ec1e61c96d002 | diff --git a/micrometer-observation-test/src/main/java/io/micrometer/observation/tck/ObservationRegistryCompatibilityKit.java b/micrometer-observation-test/src/main/java/io/micrometer/observation/tck/ObservationRegistryCompatibilityKit.java
index 0d4ef3a38..ffb7cf982 100644
--- a/micrometer-observation-test/src/main/java/io/micrometer/observation/tck/ObservationRegistryCompatibilityKit.java
+++ b/micrometer-observation-test/src/main/java/io/micrometer/observation/tck/ObservationRegistryCompatibilityKit.java
@@ -765,8 +765,6 @@ public abstract class ObservationRegistryCompatibilityKit {
.highCardinalityKeyValue("hcTag1", "0")
// should override the previous line
.highCardinalityKeyValue("hcTag1", "3").highCardinalityKeyValues(KeyValues.of("hcTag2", "4"))
- .observationConvention(new TestObservationConvention("local"))
- .observationConvention(new UnsupportedObservationConvention("local"))
.contextualName("test.observation.42").error(exception).start();
observation.stop();
@@ -774,16 +772,13 @@ public abstract class ObservationRegistryCompatibilityKit {
assertThat(context).isSameAs(testContext);
assertThat(context.getName()).isEqualTo("test.observation");
assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("lcTag1", "1"),
- KeyValue.of("lcTag2", "2"), KeyValue.of("local.context.class", "TestContext"),
- KeyValue.of("global.context.class", "TestContext"));
+ KeyValue.of("lcTag2", "2"), KeyValue.of("global.context.class", "TestContext"));
assertThat(context.getHighCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("hcTag1", "3"),
- KeyValue.of("hcTag2", "4"), KeyValue.of("local.uuid", testContext.uuid),
- KeyValue.of("global.uuid", testContext.uuid));
+ KeyValue.of("hcTag2", "4"), KeyValue.of("global.uuid", testContext.uuid));
assertThat(context.getAllKeyValues()).containsExactlyInAnyOrder(KeyValue.of("lcTag1", "1"),
- KeyValue.of("lcTag2", "2"), KeyValue.of("local.context.class", "TestContext"),
- KeyValue.of("global.context.class", "TestContext"), KeyValue.of("hcTag1", "3"),
- KeyValue.of("hcTag2", "4"), KeyValue.of("local.uuid", testContext.uuid),
+ KeyValue.of("lcTag2", "2"), KeyValue.of("global.context.class", "TestContext"),
+ KeyValue.of("hcTag1", "3"), KeyValue.of("hcTag2", "4"),
KeyValue.of("global.uuid", testContext.uuid));
assertThat((String) context.get("context.field")).isEqualTo("42");
@@ -795,9 +790,9 @@ public abstract class ObservationRegistryCompatibilityKit {
.containsOnlyOnce("contextualName='test.observation.42'")
.containsOnlyOnce("error='java.io.IOException: simulated'")
.containsOnlyOnce(
- "lowCardinalityKeyValues=[global.context.class='TestContext', lcTag1='1', lcTag2='2', local.context.class='TestContext']")
- .containsOnlyOnce("highCardinalityKeyValues=[global.uuid='" + testContext.uuid
- + "', hcTag1='3', hcTag2='4', local.uuid='" + testContext.uuid + "']")
+ "lowCardinalityKeyValues=[global.context.class='TestContext', lcTag1='1', lcTag2='2']")
+ .containsOnlyOnce(
+ "highCardinalityKeyValues=[global.uuid='" + testContext.uuid + "', hcTag1='3', hcTag2='4']")
.containsOnlyOnce("map=[context.field='42']");
});
}
diff --git a/micrometer-observation/src/main/java/io/micrometer/observation/Observation.java b/micrometer-observation/src/main/java/io/micrometer/observation/Observation.java
index 7ae94e224..17fde2019 100644
--- a/micrometer-observation/src/main/java/io/micrometer/observation/Observation.java
+++ b/micrometer-observation/src/main/java/io/micrometer/observation/Observation.java
@@ -127,6 +127,7 @@ public interface Observation extends ObservationView {
return new SimpleObservation(name, registry, context == null ? new Context() : context);
}
+ // @formatter:off
/**
* Creates but <b>does not start</b> an {@link Observation}. Remember to call
* {@link Observation#start()} when you want the measurements to start. When the
@@ -143,15 +144,37 @@ public interface Observation extends ObservationView {
* {@link ObservationRegistry.ObservationConfig#getObservationConvention(Context, ObservationConvention)})
* was found. The {@link ObservationConvention} implementation can override
* {@link Observation} names (i.e. name and contextual name) and key values.
+ * <pre>
+ * Here you can find the matrix of choosing the convention:
+ * 1. custom default no pre-configured -> custom
+ * 2. custom default pre-configured -> custom (not a valid case, just use custom)
+ * 3. no custom default no pre-configured -> default
+ * 4. no custom default pre-configured -> pre-configured
+ * 5. custom no default no pre-configured -> custom (providing default is recommended)
+ * 6. custom no default pre-configured -> custom (providing default is recommended)
+ * 7. no custom no default no pre-configured -> local names/tags will be used
+ * 8. no custom no default pre-configured -> pre-configured
+ * </pre>
+ * <p>
+ * Also, if you set a convention using,
+ * {@link Observation#observationConvention(ObservationConvention)} (not recommended),
+ * the convention you set here will be used and everything else (custom, default,
+ * pre-configured) will be ignored.
+ * </p>
+ * <p>
+ * If you want to add to the all the contexts or mutate them,
+ * use the ObservationFilter (e.g.: add region=cloud-1 or remove PII).
+ * </p>
* @param <T> type of context
* @param customConvention custom convention. If {@code null}, the default one will be
* picked.
* @param defaultConvention default convention when no custom convention was passed,
- * nor a configured one was found
+ * nor a pre-configured one was found
* @param contextSupplier supplier for the observation context
* @param registry observation registry
* @return created but not started observation
*/
+ // @formatter:on
static <T extends Context> Observation createNotStarted(@Nullable ObservationConvention<T> customConvention,
ObservationConvention<T> defaultConvention, Supplier<T> contextSupplier, ObservationRegistry registry) {
if (registry.isNoop()) {
@@ -174,6 +197,11 @@ public interface Observation extends ObservationView {
/**
* Creates and starts an {@link Observation}. When no registry is passed or
* observation is not applicable will return a no-op observation.
+ * <p>
+ * Please check the javadoc of
+ * {@link Observation#createNotStarted(ObservationConvention, ObservationConvention, Supplier, ObservationRegistry)}
+ * method for the logic of choosing the convention.
+ * </p>
* @param observationConvention observation convention
* @param registry observation registry
* @return started observation
@@ -192,6 +220,11 @@ public interface Observation extends ObservationView {
* {@link ObservationRegistry.ObservationConfig#observationPredicate(ObservationPredicate)
* ObservationConfig#observationPredicate}), a no-op observation will also be
* returned.
+ * <p>
+ * Please check the javadoc of
+ * {@link Observation#createNotStarted(ObservationConvention, ObservationConvention, Supplier, ObservationRegistry)}
+ * method for the logic of choosing the convention.
+ * </p>
* @param <T> type of context
* @param observationConvention observation convention
* @param contextSupplier mutable context supplier
@@ -216,6 +249,11 @@ public interface Observation extends ObservationView {
* provide a default one if neither a custom nor a pre-configured one (via
* {@link ObservationRegistry.ObservationConfig#getObservationConvention(Context, ObservationConvention)})
* was found.
+ * <p>
+ * Please check the javadoc of
+ * {@link Observation#createNotStarted(ObservationConvention, ObservationConvention, Supplier, ObservationRegistry)}
+ * method for the logic of choosing the convention.
+ * </p>
* @param <T> type of context
* @param registry observation registry
* @param contextSupplier the observation context supplier
@@ -235,6 +273,11 @@ public interface Observation extends ObservationView {
* {@link Observation#start()} when you want the measurements to start. When no
* registry is passed or observation is not applicable will return a no-op
* observation.
+ * <p>
+ * Please check the javadoc of
+ * {@link Observation#createNotStarted(ObservationConvention, ObservationConvention, Supplier, ObservationRegistry)}
+ * method for the logic of choosing the convention.
+ * </p>
* @param observationConvention observation convention
* @param registry observation registry
* @return created but not started observation
@@ -265,6 +308,11 @@ public interface Observation extends ObservationView {
* of {@link Context} to be passed and if you're not providing one we won't be able to
* initialize it ourselves.
* </p>
+ * <p>
+ * Please check the javadoc of
+ * {@link Observation#createNotStarted(ObservationConvention, ObservationConvention, Supplier, ObservationRegistry)}
+ * method for the logic of choosing the convention.
+ * </p>
* @param <T> type of context
* @param observationConvention observation convention
* @param contextSupplier mutable context supplier
@@ -380,8 +428,8 @@ public interface Observation extends ObservationView {
/**
* Adds an observation convention that can be used to attach key values to the
- * observation. WARNING: You must add ObservationConvention instances to the
- * Observation before it is started.
+ * observation. WARNING: You must set the ObservationConvention to the Observation
+ * before it is started.
* @param observationConvention observation convention
* @return this
*/
diff --git a/micrometer-observation/src/main/java/io/micrometer/observation/ObservationRegistry.java b/micrometer-observation/src/main/java/io/micrometer/observation/ObservationRegistry.java
index 93e51050a..7381eaec1 100644
--- a/micrometer-observation/src/main/java/io/micrometer/observation/ObservationRegistry.java
+++ b/micrometer-observation/src/main/java/io/micrometer/observation/ObservationRegistry.java
@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.Supplier;
/**
* Implementations of this interface are responsible for managing state of an
@@ -135,6 +136,11 @@ public interface ObservationRegistry {
/**
* Register an {@link ObservationConvention}.
+ * <p>
+ * Please check the javadoc of
+ * {@link Observation#createNotStarted(ObservationConvention, ObservationConvention, Supplier, ObservationRegistry)}
+ * method for the logic of choosing the convention.
+ * </p>
* @param observationConvention observation convention
* @return This configuration instance
*/
diff --git a/micrometer-observation/src/main/java/io/micrometer/observation/SimpleObservation.java b/micrometer-observation/src/main/java/io/micrometer/observation/SimpleObservation.java
index b70cab91a..7aaaa2a39 100644
--- a/micrometer-observation/src/main/java/io/micrometer/observation/SimpleObservation.java
+++ b/micrometer-observation/src/main/java/io/micrometer/observation/SimpleObservation.java
@@ -38,8 +38,9 @@ class SimpleObservation implements Observation {
private final Context context;
+ @Nullable
@SuppressWarnings("rawtypes")
- private final Collection<ObservationConvention> conventions;
+ private ObservationConvention convention;
@SuppressWarnings("rawtypes")
private final Deque<ObservationHandler> handlers;
@@ -50,16 +51,20 @@ class SimpleObservation implements Observation {
this.registry = registry;
this.context = context;
this.context.setName(name);
- this.conventions = getConventionsFromConfig(registry, context);
+ this.convention = getConventionFromConfig(registry, context);
this.handlers = getHandlersFromConfig(registry, context);
this.filters = registry.observationConfig().getObservationFilters();
}
SimpleObservation(ObservationConvention<? extends Context> convention, ObservationRegistry registry,
Context context) {
- this((String) null, registry, context); // name is set later in start()
+ this.registry = registry;
+ this.context = context;
+ // name is set later in start()
+ this.handlers = getHandlersFromConfig(registry, context);
+ this.filters = registry.observationConfig().getObservationFilters();
if (convention.supportsContext(context)) {
- this.conventions.add(convention);
+ this.convention = convention;
}
else {
throw new IllegalStateException(
@@ -67,10 +72,10 @@ class SimpleObservation implements Observation {
}
}
- private static Collection<ObservationConvention> getConventionsFromConfig(ObservationRegistry registry,
- Context context) {
+ @Nullable
+ private static ObservationConvention getConventionFromConfig(ObservationRegistry registry, Context context) {
return registry.observationConfig().getObservationConventions().stream()
- .filter(convention -> convention.supportsContext(context)).collect(Collectors.toList());
+ .filter(convention -> convention.supportsContext(context)).findFirst().orElse(null);
}
private static Deque<ObservationHandler> getHandlersFromConfig(ObservationRegistry registry, Context context) {
@@ -105,7 +110,7 @@ class SimpleObservation implements Observation {
@Override
public Observation observationConvention(ObservationConvention<?> convention) {
if (convention.supportsContext(context)) {
- this.conventions.add(convention);
+ this.convention = convention;
}
return this;
}
@@ -125,18 +130,13 @@ class SimpleObservation implements Observation {
@Override
public Observation start() {
- // We want to rename with the first matching convention
- boolean nameChanged = false;
- for (ObservationConvention convention : this.conventions) {
+ if (this.convention != null) {
this.context.addLowCardinalityKeyValues(convention.getLowCardinalityKeyValues(context));
this.context.addHighCardinalityKeyValues(convention.getHighCardinalityKeyValues(context));
- if (!nameChanged) {
- String newName = convention.getName();
- if (StringUtils.isNotBlank(newName)) {
- this.context.setName(newName);
- nameChanged = true;
- }
+ String newName = convention.getName();
+ if (StringUtils.isNotBlank(newName)) {
+ this.context.setName(newName);
}
}
@@ -152,18 +152,13 @@ class SimpleObservation implements Observation {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void stop() {
- // We want to rename with the first matching convention
- boolean contextualNameChanged = false;
- for (ObservationConvention convention : this.conventions) {
+ if (this.convention != null) {
this.context.addLowCardinalityKeyValues(convention.getLowCardinalityKeyValues(context));
this.context.addHighCardinalityKeyValues(convention.getHighCardinalityKeyValues(context));
- if (!contextualNameChanged) {
- String newContextualName = convention.getContextualName(context);
- if (StringUtils.isNotBlank(newContextualName)) {
- this.context.setContextualName(newContextualName);
- contextualNameChanged = true;
- }
+ String newContextualName = convention.getContextualName(context);
+ if (StringUtils.isNotBlank(newContextualName)) {
+ this.context.setContextualName(newContextualName);
}
}
diff --git a/micrometer-observation/src/test/java/io/micrometer/observation/ObservationRegistryTest.java b/micrometer-observation/src/test/java/io/micrometer/observation/ObservationRegistryTest.java
index d2d36fb5c..2832fd921 100644
--- a/micrometer-observation/src/test/java/io/micrometer/observation/ObservationRegistryTest.java
+++ b/micrometer-observation/src/test/java/io/micrometer/observation/ObservationRegistryTest.java
@@ -96,8 +96,6 @@ class ObservationRegistryTest {
registry.observationConfig().observationHandler(c -> true);
// Define a convention
MessagingConvention messagingConvention = new OurCompanyStandardMessagingConvention();
- // Register a semantic name provider
- registry.observationConfig().observationConvention(new OurCompanyObservationConvention());
Observation.Context myContext = new MessagingContext().put("foo", "hello");
// Observation convention wants to use a MessagingConvention
@@ -125,6 +123,12 @@ class ObservationRegistryTest {
this.messagingConvention = messagingConvention;
}
+ // Here we override the default "observation" name
+ @Override
+ public String getName() {
+ return "new name";
+ }
+
@Override
public KeyValues getLowCardinalityKeyValues(MessagingContext context) {
return KeyValues.of(this.messagingConvention.queueName(context.get("foo")));
@@ -153,22 +157,4 @@ class ObservationRegistryTest {
}
- static class OurCompanyObservationConvention implements GlobalObservationConvention<Observation.Context> {
-
- // Here we override the default "observation" name
- @Override
- public String getName() {
- return "new name";
- }
-
- // This semantic name provider is only applicable when we're using a messaging
- // context
-
- @Override
- public boolean supportsContext(Observation.Context context) {
- return context instanceof MessagingContext;
- }
-
- }
-
}
diff --git a/micrometer-observation/src/test/java/io/micrometer/observation/ObservationTests.java b/micrometer-observation/src/test/java/io/micrometer/observation/ObservationTests.java
index 39cc1f19f..81d3d2a55 100644
--- a/micrometer-observation/src/test/java/io/micrometer/observation/ObservationTests.java
+++ b/micrometer-observation/src/test/java/io/micrometer/observation/ObservationTests.java
@@ -16,6 +16,8 @@
package io.micrometer.observation;
import io.micrometer.common.KeyValue;
+import io.micrometer.common.KeyValues;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -32,7 +34,12 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
class ObservationTests {
- private final ObservationRegistry registry = ObservationRegistry.create();
+ private ObservationRegistry registry;
+
+ @BeforeEach
+ void setUp() {
+ this.registry = ObservationRegistry.create();
+ }
@Test
void notHavingAnyHandlersShouldResultInNoopObservation() {
@@ -150,6 +157,138 @@ class ObservationTests {
}
}
+ @Test
+ void customAndDefaultAndNoGlobalConventionShouldResolveToCustomConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted(new CustomConvention(), new DefaultConvention(), () -> context, registry)
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local").start().stop();
+
+ assertThat(context.getName()).isEqualTo("custom.name");
+ assertThat(context.getContextualName()).isEqualTo("custom.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("custom", "present"), KeyValue.of("low", "custom"));
+ }
+
+ @Test
+ void customAndDefaultAndGlobalConventionShouldResolveToCustomConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+ registry.observationConfig().observationConvention(new GlobalConvention());
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted(new CustomConvention(), new DefaultConvention(), () -> context, registry)
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local").start().stop();
+
+ assertThat(context.getName()).isEqualTo("custom.name");
+ assertThat(context.getContextualName()).isEqualTo("custom.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("custom", "present"), KeyValue.of("low", "custom"));
+ }
+
+ @Test
+ void noCustomAndDefaultAndNoGlobalConventionShouldResolveToDefaultConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted(null, new DefaultConvention(), () -> context, registry)
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local").start().stop();
+
+ assertThat(context.getName()).isEqualTo("default.name");
+ assertThat(context.getContextualName()).isEqualTo("default.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("default", "present"), KeyValue.of("low", "default"));
+ }
+
+ @Test
+ void noCustomAndDefaultAndGlobalConventionShouldResolveToDefaultConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+ registry.observationConfig().observationConvention(new GlobalConvention());
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted(null, new DefaultConvention(), () -> context, registry)
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local").start().stop();
+
+ assertThat(context.getName()).isEqualTo("global.name");
+ assertThat(context.getContextualName()).isEqualTo("global.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("global", "present"), KeyValue.of("low", "global"));
+ }
+
+ @Test
+ void customAndNoDefaultAndNoGlobalConventionShouldResolveToCustomConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted(new CustomConvention(), () -> context, registry)
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local").start().stop();
+
+ assertThat(context.getName()).isEqualTo("custom.name");
+ assertThat(context.getContextualName()).isEqualTo("custom.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("custom", "present"), KeyValue.of("low", "custom"));
+ }
+
+ @Test
+ void customAndNoDefaultAndGlobalConventionShouldResolveToCustomConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+ registry.observationConfig().observationConvention(new GlobalConvention());
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted(new CustomConvention(), () -> context, registry)
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local").start().stop();
+
+ assertThat(context.getName()).isEqualTo("custom.name");
+ assertThat(context.getContextualName()).isEqualTo("custom.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("custom", "present"), KeyValue.of("low", "custom"));
+ }
+
+ @Test
+ void noCustomAndNoDefaultAndNoGlobalConventionShouldResolveToNoConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted("local.name", () -> context, registry).contextualName("local.contextualName")
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local").start().stop();
+
+ assertThat(context.getName()).isEqualTo("local.name");
+ assertThat(context.getContextualName()).isEqualTo("local.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("low", "local"));
+ }
+
+ @Test
+ void noCustomAndNoDefaultAndGlobalConventionShouldResolveToGlobalConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+ registry.observationConfig().observationConvention(new GlobalConvention());
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted("local.name", () -> context, registry).contextualName("local.contextualName")
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local").start().stop();
+
+ assertThat(context.getName()).isEqualTo("global.name");
+ assertThat(context.getContextualName()).isEqualTo("global.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("global", "present"), KeyValue.of("low", "global"));
+ }
+
+ @Test
+ void instrumentationAndCustomAndDefaultAndGlobalConventionShouldResolveToInstrumentationConvention() {
+ registry.observationConfig().observationHandler(context -> true);
+ registry.observationConfig().observationConvention(new GlobalConvention());
+
+ Observation.Context context = new Observation.Context();
+ Observation.createNotStarted(new CustomConvention(), new DefaultConvention(), () -> context, registry)
+ .lowCardinalityKeyValue("local", "present").lowCardinalityKeyValue("low", "local")
+ .observationConvention(new InstrumentationConvention()).start().stop();
+
+ assertThat(context.getName()).isEqualTo("instrumentation.name");
+ assertThat(context.getContextualName()).isEqualTo("instrumentation.contextualName");
+ assertThat(context.getLowCardinalityKeyValues()).containsExactlyInAnyOrder(KeyValue.of("local", "present"),
+ KeyValue.of("instrumentation", "present"), KeyValue.of("low", "instrumentation"));
+ }
+
static class Service {
String executeCallable() throws IOException {
@@ -167,4 +306,100 @@ class ObservationTests {
}
+ static class CustomConvention implements ObservationConvention<Observation.Context> {
+
+ @Override
+ public String getName() {
+ return "custom.name";
+ }
+
+ @Override
+ public String getContextualName(Observation.Context context) {
+ return "custom.contextualName";
+ }
+
+ @Override
+ public KeyValues getLowCardinalityKeyValues(Observation.Context context) {
+ return KeyValues.of("low", "custom", "custom", "present");
+ }
+
+ @Override
+ public boolean supportsContext(Observation.Context context) {
+ return true;
+ }
+
+ }
+
+ static class DefaultConvention implements ObservationConvention<Observation.Context> {
+
+ @Override
+ public String getName() {
+ return "default.name";
+ }
+
+ @Override
+ public String getContextualName(Observation.Context context) {
+ return "default.contextualName";
+ }
+
+ @Override
+ public KeyValues getLowCardinalityKeyValues(Observation.Context context) {
+ return KeyValues.of("low", "default", "default", "present");
+ }
+
+ @Override
+ public boolean supportsContext(Observation.Context context) {
+ return true;
+ }
+
+ }
+
+ static class GlobalConvention implements GlobalObservationConvention<Observation.Context> {
+
+ @Override
+ public String getName() {
+ return "global.name";
+ }
+
+ @Override
+ public String getContextualName(Observation.Context context) {
+ return "global.contextualName";
+ }
+
+ @Override
+ public KeyValues getLowCardinalityKeyValues(Observation.Context context) {
+ return KeyValues.of("low", "global", "global", "present");
+ }
+
+ @Override
+ public boolean supportsContext(Observation.Context context) {
+ return true;
+ }
+
+ }
+
+ static class InstrumentationConvention implements ObservationConvention<Observation.Context> {
+
+ @Override
+ public String getName() {
+ return "instrumentation.name";
+ }
+
+ @Override
+ public String getContextualName(Observation.Context context) {
+ return "instrumentation.contextualName";
+ }
+
+ @Override
+ public KeyValues getLowCardinalityKeyValues(Observation.Context context) {
+ return KeyValues.of("low", "instrumentation", "instrumentation", "present");
+ }
+
+ @Override
+ public boolean supportsContext(Observation.Context context) {
+ return true;
+ }
+
+ }
+
} | ['micrometer-observation/src/test/java/io/micrometer/observation/ObservationTests.java', 'micrometer-observation/src/main/java/io/micrometer/observation/ObservationRegistry.java', 'micrometer-observation/src/main/java/io/micrometer/observation/SimpleObservation.java', 'micrometer-observation/src/main/java/io/micrometer/observation/Observation.java', 'micrometer-observation/src/test/java/io/micrometer/observation/ObservationRegistryTest.java', 'micrometer-observation-test/src/main/java/io/micrometer/observation/tck/ObservationRegistryCompatibilityKit.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 2,721,359 | 579,527 | 74,688 | 636 | 5,717 | 1,170 | 107 | 3 | 1,577 | 226 | 414 | 33 | 0 | 2 | 2022-11-23T02:19:47 | 4,034 | Java | {'Java': 4710724, 'Shell': 5270, 'Kotlin': 4163} | Apache License 2.0 |
1,331 | micrometer-metrics/micrometer/461/379 | micrometer-metrics | micrometer | https://github.com/micrometer-metrics/micrometer/issues/379 | https://github.com/micrometer-metrics/micrometer/pull/461 | https://github.com/micrometer-metrics/micrometer/pull/461 | 1 | fixes | Influx Metric Registry Publish Can Fail Silently | I had a bug in my logic to create timer metrics which passed in 'null' as one of the values of a tag. The next execution of the publish method would then throw a NullPointerException when invoking writeTimer. The exception wasn't handled in the publish method, bubbled back to the Executor which then failed silently and as result all no more metrics were ever sent.
Currently, the publish method implementation inside InfluxMetricRegistry only catches MalformedURLException and IOException ie.
```
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed InfluxDB publishing endpoint, see '" + config.prefix() + ".uri'", e);
} catch (IOException e) {
logger.warn("failed to send metrics", e);
}
```
I am unsure of the best solution for this however I believe that the NullPointerException should be handled and the appropriate log message should be displayed. | 4226e9621db2cf22b8df9d69e175f0789242883f | 9bad61aec1139afeba221a2a8d1d9a7e2d8ccabe | https://github.com/micrometer-metrics/micrometer/compare/4226e9621db2cf22b8df9d69e175f0789242883f...9bad61aec1139afeba221a2a8d1d9a7e2d8ccabe | diff --git a/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java b/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java
index 0e249361d..afe7db303 100644
--- a/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java
+++ b/implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java
@@ -81,7 +81,7 @@ public class InfluxMeterRegistry extends StepMeterRegistry {
.lines().collect(joining("\\n")));
}
}
- } catch (IOException e) {
+ } catch (Throwable e) {
logger.warn("unable to create database '{}'", config.db(), e);
} finally {
quietlyCloseUrlConnection(con); | ['implementations/micrometer-registry-influx/src/main/java/io/micrometer/influx/InfluxMeterRegistry.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,082,462 | 224,121 | 29,882 | 340 | 67 | 16 | 2 | 1 | 947 | 135 | 180 | 12 | 0 | 1 | 2018-02-22T08:12:21 | 4,034 | Java | {'Java': 4710724, 'Shell': 5270, 'Kotlin': 4163} | Apache License 2.0 |
1,333 | strimzi/strimzi-kafka-operator/2439/2411 | strimzi | strimzi-kafka-operator | https://github.com/strimzi/strimzi-kafka-operator/issues/2411 | https://github.com/strimzi/strimzi-kafka-operator/pull/2439 | https://github.com/strimzi/strimzi-kafka-operator/pull/2439 | 1 | fixes | [Bug] ZooKeeper user entry not deleted when KafkaUser is deleted | When a new `KafkaUser` resource is created with quotas, a new user entry is created in ZooKeeper in the `/config/users` znode (i.e. `/config/users/my-user`). It contains a JSON with `version` and `config` fields.
When the `KafkaUser` resource is deleted, the above entry isn't deleted but the `config` field is emptied.
Because the `KafkaUser` isn't there anymore, the user entry should be completely deleted. | aeead4d3abbd5899a2541b3585e4d02b0f013653 | 39f628583363f5cf2bcdef674d80bc88f8021a43 | https://github.com/strimzi/strimzi-kafka-operator/compare/aeead4d3abbd5899a2541b3585e4d02b0f013653...39f628583363f5cf2bcdef674d80bc88f8021a43 | diff --git a/systemtest/src/test/java/io/strimzi/systemtest/UserST.java b/systemtest/src/test/java/io/strimzi/systemtest/UserST.java
index 5c2d2f93b..c5bde6605 100644
--- a/systemtest/src/test/java/io/strimzi/systemtest/UserST.java
+++ b/systemtest/src/test/java/io/strimzi/systemtest/UserST.java
@@ -171,12 +171,19 @@ class UserST extends BaseST {
assertThat(result.out().contains("producer_byte_rate=" + prodRate), is(true));
assertThat(result.out().contains("consumer_byte_rate=" + consRate), is(true));
+ String zkListCommand = "sh /opt/kafka/bin/zookeeper-shell.sh localhost:21810 <<< 'ls /config/users'";
+ ExecResult zkResult = cmdKubeClient().execInPod(KafkaResources.zookeeperPodName(CLUSTER_NAME, 0), "/bin/bash", "-c", zkListCommand);
+ assertThat(zkResult.out().contains(userName), is(true));
+
+ // delete user
KafkaUserResource.kafkaUserClient().inNamespace(NAMESPACE).withName(userName).delete();
KafkaUserUtils.waitForKafkaUserDeletion(userName);
ExecResult resultAfterDelete = cmdKubeClient().execInPod(KafkaResources.kafkaPodName(CLUSTER_NAME, 0), "/bin/bash", "-c", command);
assertThat(resultAfterDelete.out(), emptyString());
+ ExecResult zkDeleteResult = cmdKubeClient().execInPod(KafkaResources.zookeeperPodName(CLUSTER_NAME, 0), "/bin/bash", "-c", zkListCommand);
+ assertThat(zkDeleteResult.out().contains(userName), is(false));
}
void createBigAmountOfUsers(String typeOfUser) {
diff --git a/user-operator/src/main/java/io/strimzi/operator/user/operator/KafkaUserQuotasOperator.java b/user-operator/src/main/java/io/strimzi/operator/user/operator/KafkaUserQuotasOperator.java
index 48aaf1028..5d4126c2f 100644
--- a/user-operator/src/main/java/io/strimzi/operator/user/operator/KafkaUserQuotasOperator.java
+++ b/user-operator/src/main/java/io/strimzi/operator/user/operator/KafkaUserQuotasOperator.java
@@ -195,6 +195,12 @@ public class KafkaUserQuotasOperator {
return false;
}
+ private boolean configJsonIsEmpty(JsonObject json) {
+ validateJsonVersion(json);
+ JsonObject config = json.getJsonObject("config");
+ return config.isEmpty();
+ }
+
/**
* Delete the quotas for the given user.
* It is not an error if the user doesn't exist, or doesn't currently have any quotas.
@@ -206,7 +212,13 @@ public class KafkaUserQuotasOperator {
if (data != null) {
log.debug("Deleting quotas for user {}", username);
- zkClient.writeData("/config/users/" + username, removeQuotasFromJsonUser(data));
+ JsonObject deleteJson = removeQuotasFromJsonUser(data);
+ if (configJsonIsEmpty(deleteJson)) {
+ zkClient.deleteRecursive("/config/users/" + username);
+ log.debug("User {} deleted from ZK store", username);
+ } else {
+ zkClient.writeData("/config/users/" + username, deleteJson.toBuffer().getBytes());
+ }
notifyChanges(username);
} else {
log.warn("Quotas for user {} already don't exist", username);
@@ -218,9 +230,9 @@ public class KafkaUserQuotasOperator {
*
* @param user JSON string with existing user configuration as byte[]
*
- * @return Returns the updated JSON without the quotas as byte array
+ * @return Returns the updated JSON without the quotas
*/
- protected byte[] removeQuotasFromJsonUser(byte[] user) {
+ protected JsonObject removeQuotasFromJsonUser(byte[] user) {
JsonObject json = new JsonObject(new String(user, StandardCharsets.UTF_8));
validateJsonVersion(json);
@@ -238,8 +250,7 @@ public class KafkaUserQuotasOperator {
config.remove("request_percentage");
}
}
-
- return json.encode().getBytes(StandardCharsets.UTF_8);
+ return json;
}
protected void validateJsonVersion(JsonObject json) {
diff --git a/user-operator/src/main/java/io/strimzi/operator/user/operator/ScramShaCredentials.java b/user-operator/src/main/java/io/strimzi/operator/user/operator/ScramShaCredentials.java
index 151a59567..051b098c6 100644
--- a/user-operator/src/main/java/io/strimzi/operator/user/operator/ScramShaCredentials.java
+++ b/user-operator/src/main/java/io/strimzi/operator/user/operator/ScramShaCredentials.java
@@ -56,6 +56,12 @@ public class ScramShaCredentials {
notifyChanges(username);
}
+ private boolean configJsonIsEmpty(JsonObject json) {
+ validateJsonVersion(json);
+ JsonObject config = json.getJsonObject("config");
+ return config.isEmpty();
+ }
+
/**
* Delete the SCRAM-SHA credentials for the given user.
* It is not an error if the user doesn't exist, or doesn't currently have any SCRAM-SHA credentials.
@@ -67,7 +73,12 @@ public class ScramShaCredentials {
if (data != null) {
log.debug("Deleting {} credentials for user {}", mechanism.mechanismName(), username);
- zkClient.writeData("/config/users/" + username, deleteUserJson(data));
+ JsonObject deletedJson = deleteUserJson(data);
+ if (configJsonIsEmpty(deletedJson)) {
+ zkClient.deleteRecursive("/config/users/" + username);
+ } else {
+ zkClient.writeData("/config/users/" + username, deletedJson.toBuffer().getBytes());
+ }
notifyChanges(username);
} else {
log.warn("Credentials for user {} already don't exist", username);
@@ -154,6 +165,11 @@ public class ScramShaCredentials {
}
}
+ /* test */
+ boolean isPathExist(String path) {
+ return zkClient.exists(path);
+ }
+
/**
* Generates the JSON with the credentials
*
@@ -209,9 +225,9 @@ public class ScramShaCredentials {
*
* @param user JSON string with existing user configuration as byte[]
*
- * @return Returns the updated JSON without the SCRAM credentials as byte array
+ * @return Returns the updated JSON without the SCRAM credentials
*/
- protected byte[] deleteUserJson(byte[] user) {
+ protected JsonObject deleteUserJson(byte[] user) {
JsonObject json = new JsonObject(new String(user, Charset.defaultCharset()));
validateJsonVersion(json);
@@ -224,7 +240,7 @@ public class ScramShaCredentials {
json.getJsonObject("config").remove(mechanism.mechanismName());
}
- return json.encode().getBytes(Charset.defaultCharset());
+ return json;
}
protected void validateJsonVersion(JsonObject json) {
diff --git a/user-operator/src/test/java/io/strimzi/operator/user/operator/KafkaUserQuotasIT.java b/user-operator/src/test/java/io/strimzi/operator/user/operator/KafkaUserQuotasIT.java
index 61adfafd8..63ceb649b 100644
--- a/user-operator/src/test/java/io/strimzi/operator/user/operator/KafkaUserQuotasIT.java
+++ b/user-operator/src/test/java/io/strimzi/operator/user/operator/KafkaUserQuotasIT.java
@@ -14,7 +14,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
-import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
@@ -84,6 +84,7 @@ public class KafkaUserQuotasIT {
assertThat(kuq.exists("normalDelete"), is(true));
kuq.delete("normalDelete");
assertThat(kuq.exists("normalDelete"), is(false));
+ assertThat(kuq.isPathExist("/config/users/normalDelete"), is(false));
}
@Test
@@ -94,6 +95,7 @@ public class KafkaUserQuotasIT {
kuq.delete("doubleDelete");
kuq.delete("doubleDelete");
assertThat(kuq.exists("doubleDelete"), is(false));
+ assertThat(kuq.isPathExist("/config/users/doubleDelete"), is(false));
}
@Test
@@ -141,23 +143,26 @@ public class KafkaUserQuotasIT {
@Test
public void testDeletion() {
JsonObject original = new JsonObject().put("version", 1).put("config", kuq.quotasToJson(defaultQuotas));
- JsonObject updated = new JsonObject(new String(kuq.removeQuotasFromJsonUser(original.encode().getBytes(Charset.defaultCharset())), Charset.defaultCharset()));
+ original.getJsonObject("config").put("persist", 42);
+ JsonObject updated = kuq.removeQuotasFromJsonUser(original.encode().getBytes(StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("consumer_byte_rate"), is(nullValue()));
+ assertThat(updated.getJsonObject("config").getInteger("persist"), is(42));
original = new JsonObject().put("version", 1).put("config", new JsonObject().put("producer_byte_rate", "1000").put("consumer_byte_rate", "2000"));
- updated = new JsonObject(new String(kuq.removeQuotasFromJsonUser(original.encode().getBytes(Charset.defaultCharset())), Charset.defaultCharset()));
+ updated = kuq.removeQuotasFromJsonUser(original.encode().getBytes(StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("producer_byte_rate"), is(nullValue()));
assertThat(updated.getJsonObject("config").getString("consumer_byte_rate"), is(nullValue()));
original = new JsonObject().put("version", 1).put("config", new JsonObject());
- updated = new JsonObject(new String(kuq.removeQuotasFromJsonUser(original.encode().getBytes(Charset.defaultCharset())), Charset.defaultCharset()));
+ updated = kuq.removeQuotasFromJsonUser(original.encode().getBytes(StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("consumer_byte_rate"), is(nullValue()));
assertThat(updated.getJsonObject("config").getString("producer_byte_rate"), is(nullValue()));
original = new JsonObject().put("version", 1).put("config", new JsonObject().put("consumer_byte_rate", "1000"));
- updated = new JsonObject(new String(kuq.removeQuotasFromJsonUser(original.encode().getBytes(Charset.defaultCharset())), Charset.defaultCharset()));
+ updated = kuq.removeQuotasFromJsonUser(original.encode().getBytes(StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("producer_byte_rate"), is(nullValue()));
assertThat(updated.getJsonObject("config").getString("consumer_byte_rate"), is(nullValue()));
+
}
@Test
@@ -165,14 +170,14 @@ public class KafkaUserQuotasIT {
JsonObject original = new JsonObject().put("version", 1).put("config", new JsonObject().put("consumer_byte_rate", "1000"));
KafkaUserQuotas quotas = new KafkaUserQuotas();
quotas.setConsumerByteRate(2000);
- JsonObject updated = new JsonObject(new String(kuq.updateUserJson(original.encode().getBytes(Charset.defaultCharset()), quotas), Charset.defaultCharset()));
+ JsonObject updated = new JsonObject(new String(kuq.updateUserJson(original.encode().getBytes(StandardCharsets.UTF_8), quotas), StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("consumer_byte_rate"), is(notNullValue()));
assertThat(updated.getJsonObject("config").getString("consumer_byte_rate"), is("2000"));
quotas.setConsumerByteRate(3000);
quotas.setProducerByteRate(4000);
original = new JsonObject().put("version", 1).put("config", new JsonObject().put("consumer_byte_rate", "1000").put("producer_byte_rate", "2000"));
- updated = new JsonObject(new String(kuq.updateUserJson(original.encode().getBytes(Charset.defaultCharset()), quotas), Charset.defaultCharset()));
+ updated = new JsonObject(new String(kuq.updateUserJson(original.encode().getBytes(StandardCharsets.UTF_8), quotas), StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("consumer_byte_rate"), is(notNullValue()));
assertThat(updated.getJsonObject("config").getString("producer_byte_rate"), is(notNullValue()));
assertThat(updated.getJsonObject("config").getString("producer_byte_rate"), is("4000"));
@@ -181,7 +186,7 @@ public class KafkaUserQuotasIT {
original = new JsonObject().put("version", 1).put("config", new JsonObject());
quotas.setProducerByteRate(null);
quotas.setConsumerByteRate(1000);
- updated = new JsonObject(new String(kuq.updateUserJson(original.encode().getBytes(Charset.defaultCharset()), quotas), Charset.defaultCharset()));
+ updated = new JsonObject(new String(kuq.updateUserJson(original.encode().getBytes(StandardCharsets.UTF_8), quotas), StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("consumer_byte_rate"), is(notNullValue()));
}
}
diff --git a/user-operator/src/test/java/io/strimzi/operator/user/operator/ScramShaCredentialsTest.java b/user-operator/src/test/java/io/strimzi/operator/user/operator/ScramShaCredentialsIT.java
similarity index 83%
rename from user-operator/src/test/java/io/strimzi/operator/user/operator/ScramShaCredentialsTest.java
rename to user-operator/src/test/java/io/strimzi/operator/user/operator/ScramShaCredentialsIT.java
index e174b614a..6b04446d7 100644
--- a/user-operator/src/test/java/io/strimzi/operator/user/operator/ScramShaCredentialsTest.java
+++ b/user-operator/src/test/java/io/strimzi/operator/user/operator/ScramShaCredentialsIT.java
@@ -12,7 +12,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
-import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
@@ -21,7 +21,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
-public class ScramShaCredentialsTest {
+public class ScramShaCredentialsIT {
private static EmbeddedZooKeeper zkServer;
@@ -57,6 +57,7 @@ public class ScramShaCredentialsTest {
public void normalDelete() {
scramShaCred.createOrUpdate("normalDelete", "foo-password");
scramShaCred.delete("normalDelete");
+ assertThat(scramShaCred.isPathExist("/config/users/normalDelete"), is(false));
}
@Test
@@ -64,6 +65,7 @@ public class ScramShaCredentialsTest {
scramShaCred.createOrUpdate("doubleDelete", "foo-password");
scramShaCred.delete("doubleDelete");
scramShaCred.delete("doubleDelete");
+ assertThat(scramShaCred.isPathExist("/config/users/doubleDelete"), is(false));
}
@Test
@@ -76,7 +78,6 @@ public class ScramShaCredentialsTest {
public void userExists() {
scramShaCred.createOrUpdate("userExists", "foo-password");
assertThat(scramShaCred.exists("userExists"), is(true));
-
}
@Test
@@ -124,20 +125,22 @@ public class ScramShaCredentialsTest {
@Test
public void testDeletion() {
JsonObject original = new JsonObject().put("version", 1).put("config", new JsonObject().put("SCRAM-SHA-512", "somecredentials"));
- JsonObject updated = new JsonObject(new String(scramShaCred.deleteUserJson(original.encode().getBytes(Charset.defaultCharset())), Charset.defaultCharset()));
+ original.getJsonObject("config").put("persist", 42);
+ JsonObject updated = scramShaCred.deleteUserJson(original.encode().getBytes(StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-512"), is(nullValue()));
+ assertThat(updated.getJsonObject("config").getInteger("persist"), is(42));
original = new JsonObject().put("version", 1).put("config", new JsonObject().put("SCRAM-SHA-512", "somecredentials").put("SCRAM-SHA-256", "somecredentials"));
- updated = new JsonObject(new String(scramShaCred.deleteUserJson(original.encode().getBytes(Charset.defaultCharset())), Charset.defaultCharset()));
+ updated = scramShaCred.deleteUserJson(original.encode().getBytes(StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-512"), is(nullValue()));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-256"), is("somecredentials"));
original = new JsonObject().put("version", 1).put("config", new JsonObject());
- updated = new JsonObject(new String(scramShaCred.deleteUserJson(original.encode().getBytes(Charset.defaultCharset())), Charset.defaultCharset()));
+ updated = scramShaCred.deleteUserJson(original.encode().getBytes(StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-512"), is(nullValue()));
original = new JsonObject().put("version", 1).put("config", new JsonObject().put("SCRAM-SHA-256", "somecredentials"));
- updated = new JsonObject(new String(scramShaCred.deleteUserJson(original.encode().getBytes(Charset.defaultCharset())), Charset.defaultCharset()));
+ updated = scramShaCred.deleteUserJson(original.encode().getBytes(StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-512"), is(nullValue()));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-256"), is("somecredentials"));
}
@@ -145,20 +148,20 @@ public class ScramShaCredentialsTest {
@Test
public void testUpdate() {
JsonObject original = new JsonObject().put("version", 1).put("config", new JsonObject().put("SCRAM-SHA-512", "somecredentials"));
- JsonObject updated = new JsonObject(new String(scramShaCred.updateUserJson(original.encode().getBytes(Charset.defaultCharset()), "password"), Charset.defaultCharset()));
+ JsonObject updated = new JsonObject(new String(scramShaCred.updateUserJson(original.encode().getBytes(StandardCharsets.UTF_8), "password"), StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-512"), is(notNullValue()));
original = new JsonObject().put("version", 1).put("config", new JsonObject().put("SCRAM-SHA-512", "somecredentials").put("SCRAM-SHA-256", "somecredentials"));
- updated = new JsonObject(new String(scramShaCred.updateUserJson(original.encode().getBytes(Charset.defaultCharset()), "password"), Charset.defaultCharset()));
+ updated = new JsonObject(new String(scramShaCred.updateUserJson(original.encode().getBytes(StandardCharsets.UTF_8), "password"), StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-512"), is(notNullValue()));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-256"), is("somecredentials"));
original = new JsonObject().put("version", 1).put("config", new JsonObject());
- updated = new JsonObject(new String(scramShaCred.updateUserJson(original.encode().getBytes(Charset.defaultCharset()), "password"), Charset.defaultCharset()));
+ updated = new JsonObject(new String(scramShaCred.updateUserJson(original.encode().getBytes(StandardCharsets.UTF_8), "password"), StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-512"), is(notNullValue()));
original = new JsonObject().put("version", 1).put("config", new JsonObject().put("SCRAM-SHA-256", "somecredentials"));
- updated = new JsonObject(new String(scramShaCred.updateUserJson(original.encode().getBytes(Charset.defaultCharset()), "password"), Charset.defaultCharset()));
+ updated = new JsonObject(new String(scramShaCred.updateUserJson(original.encode().getBytes(StandardCharsets.UTF_8), "password"), StandardCharsets.UTF_8));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-512"), is(notNullValue()));
assertThat(updated.getJsonObject("config").getString("SCRAM-SHA-256"), is("somecredentials"));
} | ['systemtest/src/test/java/io/strimzi/systemtest/UserST.java', 'user-operator/src/test/java/io/strimzi/operator/user/operator/ScramShaCredentialsTest.java', 'user-operator/src/main/java/io/strimzi/operator/user/operator/ScramShaCredentials.java', 'user-operator/src/test/java/io/strimzi/operator/user/operator/KafkaUserQuotasIT.java', 'user-operator/src/main/java/io/strimzi/operator/user/operator/KafkaUserQuotasOperator.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 2,034,283 | 406,489 | 49,719 | 351 | 2,109 | 406 | 45 | 2 | 411 | 62 | 101 | 3 | 0 | 0 | 2020-01-22T12:20:43 | 3,968 | Java | {'Java': 12877351, 'Shell': 138457, 'Groovy': 36170, 'Makefile': 32136, 'Mustache': 11378, 'Dockerfile': 8089, 'Awk': 514, '1C Enterprise': 272} | Apache License 2.0 |
9,979 | discord-jda/jda/1860/1859 | discord-jda | jda | https://github.com/discord-jda/JDA/issues/1859 | https://github.com/discord-jda/JDA/pull/1860 | https://github.com/discord-jda/JDA/pull/1860 | 1 | closes | Unable to resolve value with key emoji to type unsigned long: `null` | <!--
For questions join the official JDA discord server: https://discord.gg/0hMr4ce0tIl3SLv5
-->
[download]: https://bintray.com/dv8fromtheworld/maven/JDA/_latestVersion
[guild]: https://discord.gg/0hMr4ce0tIk3pSjp
[stack overflow]: https://stackoverflow.com/questions/tagged/java
## General Troubleshooting
<!--
Hey there! Before you report a bug or suggest a new feature,
please make sure to follow these steps first!
-->
- [x] I have checked for similar issues.
- [x] I have updated to the [latest JDA version][download].
- [x] I have checked the branches or the maintainers' PRs for upcoming bug fixes.
<!--
This is not the place to learn Java. Please refer to [StackOverflow][stack overflow]
for your general programming questions.
-->
## Bug Report
<!--
Provide a small description of the bug you are experiencing.
-->
### Expected Behavior
<!--
Tell us what you expect to happen instead.
-->
No exception.
### Exception or Error
```java
[JDA [71 / 132] MainWS-ReadThread] [WebSocketClient]: Got an unexpected Json-parse error. Please redirect the following message to the devs:
JDA 4.3.0_333
Unable to resolve value with key emoji to type unsigned long: null
MESSAGE_REACTION_REMOVE_EMOJI -> {"emoji":{"name":"old_delete_source","id":526232446295998475},"guild_id":guild-id,"message_id":message-id,"channel_id":channel-id}
net.dv8tion.jda.api.exceptions.ParsingException: Unable to resolve value with key emoji to type unsigned long: null
at net.dv8tion.jda.api.utils.data.DataObject.valueError(DataObject.java:807)
at net.dv8tion.jda.api.utils.data.DataObject.getUnsignedLong(DataObject.java:512)
at net.dv8tion.jda.internal.handle.MessageReactionClearEmoteHandler.handleInternally(MessageReactionClearEmoteHandler.java:68)
at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:952)
at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:839)
at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:817)
at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:991)
at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:382)
at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:983)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:746)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)
```
| 64f7a7c5dff92f75609fe8de80322c8cfae546f1 | 310dcf01b3d9dbb93764822b242597c821e281fb | https://github.com/discord-jda/jda/compare/64f7a7c5dff92f75609fe8de80322c8cfae546f1...310dcf01b3d9dbb93764822b242597c821e281fb | diff --git a/src/main/java/net/dv8tion/jda/internal/handle/MessageReactionClearEmoteHandler.java b/src/main/java/net/dv8tion/jda/internal/handle/MessageReactionClearEmoteHandler.java
index 2ef364f3..42c39bff 100644
--- a/src/main/java/net/dv8tion/jda/internal/handle/MessageReactionClearEmoteHandler.java
+++ b/src/main/java/net/dv8tion/jda/internal/handle/MessageReactionClearEmoteHandler.java
@@ -65,7 +65,7 @@ public class MessageReactionClearEmoteHandler extends SocketHandler
}
else
{
- long emoteId = emoji.getUnsignedLong("emoji");
+ long emoteId = emoji.getUnsignedLong("id");
Emote emote = getJDA().getEmoteById(emoteId);
if (emote == null)
{ | ['src/main/java/net/dv8tion/jda/internal/handle/MessageReactionClearEmoteHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,988,122 | 1,136,561 | 135,156 | 669 | 116 | 26 | 2 | 1 | 2,994 | 211 | 726 | 64 | 4 | 1 | 2021-10-07T10:23:45 | 3,830 | Java | {'Java': 6408306, 'Kotlin': 15446, 'HTML': 2425} | Apache License 2.0 |
284 | crate/crate/13311/13306 | crate | crate | https://github.com/crate/crate/issues/13306 | https://github.com/crate/crate/pull/13311 | https://github.com/crate/crate/pull/13311 | 1 | fixes | `DECLARE CURSOR` requires superuser privileges | ### CrateDB version
5.1.1
### CrateDB setup information
local / cloud logged in as non-superuser with `ALL` privileges on `cluster` level
### Steps to Reproduce
```sql
BEGIN;
DECLARE this_cursor NO SCROLL CURSOR FOR SELECT * FROM sys.summits;
END;
```
### Expected Result
Cursor is created
### Actual Result
```
UnauthorizedException[User "admin" is not authorized to execute the statement. Superuser permissions are required]
``` | 570fbd936a92839e0edbc077124a45ea28437f7c | 78a421e2e939fd63ddbe0ced26d6649812517e77 | https://github.com/crate/crate/compare/570fbd936a92839e0edbc077124a45ea28437f7c...78a421e2e939fd63ddbe0ced26d6649812517e77 | diff --git a/server/src/main/java/io/crate/auth/AccessControlImpl.java b/server/src/main/java/io/crate/auth/AccessControlImpl.java
index 8a00969d67..4f5a179573 100644
--- a/server/src/main/java/io/crate/auth/AccessControlImpl.java
+++ b/server/src/main/java/io/crate/auth/AccessControlImpl.java
@@ -46,6 +46,7 @@ import io.crate.analyze.AnalyzedCreateTable;
import io.crate.analyze.AnalyzedCreateTableAs;
import io.crate.analyze.AnalyzedCreateUser;
import io.crate.analyze.AnalyzedDeallocate;
+import io.crate.analyze.AnalyzedDeclare;
import io.crate.analyze.AnalyzedDeleteStatement;
import io.crate.analyze.AnalyzedDiscard;
import io.crate.analyze.AnalyzedDropFunction;
@@ -264,6 +265,12 @@ public final class AccessControlImpl implements AccessControl {
return null;
}
+ @Override
+ public Void visitDeclare(AnalyzedDeclare declare, User user) {
+ declare.query().accept(this, user);
+ return null;
+ }
+
@Override
public Void visitSwapTable(AnalyzedSwapTable swapTable, User user) {
if (!user.hasPrivilege(Privilege.Type.AL, Privilege.Clazz.CLUSTER, null, defaultSchema)) {
diff --git a/server/src/test/java/io/crate/auth/AccessControlMayExecuteTest.java b/server/src/test/java/io/crate/auth/AccessControlMayExecuteTest.java
index db05561b15..878789a202 100644
--- a/server/src/test/java/io/crate/auth/AccessControlMayExecuteTest.java
+++ b/server/src/test/java/io/crate/auth/AccessControlMayExecuteTest.java
@@ -700,4 +700,10 @@ public class AccessControlMayExecuteTest extends CrateDummyClusterServiceUnitTes
analyze("ANALYZE", user);
assertAskedForCluster(Privilege.Type.AL);
}
+
+ @Test
+ public void test_declare_cursor_for_non_super_users() {
+ analyze("DECLARE this_cursor NO SCROLL CURSOR FOR SELECT * FROM sys.summits;", user);
+ assertAskedForTable(Privilege.Type.DQL, "sys.summits");
+ }
} | ['server/src/test/java/io/crate/auth/AccessControlMayExecuteTest.java', 'server/src/main/java/io/crate/auth/AccessControlImpl.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 21,020,514 | 4,131,238 | 528,131 | 3,681 | 220 | 44 | 7 | 1 | 463 | 63 | 105 | 25 | 0 | 2 | 2022-11-29T19:00:33 | 3,729 | Java | {'Java': 32426037, 'Python': 71123, 'ANTLR': 46794, 'Shell': 13730, 'Batchfile': 4343} | Apache License 2.0 |
283 | crate/crate/14430/14407 | crate | crate | https://github.com/crate/crate/issues/14407 | https://github.com/crate/crate/pull/14430 | https://github.com/crate/crate/pull/14430 | 1 | fixes | Filtering on a column with `INDEX OFF` doesn't behave correctly | ### CrateDB version
5.4.0
### Problem description
Filtering on a column with `INDEX OFF` doesn't behave consistently.
### Steps to Reproduce
```
cr> create table t(a int INDEX OFF);
CREATE OK, 1 row affected (0.327 sec)
```
```
cr> select * from t where a = 1;
SQLParseException[Cannot search on field [a] since it is not indexed.]
```
this seems fine, but:
```
cr> select * from t where a > 1;
+---+
| a |
+---+
+---+
SELECT 0 rows in set (0.008 sec)
```
and:
```
cr> insert into t(a) values(2), (3);
INSERT OK, 2 rows affected (0.043 sec)
cr> refresh table t;
REFRESH OK, 1 row affected (0.003 sec)
cr> select * from t where a > 1;
+---+
| a |
+---+
+---+
SELECT 0 rows in set (0.003 sec)
cr> select * from t where a + 1 > 1;
+---+
| a |
+---+
| 3 |
| 2 |
+---+
SELECT 2 rows in set (0.008 sec)
```
| b5a431633404f49606663a724ede749b3203eeb6 | 11c896f00254852744ef79a760141d17692b22cb | https://github.com/crate/crate/compare/b5a431633404f49606663a724ede749b3203eeb6...11c896f00254852744ef79a760141d17692b22cb | diff --git a/server/src/main/java/io/crate/execution/engine/collect/collectors/OptimizeQueryForSearchAfter.java b/server/src/main/java/io/crate/execution/engine/collect/collectors/OptimizeQueryForSearchAfter.java
index c5016973f7..29e5959a94 100644
--- a/server/src/main/java/io/crate/execution/engine/collect/collectors/OptimizeQueryForSearchAfter.java
+++ b/server/src/main/java/io/crate/execution/engine/collect/collectors/OptimizeQueryForSearchAfter.java
@@ -82,20 +82,20 @@ public class OptimizeQueryForSearchAfter implements Function<FieldDoc, Query> {
BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();
booleanQuery.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
if (orderBy.reverseFlags()[i]) {
- booleanQuery.add(eqQuery.rangeQuery(columnName, null, value, false, true, ref.hasDocValues()),
+ booleanQuery.add(eqQuery.rangeQuery(columnName, null, value, false, true, ref.hasDocValues(), ref.indexType()),
BooleanClause.Occur.MUST_NOT);
} else {
- booleanQuery.add(eqQuery.rangeQuery(columnName, value, null, true, false, ref.hasDocValues()),
+ booleanQuery.add(eqQuery.rangeQuery(columnName, value, null, true, false, ref.hasDocValues(), ref.indexType()),
BooleanClause.Occur.MUST_NOT);
}
orderQuery = booleanQuery.build();
} else {
if (orderBy.reverseFlags()[i]) {
orderQuery = eqQuery.rangeQuery(
- columnName, value, null, false, false, ref.hasDocValues());
+ columnName, value, null, false, false, ref.hasDocValues(), ref.indexType());
} else {
orderQuery = eqQuery.rangeQuery(
- columnName, null, value, false, false, ref.hasDocValues());
+ columnName, null, value, false, false, ref.hasDocValues(), ref.indexType());
}
}
queryBuilder.add(orderQuery, BooleanClause.Occur.MUST);
diff --git a/server/src/main/java/io/crate/expression/operator/CmpOperator.java b/server/src/main/java/io/crate/expression/operator/CmpOperator.java
index 3882583e5b..172ee7b94d 100644
--- a/server/src/main/java/io/crate/expression/operator/CmpOperator.java
+++ b/server/src/main/java/io/crate/expression/operator/CmpOperator.java
@@ -94,13 +94,13 @@ public final class CmpOperator extends Operator<Object> {
String field = ref.column().fqn();
return switch (functionName) {
case GtOperator.NAME -> eqQuery.rangeQuery(
- field, value, null, false, false, ref.hasDocValues());
+ field, value, null, false, false, ref.hasDocValues(), ref.indexType());
case GteOperator.NAME -> eqQuery.rangeQuery(
- field, value, null, true, false, ref.hasDocValues());
+ field, value, null, true, false, ref.hasDocValues(), ref.indexType());
case LtOperator.NAME ->
- eqQuery.rangeQuery(field, null, value, false, false, ref.hasDocValues());
+ eqQuery.rangeQuery(field, null, value, false, false, ref.hasDocValues(), ref.indexType());
case LteOperator.NAME ->
- eqQuery.rangeQuery(field, null, value, false, true, ref.hasDocValues());
+ eqQuery.rangeQuery(field, null, value, false, true, ref.hasDocValues(), ref.indexType());
default -> throw new IllegalArgumentException(functionName + " is not a supported comparison operator");
};
}
diff --git a/server/src/main/java/io/crate/expression/operator/EqOperator.java b/server/src/main/java/io/crate/expression/operator/EqOperator.java
index 66b04f1f7b..7b12193ccf 100644
--- a/server/src/main/java/io/crate/expression/operator/EqOperator.java
+++ b/server/src/main/java/io/crate/expression/operator/EqOperator.java
@@ -56,7 +56,6 @@ import io.crate.expression.scalar.NumTermsPerDocQuery;
import io.crate.expression.symbol.Function;
import io.crate.expression.symbol.Literal;
import io.crate.expression.symbol.Symbol;
-import io.crate.lucene.LuceneQueryBuilder;
import io.crate.lucene.LuceneQueryBuilder.Context;
import io.crate.metadata.IndexType;
import io.crate.metadata.NodeContext;
@@ -147,26 +146,30 @@ public final class EqOperator extends Operator<Object> {
return new MatchNoDocsQuery("`" + fqn + "` = null is always null");
}
DataType<?> dataType = ref.valueType();
- if (dataType.id() != ObjectType.ID && dataType.id() != ArrayType.ID && ref.indexType() == IndexType.NONE) {
- throw new IllegalArgumentException(
- "Cannot search on field [" + fqn + "] since it is not indexed.");
- }
return switch (dataType.id()) {
- case ObjectType.ID -> refEqObject(function, fqn, (ObjectType) dataType, (Map<String, Object>) value, context);
- case ArrayType.ID -> termsAndGenericFilter(
+ case ObjectType.ID -> refEqObject(
+ function,
+ fqn,
+ (ObjectType) dataType,
+ (Map<String, Object>) value,
+ context,
+ ref.hasDocValues(),
+ ref.indexType());
+ case ArrayType.ID -> refEqArray(
function,
ref.column().fqn(),
ArrayType.unnest(dataType),
(Collection<?>) value,
- context
- );
- default -> fromPrimitive(dataType, fqn, value);
+ context,
+ ref.hasDocValues(),
+ ref.indexType());
+ default -> fromPrimitive(dataType, fqn, value, ref.hasDocValues(), ref.indexType());
};
}
@Nullable
@SuppressWarnings("unchecked")
- public static Query termsQuery(String column, DataType<?> type, Collection<?> values) {
+ public static Query termsQuery(String column, DataType<?> type, Collection<?> values, boolean hasDocValues, IndexType indexType) {
List<?> nonNullValues = values.stream().filter(Objects::nonNull).toList();
if (nonNullValues.isEmpty()) {
return null;
@@ -193,20 +196,29 @@ public final class EqOperator extends Operator<Object> {
column,
nonNullValues.stream().map(x -> new BytesRef(((BitString) x).bitSet().toByteArray())).toList()
);
- default -> booleanShould(column, type, nonNullValues);
+ default -> booleanShould(column, type, nonNullValues, hasDocValues, indexType);
};
}
@Nullable
- private static Query booleanShould(String column, DataType<?> type, Collection<?> values) {
+ private static Query booleanShould(String column,
+ DataType<?> type,
+ Collection<?> values,
+ boolean hasDocValues,
+ IndexType indexType) {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
for (var term : values) {
- builder.add(EqOperator.fromPrimitive(type, column, term), Occur.SHOULD);
+ builder.add(EqOperator.fromPrimitive(type, column, term, hasDocValues, indexType), Occur.SHOULD);
}
return new ConstantScoreQuery(builder.build());
}
- private static Query termsAndGenericFilter(Function function, String column, DataType<?> elementType, Collection<?> values, LuceneQueryBuilder.Context context) {
+ private static Query refEqArray(Function function,
+ String column,
+ DataType<?> elementType, Collection<?> values,
+ Context context,
+ boolean hasDocValues,
+ IndexType indexType) {
MappedFieldType fieldType = context.getFieldTypeOrNull(column);
if (fieldType == null) {
if (elementType.id() == ObjectType.ID) {
@@ -237,7 +249,7 @@ public final class EqOperator extends Operator<Object> {
// wrap boolTermsFilter and genericFunction filter in an additional BooleanFilter to control the ordering of the filters
// termsFilter is applied first
// afterwards the more expensive genericFunctionFilter
- Query termsQuery = termsQuery(column, elementType, values);
+ Query termsQuery = termsQuery(column, elementType, values, hasDocValues, indexType);
if (termsQuery == null) {
return genericFunctionFilter;
}
@@ -248,7 +260,7 @@ public final class EqOperator extends Operator<Object> {
}
@SuppressWarnings("unchecked")
- public static Query fromPrimitive(DataType<?> type, String column, Object value) {
+ public static Query fromPrimitive(DataType<?> type, String column, Object value, boolean hasDocValues, IndexType indexType) {
if (column.equals(DocSysColumns.ID.name())) {
return new TermQuery(new Term(column, Uid.encodeId((String) value)));
}
@@ -257,7 +269,7 @@ public final class EqOperator extends Operator<Object> {
if (eqQuery == null) {
return null;
}
- return ((EqQuery<Object>) eqQuery).termQuery(column, value);
+ return ((EqQuery<Object>) eqQuery).termQuery(column, value, hasDocValues, indexType);
}
/**
@@ -279,7 +291,9 @@ public final class EqOperator extends Operator<Object> {
String fqn,
ObjectType type,
Map<String, Object> value,
- LuceneQueryBuilder.Context context) {
+ Context context,
+ boolean hasDocValues,
+ IndexType indexType) {
BooleanQuery.Builder boolBuilder = new BooleanQuery.Builder();
int preFilters = 0;
for (Map.Entry<String, Object> entry : value.entrySet()) {
@@ -292,9 +306,10 @@ public final class EqOperator extends Operator<Object> {
String fqNestedColumn = fqn + '.' + key;
Query innerQuery;
if (DataTypes.isArray(innerType)) {
- innerQuery = termsAndGenericFilter(eq, fqNestedColumn, innerType, (Collection<?>) entry.getValue(), context);
+ innerQuery = refEqArray(
+ eq, fqNestedColumn, innerType, (Collection<?>) entry.getValue(), context, hasDocValues, indexType);
} else {
- innerQuery = fromPrimitive(innerType, fqNestedColumn, entry.getValue());
+ innerQuery = fromPrimitive(innerType, fqNestedColumn, entry.getValue(), hasDocValues, indexType);
}
if (innerQuery == null) {
continue;
diff --git a/server/src/main/java/io/crate/expression/operator/any/AnyEqOperator.java b/server/src/main/java/io/crate/expression/operator/any/AnyEqOperator.java
index 215f6a8da8..5103fdcdfe 100644
--- a/server/src/main/java/io/crate/expression/operator/any/AnyEqOperator.java
+++ b/server/src/main/java/io/crate/expression/operator/any/AnyEqOperator.java
@@ -68,7 +68,7 @@ public final class AnyEqOperator extends AnyOperator {
return new MatchNoDocsQuery("column does not exist in this index");
}
DataType<?> innerType = ArrayType.unnest(probe.valueType());
- return EqOperator.termsQuery(columnName, innerType, values);
+ return EqOperator.termsQuery(columnName, innerType, values, probe.hasDocValues(), probe.indexType());
}
@Override
@@ -85,7 +85,12 @@ public final class AnyEqOperator extends AnyOperator {
// [1, 2] = any(nested_array_ref)
return arrayLiteralEqAnyArray(any, candidates, probe.value(), context);
}
- return EqOperator.fromPrimitive(ArrayType.unnest(candidates.valueType()), candidates.column().fqn(), probe.value());
+ return EqOperator.fromPrimitive(
+ ArrayType.unnest(candidates.valueType()),
+ candidates.column().fqn(),
+ probe.value(),
+ candidates.hasDocValues(),
+ candidates.indexType());
}
private static Query arrayLiteralEqAnyArray(Function function,
@@ -97,8 +102,9 @@ public final class AnyEqOperator extends AnyOperator {
Query termsQuery = EqOperator.termsQuery(
candidates.column().fqn(),
ArrayType.unnest(candidates.valueType()),
- terms
- );
+ terms,
+ candidates.hasDocValues(),
+ candidates.indexType());
Query genericFunctionFilter = LuceneQueryBuilder.genericFunctionFilter(function, context);
if (termsQuery == null) {
return genericFunctionFilter;
diff --git a/server/src/main/java/io/crate/expression/operator/any/AnyNeqOperator.java b/server/src/main/java/io/crate/expression/operator/any/AnyNeqOperator.java
index 94bc967a96..e3fba3f4e4 100644
--- a/server/src/main/java/io/crate/expression/operator/any/AnyNeqOperator.java
+++ b/server/src/main/java/io/crate/expression/operator/any/AnyNeqOperator.java
@@ -65,7 +65,14 @@ public final class AnyNeqOperator extends AnyOperator {
BooleanQuery.Builder andBuilder = new BooleanQuery.Builder();
for (Object value : (Iterable<?>) candidates.value()) {
- andBuilder.add(EqOperator.fromPrimitive(probe.valueType(), probe.column().fqn(), value), BooleanClause.Occur.MUST);
+ andBuilder.add(
+ EqOperator.fromPrimitive(
+ probe.valueType(),
+ probe.column().fqn(),
+ value,
+ probe.hasDocValues(),
+ probe.indexType()),
+ BooleanClause.Occur.MUST);
}
Query exists = IsNullPredicate.refExistsQuery(probe, context, false);
return new BooleanQuery.Builder()
@@ -96,11 +103,11 @@ public final class AnyNeqOperator extends AnyOperator {
BooleanQuery.Builder query = new BooleanQuery.Builder();
query.setMinimumNumberShouldMatch(1);
query.add(
- eqQuery.rangeQuery(columnName, value, null, false, false, candidates.hasDocValues()),
+ eqQuery.rangeQuery(columnName, value, null, false, false, candidates.hasDocValues(), candidates.indexType()),
BooleanClause.Occur.SHOULD
);
query.add(
- eqQuery.rangeQuery(columnName, null, value, false, false, candidates.hasDocValues()),
+ eqQuery.rangeQuery(columnName, null, value, false, false, candidates.hasDocValues(), candidates.indexType()),
BooleanClause.Occur.SHOULD
);
return query.build();
diff --git a/server/src/main/java/io/crate/expression/scalar/SubscriptFunction.java b/server/src/main/java/io/crate/expression/scalar/SubscriptFunction.java
index ef31afd33e..d1da2a14f1 100644
--- a/server/src/main/java/io/crate/expression/scalar/SubscriptFunction.java
+++ b/server/src/main/java/io/crate/expression/scalar/SubscriptFunction.java
@@ -47,6 +47,7 @@ import io.crate.expression.symbol.Literal;
import io.crate.expression.symbol.Symbol;
import io.crate.lucene.LuceneQueryBuilder;
import io.crate.lucene.LuceneQueryBuilder.Context;
+import io.crate.metadata.IndexType;
import io.crate.metadata.NodeContext;
import io.crate.metadata.Reference;
import io.crate.metadata.Scalar;
@@ -224,19 +225,19 @@ public class SubscriptFunction extends Scalar<Object, Object[]> {
}
private interface PreFilterQueryBuilder {
- Query buildQuery(String field, EqQuery<Object> eqQuery, Object value, boolean hasDocValues);
+ Query buildQuery(String field, EqQuery<Object> eqQuery, Object value, boolean hasDocValues, IndexType indexType);
}
private static final Map<String, PreFilterQueryBuilder> PRE_FILTER_QUERY_BUILDER_BY_OP = Map.of(
- EqOperator.NAME, (field, eqQuery, value, haDocValues) -> eqQuery.termQuery(field, value),
- GteOperator.NAME, (field, eqQuery, value, hasDocValues) ->
- eqQuery.rangeQuery(field, value, null, true, false, hasDocValues),
- GtOperator.NAME, (field, eqQuery, value, hasDocValues) ->
- eqQuery.rangeQuery(field, value, null, false, false, hasDocValues),
- LteOperator.NAME, (field, eqQuery, value, hasDocValues) ->
- eqQuery.rangeQuery(field, null, value, false, true, hasDocValues),
- LtOperator.NAME, (field, eqQuery, value, hasDocValues) ->
- eqQuery.rangeQuery(field, null, value, false, false, hasDocValues)
+ EqOperator.NAME, (field, eqQuery, value, haDocValues, indexType) -> eqQuery.termQuery(field, value, haDocValues, indexType),
+ GteOperator.NAME, (field, eqQuery, value, hasDocValues, indexType) ->
+ eqQuery.rangeQuery(field, value, null, true, false, hasDocValues, indexType),
+ GtOperator.NAME, (field, eqQuery, value, hasDocValues, indexType) ->
+ eqQuery.rangeQuery(field, value, null, false, false, hasDocValues, indexType),
+ LteOperator.NAME, (field, eqQuery, value, hasDocValues, indexType) ->
+ eqQuery.rangeQuery(field, null, value, false, true, hasDocValues, indexType),
+ LtOperator.NAME, (field, eqQuery, value, hasDocValues, indexType) ->
+ eqQuery.rangeQuery(field, null, value, false, false, hasDocValues, indexType)
);
@Override
@@ -271,7 +272,7 @@ public class SubscriptFunction extends Scalar<Object, Object[]> {
}
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(
- preFilterQueryBuilder.buildQuery(ref.column().fqn(), eqQuery, cmpLiteral.value(), ref.hasDocValues()),
+ preFilterQueryBuilder.buildQuery(ref.column().fqn(), eqQuery, cmpLiteral.value(), ref.hasDocValues(), ref.indexType()),
BooleanClause.Occur.MUST);
builder.add(LuceneQueryBuilder.genericFunctionFilter(parent, context), BooleanClause.Occur.FILTER);
return builder.build();
diff --git a/server/src/main/java/io/crate/types/BitStringType.java b/server/src/main/java/io/crate/types/BitStringType.java
index f6e5d69d60..8c3c2e9636 100644
--- a/server/src/main/java/io/crate/types/BitStringType.java
+++ b/server/src/main/java/io/crate/types/BitStringType.java
@@ -29,6 +29,7 @@ import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
+import org.apache.lucene.document.SortedSetDocValuesField;
import org.jetbrains.annotations.Nullable;
import org.apache.lucene.document.FieldType;
@@ -45,6 +46,7 @@ import io.crate.Streamer;
import io.crate.execution.dml.BitStringIndexer;
import io.crate.execution.dml.ValueIndexer;
import io.crate.metadata.ColumnIdent;
+import io.crate.metadata.IndexType;
import io.crate.metadata.Reference;
import io.crate.metadata.RelationName;
import io.crate.metadata.settings.SessionSettings;
@@ -69,7 +71,10 @@ public final class BitStringType extends DataType<BitString> implements Streamer
new EqQuery<BitString>() {
@Override
- public Query termQuery(String field, BitString value) {
+ public Query termQuery(String field, BitString value, boolean hasDocValues, IndexType indexType) {
+ if (hasDocValues) {
+ return SortedSetDocValuesField.newSlowExactQuery(field, new BytesRef(value.bitSet().toByteArray()));
+ }
return new TermQuery(new Term(field, new BytesRef(value.bitSet().toByteArray())));
}
@@ -79,7 +84,11 @@ public final class BitStringType extends DataType<BitString> implements Streamer
BitString upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
+ boolean hasDocValues,
+ IndexType indexType) {
+ // TODO: this should be a bug:
+ // select * from t where a > b'001';
+ // => UnsupportedFunctionException[Unknown function: (doc.t.a > B'001')
return null;
}
}
diff --git a/server/src/main/java/io/crate/types/BooleanType.java b/server/src/main/java/io/crate/types/BooleanType.java
index 2c2d0095ee..7618ab5ad4 100644
--- a/server/src/main/java/io/crate/types/BooleanType.java
+++ b/server/src/main/java/io/crate/types/BooleanType.java
@@ -27,6 +27,7 @@ import java.util.Map;
import java.util.function.Function;
import org.apache.lucene.document.FieldType;
+import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
@@ -39,6 +40,7 @@ import io.crate.Streamer;
import io.crate.execution.dml.BooleanIndexer;
import io.crate.execution.dml.ValueIndexer;
import io.crate.metadata.ColumnIdent;
+import io.crate.metadata.IndexType;
import io.crate.metadata.Reference;
import io.crate.metadata.RelationName;
@@ -57,7 +59,13 @@ public class BooleanType extends DataType<Boolean> implements Streamer<Boolean>,
}
@Override
- public Query termQuery(String field, Boolean value) {
+ public Query termQuery(String field, Boolean value, boolean hasDocValues, IndexType indexType) {
+ assert value != null: "Cannot perform = NULL, IS NULL should be used";
+ if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowExactQuery(
+ field,
+ value ? 1 : 0);
+ }
return new TermQuery(new Term(field, indexedValue(value)));
}
@@ -67,7 +75,17 @@ public class BooleanType extends DataType<Boolean> implements Streamer<Boolean>,
Boolean upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
+ boolean hasDocValues,
+ IndexType indexType) {
+ if (hasDocValues) {
+ if (lowerTerm == null || upperTerm == null) {
+ return null;
+ }
+ return SortedNumericDocValuesField.newSlowRangeQuery(
+ field,
+ lowerTerm ? 1 : 0,
+ upperTerm ? 1 : 0);
+ }
return new TermRangeQuery(
field, indexedValue(lowerTerm), indexedValue(upperTerm), includeLower, includeUpper);
}
diff --git a/server/src/main/java/io/crate/types/DoubleType.java b/server/src/main/java/io/crate/types/DoubleType.java
index dc6f32d4da..e3b652889d 100644
--- a/server/src/main/java/io/crate/types/DoubleType.java
+++ b/server/src/main/java/io/crate/types/DoubleType.java
@@ -26,10 +26,10 @@ import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.function.Function;
+import org.apache.lucene.document.DoubleField;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.SortedNumericDocValuesField;
-import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.util.RamUsageEstimator;
@@ -40,6 +40,7 @@ import io.crate.Streamer;
import io.crate.execution.dml.DoubleIndexer;
import io.crate.execution.dml.ValueIndexer;
import io.crate.metadata.ColumnIdent;
+import io.crate.metadata.IndexType;
import io.crate.metadata.Reference;
import io.crate.metadata.RelationName;
@@ -55,8 +56,16 @@ public class DoubleType extends DataType<Double> implements FixedWidthType, Stre
new EqQuery<Double>() {
@Override
- public Query termQuery(String field, Double value) {
- return DoublePoint.newExactQuery(field, value);
+ public Query termQuery(String field, Double value, boolean hasDocValues, IndexType indexType) {
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return DoubleField.newExactQuery(field, value);
+ } else if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowExactQuery(field, NumericUtils.doubleToSortableLong(value));
+ } else if (isIndexed) {
+ return DoublePoint.newExactQuery(field, value);
+ }
+ return null;
}
@Override
@@ -65,7 +74,8 @@ public class DoubleType extends DataType<Double> implements FixedWidthType, Stre
Double upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
+ boolean hasDocValues,
+ IndexType indexType) {
double lower;
if (lowerTerm == null) {
lower = Double.NEGATIVE_INFINITY;
@@ -79,16 +89,18 @@ public class DoubleType extends DataType<Double> implements FixedWidthType, Stre
} else {
upper = includeUpper ? upperTerm : DoublePoint.nextDown(upperTerm);
}
- Query indexQuery = DoublePoint.newRangeQuery(field, lower, upper);
- if (hasDocValues) {
- Query dvQuery = SortedNumericDocValuesField.newSlowRangeQuery(
- field,
- NumericUtils.doubleToSortableLong(lower),
- NumericUtils.doubleToSortableLong(upper)
- );
- return new IndexOrDocValuesQuery(indexQuery, dvQuery);
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return DoubleField.newRangeQuery(field, lower, upper);
+ } else if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowRangeQuery(
+ field,
+ NumericUtils.doubleToSortableLong(lower),
+ NumericUtils.doubleToSortableLong(upper));
+ } else if (isIndexed) {
+ return DoublePoint.newRangeQuery(field, lower, upper);
}
- return indexQuery;
+ return null;
}
}
) {
diff --git a/server/src/main/java/io/crate/types/EqQuery.java b/server/src/main/java/io/crate/types/EqQuery.java
index 8cca9c0883..5e446b888f 100644
--- a/server/src/main/java/io/crate/types/EqQuery.java
+++ b/server/src/main/java/io/crate/types/EqQuery.java
@@ -23,17 +23,20 @@ package io.crate.types;
import org.apache.lucene.search.Query;
+import io.crate.metadata.IndexType;
+
/**
* For types which can be stored in Lucene and support optimized equality related queries
**/
public interface EqQuery<T> {
- Query termQuery(String field, T value);
+ Query termQuery(String field, T value, boolean hasDocValues, IndexType indexType);
Query rangeQuery(String field,
T lowerTerm,
T upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues);
+ boolean hasDocValues,
+ IndexType indexType);
}
diff --git a/server/src/main/java/io/crate/types/FloatType.java b/server/src/main/java/io/crate/types/FloatType.java
index c91ece1ca5..c8acb0c7fd 100644
--- a/server/src/main/java/io/crate/types/FloatType.java
+++ b/server/src/main/java/io/crate/types/FloatType.java
@@ -27,9 +27,9 @@ import java.math.BigInteger;
import java.util.function.Function;
import org.apache.lucene.document.FieldType;
+import org.apache.lucene.document.FloatField;
import org.apache.lucene.document.FloatPoint;
import org.apache.lucene.document.SortedNumericDocValuesField;
-import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.util.RamUsageEstimator;
@@ -40,6 +40,7 @@ import io.crate.Streamer;
import io.crate.execution.dml.FloatIndexer;
import io.crate.execution.dml.ValueIndexer;
import io.crate.metadata.ColumnIdent;
+import io.crate.metadata.IndexType;
import io.crate.metadata.Reference;
import io.crate.metadata.RelationName;
@@ -55,8 +56,16 @@ public class FloatType extends DataType<Float> implements Streamer<Float>, Fixed
new EqQuery<Float>() {
@Override
- public Query termQuery(String field, Float value) {
- return FloatPoint.newExactQuery(field, value);
+ public Query termQuery(String field, Float value, boolean hasDocValues, IndexType indexType) {
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return FloatField.newExactQuery(field, value);
+ } else if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowExactQuery(field, NumericUtils.floatToSortableInt(value));
+ } else if (isIndexed) {
+ return FloatPoint.newExactQuery(field, value);
+ }
+ return null;
}
@Override
@@ -65,7 +74,8 @@ public class FloatType extends DataType<Float> implements Streamer<Float>, Fixed
Float upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
+ boolean hasDocValues,
+ IndexType indexType) {
float lower;
if (lowerTerm == null) {
lower = Float.NEGATIVE_INFINITY;
@@ -79,16 +89,18 @@ public class FloatType extends DataType<Float> implements Streamer<Float>, Fixed
} else {
upper = includeUpper ? upperTerm : FloatPoint.nextDown(upperTerm);
}
-
- Query indexQuery = FloatPoint.newRangeQuery(field, lower, upper);
- if (hasDocValues) {
- Query dvQuery = SortedNumericDocValuesField
- .newSlowRangeQuery(field,
- NumericUtils.floatToSortableInt(lower),
- NumericUtils.floatToSortableInt(upper));
- return new IndexOrDocValuesQuery(indexQuery, dvQuery);
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return FloatField.newRangeQuery(field, lower, upper);
+ } else if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowRangeQuery(
+ field,
+ NumericUtils.floatToSortableInt(lower),
+ NumericUtils.floatToSortableInt(upper));
+ } else if (isIndexed) {
+ return FloatPoint.newRangeQuery(field, lower, upper);
}
- return indexQuery;
+ return null;
}
}
) {
diff --git a/server/src/main/java/io/crate/types/FloatVectorType.java b/server/src/main/java/io/crate/types/FloatVectorType.java
index e8005f0b49..6179bab481 100644
--- a/server/src/main/java/io/crate/types/FloatVectorType.java
+++ b/server/src/main/java/io/crate/types/FloatVectorType.java
@@ -40,6 +40,7 @@ import io.crate.Streamer;
import io.crate.execution.dml.FloatVectorIndexer;
import io.crate.execution.dml.ValueIndexer;
import io.crate.metadata.ColumnIdent;
+import io.crate.metadata.IndexType;
import io.crate.metadata.Reference;
import io.crate.metadata.RelationName;
import io.crate.sql.tree.ColumnDefinition;
@@ -57,7 +58,7 @@ public class FloatVectorType extends DataType<float[]> implements Streamer<float
private static final EqQuery<float[]> EQ_QUERY = new EqQuery<float[]>() {
@Override
- public Query termQuery(String field, float[] value) {
+ public Query termQuery(String field, float[] value, boolean hasDocValues, IndexType indexType) {
return null;
}
@@ -67,7 +68,8 @@ public class FloatVectorType extends DataType<float[]> implements Streamer<float
float[] upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
+ boolean hasDocValues,
+ IndexType indexType) {
return null;
}
};
diff --git a/server/src/main/java/io/crate/types/IntEqQuery.java b/server/src/main/java/io/crate/types/IntEqQuery.java
index 834aa49db3..585430857f 100644
--- a/server/src/main/java/io/crate/types/IntEqQuery.java
+++ b/server/src/main/java/io/crate/types/IntEqQuery.java
@@ -21,16 +21,26 @@
package io.crate.types;
+import org.apache.lucene.document.IntField;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.document.SortedNumericDocValuesField;
-import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.Query;
+import io.crate.metadata.IndexType;
+
public class IntEqQuery implements EqQuery<Number> {
@Override
- public Query termQuery(String field, Number value) {
- return IntPoint.newExactQuery(field, value.intValue());
+ public Query termQuery(String field, Number value, boolean hasDocValues, IndexType indexType) {
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return IntField.newExactQuery(field, value.intValue());
+ } else if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowExactQuery(field, value.intValue());
+ } else if (isIndexed) {
+ return IntPoint.newExactQuery(field, value.intValue());
+ }
+ return null;
}
@Override
@@ -39,7 +49,8 @@ public class IntEqQuery implements EqQuery<Number> {
Number upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
+ boolean hasDocValues,
+ IndexType indexType) {
int lower = Integer.MIN_VALUE;
if (lowerTerm != null) {
lower = includeLower ? lowerTerm.intValue() : lowerTerm.intValue() + 1;
@@ -48,11 +59,14 @@ public class IntEqQuery implements EqQuery<Number> {
if (upperTerm != null) {
upper = includeUpper ? upperTerm.intValue() : upperTerm.intValue() - 1;
}
- Query indexquery = IntPoint.newRangeQuery(field, lower, upper);
- if (hasDocValues) {
- return new IndexOrDocValuesQuery(
- indexquery, SortedNumericDocValuesField.newSlowRangeQuery(field, lower, upper));
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return IntField.newRangeQuery(field, lower, upper);
+ } else if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowRangeQuery(field, lower, upper);
+ } else if (isIndexed) {
+ return IntPoint.newRangeQuery(field, lower, upper);
}
- return indexquery;
+ return null;
}
}
diff --git a/server/src/main/java/io/crate/types/IpType.java b/server/src/main/java/io/crate/types/IpType.java
index eafca8ef2f..d40534a7c9 100644
--- a/server/src/main/java/io/crate/types/IpType.java
+++ b/server/src/main/java/io/crate/types/IpType.java
@@ -27,7 +27,10 @@ import java.util.function.Function;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.InetAddressPoint;
+import org.apache.lucene.document.SortedSetDocValuesField;
+import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.Query;
+import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
@@ -37,6 +40,7 @@ import io.crate.Streamer;
import io.crate.execution.dml.IpIndexer;
import io.crate.execution.dml.ValueIndexer;
import io.crate.metadata.ColumnIdent;
+import io.crate.metadata.IndexType;
import io.crate.metadata.Reference;
import io.crate.metadata.RelationName;
@@ -51,8 +55,19 @@ public class IpType extends DataType<String> implements Streamer<String> {
new EqQuery<String>() {
@Override
- public Query termQuery(String field, String value) {
- return InetAddressPoint.newExactQuery(field, InetAddresses.forString(value));
+ public Query termQuery(String field, String value, boolean hasDocValues, IndexType indexType) {
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return new IndexOrDocValuesQuery(
+ InetAddressPoint.newExactQuery(field, InetAddresses.forString(value)),
+ SortedSetDocValuesField.newSlowExactQuery(field, new BytesRef(InetAddressPoint.encode(InetAddresses.forString(value))))
+ );
+ } else if (hasDocValues) {
+ return SortedSetDocValuesField.newSlowExactQuery(field, new BytesRef(InetAddressPoint.encode(InetAddresses.forString(value))));
+ } else if (isIndexed) {
+ return InetAddressPoint.newExactQuery(field, InetAddresses.forString(value));
+ }
+ return null;
}
@Override
@@ -61,7 +76,8 @@ public class IpType extends DataType<String> implements Streamer<String> {
String upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
+ boolean hasDocValues,
+ IndexType indexType) {
InetAddress lower;
if (lowerTerm == null) {
lower = InetAddressPoint.MIN_VALUE;
@@ -69,6 +85,7 @@ public class IpType extends DataType<String> implements Streamer<String> {
var lowerAddress = InetAddresses.forString(lowerTerm);
lower = includeLower ? lowerAddress : InetAddressPoint.nextUp(lowerAddress);
}
+ includeLower = true; // lowerAddress has been adjusted
InetAddress upper;
if (upperTerm == null) {
@@ -77,8 +94,29 @@ public class IpType extends DataType<String> implements Streamer<String> {
var upperAddress = InetAddresses.forString(upperTerm);
upper = includeUpper ? upperAddress : InetAddressPoint.nextDown(upperAddress);
}
-
- return InetAddressPoint.newRangeQuery(field, lower, upper);
+ includeUpper = true; // upperAddress has been adjusted
+
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return new IndexOrDocValuesQuery(
+ InetAddressPoint.newRangeQuery(field, lower, upper),
+ SortedSetDocValuesField.newSlowRangeQuery(
+ field,
+ new BytesRef(InetAddressPoint.encode(lower)),
+ new BytesRef(InetAddressPoint.encode(upper)),
+ includeLower,
+ includeUpper));
+ } else if (hasDocValues) {
+ return SortedSetDocValuesField.newSlowRangeQuery(
+ field,
+ new BytesRef(InetAddressPoint.encode(lower)),
+ new BytesRef(InetAddressPoint.encode(upper)),
+ includeLower,
+ includeUpper);
+ } else if (isIndexed) {
+ return InetAddressPoint.newRangeQuery(field, lower, upper);
+ }
+ return null;
}
}
) {
diff --git a/server/src/main/java/io/crate/types/LongEqQuery.java b/server/src/main/java/io/crate/types/LongEqQuery.java
index 83904b5880..bc690f12aa 100644
--- a/server/src/main/java/io/crate/types/LongEqQuery.java
+++ b/server/src/main/java/io/crate/types/LongEqQuery.java
@@ -21,16 +21,26 @@
package io.crate.types;
+import org.apache.lucene.document.LongField;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.SortedNumericDocValuesField;
-import org.apache.lucene.search.IndexOrDocValuesQuery;
import org.apache.lucene.search.Query;
+import io.crate.metadata.IndexType;
+
public class LongEqQuery implements EqQuery<Long> {
@Override
- public Query termQuery(String field, Long value) {
- return LongPoint.newExactQuery(field, value);
+ public Query termQuery(String field, Long value, boolean hasDocValues, IndexType indexType) {
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return LongField.newExactQuery(field, value);
+ } else if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowExactQuery(field, value);
+ } else if (isIndexed) {
+ return LongPoint.newExactQuery(field, value);
+ }
+ return null;
}
@Override
@@ -39,18 +49,22 @@ public class LongEqQuery implements EqQuery<Long> {
Long upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
+ boolean hasDocValues,
+ IndexType indexType) {
long lower = lowerTerm == null
? Long.MIN_VALUE
: (includeLower ? lowerTerm : lowerTerm + 1);
long upper = upperTerm == null
? Long.MAX_VALUE
: (includeUpper ? upperTerm : upperTerm - 1);
- Query indexQuery = LongPoint.newRangeQuery(field, lower, upper);
- if (hasDocValues) {
- return new IndexOrDocValuesQuery(indexQuery,
- SortedNumericDocValuesField.newSlowRangeQuery(field, lower, upper));
+ boolean isIndexed = indexType != IndexType.NONE;
+ if (hasDocValues && isIndexed) {
+ return LongField.newRangeQuery(field, lower, upper);
+ } else if (hasDocValues) {
+ return SortedNumericDocValuesField.newSlowRangeQuery(field, lower, upper);
+ } else if (isIndexed) {
+ return LongPoint.newRangeQuery(field, lower, upper);
}
- return indexQuery;
+ return null;
}
}
diff --git a/server/src/main/java/io/crate/types/StringType.java b/server/src/main/java/io/crate/types/StringType.java
index 2c3ffde4b9..c510290a34 100644
--- a/server/src/main/java/io/crate/types/StringType.java
+++ b/server/src/main/java/io/crate/types/StringType.java
@@ -33,6 +33,7 @@ import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
+import org.apache.lucene.document.SortedSetDocValuesField;
import org.jetbrains.annotations.Nullable;
import org.apache.lucene.document.FieldType;
@@ -55,6 +56,7 @@ import io.crate.execution.dml.FulltextIndexer;
import io.crate.execution.dml.StringIndexer;
import io.crate.execution.dml.ValueIndexer;
import io.crate.metadata.ColumnIdent;
+import io.crate.metadata.IndexType;
import io.crate.metadata.Reference;
import io.crate.metadata.RelationName;
import io.crate.metadata.settings.SessionSettings;
@@ -78,8 +80,14 @@ public class StringType extends DataType<String> implements Streamer<String> {
new EqQuery<Object>() {
@Override
- public Query termQuery(String field, Object value) {
- return new TermQuery(new Term(field, BytesRefs.toBytesRef(value)));
+ public Query termQuery(String field, Object value, boolean hasDocValues, IndexType indexType) {
+ if (indexType == IndexType.PLAIN && hasDocValues) {
+ return SortedSetDocValuesField.newSlowExactQuery(field, BytesRefs.toBytesRef(value));
+ } else if (indexType != IndexType.NONE) {
+ return new TermQuery(new Term(field, BytesRefs.toBytesRef(value)));
+ } else {
+ return null;
+ }
}
@Override
@@ -88,14 +96,27 @@ public class StringType extends DataType<String> implements Streamer<String> {
Object upperTerm,
boolean includeLower,
boolean includeUpper,
- boolean hasDocValues) {
- return new TermRangeQuery(
- field,
- BytesRefs.toBytesRef(lowerTerm),
- BytesRefs.toBytesRef(upperTerm),
- includeLower,
- includeUpper
- );
+ boolean hasDocValues,
+ IndexType indexType) {
+ if (indexType == IndexType.PLAIN && hasDocValues) {
+ return SortedSetDocValuesField.newSlowRangeQuery(
+ field,
+ BytesRefs.toBytesRef(lowerTerm),
+ BytesRefs.toBytesRef(upperTerm),
+ includeLower,
+ includeUpper
+ );
+ } else if (indexType != null && upperTerm != null && lowerTerm != null) {
+ return new TermRangeQuery(
+ field,
+ BytesRefs.toBytesRef(lowerTerm),
+ BytesRefs.toBytesRef(upperTerm),
+ includeLower,
+ includeUpper
+ );
+ } else {
+ return null;
+ }
}
}
) {
diff --git a/server/src/test/java/io/crate/expression/operator/EqOperatorTest.java b/server/src/test/java/io/crate/expression/operator/EqOperatorTest.java
index 8e6ea65274..071e36ac2e 100644
--- a/server/src/test/java/io/crate/expression/operator/EqOperatorTest.java
+++ b/server/src/test/java/io/crate/expression/operator/EqOperatorTest.java
@@ -34,6 +34,7 @@ import org.junit.Test;
import io.crate.expression.scalar.ScalarTestCase;
import io.crate.lucene.GenericFunctionQuery;
+import io.crate.metadata.IndexType;
import io.crate.metadata.doc.DocSysColumns;
import io.crate.testing.Asserts;
import io.crate.testing.DataTypeTesting;
@@ -141,7 +142,17 @@ public class EqOperatorTest extends ScalarTestCase {
@Test
public void test_terms_query_on__id_encodes_ids() throws Exception {
- Query query = EqOperator.termsQuery(DocSysColumns.ID.name(), DataTypes.STRING, List.of("foo", "bar"));
+ Query query = EqOperator.termsQuery(DocSysColumns.ID.name(), DataTypes.STRING, List.of("foo", "bar"), true, IndexType.FULLTEXT);
+ assertThat(query).hasToString("_id:([7e 8a] [ff 62 61 72])");
+ query = EqOperator.termsQuery(DocSysColumns.ID.name(), DataTypes.STRING, List.of("foo", "bar"), true, IndexType.PLAIN);
+ assertThat(query).hasToString("_id:([7e 8a] [ff 62 61 72])");
+ query = EqOperator.termsQuery(DocSysColumns.ID.name(), DataTypes.STRING, List.of("foo", "bar"), true, IndexType.NONE);
+ assertThat(query).hasToString("_id:([7e 8a] [ff 62 61 72])");
+ query = EqOperator.termsQuery(DocSysColumns.ID.name(), DataTypes.STRING, List.of("foo", "bar"), false, IndexType.FULLTEXT);
+ assertThat(query).hasToString("_id:([7e 8a] [ff 62 61 72])");
+ query = EqOperator.termsQuery(DocSysColumns.ID.name(), DataTypes.STRING, List.of("foo", "bar"), false, IndexType.PLAIN);
+ assertThat(query).hasToString("_id:([7e 8a] [ff 62 61 72])");
+ query = EqOperator.termsQuery(DocSysColumns.ID.name(), DataTypes.STRING, List.of("foo", "bar"), false, IndexType.NONE);
assertThat(query).hasToString("_id:([7e 8a] [ff 62 61 72])");
}
diff --git a/server/src/test/java/io/crate/integrationtests/DDLIntegrationTest.java b/server/src/test/java/io/crate/integrationtests/DDLIntegrationTest.java
index 3ebc9f3681..44eca5c7af 100644
--- a/server/src/test/java/io/crate/integrationtests/DDLIntegrationTest.java
+++ b/server/src/test/java/io/crate/integrationtests/DDLIntegrationTest.java
@@ -30,7 +30,6 @@ import static io.crate.testing.TestingHelpers.printedTable;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.CONFLICT;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
-import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
@@ -292,11 +291,8 @@ public class DDLIntegrationTest extends IntegTestCase {
String quote = "Would it save you a lot of time if I just gave up and went mad now?";
execute("insert into quotes (id, quote) values (?, ?)", new Object[]{1, quote});
execute("refresh table quotes");
-
- Asserts.assertSQLError(() -> execute("select quote from quotes where quote = ?", new Object[]{quote}))
- .hasPGError(INTERNAL_ERROR)
- .hasHTTPError(BAD_REQUEST, 4000)
- .hasMessageContaining("Cannot search on field [quote] since it is not indexed.");
+ execute("select quote from quotes where quote = ?", new Object[]{quote});
+ assertThat(response).hasRows(quote);
}
@Test
diff --git a/server/src/test/java/io/crate/integrationtests/LuceneQueryBuilderIntegrationTest.java b/server/src/test/java/io/crate/integrationtests/LuceneQueryBuilderIntegrationTest.java
index ef5696752a..f11410a99a 100644
--- a/server/src/test/java/io/crate/integrationtests/LuceneQueryBuilderIntegrationTest.java
+++ b/server/src/test/java/io/crate/integrationtests/LuceneQueryBuilderIntegrationTest.java
@@ -36,6 +36,7 @@ import org.elasticsearch.test.IntegTestCase;
import org.junit.Test;
import io.crate.testing.DataTypeTesting;
+import io.crate.testing.UseJdbc;
import io.crate.testing.UseRandomizedOptimizerRules;
import io.crate.types.DataType;
@@ -425,4 +426,192 @@ public class LuceneQueryBuilderIntegrationTest extends IntegTestCase {
.as("query doesn't match")
.hasRowCount(0L);
}
+
+ @UseJdbc(0)
+ @Test
+ public void test_eq_queries_with_index_on_and_column_store_true() {
+ execute(
+ """
+ create table t (
+ a bit(2),
+ b double,
+ c float,
+ d ip,
+ e string,
+ f boolean,
+ g int,
+ h long,
+ i string index using fulltext
+ )
+ """
+ );
+ String firstRow = "(B'01', 1.1, 1.1, '1.1.1.1', 'a', false, 1, 1, 'a')";
+ String expectedFirstRow = "B'01'| 1.1| 1.1| 1.1.1.1| a| false| 1| 1| a";
+ String secondRow = "(B'10', 1.2, 1.2, '1.1.1.2', 'b', true, 2, 2, 'b')";
+ String expectedSecondRow = "B'10'| 1.2| 1.2| 1.1.1.2| b| true| 2| 2| b";
+ execute("insert into t values " + firstRow + ", " + secondRow);
+ refresh();
+
+ // EqQuery.termQuery
+ assertThat(execute("select * from t where a = B'01'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where b = 1.1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where c = 1.1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where d = '1.1.1.1'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where e = 'a'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where f = false")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where g = 1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where h = 1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where i = 'a'")).hasRows(expectedFirstRow);
+
+ // EqQuery.RangeQuery
+ //UnsupportedFunctionException: Unknown function: (mgjihphcgyjgklnrovd.t.a > B'01'), no overload found for matching argument types: (bit, bit). Possible candidates: op_>(byte, byte):boolean, op_>(boolean, boolean):boolean, op_>(character, character):boolean, op_>(text, text):boolean, op_>(ip, ip):boolean, op_>(double precision, double precision):boolean, op_>(real, real):boolean, op_>(smallint, smallint):boolean, op_>(integer, integer):boolean, op_>(interval, interval):boolean, op_>(bigint, bigint):boolean, op_>(timestamp with time zone, timestamp with time zone):boolean, op_>(timestamp without time zone, timestamp without time zone):boolean, op_>(date, date):boolean
+ //assertThat(execute("select * from t where a > B'01'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where b > 1.1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where c > 1.1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where d > '1.1.1.1'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where e > 'a'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where f > false")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where g > 1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where h > 1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where i > 'a'")).hasRows(expectedSecondRow);
+ }
+
+ @UseJdbc(0)
+ @Test
+ public void test_eq_queries_with_index_off_and_column_store_true() {
+ execute(
+ """
+ create table t (
+ a bit(2) index off,
+ b double index off,
+ c float index off,
+ d ip index off,
+ e string index off,
+ f boolean index off,
+ g int index off,
+ h long index off
+ )
+ """
+ );
+ String firstRow = "(B'01', 1.1, 1.1, '1.1.1.1', 'a', false, 1, 1)";
+ String expectedFirstRow = "B'01'| 1.1| 1.1| 1.1.1.1| a| false| 1| 1";
+ String secondRow = "(B'10', 1.2, 1.2, '1.1.1.2', 'b', true, 2, 2)";
+ String expectedSecondRow = "B'10'| 1.2| 1.2| 1.1.1.2| b| true| 2| 2";
+ execute("insert into t values " + firstRow + ", " + secondRow);
+ refresh();
+
+ // EqQuery.termQuery
+ assertThat(execute("select * from t where a = B'01'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where b = 1.1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where c = 1.1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where d = '1.1.1.1'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where e = 'a'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where f = false")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where g = 1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where h = 1")).hasRows(expectedFirstRow);
+
+ // EqQuery.RangeQuery
+ // UnsupportedFunctionException: Unknown function
+ //assertThat(execute("select * from t where a > B'01'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where b > 1.1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where c > 1.1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where d > '1.1.1.1'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where e > 'a'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where f > false")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where g > 1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where h > 1")).hasRows(expectedSecondRow);
+ }
+
+ @UseJdbc(0)
+ @Test
+ public void test_eq_queries_with_index_off_and_column_store_false() {
+ execute(
+ """
+ create table t (
+ a bit(2) index off,
+ b double index off storage with (columnstore=false),
+ c float index off storage with (columnstore=false),
+ d ip index off,
+ e string index off storage with (columnstore=false),
+ f boolean index off,
+ g int index off storage with (columnstore=false),
+ h long index off storage with (columnstore=false)
+ )
+ """
+ );
+ String firstRow = "(B'01', 1.1, 1.1, '1.1.1.1', 'a', false, 1, 1)";
+ String expectedFirstRow = "B'01'| 1.1| 1.1| 1.1.1.1| a| false| 1| 1";
+ String secondRow = "(B'10', 1.2, 1.2, '1.1.1.2', 'b', true, 2, 2)";
+ String expectedSecondRow = "B'10'| 1.2| 1.2| 1.1.1.2| b| true| 2| 2";
+ execute("insert into t values " + firstRow + ", " + secondRow);
+ refresh();
+
+ // EqQuery.termQuery
+ assertThat(execute("select * from t where a = B'01'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where b = 1.1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where c = 1.1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where d = '1.1.1.1'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where e = 'a'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where f = false")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where g = 1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where h = 1")).hasRows(expectedFirstRow);
+
+ // EqQuery.RangeQuery
+ //assertThat(execute("select * from t where a > B'01'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where b > 1.1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where c > 1.1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where d > '1.1.1.1'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where e > 'a'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where f > false")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where g > 1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where h > 1")).hasRows(expectedSecondRow);
+ }
+
+ @UseJdbc(0)
+ @Test
+ public void test_eq_queries_with_index_on_and_column_store_false() {
+ execute(
+ """
+ create table t (
+ a bit(2),
+ b double storage with (columnstore=false),
+ c float storage with (columnstore=false),
+ d ip,
+ e string storage with (columnstore=false),
+ f boolean,
+ g int storage with (columnstore=false),
+ h long storage with (columnstore=false),
+ i text index using fulltext storage with (columnstore=false)
+ )
+ """
+ );
+ String firstRow = "(B'01', 1.1, 1.1, '1.1.1.1', 'a', false, 1, 1, 'a')";
+ String expectedFirstRow = "B'01'| 1.1| 1.1| 1.1.1.1| a| false| 1| 1| a";
+ String secondRow = "(B'10', 1.2, 1.2, '1.1.1.2', 'b', true, 2, 2, 'b')";
+ String expectedSecondRow = "B'10'| 1.2| 1.2| 1.1.1.2| b| true| 2| 2| b";
+ execute("insert into t values " + firstRow + ", " + secondRow);
+ refresh();
+
+ // EqQuery.termQuery
+ assertThat(execute("select * from t where a = B'01'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where b = 1.1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where c = 1.1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where d = '1.1.1.1'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where e = 'a'")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where f = false")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where g = 1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where h = 1")).hasRows(expectedFirstRow);
+ assertThat(execute("select * from t where i = 'a'")).hasRows(expectedFirstRow);
+
+ // EqQuery.RangeQuery
+ //assertThat(execute("select * from t where a > B'01'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where b > 1.1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where c > 1.1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where d > '1.1.1.1'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where e > 'a'")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where f > false")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where g > 1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where h > 1")).hasRows(expectedSecondRow);
+ assertThat(execute("select * from t where i > 'a'")).hasRows(expectedSecondRow);
+ }
} | ['server/src/main/java/io/crate/types/FloatVectorType.java', 'server/src/main/java/io/crate/expression/scalar/SubscriptFunction.java', 'server/src/main/java/io/crate/types/BooleanType.java', 'server/src/main/java/io/crate/expression/operator/any/AnyEqOperator.java', 'server/src/main/java/io/crate/types/LongEqQuery.java', 'server/src/main/java/io/crate/types/StringType.java', 'server/src/main/java/io/crate/types/IpType.java', 'server/src/main/java/io/crate/expression/operator/any/AnyNeqOperator.java', 'server/src/test/java/io/crate/integrationtests/DDLIntegrationTest.java', 'server/src/main/java/io/crate/types/EqQuery.java', 'server/src/main/java/io/crate/execution/engine/collect/collectors/OptimizeQueryForSearchAfter.java', 'server/src/main/java/io/crate/expression/operator/EqOperator.java', 'server/src/main/java/io/crate/types/BitStringType.java', 'server/src/main/java/io/crate/types/FloatType.java', 'server/src/test/java/io/crate/expression/operator/EqOperatorTest.java', 'server/src/test/java/io/crate/integrationtests/LuceneQueryBuilderIntegrationTest.java', 'server/src/main/java/io/crate/expression/operator/CmpOperator.java', 'server/src/main/java/io/crate/types/IntEqQuery.java', 'server/src/main/java/io/crate/types/DoubleType.java'] | {'.java': 19} | 19 | 19 | 0 | 0 | 19 | 21,201,169 | 4,171,457 | 533,389 | 3,713 | 24,331 | 4,486 | 400 | 16 | 861 | 165 | 290 | 51 | 0 | 4 | 2023-07-17T22:54:00 | 3,729 | Java | {'Java': 32426037, 'Python': 71123, 'ANTLR': 46794, 'Shell': 13730, 'Batchfile': 4343} | Apache License 2.0 |
1,324 | kestra-io/kestra/1821/1809 | kestra-io | kestra | https://github.com/kestra-io/kestra/issues/1809 | https://github.com/kestra-io/kestra/pull/1821 | https://github.com/kestra-io/kestra/pull/1821 | 1 | close | Simplify `EachParallel` with `WorkingDirectory` child tasks | ### Issue description
This flow works:
```yaml
id: reproducer
namespace: dev
tasks:
- id: parallel
type: io.kestra.core.tasks.flows.EachParallel
value: ["1", "2", "3", "4", "5", "6"]
tasks:
- id: seq
type: io.kestra.core.tasks.flows.Sequential
tasks:
- id: pythonScripts
type: io.kestra.core.tasks.flows.WorkingDirectory
tasks:
- id: cloneRepository
type: io.kestra.plugin.git.Clone
url: https://github.com/kestra-io/scripts
branch: main
- id: python
type: io.kestra.plugin.scripts.python.Commands
runner: DOCKER
docker:
image: ghcr.io/kestra-io/pydata:latest
commands:
- python etl/parametrized.py {{ parents[0].taskrun.value }}
```
however, it seems that it should already work without having to add the `Sequential` task, because `WorkingDirectory` already runs everything sequentially. However, without Sequential, the `taskrun.value` cannot be accessed:
```yaml
id: reproducer
namespace: dev
tasks:
- id: parallel
type: io.kestra.core.tasks.flows.EachParallel
value: ["1", "2", "3", "4", "5", "6"]
tasks:
- id: pythonScripts
type: io.kestra.core.tasks.flows.WorkingDirectory
tasks:
- id: cloneRepository
type: io.kestra.plugin.git.Clone
url: https://github.com/kestra-io/scripts
branch: main
- id: python
type: io.kestra.plugin.scripts.python.Commands
runner: DOCKER
docker:
image: ghcr.io/kestra-io/pydata:latest
commands:
- python etl/parametrized.py {{ taskrun.value }}
```
this gives - `Missing variable: 'value' on 'python etl/parametrized.py {{ taskrun.value }}' at line 1`
cc @loicmathieu | f8c55c52b10426343ac918b0579fc875b7e5dbe8 | 321df04d6bdc6efd0b32a75b2f5216ac38d30448 | https://github.com/kestra-io/kestra/compare/f8c55c52b10426343ac918b0579fc875b7e5dbe8...321df04d6bdc6efd0b32a75b2f5216ac38d30448 | diff --git a/core/src/main/java/io/kestra/core/tasks/flows/WorkingDirectory.java b/core/src/main/java/io/kestra/core/tasks/flows/WorkingDirectory.java
index ffbb49d2..77b7a0b2 100644
--- a/core/src/main/java/io/kestra/core/tasks/flows/WorkingDirectory.java
+++ b/core/src/main/java/io/kestra/core/tasks/flows/WorkingDirectory.java
@@ -166,6 +166,7 @@ public class WorkingDirectory extends Sequential {
.flowId(parent.getFlowId())
.taskId(task.getId())
.parentTaskRunId(parent.getId())
+ .value(parent.getValue()) // copy parent value so that it can be used with existing flowable tasks easily
.state(new State())
.build()
) | ['core/src/main/java/io/kestra/core/tasks/flows/WorkingDirectory.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,534,511 | 301,579 | 43,905 | 538 | 122 | 23 | 1 | 1 | 1,954 | 162 | 474 | 62 | 2 | 2 | 2023-07-26T16:14:34 | 3,672 | Java | {'Java': 2257332, 'Vue': 639984, 'JavaScript': 128289, 'SCSS': 30353, 'PLpgSQL': 10778, 'Handlebars': 5013, 'CSS': 2172, 'Python': 1969, 'Batchfile': 1966, 'HTML': 1430, 'Shell': 1308, 'Dockerfile': 611} | Apache License 2.0 |
3,448 | pytorch/serve/1143/1130 | pytorch | serve | https://github.com/pytorch/serve/issues/1130 | https://github.com/pytorch/serve/pull/1143 | https://github.com/pytorch/serve/pull/1143 | 1 | fixes | Custom Requirements installation failed | Please have a look at [FAQ's](../../docs/FAQs.md) and [Troubleshooting guide](../../docs/Troubleshooting.md), your query may be already addressed.
Your issue may already be reported!
Please search on the [issue tracker](https://github.com/pytorch/serve/issues) before creating one.
## Context
We are using torchserve to deploy, predict and explain pytorch lightning models in kubelow.
For the inference service, we are using the official docker hub image - `pytorch/torchserve-kfs:0.4.0`
Since the docker image doen't contain `pytorch-lightning` package. We are added it in `requirements.txt` and bundling it using `torch-model-archiver`.
When `install_py_dep_per_model` is set to `true` the packages listed in the `requirements.txt` are **not getting installed**. The issue is getting reproduced in both standalone and docker images.
* torchserve version: 0.4.0
* torch-model-archiver version: 0.4.0
* torch version: 1.8.1
* torchvision version [if any]: 0.9.1
* torchtext version [if any]: 0.9.1
* torchaudio version [if any]:
* java version:
ubuntu@ubuntu-ThinkPad-L490:~/Documents/facebook/phase2/mlflow-torchserve/examples/IrisClassification$ java --version
openjdk 11.0.11-ea 2021-04-20
OpenJDK Runtime Environment (build 11.0.11-ea+4-Ubuntu-0ubuntu3.16.04.1)
OpenJDK 64-Bit Server VM (build 11.0.11-ea+4-Ubuntu-0ubuntu3.16.04.1, mixed mode, sharing)
* Operating System and version: Ubuntu - 16.04
## Your Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
* Installed using source? [yes/no]: no
* Are you planning to deploy it using docker container? [yes/no]: yes
* Is it a CPU or GPU environment?: CPU
* Using a default/custom handler? [If possible upload/share custom handler/model]: custom
* What kind of model is it e.g. vision, text, audio?: vision/text
* Are you planning to use local models from model-store or public url being used e.g. from S3 bucket etc.?
[If public url then provide link.]: local model
* Provide config.properties, logs [ts.log] and parameters used for model registration/update APIs:
* Link to your project [if any]:
## Expected Behavior
When `install_py_dep_per_model` is set to `true`, pytorch lightning should be installed and model should load successfully.
## Current Behavior
when `install_py_dep_per_model` is set to `true`, torchserve is throwing the error (attached logs)
It is strange that, even if `pytorch_lightning` is present in the environment and `install_py_dep_per_model` is set to `true`, the same error is getting reproduced.
## Possible Solution
<!--- Not obligatory, but suggest a fix/reason for the bug -->
## Steps to Reproduce
[iris.zip](https://github.com/pytorch/serve/files/6677618/iris.zip)
1. Unzip iris.zip - It contains `iris.mar` and `config.properties` file
2. Create a directory `model-store`
3. copy iris.mar inside `model-store`
4. set `install_py_dep_per_model=false` in config.properties
5. Install pytorch lightning using pip - `pip install pytorch_lightning==1.3.2`
5. start torchserve with following command
`torchserve --start --ts-config config.properties`
6. Model will be loaded successfully.
7. Stop the torchserve - `torchserve --stop`
8. Uninstall pytorch lightining using `pip uninstall pytorch-lightning`
9. set `install_py_dep_per_model` to true now.
10. start torchserve with following command
`torchserve --start --ts-config config.properties`
## Failure Logs [if any]
Failure logs are attached in ts-failure.txt
[ts-failure.txt](https://github.com/pytorch/serve/files/6677666/ts-failure.txt)
Success scenario log
[ts-success.txt](https://github.com/pytorch/serve/files/6677678/ts-success.txt)
| a2822284d3e70fee342b4c009a6fab643b965067 | f8f519b924c0dc3472844f448d88f2f7f5127f71 | https://github.com/pytorch/serve/compare/a2822284d3e70fee342b4c009a6fab643b965067...f8f519b924c0dc3472844f448d88f2f7f5127f71 | diff --git a/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java b/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java
index 372d2afd..b633b9e7 100644
--- a/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java
+++ b/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java
@@ -1,8 +1,10 @@
package org.pytorch.serve.wlm;
import com.google.gson.JsonObject;
+import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
+import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -145,10 +147,10 @@ public final class ModelManager {
}
}
- logger.info("Model {} loaded.", tempModel.getModelName());
-
setupModelDependencies(tempModel);
+ logger.info("Model {} loaded.", tempModel.getModelName());
+
return archive;
}
@@ -211,15 +213,40 @@ public final class ModelManager {
+ requirementsFilePath; // NOPMD
String[] envp =
- EnvironmentUtils.getEnvString(configManager.getModelServerHome(), null, null);
+ EnvironmentUtils.getEnvString(
+ configManager.getModelServerHome(),
+ model.getModelDir().getAbsolutePath(),
+ null);
+
Process process =
Runtime.getRuntime()
.exec(
packageInstallCommand,
envp,
model.getModelDir().getAbsoluteFile());
+
int exitCode = process.waitFor();
+
if (exitCode != 0) {
+
+ String line;
+ StringBuilder outputString = new StringBuilder();
+ // process's stdout is InputStream for caller process
+ BufferedReader brdr =
+ new BufferedReader(new InputStreamReader(process.getInputStream()));
+ while ((line = brdr.readLine()) != null) {
+ outputString.append(line);
+ }
+ StringBuilder errorString = new StringBuilder();
+ // process's stderr is ErrorStream for caller process
+ brdr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ while ((line = brdr.readLine()) != null) {
+ errorString.append(line);
+ }
+
+ logger.info("Dependency installation stdout:\\n" + outputString.toString());
+ logger.error("Dependency installation stderr:\\n" + errorString.toString());
+
throw new ModelException(
"Custom pip package installation failed for " + model.getModelName());
} | ['frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 515,574 | 96,636 | 14,821 | 159 | 1,509 | 220 | 33 | 1 | 3,740 | 457 | 955 | 79 | 4 | 0 | 2021-06-25T10:40:18 | 3,585 | Java | {'Java': 876672, 'Python': 695487, 'Jupyter Notebook': 83389, 'Shell': 34326, 'Dockerfile': 7806, 'Mustache': 1583} | Apache License 2.0 |
3,445 | pytorch/serve/1550/1549 | pytorch | serve | https://github.com/pytorch/serve/issues/1549 | https://github.com/pytorch/serve/pull/1550 | https://github.com/pytorch/serve/pull/1550 | 1 | fixes | When an envelope is set in config.properties, the envelope of the workflow function is still null. | ## Context
<!--- How has this issue affected you? What are you trying to accomplish? -->
<!--- Providing context helps us come up with a solution that is most useful in the real world -->
* torchserve version: `0.5.3`
* torch-model-archiver version:
* torch version: `1.10.0`
* torchvision version [if any]:
* torchtext version [if any]:
* torchaudio version [if any]:
* java version:
* Operating System and version: Ubuntu 18.04
## Your Environment
I use the image `pytorch/torchserve:0.5.3-cpu` as the environment.
* Installed using source? [yes/no]: No
* Are you planning to deploy it using docker container? [yes/no]: yes
* Is it a CPU or GPU environment?: CPU
* Using a default/custom handler? [If possible upload/share custom handler/model]: custom, see below.
* What kind of model is it e.g. vision, text, audio?: vision
**I test with two workflows:**
- dog_breed_classification in the examples
* Are you planning to use local models from model-store or public url being used e.g. from S3 bucket etc.?
[If public url then provide link.]:
* Provide config.properties, logs [ts.log] and parameters used for model registration/update APIs:
```
inference_address=http://0.0.0.0:8000
management_address=http://0.0.0.0:8001
metrics_address=http://0.0.0.0:8002
number_of_netty_threads=32
job_queue_size=1000
install_py_dep_per_model=true
service_envelope=kservev2
load_models=all
```
* Link to your project [if any]:
## Expected Behavior
The workflow function should have the same envelope as the workflow model does.
The envelope of the workflow functions and models should be the same as specified in the config.properties.
## Current Behavior
The workflow function's envelope is null while the workflow model's envelope is as specified in the config.properties.
## Reasons
### The envelope of the workflow function is not set correctly.
> https://github.com/pytorch/serve/blob/6a191f822f2e759c2aad07b8f9eacbedcb039827/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java#L122
While the models' envelope are set to the default envelope specified in config.properties, the workflow funcitons' envelope is null.
## Possible Solution
It is possible to set all the workflow model/functions' envelope to null, whatever the service_envelope specifed in the config.properties. However, this creates an inconsistence between the model api standard and the workflow api standard. And all the models in the workflow use null envelope while other models use another envelope. Therefore, it is not a desired solution.
In order to solve the issue and maintain the consistency between APIs of workflow and standalone models:
Set the envelope of workflow functions to the default envelope as regular models (those have `.mar` files)
## Steps to Reproduce
1. Pull the image `pytorch/torchserve:0.5.3-cpu`
2. Set the `service_envelope` to any envelope, run the container with the workflow.
## Failure Logs [if any]
I add some print in `ts/model_service_worker.py`:
```python
class TorchModelServiceWorker(object):
@staticmethod
def load_model(load_model_request):
try:
model_dir = load_model_request["modelPath"].decode("utf-8")
model_name = load_model_request["modelName"].decode("utf-8")
handler = load_model_request["handler"].decode("utf-8") if load_model_request["handler"] else None
envelope = load_model_request["envelope"].decode("utf-8") if "envelope" in load_model_request else None
envelope = envelope if envelope is not None and len(envelope) > 0 else None
print("=" * 50)
print("model name:", model_name)
print("envelope: ", envelope)
```
Below are the logs when loading the `dog_breed_classification`:
```diff
+ 2022-03-22T06:39:04,375 [INFO ] W-9024-dog_breed_wf_new__pre_processing_1.0-stdout MODEL_LOG - ==================================================
+ 2022-03-22T06:39:04,375 [INFO ] W-9024-dog_breed_wf_new__pre_processing_1.0-stdout MODEL_LOG - model_name: dog_breed_wf_new__pre_processing
+ 2022-03-22T06:39:04,375 [INFO ] W-9024-dog_breed_wf_new__pre_processing_1.0-stdout MODEL_LOG - envelope: None
2022-03-22T06:39:04,375 [INFO ] W-9024-dog_breed_wf_new__pre_processing_1.0-stdout MODEL_LOG - model_name: dog_breed_wf_new__pre_processing, batchSize: 1
2022-03-22T06:39:04,376 [INFO ] W-9024-dog_breed_wf_new__pre_processing_1.0 org.pytorch.serve.wlm.WorkerThread - Backend response time: 1
2022-03-22T06:39:04,376 [DEBUG] W-9024-dog_breed_wf_new__pre_processing_1.0 org.pytorch.serve.wlm.WorkerThread - W-9024-dog_breed_wf_new__pre_processing_1.0 State change WORKER_STARTED -> WORKER_MODEL_LOADED
2022-03-22T06:39:04,376 [INFO ] W-9024-dog_breed_wf_new__pre_processing_1.0 TS_METRICS - W-9024-dog_breed_wf_new__pre_processing_1.0.ms:959|#Level:Host|#hostname:8b026932f222,timestamp:1647931144
2022-03-22T06:39:04,376 [INFO ] W-9024-dog_breed_wf_new__pre_processing_1.0 TS_METRICS - WorkerThreadTime.ms:1|#Level:Host|#hostname:8b026932f222,timestamp:null
2022-03-22T06:39:04,875 [DEBUG] pool-6-thread-2 org.pytorch.serve.wlm.ModelVersionedRefs - Adding new version 1.0 for model dog_breed_wf_new__dog_breed_classification
2022-03-22T06:39:04,875 [DEBUG] pool-6-thread-2 org.pytorch.serve.wlm.ModelVersionedRefs - Setting default version to 1.0 for model dog_breed_wf_new__dog_breed_classification
2022-03-22T06:39:04,875 [INFO ] pool-6-thread-2 org.pytorch.serve.wlm.ModelManager - Model dog_breed_wf_new__dog_breed_classification loaded.
2022-03-22T06:39:04,875 [DEBUG] pool-6-thread-2 org.pytorch.serve.wlm.ModelManager - updateModel: dog_breed_wf_new__dog_breed_classification, count: 1
2022-03-22T06:39:04,876 [DEBUG] W-9026-dog_breed_wf_new__dog_breed_classification_1.0 org.pytorch.serve.wlm.WorkerLifeCycle - Worker cmdline: [/home/venv/bin/python, /home/venv/lib/python3.8/site-packages/ts/model_service_worker.py, --sock-type, unix, --sock-name, /home/model-server/tmp/.ts.sock.9026]
2022-03-22T06:39:05,040 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - Listening on port: /home/model-server/tmp/.ts.sock.9025
2022-03-22T06:39:05,041 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - [PID]14321
2022-03-22T06:39:05,041 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - Torch worker started.
2022-03-22T06:39:05,041 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - Python runtime: 3.8.0
2022-03-22T06:39:05,041 [DEBUG] W-9025-dog_breed_wf_new__cat_dog_classification_1.0 org.pytorch.serve.wlm.WorkerThread - W-9025-dog_breed_wf_new__cat_dog_classification_1.0 State change null -> WORKER_STARTED
2022-03-22T06:39:05,041 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0 org.pytorch.serve.wlm.WorkerThread - Connecting to: /home/model-server/tmp/.ts.sock.9025
2022-03-22T06:39:05,042 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - Connection accepted: /home/model-server/tmp/.ts.sock.9025.
2022-03-22T06:39:05,042 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0 org.pytorch.serve.wlm.WorkerThread - Flushing req. to backend at: 1647931145042
+ 2022-03-22T06:39:05,042 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - ==================================================
+ 2022-03-22T06:39:05,043 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - model_name: dog_breed_wf_new__cat_dog_classification
+ 2022-03-22T06:39:05,043 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - envelope: kservev2
2022-03-22T06:39:05,043 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - model_name: dog_breed_wf_new__cat_dog_classification, batchSize: 4
2022-03-22T06:39:05,781 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - Listening on port: /home/model-server/tmp/.ts.sock.9026
2022-03-22T06:39:05,782 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - [PID]14334
2022-03-22T06:39:05,782 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - Torch worker started.
2022-03-22T06:39:05,782 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - Python runtime: 3.8.0
2022-03-22T06:39:05,782 [DEBUG] W-9026-dog_breed_wf_new__dog_breed_classification_1.0 org.pytorch.serve.wlm.WorkerThread - W-9026-dog_breed_wf_new__dog_breed_classification_1.0 State change null -> WORKER_STARTED
2022-03-22T06:39:05,782 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0 org.pytorch.serve.wlm.WorkerThread - Connecting to: /home/model-server/tmp/.ts.sock.9026
2022-03-22T06:39:05,783 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - Connection accepted: /home/model-server/tmp/.ts.sock.9026.
2022-03-22T06:39:05,783 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0 org.pytorch.serve.wlm.WorkerThread - Flushing req. to backend at: 1647931145783
+ 2022-03-22T06:39:05,783 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - ==================================================
+ 2022-03-22T06:39:05,783 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - model_name: dog_breed_wf_new__dog_breed_classification
+ 2022-03-22T06:39:05,783 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - envelope: kservev2
2022-03-22T06:39:05,783 [INFO ] W-9026-dog_breed_wf_new__dog_breed_classification_1.0-stdout MODEL_LOG - model_name: dog_breed_wf_new__dog_breed_classification, batchSize: 4
2022-03-22T06:39:06,366 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0-stdout MODEL_LOG - Missing the index_to_name.json file. Inference output will not include class name.
2022-03-22T06:39:06,366 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0 org.pytorch.serve.wlm.WorkerThread - Backend response time: 1324
2022-03-22T06:39:06,366 [DEBUG] W-9025-dog_breed_wf_new__cat_dog_classification_1.0 org.pytorch.serve.wlm.WorkerThread - W-9025-dog_breed_wf_new__cat_dog_classification_1.0 State change WORKER_STARTED -> WORKER_MODEL_LOADED
2022-03-22T06:39:06,366 [INFO ] W-9025-dog_breed_wf_new__cat_dog_classification_1.0 TS_METRICS - W-9025-dog_breed_wf_new__cat_dog_classification_1.0.ms:2231|#Level:Host|#hostname:8b026932f222,tim
```
| 7aae58eb0f1d6fc1b61524fb99a7fd9dfc44f71c | 62ec076e60edd51f819c5f1ba054c5ecbd566e0e | https://github.com/pytorch/serve/compare/7aae58eb0f1d6fc1b61524fb99a7fd9dfc44f71c...62ec076e60edd51f819c5f1ba054c5ecbd566e0e | diff --git a/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java b/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java
index 2cc8d7a2..7245241c 100644
--- a/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java
+++ b/frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java
@@ -125,7 +125,7 @@ public final class ModelManager {
manifest.getModel().setModelVersion("1.0");
manifest.getModel().setModelName(modelName);
manifest.getModel().setHandler(new File(handler).getName());
-
+ manifest.getModel().setEnvelope(configManager.getTsServiceEnvelope());
File f = new File(handler.substring(0, handler.lastIndexOf(':')));
archive = new ModelArchive(manifest, url, f.getParentFile(), true);
} else { | ['frontend/server/src/main/java/org/pytorch/serve/wlm/ModelManager.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 537,614 | 100,530 | 15,317 | 159 | 85 | 14 | 2 | 1 | 10,564 | 872 | 3,272 | 135 | 4 | 3 | 2022-04-06T07:43:12 | 3,585 | Java | {'Java': 876672, 'Python': 695487, 'Jupyter Notebook': 83389, 'Shell': 34326, 'Dockerfile': 7806, 'Mustache': 1583} | Apache License 2.0 |
86 | movingblocks/terasology/3588/3587 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3587 | https://github.com/MovingBlocks/Terasology/pull/3588 | https://github.com/MovingBlocks/Terasology/pull/3588 | 1 | fixes | Game behaves poorly on interacting with the windowed/fullscreen option | ### What you were trying to do
Change from windowed to fullscreen mode. Expected that interacting with (clicking/activating) the display mode drop-down would show all the available options on one interaction then let me choose with a second interaction
### What actually happened
Game window disappeared (as if about to change display mode) but game kept running and the whole OS started mildly freaking out (seems like it outright crashed an OS process for @Adrijaned on Linux). It feels like the game gets stuck in a state where it is trying to swap windowed state constantly
Theory is that it relates to how activating the UI widget works, likely after tabbing was introduced. Actually tabbing to the widget and varying the display mode with down arrow works. Only clicking the widget with the mouse makes the game freak out.
It seems like too much happens at once. Interacting with the drop-down should first reveal the options then not activate a given item until a second interaction (second mouse click or hitting enter after selecting an option with the arrow keys)
May similarly affect the drop-down widget in general? See also #3581 and #3561 for potential clues
### How to reproduce
* Run game
* Go to video settings
* Click on the Display Mode drop-down (using tab plus arrow keys still work fine)
If other drop-downs are also affected it may be easier to test with those. After interacting poorly with the display mode drop-down i have to force-kill the game - it may destabilize your OS, beware!
### Log details and game version
No applicable logging, latest develop branch as of this write-up
### Computer details
Win10 with a 4k monitor in case it matters | 2bad493b1e9e095f17d0d2f1a432831cb8b3e299 | 53377977162105b02b7421c8719bd38cde9956d9 | https://github.com/movingblocks/terasology/compare/2bad493b1e9e095f17d0d2f1a432831cb8b3e299...53377977162105b02b7421c8719bd38cde9956d9 | diff --git a/engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdown.java b/engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdown.java
index ae4a319e5..188408a74 100644
--- a/engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdown.java
+++ b/engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdown.java
@@ -110,7 +110,7 @@ public void onDraw(Canvas canvas) {
for (int i = 0; i < optionListeners.size(); ++i) {
if (optionListeners.get(i).isMouseOver()) {
canvas.setMode(HOVER_MODE);
- } else if (i==highlighted) {
+ } else if (i==highlighted && TabbingManager.focusedWidget != null && TabbingManager.focusedWidget.equals(this)) {
canvas.setMode(HOVER_MODE);
setSelection(getOptions().get(highlighted));
} else {
diff --git a/engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdownScrollable.java b/engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdownScrollable.java
index 7bf230520..5b91489f7 100644
--- a/engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdownScrollable.java
+++ b/engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdownScrollable.java
@@ -24,6 +24,7 @@
import org.terasology.rendering.nui.Canvas;
import org.terasology.rendering.nui.InteractionListener;
import org.terasology.rendering.nui.SubRegion;
+import org.terasology.rendering.nui.TabbingManager;
import org.terasology.rendering.nui.databinding.Binding;
import org.terasology.rendering.nui.databinding.DefaultBinding;
import org.terasology.rendering.nui.events.NUIMouseClickEvent;
@@ -191,7 +192,7 @@ private void createScrollbarItems(Canvas canvas, Rect2i frame, Font font, Border
private void readItemMouseOver(Canvas canvas, int i) {
if (optionListeners.get(i).isMouseOver()) {
canvas.setMode(HOVER_MODE);
- } else if (i == highlighted) {
+ } else if (i == highlighted && TabbingManager.focusedWidget != null && TabbingManager.focusedWidget.equals(this)) {
canvas.setMode(HOVER_MODE);
setSelection(getOptions().get(highlighted));
} else { | ['engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdown.java', 'engine/src/main/java/org/terasology/rendering/nui/widgets/UIDropdownScrollable.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,490,705 | 2,031,829 | 264,107 | 2,217 | 393 | 92 | 5 | 2 | 1,712 | 286 | 350 | 29 | 0 | 0 | 2018-12-25T21:07:46 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
83 | movingblocks/terasology/3666/3665 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3665 | https://github.com/MovingBlocks/Terasology/pull/3666 | https://github.com/MovingBlocks/Terasology/pull/3666 | 1 | fixes | OpenGL Line Width Warning | When hovering over anything that creates a hitbox outline, the following error gets printed out every tick:
`[main] WARN OpenGL - [api] [deprecated] API_ID_LINE_WIDTH deprecated behavior warning has been generated. Wide lines have been deprecated. glLineWidth set to 2.000000. glLineWidth with width greater than 1.0 will generate GL_INVALID_VALUE error in future versions`
This is due to several `glLineWidth` calls where the parameter is 2 (unsurprisingly). This means the fix is very simply just changing these calls to use 1 instead. | 65729fc3ae0dea8ac45458302bc653e8530274f7 | b845970bd8f613ccc1bf1c3b7213d34fe65bf3eb | https://github.com/movingblocks/terasology/compare/65729fc3ae0dea8ac45458302bc653e8530274f7...b845970bd8f613ccc1bf1c3b7213d34fe65bf3eb | diff --git a/engine/src/main/java/org/terasology/logic/players/LocalPlayerSystem.java b/engine/src/main/java/org/terasology/logic/players/LocalPlayerSystem.java
index 329a431d8..d2052c7c7 100644
--- a/engine/src/main/java/org/terasology/logic/players/LocalPlayerSystem.java
+++ b/engine/src/main/java/org/terasology/logic/players/LocalPlayerSystem.java
@@ -399,7 +399,7 @@ public void renderOverlay() {
if (config.getRendering().isRenderPlacingBox()) {
if (aabb != null) {
aabbRenderer.setAABB(aabb);
- aabbRenderer.render(2f);
+ aabbRenderer.render(1f);
}
}
}
diff --git a/engine/src/main/java/org/terasology/rendering/logic/RegionOutlineRenderer.java b/engine/src/main/java/org/terasology/rendering/logic/RegionOutlineRenderer.java
index fd2233ceb..726acb32e 100644
--- a/engine/src/main/java/org/terasology/rendering/logic/RegionOutlineRenderer.java
+++ b/engine/src/main/java/org/terasology/rendering/logic/RegionOutlineRenderer.java
@@ -96,7 +96,7 @@ public void renderOverlay() {
return; // skip everything if there is nothing to do to avoid possibly costly draw mode changes
}
glDisable(GL_DEPTH_TEST);
- glLineWidth(2);
+ glLineWidth(1);
Vector3f cameraPosition = worldRenderer.getActiveCamera().getPosition();
FloatBuffer tempMatrixBuffer44 = BufferUtils.createFloatBuffer(16);
diff --git a/engine/src/main/java/org/terasology/rendering/logic/SkeletonRenderer.java b/engine/src/main/java/org/terasology/rendering/logic/SkeletonRenderer.java
index 1b5812169..3648d92ad 100644
--- a/engine/src/main/java/org/terasology/rendering/logic/SkeletonRenderer.java
+++ b/engine/src/main/java/org/terasology/rendering/logic/SkeletonRenderer.java
@@ -312,7 +312,7 @@ public void renderOverlay() {
material.setFloat("sunlight", 1.0f, true);
material.setFloat("blockLight", 1.0f, true);
material.setMatrix4("projectionMatrix", worldRenderer.getActiveCamera().getProjectionMatrix());
- glLineWidth(2);
+ glLineWidth(1);
Vector3f worldPos = new Vector3f();
| ['engine/src/main/java/org/terasology/logic/players/LocalPlayerSystem.java', 'engine/src/main/java/org/terasology/rendering/logic/RegionOutlineRenderer.java', 'engine/src/main/java/org/terasology/rendering/logic/SkeletonRenderer.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 9,342,824 | 1,999,580 | 260,006 | 2,166 | 189 | 42 | 6 | 3 | 544 | 80 | 120 | 5 | 0 | 0 | 2019-04-27T17:35:11 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
82 | movingblocks/terasology/3689/3688 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3688 | https://github.com/MovingBlocks/Terasology/pull/3689 | https://github.com/MovingBlocks/Terasology/pull/3689 | 1 | fixes | Terrible things happen when starting a _second_ game without a game restart | ### What you were trying to do
Test unrelated things! Which sometimes involve jumping into more than one world.
### What actually happened
Inconsistently would get warped worlds with messed up data, from broken chunks to entirely messed up block data (hills of torches, pure water world, etc)
### How to reproduce
This is the minimal use case I could consistently reproduce real quick
* Step 0: (Unsure if needed: start from a clean game, no saves or config)
* Step 1: Start the game from source, create a new game, pick Core, quick start
* Step 2: Verify all looks well, exit back to the main menu
* Step 3: Create a new game, pick Core, quick start - bad things happen
Similar issues have happened in the past (malformed block ids through some scenario), but I thought they were all long gone. Game state handling between multiple games in one game launch has remained a fragile area, however. Chances are something isn't being reset properly when leaving the first game world. | 67024bd9c97aee9122039080795a508d9a3a629e | 6ab352f0f34052ef63b9941b8ad2987394d2c8a8 | https://github.com/movingblocks/terasology/compare/67024bd9c97aee9122039080795a508d9a3a629e...6ab352f0f34052ef63b9941b8ad2987394d2c8a8 | diff --git a/engine/src/main/java/org/terasology/rendering/nui/widgets/UIText.java b/engine/src/main/java/org/terasology/rendering/nui/widgets/UIText.java
index 609681bef..40fc96c2e 100644
--- a/engine/src/main/java/org/terasology/rendering/nui/widgets/UIText.java
+++ b/engine/src/main/java/org/terasology/rendering/nui/widgets/UIText.java
@@ -17,6 +17,7 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
+import com.google.common.collect.ObjectArrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.input.Keyboard;
@@ -677,15 +678,7 @@ public void bindText(Binding<String> binding) {
* contents of linesOfText or text accordingly.
*/
public String getText() {
- String arrayText = "";
- if(linesOfText.length > 0) {
- arrayText = String.join("\\n", linesOfText);
- }
-
- if(text.get() != "") {
- return text.get() + "\\n" + arrayText;
- }
- return text.get() + arrayText;
+ return String.join("\\n", ObjectArrays.concat(text.get(), linesOfText));
}
/** | ['engine/src/main/java/org/terasology/rendering/nui/widgets/UIText.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,344,953 | 2,000,040 | 260,072 | 2,166 | 402 | 89 | 11 | 1 | 1,003 | 173 | 220 | 18 | 0 | 0 | 2019-06-14T10:24:35 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
81 | movingblocks/terasology/3749/3745 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3745 | https://github.com/MovingBlocks/Terasology/pull/3749 | https://github.com/MovingBlocks/Terasology/pull/3749 | 1 | fix | Can't run game with "./gradlew game" | I create local repo on my machine. Follow instructions, but if I try do **./gradlew game** i see this:
**java.lang.RuntimeException: java.util.concurrent.ExecutionException: org.reflections.ReflectionsException: could not create Vfs.Dir from url, no matching UrlType was found [file:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/libatk-wrapper.so]
either use fromURL(final URL url, final List<UrlType> urlTypes) or use the static setDefaultURLTypes(final List<UrlType> urlTypes) or addDefaultURLTypes(UrlType urlType) with your specialized UrlType.**
Logs file here
[Terasology-init.log](https://github.com/MovingBlocks/Terasology/files/3665893/Terasology-init.log)
And, i think, that's my another problem, but i hope u can help. If I try run any build in my IDEA, i see this:
**Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1394)
at org.terasology.splash.overlay.ImageOverlay.<init>(ImageOverlay.java:38)
at org.terasology.splash.overlay.TriggerImageOverlay.<init>(TriggerImageOverlay.java:30)
at org.terasology.engine.Terasology.configureSplashScreen(Terasology.java:206)
at org.terasology.engine.Terasology.main(Terasology.java:125)**
OS - Ubuntu 18.04.3 LTS
java -version
openjdk version "1.8.0_222"
OpenJDK Runtime Environment (build 1.8.0_222-8u222-b10-1ubuntu1~18.04.1-b10)
OpenJDK 64-Bit Server VM (build 25.222-b10, mixed mode)
| bd30280ea1b914218dfdee0a721456b28e7c7d56 | 4717dce65980f0457241d9c1d9c7031c675ca1ff | https://github.com/movingblocks/terasology/compare/bd30280ea1b914218dfdee0a721456b28e7c7d56...4717dce65980f0457241d9c1d9c7031c675ca1ff | diff --git a/engine/src/main/java/org/terasology/reflection/TypeRegistry.java b/engine/src/main/java/org/terasology/reflection/TypeRegistry.java
index 78c1d801a..ecd1d42e6 100644
--- a/engine/src/main/java/org/terasology/reflection/TypeRegistry.java
+++ b/engine/src/main/java/org/terasology/reflection/TypeRegistry.java
@@ -110,7 +110,6 @@ private void initializeReflections(ClassLoader classLoader) {
.toArray(ClassLoader[]::new)
))
.filterInputsBy(TypeRegistry::filterWhitelistedTypes)
- .useParallelExecutor()
);
} | ['engine/src/main/java/org/terasology/reflection/TypeRegistry.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,398,927 | 2,010,373 | 261,695 | 2,185 | 39 | 6 | 1 | 1 | 1,461 | 126 | 395 | 31 | 1 | 0 | 2019-10-02T05:03:56 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
89 | movingblocks/terasology/3294/2755 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/2755 | https://github.com/MovingBlocks/Terasology/pull/3294 | https://github.com/MovingBlocks/Terasology/pull/3294 | 2 | fix | StackOverflow in NUI editor when setting to 2 items to be on top of each other | <!-- Thanks for taking the time to submit a thorough issue report for Terasology! :-)
Please fill out whichever details below seem relevant to your issue.
Note that suggestions, general questions & support should go in the forum:
* http://forum.terasology.org/forum/suggestions.21
* http://forum.terasology.org/forum/support.20/
Bug reports and crashes likely resulting from bugs in the engine go here on GitHub. -->
### What you were trying to do
When using the NUI editor, had an item with its position-bottom target set to TOP and widget to the id of the second item.
Then accidentally set the second item's position-top target set to TOP and widget to the id of the first item.
### What actually happened
A StackOverflow error is thrown, and everytime the NUI Editor is launched the exception is thrown again. Probably because when throwing the exception the file is auto-saved then when relaunching the editor it loads the auto-save and the exception is thrown again.
### How to reproduce
* Create a new screen in the NUI Editor
* Add 2 UILabels (for example, but probably can be done with anything)
* Add a position-bottom to the first UILabel. Set its widget value to the id of the second UILabel, and its target to TOP
* Add a position-top to the second UILabel. Set its widget value to the id of the first UILabel
### Log details, and UI code
[Terasology Menu Log](https://github.com/MovingBlocks/Terasology/files/702622/Terasology-menu.log.txt)
And the UI where it occured.
```json
{
"selectedAsset": "New Screen",
"editorContents": {
"type": "PlaceholderScreen",
"skin": "engine:default",
"contents": {
"type": "RelativeLayout",
"contents": [
{
"type": "UILabel",
"id": "sampleLabel",
"layoutInfo": {
"width": 500,
"position-horizontal-center": {},
"position-vertical-center": {},
"position-bottom": {
"widget": "newWidget",
"target": "TOP"
}
},
"text": "Welcome to the Terasology NUI editor!\\r\\nVisit https://github.com/Terasology/TutorialNui/wiki for a quick overview of the editor,\\r\\nas well as the NUI framework itself."
},
{
"type": "engine:UILabel",
"id": "newWidget",
"layoutInfo": {
"position-top": {
"target": "TOP",
"widget": "sampleLabel"
}
}
}
]
}
}
}
``` | 9e037d1c197a448573e2a33b1011a7a9d391ee85 | 83fb6f6a5f3dbfd88c5ae3af00bf5fc334501817 | https://github.com/movingblocks/terasology/compare/9e037d1c197a448573e2a33b1011a7a9d391ee85...83fb6f6a5f3dbfd88c5ae3af00bf5fc334501817 | diff --git a/engine/src/main/java/org/terasology/rendering/nui/layouts/relative/RelativeLayout.java b/engine/src/main/java/org/terasology/rendering/nui/layouts/relative/RelativeLayout.java
index 1a93c0ea9..340896884 100644
--- a/engine/src/main/java/org/terasology/rendering/nui/layouts/relative/RelativeLayout.java
+++ b/engine/src/main/java/org/terasology/rendering/nui/layouts/relative/RelativeLayout.java
@@ -190,9 +190,13 @@ private Rect2i getTargetRegion(String id, Canvas canvas) {
}
WidgetInfo target = contentLookup.get(id);
if (target != null) {
- Rect2i region = getRegion(target, canvas);
- loopDetectionId = "";
- return region;
+ try {
+ Rect2i region = getRegion(target, canvas);
+ loopDetectionId = "";
+ return region;
+ } catch (StackOverflowError e){
+ logger.error("Stack Overflow detected resolving layout of element {}, unable to render", loopDetectionId);
+ }
}
}
loopDetectionId = ""; | ['engine/src/main/java/org/terasology/rendering/nui/layouts/relative/RelativeLayout.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 8,877,754 | 1,904,632 | 248,667 | 2,136 | 492 | 78 | 10 | 1 | 2,551 | 320 | 568 | 64 | 4 | 1 | 2018-03-17T21:35:59 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
80 | movingblocks/terasology/3763/3740 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3740 | https://github.com/MovingBlocks/Terasology/pull/3763 | https://github.com/MovingBlocks/Terasology/pull/3763 | 1 | fixes | Trees in JoshariasSurvival are broken, yet same worldgen in plain Core is fine. BiomesAPI quirk? | Also happens if you use the Shattered Planes worldgen. Trees just have trunk pieces, no leaf blocks.
Happened relatively recently, the closest guess I have is that it happened with the BiomesAPI thing where we also lost the hue on leaf/grass blocks temporarily until a better redo later? | 45f5dcc0ae00563bb97d9f75f5c16d246b9516c9 | b04a0700666a01fa3dd366c2417e40d674c6a9bb | https://github.com/movingblocks/terasology/compare/45f5dcc0ae00563bb97d9f75f5c16d246b9516c9...b04a0700666a01fa3dd366c2417e40d674c6a9bb | diff --git a/modules/Core/src/main/java/org/terasology/core/world/generator/rasterizers/TreeRasterizer.java b/modules/Core/src/main/java/org/terasology/core/world/generator/rasterizers/TreeRasterizer.java
index a445fd679..5b6654325 100644
--- a/modules/Core/src/main/java/org/terasology/core/world/generator/rasterizers/TreeRasterizer.java
+++ b/modules/Core/src/main/java/org/terasology/core/world/generator/rasterizers/TreeRasterizer.java
@@ -43,6 +43,15 @@ public class TreeRasterizer implements WorldRasterizer {
@Override
public void initialize() {
blockManager = CoreRegistry.get(BlockManager.class);
+ //TODO: Remove these lines when lazy block registration is fixed
+ //Currently they are required to ensure that the blocks are all registered before worldgen
+ blockManager.getBlock("CoreBlocks:OakTrunk");
+ blockManager.getBlock("CoreBlocks:PineTrunk");
+ blockManager.getBlock("CoreBlocks:BirchTrunk");
+ blockManager.getBlock("CoreBlocks:GreenLeaf");
+ blockManager.getBlock("CoreBlocks:DarkLeaf");
+ blockManager.getBlock("CoreBlocks:RedLeaf");
+ blockManager.getBlock("CoreBlocks:Cactus");
}
@Override | ['modules/Core/src/main/java/org/terasology/core/world/generator/rasterizers/TreeRasterizer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,399,048 | 2,010,305 | 261,700 | 2,188 | 559 | 112 | 9 | 1 | 290 | 48 | 62 | 3 | 0 | 0 | 2019-10-16T22:58:03 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
79 | movingblocks/terasology/3790/3768 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3768 | https://github.com/MovingBlocks/Terasology/pull/3790 | https://github.com/MovingBlocks/Terasology/pull/3790 | 1 | fixes | Error Dialog cannot be closed | # What you were trying to do
Close the error dialog coming up on starting a game whilst having dependency issues underneath.
### What actually happened
The "Ok" button is not clickable. It's also not greyed out or anything, but if I click on it, simply nothing happens.
### How to reproduce
* Create and save a game and exit Terasology (e.g. LaS)
* Enforce a dependency issue for some module used in the game (e.g. adapt dependency version of LaS dependency)
* Try to load the game (should result in an error dialog popping up)
* Try to click the "Ok" button
| b8e06611b9c436b9b0980444802a1ae4085ed1ad | 70ac0dca842a321db86c5f9a2f7c75a7270b9d62 | https://github.com/movingblocks/terasology/compare/b8e06611b9c436b9b0980444802a1ae4085ed1ad...70ac0dca842a321db86c5f9a2f7c75a7270b9d62 | diff --git a/engine/src/main/java/org/terasology/input/InputSystem.java b/engine/src/main/java/org/terasology/input/InputSystem.java
index 4a25ee0cd..4436af65f 100644
--- a/engine/src/main/java/org/terasology/input/InputSystem.java
+++ b/engine/src/main/java/org/terasology/input/InputSystem.java
@@ -155,8 +155,8 @@ private void updateInputEntities() {
|| inputEntities.length != 2
|| inputEntities[0] == null
|| inputEntities[1] == null
- || !inputEntities[0].equals(localPlayer.getClientEntity())
- || !inputEntities[1].equals(localPlayer.getCharacterEntity())) {
+ || inputEntities[0] != localPlayer.getClientEntity()
+ || inputEntities[1] != localPlayer.getCharacterEntity()) {
inputEntities = new EntityRef[]{localPlayer.getClientEntity(), localPlayer.getCharacterEntity()};
}
} | ['engine/src/main/java/org/terasology/input/InputSystem.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,409,605 | 2,012,639 | 261,959 | 2,192 | 303 | 58 | 4 | 1 | 572 | 103 | 133 | 12 | 0 | 0 | 2019-12-04T18:36:21 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
78 | movingblocks/terasology/3824/3556 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3556 | https://github.com/MovingBlocks/Terasology/pull/3824 | https://github.com/MovingBlocks/Terasology/pull/3824 | 1 | fixes | Unplugging joystick leads to crash | ### What you were trying to do
* I tried unplugging my joystick by pulling the cord
### What actually happened
* My joystick got unplugged as planned
* Terasology crashed in a way not planned at all
### How to reproduce
* Step 1: Use a joystick
* Step 2: Pull the cord
* Step 3: No profit
### Log details and game version
https://pastebin.com/vKT69jL3
### Computer details
* In the logfile. More info on request.
| 4e95d495f21d5a687a48d1edb0f389fb66d7e1cc | c58ddbf8e8cd6336a402bb7368731cccd88a52b7 | https://github.com/movingblocks/terasology/compare/4e95d495f21d5a687a48d1edb0f389fb66d7e1cc...c58ddbf8e8cd6336a402bb7368731cccd88a52b7 | diff --git a/engine/src/main/java/org/terasology/input/lwjgl/JInputControllerDevice.java b/engine/src/main/java/org/terasology/input/lwjgl/JInputControllerDevice.java
index 83c40910d..5d147734c 100644
--- a/engine/src/main/java/org/terasology/input/lwjgl/JInputControllerDevice.java
+++ b/engine/src/main/java/org/terasology/input/lwjgl/JInputControllerDevice.java
@@ -46,6 +46,7 @@
import java.util.Map;
import java.util.Queue;
import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
/**
* Retrieves information on connected controllers through JInput.
@@ -72,7 +73,8 @@ public class JInputControllerDevice implements ControllerDevice {
.build();
private ControllerConfig config;
- private final List<Controller> controllers = new ArrayList<>();
+ /* MUST be a CopyOnWriteArrayList! Or else you just get crashes when unplugging controllers. */
+ private final List<Controller> controllers = new CopyOnWriteArrayList<>();
public JInputControllerDevice(ControllerConfig config) {
this.config = config; | ['engine/src/main/java/org/terasology/input/lwjgl/JInputControllerDevice.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,417,930 | 2,014,478 | 262,176 | 2,194 | 300 | 58 | 4 | 1 | 443 | 77 | 112 | 22 | 1 | 0 | 2020-01-15T22:32:00 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
91 | movingblocks/terasology/3097/3091 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3091 | https://github.com/MovingBlocks/Terasology/pull/3097 | https://github.com/MovingBlocks/Terasology/pull/3097 | 1 | fix | Telemetry: indirect breaking of blocks causes NullPointerException | Relatively minor issue: some types of destruction can result in indirect breakage of blocks, such as when you break a block *below* a billboard plant, torch, or loose rock in JoshariasSurvival. This can lead to `EntityDestructionAuthoritySystem.recordDestroyed()` encountering a null `instigator` causing an NPE and stopping the destruction (meaning the thing on top doesn't pop)
We should either null-proof the use of instigator or find an alternative way to associate the block destruction with whomever did it. Likely of interest to @GabrielXia :-)
```
13:29:57.153 [main] INFO o.t.n.internal.NetworkSystemImpl - Component class org.terasology.network.NetworkComponent added to EntityRef{id = 55761, netId = 1999, prefab = 'Core:dustEffect'}
13:29:57.153 [main] INFO o.t.n.internal.NetworkSystemImpl - Component class org.terasology.logic.location.LocationComponent added to EntityRef{id = 55761, netId = 1999, prefab = 'Core:dustEffect'}
13:29:57.153 [main] INFO o.t.n.internal.NetworkSystemImpl - Component class org.terasology.entitySystem.entity.internal.EntityInfoComponent removed from EntityRef{id = 55758, netId = 1997}
13:29:57.153 [main] INFO o.t.n.internal.NetworkSystemImpl - Component class org.terasology.entitySystem.entity.internal.EntityInfoComponent added to EntityRef{id = 55758, netId = 1997}
13:29:57.153 [main] INFO o.t.n.internal.NetworkSystemImpl - Component class org.terasology.logic.health.HealthComponent removed from EntityRef{id = 55758, netId = 1997}
13:29:57.154 [main] ERROR o.t.e.event.internal.EventSystemImpl - Failed to invoke event
java.lang.NullPointerException: null
at org.terasology.logic.health.EntityDestructionAuthoritySystem.recordDestroyed(EntityDestructionAuthoritySystem.java:47)
at org.terasology.logic.health.EntityDestructionAuthoritySystem.onDestroy(EntityDestructionAuthoritySystem.java:33)
at org.terasology.logic.health.EntityDestructionAuthoritySystemMethodAccess.invoke(Unknown Source)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.world.block.structure.BlockStructuralSupportSystem.validateSupportForBlockOnSide(BlockStructuralSupportSystem.java:113)
at org.terasology.world.block.structure.BlockStructuralSupportSystem.checkForSupportRemoved(BlockStructuralSupportSystem.java:85)
at org.terasology.world.block.structure.BlockStructuralSupportSystemMethodAccess.invoke(Unknown Source)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.world.internal.EntityAwareWorldProvider.updateBlockEntity(EntityAwareWorldProvider.java:155)
at org.terasology.world.internal.EntityAwareWorldProvider.setBlock(EntityAwareWorldProvider.java:120)
at org.terasology.world.internal.WorldProviderWrapper.setBlock(WorldProviderWrapper.java:52)
at org.terasology.world.block.entity.BlockEntitySystem.doDestroy(BlockEntitySystem.java:88)
at org.terasology.world.block.entity.BlockEntitySystemMethodAccess.invoke(Unknown Source)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.logic.health.EntityDestructionAuthoritySystem.onDestroy(EntityDestructionAuthoritySystem.java:37)
at org.terasology.logic.health.EntityDestructionAuthoritySystemMethodAccess.invoke(Unknown Source)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.logic.health.HealthAuthoritySystem.doDamage(HealthAuthoritySystem.java:181)
at org.terasology.logic.health.HealthAuthoritySystem.checkDamage(HealthAuthoritySystem.java:196)
at org.terasology.logic.health.HealthAuthoritySystem.onDamage(HealthAuthoritySystem.java:188)
at org.terasology.logic.health.HealthAuthoritySystemMethodAccess.invoke(Unknown Source)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.logic.health.HealthAuthoritySystem.damageEntity(HealthAuthoritySystem.java:121)
at org.terasology.logic.health.BlockDamageAuthoritySystem.onAttackHealthlessBlock(BlockDamageAuthoritySystem.java:221)
at org.terasology.logic.health.BlockDamageAuthoritySystemMethodAccess.invoke(Unknown Source)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendConsumableEvent(EventSystemImpl.java:279)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:258)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.logic.characters.CharacterSystem.onAttackRequest(CharacterSystem.java:217)
at org.terasology.logic.characters.CharacterSystemMethodAccess.invoke(Unknown Source)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.network.internal.NetClient.processEvents(NetClient.java:527)
at org.terasology.network.internal.NetClient.processReceivedMessages(NetClient.java:423)
at org.terasology.network.internal.NetClient.update(NetClient.java:230)
at org.terasology.network.internal.NetworkSystemImpl.update(NetworkSystemImpl.java:319)
at org.terasology.engine.subsystem.common.NetworkSubsystem.preUpdate(NetworkSubsystem.java:46)
at org.terasology.engine.TerasologyEngine.tick(TerasologyEngine.java:428)
at org.terasology.engine.TerasologyEngine.mainLoop(TerasologyEngine.java:400)
at org.terasology.engine.TerasologyEngine.run(TerasologyEngine.java:376)
at org.terasology.engine.Terasology.main(Terasology.java:142)
13:29:57.483 [main] INFO o.t.n.internal.NetworkSystemImpl - Component class org.terasology.particles.components.affectors.AccelerationAffectorComponent added to EntityRef{id = 55882, netId = 2000, prefab = 'Core:defaultBlockParticles'}
13:29:57.483 [main] INFO o.t.n.internal.NetworkSystemImpl - Component class org.terasology.entitySystem.entity.internal.EntityInfoComponent added to EntityRef{id = 55882, netId = 2000, prefab = 'Core:defaultBlockParticles'}
13:29:57.483 [main] INFO o.t.n.internal.NetworkSystemImpl - Component class org.terasology.network.NetworkComponent added to EntityRef{id = 55882, netId = 2000, prefab = 'Core:defaultBlockParticles'}
``` | 79e6d0182ac888f1f52881aa97b6e299f219b24e | 1060b88e32842d99a3f4e48387579abb985d233c | https://github.com/movingblocks/terasology/compare/79e6d0182ac888f1f52881aa97b6e299f219b24e...1060b88e32842d99a3f4e48387579abb985d233c | diff --git a/engine/src/main/java/org/terasology/logic/health/EntityDestructionAuthoritySystem.java b/engine/src/main/java/org/terasology/logic/health/EntityDestructionAuthoritySystem.java
index e79321d66..84c633a32 100644
--- a/engine/src/main/java/org/terasology/logic/health/EntityDestructionAuthoritySystem.java
+++ b/engine/src/main/java/org/terasology/logic/health/EntityDestructionAuthoritySystem.java
@@ -30,7 +30,7 @@
public class EntityDestructionAuthoritySystem extends BaseComponentSystem {
@ReceiveEvent
public void onDestroy(DestroyEvent event, EntityRef entity) {
- recordDestroyed(event,entity);
+ recordDestroyed(event, entity);
BeforeDestroyEvent destroyCheck = new BeforeDestroyEvent(event.getInstigator(), event.getDirectCause(), event.getDamageType());
entity.send(destroyCheck);
if (!destroyCheck.isConsumed()) {
@@ -41,40 +41,42 @@ public void onDestroy(DestroyEvent event, EntityRef entity) {
private void recordDestroyed(DestroyEvent event, EntityRef entityRef) {
EntityRef instigator = event.getInstigator();
- if (entityRef.hasComponent(BlockComponent.class)) {
- BlockComponent blockComponent = entityRef.getComponent(BlockComponent.class);
- String blockName = blockComponent.getBlock().getDisplayName();
- if (instigator.hasComponent(GamePlayStatsComponent.class)) {
- GamePlayStatsComponent gamePlayStatsComponent = instigator.getComponent(GamePlayStatsComponent.class);
- Map<String, Integer> blockDestroyedMap = gamePlayStatsComponent.blockDestroyedMap;
- if (blockDestroyedMap.containsKey(blockName)) {
- blockDestroyedMap.put(blockName, blockDestroyedMap.get(blockName) + 1);
+ if (instigator != null) {
+ if (entityRef.hasComponent(BlockComponent.class)) {
+ BlockComponent blockComponent = entityRef.getComponent(BlockComponent.class);
+ String blockName = blockComponent.getBlock().getDisplayName();
+ if (instigator.hasComponent(GamePlayStatsComponent.class)) {
+ GamePlayStatsComponent gamePlayStatsComponent = instigator.getComponent(GamePlayStatsComponent.class);
+ Map<String, Integer> blockDestroyedMap = gamePlayStatsComponent.blockDestroyedMap;
+ if (blockDestroyedMap.containsKey(blockName)) {
+ blockDestroyedMap.put(blockName, blockDestroyedMap.get(blockName) + 1);
+ } else {
+ blockDestroyedMap.put(blockName, 1);
+ }
+ instigator.saveComponent(gamePlayStatsComponent);
} else {
+ GamePlayStatsComponent gamePlayStatsComponent = new GamePlayStatsComponent();
+ Map<String, Integer> blockDestroyedMap = gamePlayStatsComponent.blockDestroyedMap;
blockDestroyedMap.put(blockName, 1);
+ instigator.addOrSaveComponent(gamePlayStatsComponent);
}
- instigator.saveComponent(gamePlayStatsComponent);
- } else {
- GamePlayStatsComponent gamePlayStatsComponent = new GamePlayStatsComponent();
- Map<String, Integer> blockDestroyedMap = gamePlayStatsComponent.blockDestroyedMap;
- blockDestroyedMap.put(blockName, 1);
- instigator.addOrSaveComponent(gamePlayStatsComponent);
- }
- } else if (entityRef.hasComponent(CharacterComponent.class)) {
- String monsterName = entityRef.getParentPrefab().getName();
- if (instigator.hasComponent(GamePlayStatsComponent.class)) {
- GamePlayStatsComponent gamePlayStatsComponent = instigator.getComponent(GamePlayStatsComponent.class);
- Map<String, Integer> creatureKilled = gamePlayStatsComponent.creatureKilled;
- if (creatureKilled.containsKey(monsterName)) {
- creatureKilled.put(monsterName, creatureKilled.get(monsterName) + 1);
+ } else if (entityRef.hasComponent(CharacterComponent.class)) {
+ String creatureName = entityRef.getParentPrefab().getName();
+ if (instigator.hasComponent(GamePlayStatsComponent.class)) {
+ GamePlayStatsComponent gamePlayStatsComponent = instigator.getComponent(GamePlayStatsComponent.class);
+ Map<String, Integer> creatureKilled = gamePlayStatsComponent.creatureKilled;
+ if (creatureKilled.containsKey(creatureName)) {
+ creatureKilled.put(creatureName, creatureKilled.get(creatureName) + 1);
+ } else {
+ creatureKilled.put(creatureName, 1);
+ }
+ instigator.saveComponent(gamePlayStatsComponent);
} else {
- creatureKilled.put(monsterName, 1);
+ GamePlayStatsComponent gamePlayStatsComponent = new GamePlayStatsComponent();
+ Map<String, Integer> creatureKilled = gamePlayStatsComponent.creatureKilled;
+ creatureKilled.put(creatureName, 1);
+ instigator.addOrSaveComponent(gamePlayStatsComponent);
}
- instigator.saveComponent(gamePlayStatsComponent);
- } else {
- GamePlayStatsComponent gamePlayStatsComponent = new GamePlayStatsComponent();
- Map<String, Integer> creatureKilled = gamePlayStatsComponent.creatureKilled;
- creatureKilled.put(monsterName, 1);
- instigator.addOrSaveComponent(gamePlayStatsComponent);
}
}
} | ['engine/src/main/java/org/terasology/logic/health/EntityDestructionAuthoritySystem.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 8,644,562 | 1,855,564 | 242,122 | 2,064 | 4,582 | 799 | 62 | 1 | 8,265 | 363 | 1,881 | 75 | 0 | 1 | 2017-09-03T13:50:18 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
76 | movingblocks/terasology/3852/3850 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3850 | https://github.com/MovingBlocks/Terasology/pull/3852 | https://github.com/MovingBlocks/Terasology/pull/3852 | 1 | fixes | Server connection test updates actively selected server not the origin server | ### What you were trying to do
Look at servers accurately on the Join Game screen showing multiple servers
### What actually happened
Clicked a bad server (offline) first by accident, then selected a working server. When the failed ping test came back from the bad server it showed the result (being unable to connect to the server) on the good server, despite the other stats showing online and all is well.
Some threaded check holding that call probably needs to pick its update target better. Maybe at present it just updates the field regardless of the selected server, when perhaps it should be a call-back with the specific server queried? And if that isn't visible /selected then don't show it.
### How to reproduce
* Make sure there's both a working and not-working server in the join game list
* Select the broken server (should start a server query that'll time out)
* Quickly select a working server and wait a second or two, the connection to the good server will show that it "failed" | 95ee75e3eaef95d45569a3edfbf4ad875536d49c | d2f7e685392760395747ff2c1f09ae37d653d8ea | https://github.com/movingblocks/terasology/compare/95ee75e3eaef95d45569a3edfbf4ad875536d49c...d2f7e685392760395747ff2c1f09ae37d653d8ea | diff --git a/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/JoinGameScreen.java b/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/JoinGameScreen.java
index 8948a88be..ab0562a63 100644
--- a/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/JoinGameScreen.java
+++ b/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/JoinGameScreen.java
@@ -473,6 +473,7 @@ private String getModulesText(Future<ServerInfoMessage> info) {
private void refreshPing() {
String address = visibleList.getSelection().getAddress();
int port = visibleList.getSelection().getPort();
+ String name = visibleList.getSelection().getName();
UILabel ping = find("ping", UILabel.class);
ping.setText("Requested");
@@ -486,6 +487,8 @@ private void refreshPing() {
}
} catch (IOException e) {
String text = translationSystem.translate("${engine:menu#connection-failed}");
+ // Check if selection name is same as earlier when response is received before updating ping field
+ if (name.equals(visibleList.getSelection().getName()))
GameThread.asynch(() -> ping.setText(FontColor.getColored(text, Color.RED)));
}
}); | ['engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/JoinGameScreen.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,435,111 | 2,018,726 | 262,588 | 2,195 | 248 | 40 | 3 | 1 | 1,018 | 176 | 206 | 15 | 0 | 0 | 2020-03-11T16:37:03 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
75 | movingblocks/terasology/3858/3741 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3741 | https://github.com/MovingBlocks/Terasology/pull/3858 | https://github.com/MovingBlocks/Terasology/pull/3858 | 1 | fixed | Harden 'search' command against malformed assets | ### What you were trying to do
Search for stuff in the in-game console, like `search stone`
### What actually happened
Got a one-line error in the game console. Turned out an asset was misconfigured (was pointing to a template asset in the wrong module). After fixing that another similar case hit where the JSON in another asset was malformed, yet the error didn't give any clue _which _ asset.
Turns out I guess that to be able to search the engine goes and looks at every possible asset which means if it encounters even a single broken asset it'll error out and the search fails.
#1402 is a bigger goal to better validate assets (warnings at compile time somehow? Code scanning step?). But maybe we can harden `search` to better log what is breaking it?
#2874 also seems mildly similar
### How to reproduce
* Break an asset (like remove a comma or mess up a module name in a URI)
* Run the game and make sure the asset is within the active module set
* Run a `search` command for anything - get error!
### Example log
`An error occurred while executing command 'search': Unable to resolve based block definition 'CoreBlocks:rock'`
(in that case the `rock` template actually lived in the CoreAssets module instead) | 118079bb09ad795a88475bd3d78ff80a7cc1e54c | e417b18b83cb5595033880257124fff637c80eef | https://github.com/movingblocks/terasology/compare/118079bb09ad795a88475bd3d78ff80a7cc1e54c...e417b18b83cb5595033880257124fff637c80eef | diff --git a/engine/src/main/java/org/terasology/logic/console/commands/CoreCommands.java b/engine/src/main/java/org/terasology/logic/console/commands/CoreCommands.java
index a566bf51a..3b8bd34a9 100644
--- a/engine/src/main/java/org/terasology/logic/console/commands/CoreCommands.java
+++ b/engine/src/main/java/org/terasology/logic/console/commands/CoreCommands.java
@@ -49,6 +49,7 @@
import org.terasology.logic.console.suggesters.ScreenSuggester;
import org.terasology.logic.console.suggesters.SkinSuggester;
import org.terasology.logic.inventory.events.DropItemEvent;
+import org.terasology.logic.location.Location;
import org.terasology.logic.location.LocationComponent;
import org.terasology.logic.permission.PermissionManager;
import org.terasology.math.Direction;
@@ -83,15 +84,15 @@
import java.io.IOException;
import java.net.UnknownHostException;
-import java.util.concurrent.Callable;
-import java.util.stream.Collectors;
-import java.util.stream.StreamSupport;
import java.util.List;
import java.util.Set;
-import java.util.LinkedList;
+import java.util.ArrayList;
import java.util.Locale;
import java.util.Optional;
import java.util.Arrays;
+import java.util.concurrent.Callable;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
/**
* Adds a series of useful commands to the game. Likely these could be moved to more fitting places over time.
@@ -253,10 +254,27 @@ private List<String> findPrefabMatches(String searchLowercase) {
* @return List of blocks that match searched string
*/
private List<String> findBlockMatches(String searchLowercase) {
- return assetManager.getAvailableAssets(BlockFamilyDefinition.class)
- .stream().<Optional<BlockFamilyDefinition>>map(urn -> assetManager.getAsset(urn, BlockFamilyDefinition.class))
- .filter(def -> def.isPresent() && def.get().isLoadable() && matchesSearch(searchLowercase, def.get()))
- .map(r -> new BlockUri(r.get().getUrn()).toString()).collect(Collectors.toList());
+ ResourceUrn curUrn;
+ List<String> outputList=new ArrayList<String>();
+ for (ResourceUrn urn : assetManager.getAvailableAssets(BlockFamilyDefinition.class)) {
+ // Current urn for logging purposes to find the broken urn
+ curUrn = urn;
+ try{
+ Optional<BlockFamilyDefinition> def = assetManager.getAsset(urn, BlockFamilyDefinition.class);
+ if (def.isPresent() && def.get().isLoadable() && matchesSearch(searchLowercase, def.get())) {
+ outputList.add(new BlockUri(def.get().getUrn()).toString());
+ }
+ }
+ // If a prefab is broken , it will throw an exception
+ catch(Exception e){
+ console.addMessage("Note : Search may not return results if invalid assets are present");
+ console.addMessage("Error parsing : "+curUrn.toString());
+ console.addMessage(e.toString());
+ continue;
+ }
+ }
+ return outputList;
+
}
/** | ['engine/src/main/java/org/terasology/logic/console/commands/CoreCommands.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,435,403 | 2,018,772 | 262,593 | 2,195 | 1,818 | 340 | 34 | 1 | 1,253 | 217 | 273 | 25 | 0 | 0 | 2020-03-16T22:10:01 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
74 | movingblocks/terasology/4056/4031 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/4031 | https://github.com/MovingBlocks/Terasology/pull/4056 | https://github.com/MovingBlocks/Terasology/pull/4056 | 1 | fixes | Serialization stack overflow | The game crashed with a stack overflow error. The stack trace was the following, repeated many times:
at org.terasology.persistence.typeHandling.FutureTypeHandler.serialize(FutureTypeHandler.java:32)
at org.terasology.persistence.typeHandling.coreTypes.RuntimeDelegatingTypeHandler.serializeViaDelegate(RuntimeDelegatingTypeHandler.java:162)
at org.terasology.persistence.typeHandling.coreTypes.RuntimeDelegatingTypeHandler.serializeNonNull(RuntimeDelegatingTypeHandler.java:118)
at org.terasology.persistence.typeHandling.TypeHandler.serialize(TypeHandler.java:49)
at org.terasology.persistence.typeHandling.coreTypes.ObjectFieldMapTypeHandler.serializeNonNull(ObjectFieldMapTypeHandler.java:71)
at org.terasology.persistence.typeHandling.TypeHandler.serialize(TypeHandler.java:49)
It ran for a minute or so before this happened, using much more CPU than usual (but this was probably just the ocean falling into caves). I was using JS + FlowingLiquids (and some almost certainly irrelevant changes that would never have even executed under the circumstances).
I haven't been able to replicate it in any other worlds, and I can't load the one where I originally saw it because chunk generation times out. | 26f605be6552cf6473a7b25a1270f9a0de014476 | b955fe6f9c5134f2e2de9c31a8afc0340e429920 | https://github.com/movingblocks/terasology/compare/26f605be6552cf6473a7b25a1270f9a0de014476...b955fe6f9c5134f2e2de9c31a8afc0340e429920 | diff --git a/engine/src/main/java/org/terasology/particles/components/ParticleEmitterComponent.java b/engine/src/main/java/org/terasology/particles/components/ParticleEmitterComponent.java
index 3e974f550..212e9006c 100644
--- a/engine/src/main/java/org/terasology/particles/components/ParticleEmitterComponent.java
+++ b/engine/src/main/java/org/terasology/particles/components/ParticleEmitterComponent.java
@@ -94,7 +94,7 @@ public class ParticleEmitterComponent implements Component {
/**
* This emitter's particle pool.
*/
- public ParticlePool particlePool;
+ public transient ParticlePool particlePool;
/**
* Maps Generator component -> Function that processes that Generator
diff --git a/engine/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java b/engine/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java
index 2ae9261e8..b524383b7 100644
--- a/engine/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java
+++ b/engine/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java
@@ -68,9 +68,14 @@ public PersistedData serializeNonNull(T value, PersistedDataSerializer serialize
if (!Objects.equals(val, Defaults.defaultValue(field.getType()))) {
TypeHandler handler = entry.getValue();
- PersistedData fieldValue = handler.serialize(val, serializer);
- if (fieldValue != null) {
- mappedData.put(getFieldName(field), fieldValue);
+ try {
+ PersistedData fieldValue = handler.serialize(val, serializer);
+ if (fieldValue != null) {
+ mappedData.put(getFieldName(field), fieldValue);
+ }
+ } catch (StackOverflowError e) {
+ logger.error("Likely circular reference in field {}.", field);
+ throw e;
}
}
} | ['engine/src/main/java/org/terasology/particles/components/ParticleEmitterComponent.java', 'engine/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,199,192 | 1,963,203 | 257,100 | 2,122 | 694 | 110 | 13 | 2 | 1,224 | 103 | 251 | 12 | 0 | 0 | 2020-06-18T00:30:08 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
73 | movingblocks/terasology/4093/4092 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/4092 | https://github.com/MovingBlocks/Terasology/pull/4093 | https://github.com/MovingBlocks/Terasology/pull/4093 | 1 | fixes | Null pointer exception when trying to use load latest. | <!-- Thanks for taking the time to submit a thorough issue report for Terasology! :-)
Please fill out whichever details below seem relevant to your issue.
Note that suggestions, general questions & support should go in the forum:
* http://forum.terasology.org/forum/suggestions.21
* http://forum.terasology.org/forum/support.20/
Bug reports and crashes likely resulting from bugs in the engine go here on GitHub. -->
### What you were trying to do
Use the load latest configuration.
### What actually happened
Null pointer exception in the Terasology java class
### How to reproduce
* Step 1
Try to use the load latest configuration.
* Step 2
Crash...
### Log details and game version
I think 3.2.0
### Computer details
i7 7700k
GTX 2080ti
16GB Ram
NVMe 128gb SSD
| f683f12906677363da41fc261ca82566d20b8c2b | dc2250151f3559ccadc88e886ea2720c5a529713 | https://github.com/movingblocks/terasology/compare/f683f12906677363da41fc261ca82566d20b8c2b...dc2250151f3559ccadc88e886ea2720c5a529713 | diff --git a/engine/src/main/java/org/terasology/engine/TerasologyEngine.java b/engine/src/main/java/org/terasology/engine/TerasologyEngine.java
index 209e1fb95..3ece241eb 100644
--- a/engine/src/main/java/org/terasology/engine/TerasologyEngine.java
+++ b/engine/src/main/java/org/terasology/engine/TerasologyEngine.java
@@ -137,6 +137,7 @@ public class TerasologyEngine implements GameEngine {
private TimeSubsystem timeSubsystem;
private Deque<EngineSubsystem> allSubsystems;
private ModuleAwareAssetTypeManager assetTypeManager;
+ private boolean initialisedAlready;
/**
* Contains objects that live for the duration of this engine.
@@ -201,40 +202,43 @@ protected void addToClassesOnClasspathsToAddToEngine(Class<?> clazz) {
public void initialize() {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Stopwatch totalInitTime = Stopwatch.createStarted();
- try {
- logger.info("Initializing Terasology...");
- logEnvironmentInfo();
+ if (!initialisedAlready) {
+ try {
+ logger.info("Initializing Terasology...");
+ logEnvironmentInfo();
- // TODO: Need to get everything thread safe and get rid of the concept of "GameThread" as much as possible.
- GameThread.setToCurrentThread();
+ // TODO: Need to get everything thread safe and get rid of the concept of "GameThread" as much as possible.
+ GameThread.setToCurrentThread();
- preInitSubsystems();
+ preInitSubsystems();
- initManagers();
+ initManagers();
- initSubsystems();
+ initSubsystems();
- changeStatus(TerasologyEngineStatus.INITIALIZING_ASSET_MANAGEMENT);
- initAssets();
+ changeStatus(TerasologyEngineStatus.INITIALIZING_ASSET_MANAGEMENT);
+ initAssets();
- EnvironmentSwitchHandler environmentSwitcher = new EnvironmentSwitchHandler();
- rootContext.put(EnvironmentSwitchHandler.class, environmentSwitcher);
+ EnvironmentSwitchHandler environmentSwitcher = new EnvironmentSwitchHandler();
+ rootContext.put(EnvironmentSwitchHandler.class, environmentSwitcher);
- environmentSwitcher.handleSwitchToGameEnvironment(rootContext);
+ environmentSwitcher.handleSwitchToGameEnvironment(rootContext);
- postInitSubsystems();
+ postInitSubsystems();
- verifyInitialisation();
+ verifyInitialisation();
- /*
- * Prevent objects being put in engine context after init phase. Engine states should use/create a
- * child context.
- */
- CoreRegistry.setContext(null);
- } catch (RuntimeException e) {
- logger.error("Failed to initialise Terasology", e);
- cleanup();
- throw e;
+ /*
+ * Prevent objects being put in engine context after init phase. Engine states should use/create a
+ * child context.
+ */
+ CoreRegistry.setContext(null);
+ initialisedAlready = true;
+ } catch (RuntimeException e) {
+ logger.error("Failed to initialise Terasology", e);
+ cleanup();
+ throw e;
+ }
}
double seconds = 0.001 * totalInitTime.elapsed(TimeUnit.MILLISECONDS);
diff --git a/facades/PC/src/main/java/org/terasology/engine/Terasology.java b/facades/PC/src/main/java/org/terasology/engine/Terasology.java
index 9887c9417..bac293d19 100644
--- a/facades/PC/src/main/java/org/terasology/engine/Terasology.java
+++ b/facades/PC/src/main/java/org/terasology/engine/Terasology.java
@@ -152,6 +152,7 @@ public static void main(String[] args) {
engine.run(new StateHeadlessSetup());
} else {
if (loadLastGame) {
+ engine.initialize(); //initialize the managers first
engine.getFromEngineContext(ThreadManager.class).submitTask("loadGame", () -> {
GameManifest gameManifest = getLatestGameManifest();
if (gameManifest != null) { | ['facades/PC/src/main/java/org/terasology/engine/Terasology.java', 'engine/src/main/java/org/terasology/engine/TerasologyEngine.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,212,258 | 1,966,564 | 257,392 | 2,122 | 2,644 | 434 | 53 | 2 | 793 | 121 | 194 | 26 | 2 | 0 | 2020-07-21T18:33:27 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
72 | movingblocks/terasology/4131/2469 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/2469 | https://github.com/MovingBlocks/Terasology/pull/4131 | https://github.com/MovingBlocks/Terasology/pull/4131 | 1 | fixes | Crash when Characters die from fall damage during server prediction | ### What you were trying to do
Move a deer with high movement speed off a cliff
### What actually happened
Server crashes with ConcurrentModificationException, similar to (but distinct from) #2468 since it's a different collection and the event is dispatch from the `update` method of a component system rather than a BT Node.
### How to reproduce
Kill a (non-player) character with fall damage (via CharacterMoveInputEvent).
### Log details and game version
```
"main@1" prio=10 tid=0x1 nid=NA runnable
java.lang.Thread.State: RUNNABLE
at org.terasology.logic.characters.ServerCharacterPredictionSystem.onDestroy(ServerCharacterPredictionSystem.java:97)
at org.terasology.logic.characters.ServerCharacterPredictionSystemMethodAccess.invoke(Unknown Source:-1)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.PojoEntityManager.destroy(PojoEntityManager.java:538)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.destroy(BaseEntityRef.java:138)
at org.terasology.logic.health.EntityDestructionAuthoritySystem.onDestroy(EntityDestructionAuthoritySystem.java:32)
at org.terasology.logic.health.EntityDestructionAuthoritySystemMethodAccess.invoke(Unknown Source:-1)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.logic.health.HealthAuthoritySystem.doDamage(HealthAuthoritySystem.java:185)
at org.terasology.logic.health.HealthAuthoritySystem.checkDamage(HealthAuthoritySystem.java:200)
at org.terasology.logic.health.HealthAuthoritySystem.onLand(HealthAuthoritySystem.java:241)
at org.terasology.logic.health.HealthAuthoritySystemMethodAccess.invoke(Unknown Source:-1)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.logic.characters.KinematicCharacterMover.walk(KinematicCharacterMover.java:647)
at org.terasology.logic.characters.KinematicCharacterMover.updatePosition(KinematicCharacterMover.java:559)
at org.terasology.logic.characters.KinematicCharacterMover.step(KinematicCharacterMover.java:103)
at org.terasology.logic.characters.ServerCharacterPredictionSystem.stepState(ServerCharacterPredictionSystem.java:168)
at org.terasology.logic.characters.ServerCharacterPredictionSystem.onPlayerInput(ServerCharacterPredictionSystem.java:126)
at org.terasology.logic.characters.ServerCharacterPredictionSystemMethodAccess.invoke(Unknown Source:-1)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:506)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:269)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:260)
at org.terasology.entitySystem.entity.internal.BaseEntityRef.send(BaseEntityRef.java:145)
at org.terasology.flexiblemovement.FlexibleMovementSystem.update(FlexibleMovementSystem.java:37)
at org.terasology.engine.modes.StateIngame.update(StateIngame.java:176)
at org.terasology.engine.TerasologyEngine.mainLoop(TerasologyEngine.java:413)
at org.terasology.engine.TerasologyEngine.run(TerasologyEngine.java:368)
- locked <0x1906> (a org.terasology.engine.TerasologyEngine)
at org.terasology.engine.Terasology.main(Terasology.java:152)
```
##
| a3d99b4f794f509c7f197d3d7b2b2b0f60b9ac8f | b34013d7c529d8eb3540ed0034c36fb66a8367dc | https://github.com/movingblocks/terasology/compare/a3d99b4f794f509c7f197d3d7b2b2b0f60b9ac8f...b34013d7c529d8eb3540ed0034c36fb66a8367dc | diff --git a/engine/src/main/java/org/terasology/logic/characters/ServerCharacterPredictionSystem.java b/engine/src/main/java/org/terasology/logic/characters/ServerCharacterPredictionSystem.java
index 91906d244..562c279f1 100644
--- a/engine/src/main/java/org/terasology/logic/characters/ServerCharacterPredictionSystem.java
+++ b/engine/src/main/java/org/terasology/logic/characters/ServerCharacterPredictionSystem.java
@@ -16,6 +16,8 @@
package org.terasology.logic.characters;
+
+import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -43,6 +45,7 @@
import org.terasology.utilities.collection.CircularBuffer;
import org.terasology.world.WorldProvider;
+import java.util.List;
import java.util.Map;
@RegisterSystem(RegisterMode.AUTHORITY)
@@ -81,6 +84,7 @@ public class ServerCharacterPredictionSystem extends BaseComponentSystem impleme
private CharacterMover characterMover;
private Map<EntityRef, CircularBuffer<CharacterStateEvent>> characterStates = Maps.newHashMap();
+ private List<EntityRef> characterStatesToRemove = Lists.newArrayList();
private Map<EntityRef, CharacterMoveInputEvent> lastInputEvent = Maps.newHashMap();
private long nextSendState;
private CharacterMovementSystemUtility characterMovementSystemUtility;
@@ -103,7 +107,7 @@ public void onCreate(final OnActivatedComponent event, final EntityRef entity) {
@ReceiveEvent(components = {CharacterMovementComponent.class, LocationComponent.class, AliveCharacterComponent.class})
public void onDestroy(final BeforeDeactivateComponent event, final EntityRef entity) {
physics.removeCharacterCollider(entity);
- characterStates.remove(entity);
+ characterStatesToRemove.add(entity);
lastInputEvent.remove(entity);
}
@@ -200,7 +204,8 @@ public void update(float delta) {
// Haven't received input in a while, repeat last input
CharacterMoveInputEvent lastInput = lastInputEvent.get(entry.getKey());
if (lastInput != null) {
- CharacterMoveInputEvent newInput = new CharacterMoveInputEvent(lastInput, (int) (time.getGameTimeInMs() - state.getTime()));
+ CharacterMoveInputEvent newInput = new CharacterMoveInputEvent(lastInput,
+ (int) (time.getGameTimeInMs() - state.getTime()));
onPlayerInput(newInput, entry.getKey());
}
entry.getKey().send(state);
@@ -214,9 +219,12 @@ public void update(float delta) {
if (entry.getKey().equals(localPlayer.getCharacterEntity())) {
continue;
}
-
- setToTime(renderTime, entry.getKey(), entry.getValue());
+ if (!characterStatesToRemove.contains(entry.getKey())) {
+ setToTime(renderTime, entry.getKey(), entry.getValue());
+ }
}
+ characterStates.keySet().removeAll(characterStatesToRemove);
+ characterStatesToRemove.clear();
}
private void setToTime(long renderTime, EntityRef entity, CircularBuffer<CharacterStateEvent> buffer) { | ['engine/src/main/java/org/terasology/logic/characters/ServerCharacterPredictionSystem.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 8,571,840 | 1,830,414 | 237,834 | 1,976 | 918 | 160 | 16 | 1 | 4,422 | 164 | 985 | 54 | 0 | 1 | 2020-08-18T21:24:45 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
90 | movingblocks/terasology/3174/3158 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3158 | https://github.com/MovingBlocks/Terasology/pull/3174 | https://github.com/MovingBlocks/Terasology/pull/3174 | 1 | resolves | Improve null handling / logging in ItemPickupAuthoritySystem | Noticed this issue on startup with the new module BasicCrafting enabled. It isn't caused by BC but that module exercises stuff on initialization that triggers it. Some block somewhere isn't fully configured right and that's tripping up that bit of code - it doesn't seem to lead to any issues, but it would be good to be able to log more cleanly what is going on.
```
21:40:17.348 [main] INFO o.t.w.b.internal.BlockManagerImpl - Registered Block core:RedShroom with id 31
21:40:17.374 [main] ERROR o.t.e.event.internal.EventSystemImpl - Failed to invoke event
java.lang.NullPointerException: null
at org.terasology.logic.inventory.ItemPickupAuthoritySystem.updateExtentsOnBlockItemBoxShape(ItemPickupAuthoritySystem.java:92)
at org.terasology.logic.inventory.ItemPickupAuthoritySystemMethodAccess.invoke(Unknown Source)
at org.terasology.entitySystem.event.internal.EventSystemImpl$ByteCodeEventHandlerInfo.invoke(EventSystemImpl.java:516)
at org.terasology.entitySystem.event.internal.EventSystemImpl.sendStandardEvent(EventSystemImpl.java:279)
at org.terasology.entitySystem.event.internal.EventSystemImpl.send(EventSystemImpl.java:270)
at org.terasology.entitySystem.entity.internal.PojoEntityManager.create(PojoEntityManager.java:166)
at org.terasology.entitySystem.entity.internal.PojoEntityManager.create(PojoEntityManager.java:274)
at org.terasology.crafting.systems.IconManagerImpl.loadItems(IconManagerImpl.java:144)
at org.terasology.crafting.systems.IconManagerImpl.postBegin(IconManagerImpl.java:69)
at org.terasology.engine.modes.loadProcesses.PostBeginSystems.step(PostBeginSystems.java:53)
at org.terasology.engine.modes.StateLoading.update(StateLoading.java:242)
at org.terasology.engine.TerasologyEngine.tick(TerasologyEngine.java:437)
at org.terasology.engine.TerasologyEngine.mainLoop(TerasologyEngine.java:400)
at org.terasology.engine.TerasologyEngine.run(TerasologyEngine.java:376)
at org.terasology.engine.Terasology.main(Terasology.java:154)
21:40:17.439 [main] INFO o.t.w.b.internal.BlockManagerImpl - Registered BlockFamily[Core:Cotton4]
21:40:17.439 [main] INFO o.t.w.b.internal.BlockManagerImpl - Registered Block Core:Cotton4 with id 32
```
Goal: Catch and handle the null more gracefully in `ItemPickupAuthoritySystem.updateExtentsOnBlockItemBoxShape` - try to see what other information is available and log the details at WARN level then continue normally instead of throwing the stacktrace.
Running with Core + BC enabled and checking the startup logs shows this issue repeatedly so it shouldn't be hard to trigger the condition.
Good bite-sized issue and we can create a GCI task for it if somebody is interested. | 9377f61647a9d2dd313adb17aae4a1aea01c3a3d | f8ed134e1a619f0ba9fccb7c96a33f1121f02494 | https://github.com/movingblocks/terasology/compare/9377f61647a9d2dd313adb17aae4a1aea01c3a3d...f8ed134e1a619f0ba9fccb7c96a33f1121f02494 | diff --git a/engine/src/main/java/org/terasology/logic/inventory/ItemPickupAuthoritySystem.java b/engine/src/main/java/org/terasology/logic/inventory/ItemPickupAuthoritySystem.java
index f84565863..389923880 100644
--- a/engine/src/main/java/org/terasology/logic/inventory/ItemPickupAuthoritySystem.java
+++ b/engine/src/main/java/org/terasology/logic/inventory/ItemPickupAuthoritySystem.java
@@ -17,6 +17,8 @@
package org.terasology.logic.inventory;
import com.bulletphysics.collision.shapes.BoxShape;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.terasology.engine.Time;
import org.terasology.entitySystem.Component;
import org.terasology.entitySystem.entity.EntityRef;
@@ -44,6 +46,8 @@
*/
@RegisterSystem(RegisterMode.AUTHORITY)
public class ItemPickupAuthoritySystem extends BaseComponentSystem {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ItemPickupAuthoritySystem.class);
+
@In
private EntitySystemLibrary library;
@@ -89,6 +93,12 @@ public void updateExtentsOnBlockItemBoxShape(OnAddedComponent event, EntityRef i
BlockItemComponent blockItemComponent,
BoxShapeComponent boxShapeComponent) {
BlockFamily blockFamily = blockItemComponent.blockFamily;
+
+ if (blockFamily == null) {
+ LOGGER.warn("Prefab " + itemEntity.getParentPrefab().getName() + " does not have a block family");
+ return;
+ }
+
if (blockFamily.getArchetypeBlock().getCollisionShape() instanceof BoxShape) {
javax.vecmath.Vector3f extents = ((BoxShape) blockFamily.getArchetypeBlock().getCollisionShape()).getHalfExtentsWithoutMargin(new javax.vecmath.Vector3f());
extents.scale(2.0f); | ['engine/src/main/java/org/terasology/logic/inventory/ItemPickupAuthoritySystem.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 8,679,084 | 1,862,644 | 243,101 | 2,070 | 344 | 68 | 10 | 1 | 2,698 | 213 | 637 | 30 | 0 | 1 | 2017-12-10T05:12:33 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
88 | movingblocks/terasology/3492/3486 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3486 | https://github.com/MovingBlocks/Terasology/pull/3492 | https://github.com/MovingBlocks/Terasology/pull/3492 | 1 | fixes | Region3i.EMPTY bug | There is a serious flaw in the way Region3i deals with empty regions.
For some reason (optimization?) Region3i has a public and static instance Region3i.EMPTY.
There is nothing that prevents users from accidentally changing the empty region.
What makes it even worse is that the factory functions sometimes just return Region3i.EMPTY, to save the costs of a copy constructor.
This code snippet can destroy the invariant of the empty region being empty:
```
Vector3i a = foo();
Vector3i b = bar();
Region3i region = Region3i.createFromMinMax(a, b);
region.expand(otherRegion); // Oops, Region3i.EMPTY is now equal to otherRegion
```
### How to confirm
This test fails if added to the Region3i tests.
```
@Test
public void testFactoryShouldNotReturnTheEmptySingleton() {
Region3i constructed = Region3i.createFromMinMax(Vector3i.zero(), Vector3i.one().negate());
assertFalse(constructed == Region3i.EMPTY); // This fails
}
```
### Suggested Solution
Remove Region3i.EMPTY, and no longer threat is as special instance.
Add Region3i.empty(), creating a new empty region each time it is called. | b6f2a203f8d5236485c3af1f383301cbdd303fe4 | 0f117c1565f686783717c9b7bcf57eff6d83de89 | https://github.com/movingblocks/terasology/compare/b6f2a203f8d5236485c3af1f383301cbdd303fe4...0f117c1565f686783717c9b7bcf57eff6d83de89 | diff --git a/engine-tests/src/test/java/org/terasology/math/Region3iTest.java b/engine-tests/src/test/java/org/terasology/math/Region3iTest.java
index 056719183..2101f3ba8 100644
--- a/engine-tests/src/test/java/org/terasology/math/Region3iTest.java
+++ b/engine-tests/src/test/java/org/terasology/math/Region3iTest.java
@@ -33,10 +33,9 @@
public class Region3iTest {
@Test
- public void testEmptyConstructor() {
- Region3i region = Region3i.EMPTY;
- assertEquals(new Vector3i(), region.size());
- assertTrue(region.isEmpty());
+ public void testEmptyRegion() {
+ assertEquals(Region3i.empty().size(), Vector3i.zero());
+ assertTrue(Region3i.empty().isEmpty());
}
@Test
@@ -127,7 +126,7 @@ public void testSimpleIntersect() {
public void testNonTouchingIntersect() {
Region3i region1 = Region3i.createFromMinMax(new Vector3i(), new Vector3i(32, 32, 32));
Region3i region2 = Region3i.createFromMinMax(new Vector3i(103, 103, 103), new Vector3i(170, 170, 170));
- assertEquals(Region3i.EMPTY, region1.intersect(region2));
+ assertEquals(Region3i.empty(), region1.intersect(region2));
}
@Test
diff --git a/engine/src/main/java/org/terasology/math/Region3i.java b/engine/src/main/java/org/terasology/math/Region3i.java
index 11a706c23..700e0753d 100644
--- a/engine/src/main/java/org/terasology/math/Region3i.java
+++ b/engine/src/main/java/org/terasology/math/Region3i.java
@@ -28,7 +28,14 @@
*
*/
public final class Region3i implements Iterable<Vector3i> {
- public static final Region3i EMPTY = new Region3i();
+
+ /**
+ * @deprecated As of 24 sep 2018, because it is error prone.
+ * Everyone can change this instance and destroy the invariant properties.
+ * Some methods used to return this instance silently on special cases.
+ */
+ @Deprecated
+ public static final Region3i EMPTY = Region3i.empty();
private final Vector3i min = new Vector3i();
private final Vector3i size = new Vector3i();
@@ -44,6 +51,14 @@ private Region3i(BaseVector3i min, BaseVector3i size) {
this.size.set(size);
}
+ /**
+ * An empty Region with size (0,0,0).
+ * @return An empty Region3i
+ */
+ public static Region3i empty() {
+ return new Region3i();
+ }
+
/**
* @param min the min point of the region
* @param size the size of the region
@@ -51,7 +66,7 @@ private Region3i(BaseVector3i min, BaseVector3i size) {
*/
public static Region3i createFromMinAndSize(BaseVector3i min, BaseVector3i size) {
if (size.x() <= 0 || size.y() <= 0 || size.z() <= 0) {
- return EMPTY;
+ return empty();
}
return new Region3i(min, size);
}
@@ -118,7 +133,7 @@ public static Region3i createBounded(BaseVector3i a, BaseVector3i b) {
public static Region3i createFromMinMax(BaseVector3i min, BaseVector3i max) {
Vector3i size = new Vector3i(max.x() - min.x() + 1, max.y() - min.y() + 1, max.z() - min.z() + 1);
if (size.x <= 0 || size.y <= 0 || size.z <= 0) {
- return EMPTY;
+ return empty();
}
return new Region3i(min, size);
}
diff --git a/engine/src/main/java/org/terasology/rendering/world/RenderableWorldImpl.java b/engine/src/main/java/org/terasology/rendering/world/RenderableWorldImpl.java
index 153119133..44a1f3634 100644
--- a/engine/src/main/java/org/terasology/rendering/world/RenderableWorldImpl.java
+++ b/engine/src/main/java/org/terasology/rendering/world/RenderableWorldImpl.java
@@ -65,7 +65,7 @@ class RenderableWorldImpl implements RenderableWorld {
private ChunkTessellator chunkTessellator;
private final ChunkMeshUpdateManager chunkMeshUpdateManager;
private final List<RenderableChunk> chunksInProximityOfCamera = Lists.newArrayListWithCapacity(MAX_LOADABLE_CHUNKS);
- private Region3i renderableRegion = Region3i.EMPTY;
+ private Region3i renderableRegion = Region3i.empty();
private ViewDistance currentViewDistance;
private RenderQueuesHelper renderQueues;
diff --git a/engine/src/main/java/org/terasology/world/block/regions/BlockRegionComponent.java b/engine/src/main/java/org/terasology/world/block/regions/BlockRegionComponent.java
index 4c006d86d..8338f8ba5 100644
--- a/engine/src/main/java/org/terasology/world/block/regions/BlockRegionComponent.java
+++ b/engine/src/main/java/org/terasology/world/block/regions/BlockRegionComponent.java
@@ -24,7 +24,7 @@
*/
public class BlockRegionComponent implements Component {
@Replicate
- public Region3i region = Region3i.EMPTY;
+ public Region3i region = Region3i.empty();
public boolean overrideBlockEntities = true;
public BlockRegionComponent() {
diff --git a/engine/src/main/java/org/terasology/world/chunks/internal/ChunkRelevanceRegion.java b/engine/src/main/java/org/terasology/world/chunks/internal/ChunkRelevanceRegion.java
index 86bc73e08..abecb8a81 100644
--- a/engine/src/main/java/org/terasology/world/chunks/internal/ChunkRelevanceRegion.java
+++ b/engine/src/main/java/org/terasology/world/chunks/internal/ChunkRelevanceRegion.java
@@ -36,8 +36,8 @@ public class ChunkRelevanceRegion {
private Vector3i relevanceDistance = new Vector3i();
private boolean dirty;
private Vector3i center = new Vector3i();
- private Region3i currentRegion = Region3i.EMPTY;
- private Region3i previousRegion = Region3i.EMPTY;
+ private Region3i currentRegion = Region3i.empty();
+ private Region3i previousRegion = Region3i.empty();
private ChunkRegionListener listener;
private Set<Vector3i> relevantChunks = Sets.newLinkedHashSet();
@@ -123,7 +123,7 @@ private Region3i calculateRegion() {
Vector3i extents = new Vector3i(relevanceDistance.x / 2, relevanceDistance.y / 2, relevanceDistance.z / 2);
return Region3i.createFromCenterExtents(ChunkMath.calcChunkPos(loc.getWorldPosition()), extents);
}
- return Region3i.EMPTY;
+ return Region3i.empty();
}
private Vector3i calculateCenter() { | ['engine/src/main/java/org/terasology/world/block/regions/BlockRegionComponent.java', 'engine-tests/src/test/java/org/terasology/math/Region3iTest.java', 'engine/src/main/java/org/terasology/world/chunks/internal/ChunkRelevanceRegion.java', 'engine/src/main/java/org/terasology/math/Region3i.java', 'engine/src/main/java/org/terasology/rendering/world/RenderableWorldImpl.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 9,386,155 | 2,010,049 | 260,995 | 2,197 | 1,158 | 264 | 31 | 4 | 1,125 | 153 | 253 | 26 | 0 | 2 | 2018-09-24T12:19:55 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
87 | movingblocks/terasology/3499/3010 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3010 | https://github.com/MovingBlocks/Terasology/pull/3499 | https://github.com/MovingBlocks/Terasology/pull/3499 | 1 | fixes | Advanced chunk monitor prevents game from closing cleanly | ### What you were trying to do
Run and close the game cleanly with `monitoringEnabled` set to true (for example to test #3006)
### What actually happened
Game windows (there are two with the monitor visible) closed, but the game didn't exit. Some thread triggered by the monitor isn't exiting on game exit
### How to reproduce
* Toggle `"monitoringEnabled": false,` to `true` in `config.cfg` (run the game once to get one)
* Run the game
* Close the game
* Protip: Trigger a thread dump in IntelliJ to inspect threads that are still alive after exiting (little camera looking icon near the bottom left, in the run window) | 9118708ad3f34f0bc05572fe54ad47538c3164bb | d1c5439d855defae557458d6b0f5b5eefcd8377c | https://github.com/movingblocks/terasology/compare/9118708ad3f34f0bc05572fe54ad47538c3164bb...d1c5439d855defae557458d6b0f5b5eefcd8377c | diff --git a/engine/src/main/java/org/terasology/engine/subsystem/common/MonitoringSubsystem.java b/engine/src/main/java/org/terasology/engine/subsystem/common/MonitoringSubsystem.java
index 2b02119e9..04e574d6a 100644
--- a/engine/src/main/java/org/terasology/engine/subsystem/common/MonitoringSubsystem.java
+++ b/engine/src/main/java/org/terasology/engine/subsystem/common/MonitoringSubsystem.java
@@ -21,9 +21,6 @@
import org.terasology.engine.subsystem.EngineSubsystem;
import org.terasology.monitoring.gui.AdvancedMonitor;
-/**
- *
- */
public class MonitoringSubsystem implements EngineSubsystem {
private AdvancedMonitor advancedMonitor;
@@ -44,7 +41,7 @@ public void initialise(GameEngine engine, Context rootContext) {
@Override
public void shutdown() {
if (advancedMonitor != null) {
- advancedMonitor.setVisible(false);
+ advancedMonitor.close();
}
}
}
diff --git a/engine/src/main/java/org/terasology/monitoring/gui/AdvancedMonitor.java b/engine/src/main/java/org/terasology/monitoring/gui/AdvancedMonitor.java
index 1b083560b..b9f0d7b3d 100644
--- a/engine/src/main/java/org/terasology/monitoring/gui/AdvancedMonitor.java
+++ b/engine/src/main/java/org/terasology/monitoring/gui/AdvancedMonitor.java
@@ -15,17 +15,16 @@
*/
package org.terasology.monitoring.gui;
-import javax.swing.*;
-import java.awt.*;
+import javax.swing.JTabbedPane;
+import javax.swing.JFrame;
+import java.awt.BorderLayout;
@SuppressWarnings("serial")
public class AdvancedMonitor extends JFrame {
- private final JTabbedPane tabs;
-
private final ThreadMonitorPanel threadMonitor;
private final ChunkMonitorPanel chunkMonitor;
- private final PerformanceMonitorPanel perfMonitor;
+ private final PerformanceMonitorPanel performanceMonitor;
public AdvancedMonitor() {
this("Advanced Monitoring Tool", 10, 10, 800, 600);
@@ -36,7 +35,7 @@ public AdvancedMonitor(String title, int x, int y, int width, int height) {
setBounds(x, y, width, height);
setLayout(new BorderLayout());
- tabs = new JTabbedPane();
+ JTabbedPane tabs = new JTabbedPane();
threadMonitor = new ThreadMonitorPanel();
threadMonitor.setVisible(true);
@@ -44,13 +43,30 @@ public AdvancedMonitor(String title, int x, int y, int width, int height) {
chunkMonitor = new ChunkMonitorPanel();
chunkMonitor.setVisible(true);
- perfMonitor = new PerformanceMonitorPanel();
- perfMonitor.setVisible(true);
+ performanceMonitor = new PerformanceMonitorPanel();
+ performanceMonitor.setVisible(true);
tabs.add("Threads", threadMonitor);
tabs.add("Chunks", chunkMonitor);
- tabs.add("Performance", perfMonitor);
+ tabs.add("Performance", performanceMonitor);
add(tabs, BorderLayout.CENTER);
}
+
+ /**
+ * Closes advanced monitor panel.
+ *
+ * This method goes through three steps:
+ * 1. Hides this windows.
+ * 2. Releases all of the native screen resources used by this windows.
+ * 3. Stops monitoring threads gracefully.
+ */
+ public void close() {
+ setVisible(false);
+ dispose();
+
+ threadMonitor.stopThread();
+ chunkMonitor.stopThread();
+ performanceMonitor.stopThread();
+ }
}
diff --git a/engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorDisplay.java b/engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorDisplay.java
index 01bae7f85..cf31f9098 100644
--- a/engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorDisplay.java
+++ b/engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorDisplay.java
@@ -62,16 +62,11 @@
@SuppressWarnings("serial")
public class ChunkMonitorDisplay extends JPanel {
- public static final Color COLOR_COMPLETE = new Color(0, 38, 28);
- public static final Color COLOR_INTERNAL_LIGHT_GENERATION_PENDING = new Color(4, 76, 41);
- public static final Color COLOR_ADJACENCY_GENERATION_PENDING = new Color(150, 237, 137);
-
- public static final Color COLOR_HIGHLIGHT_TESSELLATION = Color.blue.brighter().brighter();
-
- public static final Color COLOR_SELECTED_CHUNK = new Color(255, 102, 0);
-
- public static final Color COLOR_DEAD = Color.lightGray;
- public static final Color COLOR_INVALID = Color.red;
+ private static final Color COLOR_COMPLETE = new Color(0, 38, 28);
+ private static final Color COLOR_INTERNAL_LIGHT_GENERATION_PENDING = new Color(4, 76, 41);
+ private static final Color COLOR_HIGHLIGHT_TESSELLATION = Color.blue.brighter().brighter();
+ private static final Color COLOR_SELECTED_CHUNK = new Color(255, 102, 0);
+ private static final Color COLOR_DEAD = Color.LIGHT_GRAY;
private static final Logger logger = LoggerFactory.getLogger(ChunkMonitorDisplay.class);
@@ -89,13 +84,15 @@ public class ChunkMonitorDisplay extends JPanel {
private int renderY;
private int minRenderY;
private int maxRenderY;
- private boolean followPlayer = true;
+ private boolean followPlayer;
private Vector3i selectedChunk;
- private final BlockingQueue<Request> queue = new LinkedBlockingQueue<>();
+ private final BlockingQueue<Request> queue;
private final transient ExecutorService executor;
- private final transient Runnable renderTask;
+
+ // If true, the active monitoring thread in executor service should stop.
+ private boolean stopThread;
public ChunkMonitorDisplay(int refreshInterval, int chunkSize) {
Preconditions.checkArgument(refreshInterval >= 500, "Parameter 'refreshInterval' has to be greater or equal 500 (" + refreshInterval + ")");
@@ -105,13 +102,18 @@ public ChunkMonitorDisplay(int refreshInterval, int chunkSize) {
addMouseListener(ml);
addMouseMotionListener(ml);
addMouseWheelListener(ml);
+ this.followPlayer = true;
this.refreshInterval = refreshInterval;
this.chunkSize = chunkSize;
this.executor = Executors.newSingleThreadExecutor();
- this.renderTask = new RenderTask();
ChunkMonitor.registerForEvents(this);
- queue.offer(new InitialRequest());
- executor.execute(renderTask);
+ this.queue = new LinkedBlockingQueue<>();
+ this.queue.offer(new InitialRequest());
+ this.executor.execute(new RenderTask());
+ }
+
+ public void stopThread() {
+ stopThread = true;
}
private void fireChunkSelectedEvent(Vector3i pos) {
@@ -165,26 +167,6 @@ private Vector3i calcPlayerChunkPos() {
return null;
}
- public int getChunkSize() {
- return chunkSize;
- }
-
- public ChunkMonitorDisplay setChunkSize(int value) {
- if (value != chunkSize) {
- Preconditions.checkArgument(value >= 6, "Parameter 'value' has to be greater or equal 6 (" + value + ")");
- chunkSize = value;
- updateDisplay(true);
- }
- return this;
- }
-
- public Vector3i getSelectedChunk() {
- if (selectedChunk == null) {
- return null;
- }
- return new Vector3i(selectedChunk);
- }
-
public ChunkMonitorDisplay setSelectedChunk(Vector3i chunk) {
if (selectedChunk == null) {
if (chunk != null) {
@@ -202,18 +184,6 @@ public ChunkMonitorDisplay setSelectedChunk(Vector3i chunk) {
return this;
}
- public int getRenderY() {
- return renderY;
- }
-
- public int getMinRenderY() {
- return minRenderY;
- }
-
- public int getMaxRenderY() {
- return maxRenderY;
- }
-
public ChunkMonitorDisplay setRenderY(int value) {
int clampedValue = value;
if (value < minRenderY) {
@@ -237,6 +207,7 @@ public boolean getFollowPlayer() {
return followPlayer;
}
+ // TODO: Add a checkbox to toggle whether the chunk display will follow where the player goes or not.
public ChunkMonitorDisplay setFollowPlayer(boolean value) {
if (followPlayer != value) {
followPlayer = value;
@@ -259,24 +230,10 @@ public ChunkMonitorDisplay setOffset(int x, int y) {
this.offsetY = y;
updateDisplay(true);
}
- return this;
- }
-
- public int getRefreshInterval() {
- return refreshInterval;
- }
- public ChunkMonitorDisplay setRefreshInterval(int value) {
- Preconditions.checkArgument(value >= 500, "Parameter 'value' has to be greater or equal 500 (" + value + ")");
- this.refreshInterval = value;
return this;
}
- public void registerForEvents(Object object) {
- Preconditions.checkNotNull(object, "The parameter 'object' must not be null");
- eventbus.register(object);
- }
-
@Subscribe
public void receiveChunkEvent(ChunkMonitorEvent event) {
if (event != null) {
@@ -299,10 +256,6 @@ private static class ImageBuffer {
private BufferedImage imageA;
private BufferedImage imageB;
- ImageBuffer(int width, int height) {
- resize(width, height);
- }
-
ImageBuffer() {
}
@@ -694,12 +647,12 @@ private void renderSelectedChunk(Graphics2D g, int offsetx, int offsety, Vector3
}
private void renderBox(Graphics2D g, int offsetx, int offsety, Rectangle box) {
- g.setColor(Color.white);
+ g.setColor(Color.WHITE);
g.drawRect(box.x * chunkSize + offsetx, box.y * chunkSize + offsety, box.width * chunkSize - 1, box.height * chunkSize - 1);
}
private void renderBackground(Graphics2D g, int width, int height) {
- g.setColor(Color.black);
+ g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
}
@@ -761,7 +714,7 @@ public void run() {
final List<Request> requests = new LinkedList<>();
try {
- while (true) {
+ while (!stopThread) {
final long slept = poll(requests);
boolean needsRendering = false;
@@ -772,7 +725,7 @@ public void run() {
r.execute();
} catch (Exception e) {
ThreadMonitor.addError(e);
- logger.error("Thread error", e);
+ logger.error("Error executing chunk monitor update", e);
} finally {
needsRendering |= r.needsRendering();
fastResume |= r.fastResume();
@@ -790,13 +743,15 @@ public void run() {
}
if (!fastResume && (slept <= 400)) {
- Thread.sleep(500 - slept);
+ Thread.sleep(refreshInterval - slept);
}
}
} catch (Exception e) {
ThreadMonitor.addError(e);
- logger.error("Thread error", e);
+ logger.error("Error executing chunk monitor update", e);
}
+
+ executor.shutdownNow();
}
}
}
diff --git a/engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorPanel.java b/engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorPanel.java
index 9f88215c2..c332fcc0f 100644
--- a/engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorPanel.java
+++ b/engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorPanel.java
@@ -15,8 +15,8 @@
*/
package org.terasology.monitoring.gui;
-import javax.swing.*;
-import java.awt.*;
+import javax.swing.JPanel;
+import java.awt.BorderLayout;
@SuppressWarnings("serial")
public class ChunkMonitorPanel extends JPanel {
@@ -32,4 +32,7 @@ public ChunkMonitorPanel() {
add(display, BorderLayout.CENTER);
}
+ public void stopThread() {
+ display.stopThread();
+ }
}
diff --git a/engine/src/main/java/org/terasology/monitoring/gui/PerformanceMonitorPanel.java b/engine/src/main/java/org/terasology/monitoring/gui/PerformanceMonitorPanel.java
index 591a037e0..50dfc365b 100644
--- a/engine/src/main/java/org/terasology/monitoring/gui/PerformanceMonitorPanel.java
+++ b/engine/src/main/java/org/terasology/monitoring/gui/PerformanceMonitorPanel.java
@@ -23,8 +23,18 @@
import org.terasology.monitoring.ThreadActivity;
import org.terasology.monitoring.ThreadMonitor;
-import javax.swing.*;
-import java.awt.*;
+import javax.swing.JPanel;
+import javax.swing.JList;
+import javax.swing.JLabel;
+import javax.swing.ListCellRenderer;
+import javax.swing.SwingUtilities;
+import javax.swing.AbstractListModel;
+import javax.swing.SwingConstants;
+import java.awt.BorderLayout;
+import java.awt.FlowLayout;
+import java.awt.Dimension;
+import java.awt.Component;
+import java.awt.Color;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
@@ -37,22 +47,25 @@
@SuppressWarnings("serial")
public class PerformanceMonitorPanel extends JPanel {
- private static final Logger logger = LoggerFactory.getLogger(PerformanceMonitorPanel.class);
-
- private final HeaderPanel header;
- private final JList list;
+ private static final Logger LOGGER = LoggerFactory.getLogger(PerformanceMonitorPanel.class);
+ // If true, the active monitoring thread in executor service should stop.
+ private boolean stopThread;
public PerformanceMonitorPanel() {
setLayout(new BorderLayout());
- header = new HeaderPanel();
- list = new JList(new PerformanceListModel());
+ HeaderPanel header = new HeaderPanel();
+ JList list = new JList(new PerformanceListModel());
list.setCellRenderer(new PerformanceListRenderer(header));
list.setVisible(true);
add(header, BorderLayout.PAGE_START);
add(list, BorderLayout.CENTER);
}
+ public void stopThread() {
+ stopThread = true;
+ }
+
private static class HeaderPanel extends JPanel {
private final JLabel lName = new JLabel("Title");
@@ -137,15 +150,15 @@ private static class MyRenderer extends JPanel {
MyRenderer(HeaderPanel header) {
this.header = Preconditions.checkNotNull(header, "The parameter 'header' must not be null");
- setBackground(Color.white);
+ setBackground(Color.WHITE);
setLayout(new FlowLayout(FlowLayout.LEFT, 4, 2));
lMean.setHorizontalAlignment(SwingConstants.RIGHT);
- lMean.setForeground(Color.gray);
+ lMean.setForeground(Color.GRAY);
lMean.setPreferredSize(header.lMean.getPreferredSize());
lSpike.setHorizontalAlignment(SwingConstants.RIGHT);
- lSpike.setForeground(Color.gray);
+ lSpike.setForeground(Color.GRAY);
lSpike.setPreferredSize(header.lSpike.getPreferredSize());
add(lName);
@@ -156,7 +169,7 @@ private static class MyRenderer extends JPanel {
public void setEntry(Entry entry) {
if (entry != null) {
lName.setPreferredSize(null);
- lName.setForeground(entry.active ? Color.blue : Color.gray);
+ lName.setForeground(entry.active ? Color.BLUE : Color.GRAY);
lName.setText(entry.name);
Dimension tmp = lName.getPreferredSize();
if (tmp.width > dName.width || tmp.height > dName.height) {
@@ -176,7 +189,7 @@ public void setEntry(Entry entry) {
}
}
- private static final class PerformanceListModel extends AbstractListModel {
+ private final class PerformanceListModel extends AbstractListModel {
private final List<Entry> list = new ArrayList<>();
private final Map<String, Entry> map = new HashMap<>();
@@ -186,7 +199,7 @@ private PerformanceListModel() {
executor.execute(() -> {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
try {
- while (true) {
+ while (!stopThread) {
Thread.sleep(1000);
try (ThreadActivity ignored = ThreadMonitor.startThreadActivity("Poll")) {
updateEntries(PerformanceMonitor.getRunningMean(), PerformanceMonitor.getDecayingSpikes());
@@ -194,8 +207,10 @@ private PerformanceListModel() {
}
} catch (Exception e) {
ThreadMonitor.addError(e);
- logger.error("Error executing performance monitor update", e);
+ LOGGER.error("Error executing performance monitor update", e);
}
+
+ executor.shutdownNow();
});
}
@@ -204,11 +219,6 @@ private void invokeIntervalAdded(final int a, final int b) {
SwingUtilities.invokeLater(() -> fireIntervalAdded(source, a, b));
}
- private void invokeIntervalRemoved(final int a, final int b) {
- final Object source = this;
- SwingUtilities.invokeLater(() -> fireIntervalRemoved(source, a, b));
- }
-
private void invokeContentsChanged(final int a, final int b) {
final Object source = this;
SwingUtilities.invokeLater(() -> fireContentsChanged(source, a, b));
@@ -238,6 +248,7 @@ private void updateEntries(TObjectDoubleMap<String> means, TObjectDoubleMap<Stri
}
return true;
});
+
Collections.sort(list);
invokeContentsChanged(0, list.size() - 1);
}
diff --git a/engine/src/main/java/org/terasology/monitoring/gui/ThreadMonitorPanel.java b/engine/src/main/java/org/terasology/monitoring/gui/ThreadMonitorPanel.java
index 78b20fed5..49b7eff4e 100644
--- a/engine/src/main/java/org/terasology/monitoring/gui/ThreadMonitorPanel.java
+++ b/engine/src/main/java/org/terasology/monitoring/gui/ThreadMonitorPanel.java
@@ -23,8 +23,18 @@
import org.terasology.monitoring.impl.SingleThreadMonitor;
import org.terasology.monitoring.impl.ThreadMonitorEvent;
-import javax.swing.*;
-import java.awt.*;
+import javax.swing.JPanel;
+import javax.swing.JList;
+import javax.swing.JLabel;
+import javax.swing.ListCellRenderer;
+import javax.swing.SwingUtilities;
+import javax.swing.AbstractListModel;
+import javax.swing.SwingConstants;
+import java.awt.BorderLayout;
+import java.awt.FlowLayout;
+import java.awt.Dimension;
+import java.awt.Component;
+import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.BlockingQueue;
@@ -36,24 +46,31 @@
@SuppressWarnings("serial")
public class ThreadMonitorPanel extends JPanel {
- private static final Color BACKGROUND = Color.white;
- private static final Logger logger = LoggerFactory.getLogger(ThreadMonitorPanel.class);
+ private static final Color BACKGROUND = Color.WHITE;
+ private static final Logger LOGGER = LoggerFactory.getLogger(ThreadMonitorPanel.class);
- private final JList list;
+ /**
+ * If true, the active monitoring thread in executor service should stop.
+ */
+ private boolean stopThread;
public ThreadMonitorPanel() {
setLayout(new BorderLayout());
- list = new JList(new ThreadListModel());
+ JList list = new JList(new ThreadListModel());
list.setCellRenderer(new ThreadListRenderer());
list.setVisible(true);
add(list, BorderLayout.CENTER);
}
+ public void stopThread() {
+ this.stopThread = true;
+ }
+
private abstract static class Task {
private String name;
- Task(String name) {
+ Task(String name) {
this.name = name;
}
@@ -94,7 +111,7 @@ private static class MyRenderer extends JPanel {
private Dimension dId = new Dimension(0, 0);
private Dimension dName = new Dimension(0, 0);
- MyRenderer() {
+ MyRenderer() {
setBackground(BACKGROUND);
setLayout(new BorderLayout());
@@ -105,8 +122,8 @@ private static class MyRenderer extends JPanel {
pHead.add(pError, BorderLayout.PAGE_END);
lId.setHorizontalAlignment(SwingConstants.RIGHT);
- lName.setForeground(Color.blue);
- lCounters.setForeground(Color.gray);
+ lName.setForeground(Color.BLUE);
+ lCounters.setForeground(Color.GRAY);
pList.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 2));
pList.setBackground(BACKGROUND);
@@ -120,7 +137,7 @@ private static class MyRenderer extends JPanel {
pError.add(lErrorSpacer);
pError.add(lError);
- lError.setForeground(Color.red);
+ lError.setForeground(Color.RED);
add(pHead, BorderLayout.PAGE_START);
}
@@ -148,14 +165,14 @@ public void setMonitor(SingleThreadMonitor monitor) {
if (monitor.isAlive()) {
if (monitor.isActive()) {
- lActive.setForeground(Color.green);
+ lActive.setForeground(Color.GREEN);
lActive.setText("Active");
} else {
- lActive.setForeground(Color.gray);
+ lActive.setForeground(Color.GRAY);
lActive.setText("Inactive");
}
} else {
- lActive.setForeground(Color.red);
+ lActive.setForeground(Color.RED);
lActive.setText("Disposed");
}
@@ -175,7 +192,7 @@ public void setMonitor(SingleThreadMonitor monitor) {
}
}
- private static final class ThreadListModel extends AbstractListModel {
+ private final class ThreadListModel extends AbstractListModel {
private final java.util.List<SingleThreadMonitor> monitors = new ArrayList<>();
private final ExecutorService executor = Executors.newSingleThreadExecutor();
@@ -193,30 +210,29 @@ public void execute() {
}
}
});
- executor.execute(new Runnable() {
- @Override
- public void run() {
- Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
- try {
- while (true) {
- final Task task = queue.poll(500, TimeUnit.MILLISECONDS);
- if (task != null) {
- try (ThreadActivity ignored = ThreadMonitor.startThreadActivity(task.getName())) {
- task.execute();
- }
- } else {
- try (ThreadActivity ignored = ThreadMonitor.startThreadActivity("Sort Monitors")) {
- Collections.sort(monitors);
- invokeContentsChanged(0, monitors.size() - 1);
- }
+
+ executor.execute(() -> {
+ Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
+ try {
+ while (!stopThread) {
+ final Task task = queue.poll(500, TimeUnit.MILLISECONDS);
+ if (task != null) {
+ try (ThreadActivity ignored = ThreadMonitor.startThreadActivity(task.getName())) {
+ task.execute();
+ }
+ } else {
+ try (ThreadActivity ignored = ThreadMonitor.startThreadActivity("Sort Monitors")) {
+ Collections.sort(monitors);
+ invokeContentsChanged(0, monitors.size() - 1);
}
}
- } catch (Exception e) {
- ThreadMonitor.addError(e);
- logger.error("Error executing thread monitor update", e);
}
- invokeContentsChanged(0, monitors.size() - 1);
+ } catch (Exception e) {
+ ThreadMonitor.addError(e);
+ LOGGER.error("Error executing thread monitor update", e);
}
+
+ executor.shutdownNow();
});
}
@@ -225,11 +241,6 @@ private void invokeIntervalAdded(final int a, final int b) {
SwingUtilities.invokeLater(() -> fireIntervalAdded(source, a, b));
}
- private void invokeIntervalRemoved(final int a, final int b) {
- final Object source = this;
- SwingUtilities.invokeLater(() -> fireIntervalRemoved(source, a, b));
- }
-
private void invokeContentsChanged(final int a, final int b) {
final Object source = this;
SwingUtilities.invokeLater(() -> fireContentsChanged(source, a, b)); | ['engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorDisplay.java', 'engine/src/main/java/org/terasology/monitoring/gui/PerformanceMonitorPanel.java', 'engine/src/main/java/org/terasology/engine/subsystem/common/MonitoringSubsystem.java', 'engine/src/main/java/org/terasology/monitoring/gui/ChunkMonitorPanel.java', 'engine/src/main/java/org/terasology/monitoring/gui/AdvancedMonitor.java', 'engine/src/main/java/org/terasology/monitoring/gui/ThreadMonitorPanel.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 9,393,122 | 2,011,502 | 261,227 | 2,199 | 11,836 | 2,076 | 287 | 6 | 639 | 109 | 147 | 14 | 0 | 0 | 2018-10-06T20:15:41 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
92 | movingblocks/terasology/3090/3066 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3066 | https://github.com/MovingBlocks/Terasology/pull/3090 | https://github.com/MovingBlocks/Terasology/pull/3090 | 1 | fixes | Breaking blocks in SampleBuilderGameplay doesn't work right | ### What you were trying to do
Test Alpha 8 - SampleBuilderGameplay world
* Left click should remove a block without any drops and "select" that block type
* Right click should place a block of whatever selected type
### What actually happened
Right click is fine. But Left click fails to remove a block and instead a physics-cube pops out and flies off to the side, one per click.
Probably some change to how block drops are handled in the engine caused this?
### How to reproduce
* Run the game and pick BuilderSampleGameplay plus its world
* Try to break any block (left click)
* See the block not disappear, yet a new physics-enabled cube pops out and bounces around
High priority issue since it effectively breaks the BSG template. | 12f44ace575177f4e84dd16031b9d5bfb66da8c3 | ee0da21d523fd67ca951a1c600d80c3b85a17564 | https://github.com/movingblocks/terasology/compare/12f44ace575177f4e84dd16031b9d5bfb66da8c3...ee0da21d523fd67ca951a1c600d80c3b85a17564 | diff --git a/engine/src/main/java/org/terasology/world/block/entity/BlockEntitySystem.java b/engine/src/main/java/org/terasology/world/block/entity/BlockEntitySystem.java
index 6e137b721..f77d0abd6 100644
--- a/engine/src/main/java/org/terasology/world/block/entity/BlockEntitySystem.java
+++ b/engine/src/main/java/org/terasology/world/block/entity/BlockEntitySystem.java
@@ -159,8 +159,11 @@ private void commonDestroyed(DoDestroyEvent event, EntityRef entity, Block block
// dust particle effect
if (entity.hasComponent(LocationComponent.class) && block.isDebrisOnDestroy()) {
EntityBuilder dustBuilder = entityManager.newBuilder("core:dustEffect");
- dustBuilder.getComponent(LocationComponent.class).setWorldPosition(entity.getComponent(LocationComponent.class).getWorldPosition());
- dustBuilder.build();
+ // TODO: particle system stuff should be split out better - this is effectively a stealth dependency on Core from the engine
+ if (dustBuilder.hasComponent(LocationComponent.class)) {
+ dustBuilder.getComponent(LocationComponent.class).setWorldPosition(entity.getComponent(LocationComponent.class).getWorldPosition());
+ dustBuilder.build();
+ }
}
// sound to play for destroyed block | ['engine/src/main/java/org/terasology/world/block/entity/BlockEntitySystem.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 8,641,937 | 1,855,087 | 242,084 | 2,064 | 618 | 92 | 7 | 1 | 763 | 132 | 163 | 20 | 0 | 0 | 2017-09-01T01:47:53 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
84 | movingblocks/terasology/3638/3464 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3464 | https://github.com/MovingBlocks/Terasology/pull/3638 | https://github.com/MovingBlocks/Terasology/pull/3638 | 1 | fixes | Module details when a module exists with unresolved dependencies causes crash | ### What you were trying to do
View module details for GooeyDefence to figure out its dependencies and what might be missing
### What actually happened
Game crashed when I clicked "FlexiblePathfinding" (the missing dependency)
### How to reproduce
* Grab Omega zip 977 or comparable source dir. Or just remove any dependency
* Run the game and go to module details under advanced game setup
* Click a button representing a module that isn't present
### Log details and game version
Omega 977
```
12:23:21.566 [main] WARN o.t.engine.internal.TimeBase - Delta too great (10474), capping to 1000
12:23:21.572 [main] INFO o.t.logic.console.ConsoleImpl - [NOTIFICATION] Identity storage service: No configuration data is present, staying logged out.
12:24:08.604 [main] ERROR o.terasology.engine.TerasologyEngine - Uncaught exception, attempting clean game shutdown
java.lang.NullPointerException: null
at org.terasology.rendering.nui.layers.mainMenu.moduleDetailsScreen.ModuleDetailsScreen$6.get(ModuleDetailsScreen.java:229)
at org.terasology.rendering.nui.layers.mainMenu.moduleDetailsScreen.ModuleDetailsScreen$6.get(ModuleDetailsScreen.java:225)
at org.terasology.rendering.nui.widgets.UILabel.getText(UILabel.java:68)
at org.terasology.rendering.nui.widgets.UILabel.getPreferredContentSize(UILabel.java:101)
at org.terasology.rendering.nui.internal.CanvasImpl.calculateRestrictedSize(CanvasImpl.java:347)
at org.terasology.rendering.nui.layouts.ColumnLayout.calculateRowSize(ColumnLayout.java:212)
at org.terasology.rendering.nui.layouts.ColumnLayout.lambda$onDraw$0(ColumnLayout.java:133)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.collect(Unknown Source)
at org.terasology.rendering.nui.layouts.ColumnLayout.onDraw(ColumnLayout.java:133)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.layouts.relative.RelativeLayout.onDraw(RelativeLayout.java:85)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.layouts.ColumnLayout.onDraw(ColumnLayout.java:191)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.layouts.relative.RelativeLayout.onDraw(RelativeLayout.java:85)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.layouts.relative.RelativeLayout.onDraw(RelativeLayout.java:85)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.layouts.ColumnLayout.onDraw(ColumnLayout.java:191)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.layouts.relative.RelativeLayout.onDraw(RelativeLayout.java:85)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.layouts.relative.RelativeLayout.onDraw(RelativeLayout.java:85)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.CoreScreenLayer.onDraw(CoreScreenLayer.java:115)
at org.terasology.rendering.nui.internal.CanvasImpl.drawStyledWidget(CanvasImpl.java:406)
at org.terasology.rendering.nui.internal.CanvasImpl.drawWidget(CanvasImpl.java:392)
at org.terasology.rendering.nui.internal.NUIManagerInternal.render(NUIManagerInternal.java:475)
at org.terasology.engine.modes.StateMainMenu.render(StateMainMenu.java:210)
at org.terasology.engine.subsystem.lwjgl.LwjglGraphics.postUpdate(LwjglGraphics.java:166)
at org.terasology.engine.TerasologyEngine.tick(TerasologyEngine.java:467)
at org.terasology.engine.TerasologyEngine.mainLoop(TerasologyEngine.java:421)
at org.terasology.engine.TerasologyEngine.run(TerasologyEngine.java:397)
at org.terasology.engine.Terasology.main(Terasology.java:154)
12:24:08.610 [main] INFO o.terasology.engine.TerasologyEngine - Shutting down Terasology...
12:24:08.972 [main] WARN o.t.w.g.i.WorldGeneratorManager - Could not resolve dependencies for module: GooeyDefence-0.1.0-SNAPSHOT
```
Maybe of interest to @ar0ne. Probably not a very difficult bug. | 12207a8a2265f44876cc8a94ef095fef404a0c8c | 094217614c996d50627bc721b0faf5a3d8fed945 | https://github.com/movingblocks/terasology/compare/12207a8a2265f44876cc8a94ef095fef404a0c8c...094217614c996d50627bc721b0faf5a3d8fed945 | diff --git a/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/moduleDetailsScreen/ModuleDetailsScreen.java b/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/moduleDetailsScreen/ModuleDetailsScreen.java
index 95a637ce6..8b4818f9c 100644
--- a/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/moduleDetailsScreen/ModuleDetailsScreen.java
+++ b/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/moduleDetailsScreen/ModuleDetailsScreen.java
@@ -228,7 +228,7 @@ public String get() {
installedVersion.bindText(new ReadOnlyBinding<String>() {
@Override
public String get() {
- if (dependencyInfoBinding.get() != null) {
+ if (dependencyInfoBinding.get() != null && moduleManager.getRegistry().getLatestModuleVersion(dependencyInfoBinding.get().getId()) != null) {
return String.valueOf(moduleManager.getRegistry().getLatestModuleVersion(dependencyInfoBinding.get().getId()).getVersion());
}
return "";
@@ -288,6 +288,11 @@ private String getString(DependencyInfo value) {
@Override
public void draw(DependencyInfo value, Canvas canvas) {
+ if (moduleManager.getRegistry().getLatestModuleVersion(value.getId()) == null) {
+ canvas.setMode("invalid");
+ } else {
+ canvas.setMode("available");
+ }
canvas.drawText(getString(value), canvas.getRegion());
}
@@ -316,7 +321,7 @@ private void setUpUpdateModuleButton() {
public Boolean get() {
final String online = onlineVersion.getText();
final String installed = installedVersion.getText();
- if (StringUtils.isNotBlank(online)) {
+ if (StringUtils.isNotBlank(online) && StringUtils.isNotBlank(installed)) {
return new Version(online).compareTo(new Version(installed)) > 0;
}
return false; | ['engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/moduleDetailsScreen/ModuleDetailsScreen.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,499,271 | 2,032,840 | 264,329 | 2,221 | 606 | 107 | 9 | 1 | 5,407 | 262 | 1,295 | 76 | 0 | 1 | 2019-03-15T10:18:59 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
85 | movingblocks/terasology/3612/3610 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3610 | https://github.com/MovingBlocks/Terasology/pull/3612 | https://github.com/MovingBlocks/Terasology/pull/3612 | 1 | fixes | Worldgen seed not unique | <!-- Thanks for taking the time to submit a thorough issue report for Terasology! :-)
Please fill out whichever details below seem relevant to your issue.
Note that suggestions, general questions & support should go in the forum:
* http://forum.terasology.org/forum/suggestions.21
* http://forum.terasology.org/forum/support.20/
Bug reports and crashes likely resulting from bugs in the engine go here on GitHub. -->
### What you were trying to do
I was using noise to generate my world based on the seed provided to my world generator. I assumed this was the seed shown in the world-setup screen.
### What actually happened
Instead of the seed shown in the world-setup screen, the method `BaseFacetedWorldGenerator .setWorldSeed()` got called with parameter `LOTR World-00`. This is supposed to be unique according to docs at `WorldPreGenerationScreen.createSeed()`, but it appears that the integer which gets appended is only incremented when remaining in the menu-area. When starting a world or restarting the game, it gets reset to 0. This makes the world seed be dependant on only the world-generator name and as this stays constant, the generated noise will be the same.
### How to reproduce
* Start the game and create a world using the Perlin generator from the Core module (I used my own generator but this seems to be the case for all generators). Don't touch the seed, maybe set some breakpoints in the setSeed() method of the FacetProviders or BaseFacetedWorldGenerator to check the integer or string you get passed. Let the world generate.
* Generate a second world and use the same approach.
This world (if the issue is an actual issue) should be the same as the first. Note that the seed which we saw in the menu was different.
### EDIT: clearer reproduction steps
1) Run the game (either from scratch or with additional modules)
2) Select a world generator (Perlin is a good choice because you immediately see the preview, allowing you to verify more easily)
3) Run and repeat. | 5b874d87652e667c3f8db1b5eedc768bfcc43b38 | 0c8c17366e3d02fd8e781e52430d6ab2adcdd280 | https://github.com/movingblocks/terasology/compare/5b874d87652e667c3f8db1b5eedc768bfcc43b38...0c8c17366e3d02fd8e781e52430d6ab2adcdd280 | diff --git a/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/GameManifestProvider.java b/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/GameManifestProvider.java
index 7e9bea2e7..fdaf9c33f 100644
--- a/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/GameManifestProvider.java
+++ b/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/GameManifestProvider.java
@@ -78,7 +78,7 @@ public static GameManifest createGameManifest(final UniverseWrapper universeWrap
String seed;
if (universeWrapper.getTargetWorld() != null) {
uri = universeWrapper.getTargetWorld().getWorldGenerator().getUri();
- seed = universeWrapper.getTargetWorld().getWorldName().toString() + 0;
+ seed = universeWrapper.getTargetWorld().getWorldGenerator().getWorldSeed();
gameManifest.setSeed(seed);
} else {
uri = config.getWorldGeneration().getDefaultGenerator();
diff --git a/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/WorldPreGenerationScreen.java b/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/WorldPreGenerationScreen.java
index 9b5edfcea..d0970ebe0 100644
--- a/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/WorldPreGenerationScreen.java
+++ b/engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/WorldPreGenerationScreen.java
@@ -267,7 +267,8 @@ private WorldSetupWrapper findWorldByName(String searchWorld) {
* @return The seed as a string.
*/
private String createSeed(String world) {
- return world + seedNumber++;
+ String seed = context.get(UniverseWrapper.class).getSeed();
+ return seed + world + seedNumber++;
}
private void setWorldGenerators() { | ['engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/WorldPreGenerationScreen.java', 'engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/GameManifestProvider.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,476,978 | 2,028,030 | 263,697 | 2,215 | 323 | 64 | 5 | 2 | 2,024 | 326 | 432 | 24 | 2 | 0 | 2019-02-07T17:47:56 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
71 | movingblocks/terasology/3534/3582 | movingblocks | terasology | https://github.com/MovingBlocks/Terasology/issues/3582 | https://github.com/MovingBlocks/Terasology/pull/3534 | https://github.com/MovingBlocks/Terasology/pull/3534#issuecomment-449671307 | 2 | fixes | On restarting a headless server with an existing world no world is retrieved from the game manifest | ### What you were trying to do
Test something unrelated, by which I ended up restarting a headless server.
### What actually happened
The restart failed to bring the game server back up
### How to reproduce
* Start a headless server with any config (like just starting the headless run config in IntelliJ)
* Stop the server (can potentially skip steps 1 & 2 if you can reproduce with an existing save)
* Start the server again
On `InitialiseWorld` line 100 the failure occurs. The `gameManifest` loads but has no entries in its `worlds` list
### Log details and game version
Latest develop
```
16:48:21.601 [main] INFO o.t.w.c.b.ExtraBlockDataManager - Extra data slots registered:
16:48:21.604 [main] ERROR o.terasology.engine.TerasologyEngine - Uncaught exception, attempting clean game shutdown
java.lang.NullPointerException: null
at org.terasology.engine.modes.loadProcesses.InitialiseWorld.step(InitialiseWorld.java:101)
at org.terasology.engine.modes.StateLoading.update(StateLoading.java:243)
at org.terasology.engine.TerasologyEngine.tick(TerasologyEngine.java:458)
at org.terasology.engine.TerasologyEngine.mainLoop(TerasologyEngine.java:421)
at org.terasology.engine.TerasologyEngine.run(TerasologyEngine.java:397)
at org.terasology.engine.Terasology.main(Terasology.java:145)
16:48:21.604 [main] INFO o.terasology.engine.TerasologyEngine - Shutting down Terasology...
```
### Theory
Either the game isn't correctly saving the world in the first place or the game manifest isn't correctly figuring out where the actual world went so it can list it. Might relate to some of the multi-world changes, although that was a few months ago. Since it works fine the _first_ time you launch a headless server maybe we somehow missed it this long.
Also works partially with a client/server hosting a fresh game, exiting, then re-hosting. No crash, although when I tried it the client loaded into a black screen with no world visible (did have toolbar items etc) | 7cf495ee093ff7d3829498288660138d266761d8 | 648c9b1558a0bf73abbd5e6202621bc1392e4f3f | https://github.com/movingblocks/terasology/compare/7cf495ee093ff7d3829498288660138d266761d8...648c9b1558a0bf73abbd5e6202621bc1392e4f3f | diff --git a/engine/src/main/java/org/terasology/engine/subsystem/headless/mode/StateHeadlessSetup.java b/engine/src/main/java/org/terasology/engine/subsystem/headless/mode/StateHeadlessSetup.java
index 6d53f56e4..25fee757e 100644
--- a/engine/src/main/java/org/terasology/engine/subsystem/headless/mode/StateHeadlessSetup.java
+++ b/engine/src/main/java/org/terasology/engine/subsystem/headless/mode/StateHeadlessSetup.java
@@ -106,6 +106,13 @@ public void init(GameEngine gameEngine) {
} else {
gameManifest = createGameManifest();
}
+
+ Config config = context.get(Config.class);
+ WorldInfo worldInfo = gameManifest.getWorldInfo(TerasologyConstants.MAIN_WORLD);
+ config.getUniverseConfig().addWorldManager(worldInfo);
+ config.getUniverseConfig().setSpawnWorldTitle(worldInfo.getTitle());
+ config.getUniverseConfig().setUniverseSeed(gameManifest.getSeed());
+
gameEngine.changeState(new StateLoading(gameManifest, NetworkMode.LISTEN_SERVER));
}
| ['engine/src/main/java/org/terasology/engine/subsystem/headless/mode/StateHeadlessSetup.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,391,755 | 2,011,220 | 261,204 | 2,200 | 364 | 71 | 7 | 1 | 2,019 | 250 | 476 | 38 | 0 | 1 | 2018-10-29T19:24:26 | 3,534 | Java | {'Java': 7127511, 'Groovy': 55969, 'Kotlin': 49638, 'GLSL': 23786, 'Shell': 12152, 'Batchfile': 4149, 'Dockerfile': 292} | Apache License 2.0 |
1,332 | spring-cloud/spring-cloud-kubernetes/440/402 | spring-cloud | spring-cloud-kubernetes | https://github.com/spring-cloud/spring-cloud-kubernetes/issues/402 | https://github.com/spring-cloud/spring-cloud-kubernetes/pull/440 | https://github.com/spring-cloud/spring-cloud-kubernetes/pull/440 | 2 | fixes | ConfigMap change does not trigger bean refresh | I am doing some training with spring-cloud-kubernetes on Red Hat minishift. I managed to define a ConfigMap which is correctly found and the configured message ${service.message} is shown..
However, when I change the value in the ConfigMap, the RestController in the @RefreshScope seems not to be refreshed and the message stays the same. Only a restart of the app updates the message.
According to the documentation I assumed this should work. Did I miss some additional step or is this not working yet?
```java
@Controller
@RefreshScope
public class RestController {
private final String message;
public RestController(@Value("${service.message}") String message) {
this.message = message;
}
/**
* Say hello to earth
*
* @return First word from the moon
*
*/
@GetMapping("/hello")
@ResponseBody
public String hello() {
return message + " (" + LocalDateTime.now().toString() + ")";
}
}
```
The ConfigMap
```yaml
apiVersion: v1
data:
application.yml: |-
service:
message: Say hello to the world
kind: ConfigMap
metadata:
creationTimestamp: '2019-06-02T17:35:24Z'
name: openshift-spring-boot-service
namespace: dsp-dev
resourceVersion: '67065'
selfLink: /api/v1/namespaces/dsp-dev/configmaps/openshift-spring-boot-service
uid: cd7a8217-855c-11e9-8dc5-00155d010b07
```
| 2d3b9c59019047b52f5f0dc91f4d7a7cb4a09024 | 6ae6a3b2bd91c6b25d77c464121f0b54a3a67831 | https://github.com/spring-cloud/spring-cloud-kubernetes/compare/2d3b9c59019047b52f5f0dc91f4d7a7cb4a09024...6ae6a3b2bd91c6b25d77c464121f0b54a3a67831 | diff --git a/spring-cloud-kubernetes-config/src/main/java/org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration.java b/spring-cloud-kubernetes-config/src/main/java/org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration.java
index b811f827..880319b6 100644
--- a/spring-cloud-kubernetes-config/src/main/java/org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration.java
+++ b/spring-cloud-kubernetes-config/src/main/java/org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration.java
@@ -38,6 +38,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.util.Assert;
/**
* Definition of beans needed for the automatic reload of configuration.
@@ -110,9 +111,11 @@ public class ConfigReloadAutoConfiguration {
@ConditionalOnMissingBean
public ConfigurationUpdateStrategy configurationUpdateStrategy(
ConfigReloadProperties properties, ConfigurableApplicationContext ctx,
- RestartEndpoint restarter, ContextRefresher refresher) {
+ @Autowired(required = false) RestartEndpoint restarter,
+ ContextRefresher refresher) {
switch (properties.getStrategy()) {
case RESTART_CONTEXT:
+ Assert.notNull(restarter, "Restart endpoint is not enabled");
return new ConfigurationUpdateStrategy(properties.getStrategy().name(),
restarter::restart);
case REFRESH: | ['spring-cloud-kubernetes-config/src/main/java/org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 205,027 | 43,376 | 6,838 | 73 | 265 | 54 | 5 | 1 | 1,371 | 168 | 342 | 48 | 0 | 2 | 2019-07-30T21:45:54 | 3,341 | Java | {'Java': 3113351, 'Shell': 548} | Apache License 2.0 |
332 | immutables/immutables/884/736 | immutables | immutables | https://github.com/immutables/immutables/issues/736 | https://github.com/immutables/immutables/pull/884 | https://github.com/immutables/immutables/pull/884 | 2 | fixes | Why declared immuables library style in package-info.java doesn't apply for subpackages in java 9 project? | Please see https://github.com/originalrusyn/java9_immutables for more details
So, the following config works correctly with sourceCompatibility = 1.8
```
p.package-info.java
@Value.Style(
defaults = @Value.Immutable(copy = false),
strictBuilder = true,
overshadowImplementation = true,
implementationNestedInBuilder = true
)
package p;
import org.immutables.value.Value;
```
build.gradle
```
buildscript {
ext {
immutablesVersion = '2.5.6'
}
repositories {
mavenCentral()
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "net.ltgt.gradle:gradle-apt-plugin:0.13"
}
}
group 'java9'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'net.ltgt.apt'
sourceCompatibility = 1.9
repositories {
mavenCentral()
}
sourceSets {
main
generated
test
}
compileJava {
generatedSourcesDestinationDir = "$projectDir/src/generated/java"
}
task wrapper(type: Wrapper) {
gradleVersion = '4.4'
}
dependencies {
apt "org.immutables:value:${immutablesVersion}"
compileOnly "org.immutables:value:${immutablesVersion}:annotations"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
```
p.b.B.java
```
package p.b;
import org.immutables.value.Value;
@Value.Immutable
public interface B {
String getText();
}
```
Why does it produce p.b.ImmutableB.java rather than p.b.BBuilder.java for sourceCompatibility=1.9? | 0e81280505a1261ea19c90d2169d47aab0a092eb | cfcae50bf4e379eeb99ae5c0635ca5d1b1fc3b66 | https://github.com/immutables/immutables/compare/0e81280505a1261ea19c90d2169d47aab0a092eb...cfcae50bf4e379eeb99ae5c0635ca5d1b1fc3b66 | diff --git a/value-processor/src/org/immutables/value/processor/meta/Proto.java b/value-processor/src/org/immutables/value/processor/meta/Proto.java
index 3b07678b..7c55ab44 100644
--- a/value-processor/src/org/immutables/value/processor/meta/Proto.java
+++ b/value-processor/src/org/immutables/value/processor/meta/Proto.java
@@ -723,7 +723,7 @@ public class Proto {
@Value.Lazy
Optional<DeclaringPackage> namedParentPackage() {
String parentPackageName = SourceNames.parentPackageName(element());
- if (!parentPackageName.isEmpty()) {
+ while (!parentPackageName.isEmpty()) {
@Nullable PackageElement parentPackage =
environment().processing()
.getElementUtils()
@@ -737,6 +737,11 @@ public class Proto {
.element(parentPackage)
.build()));
}
+
+ // With JDK 9+ package elements are only returned for packages with a
+ // `package-info.class` file. So although the parent may not be found,
+ // there may be "ancestor packages" further up the hierarchy.
+ parentPackageName = SourceNames.parentPackageName(parentPackageName);
}
return Optional.absent();
}
diff --git a/value-processor/src/org/immutables/value/processor/meta/SourceNames.java b/value-processor/src/org/immutables/value/processor/meta/SourceNames.java
index 6cc5ec4d..23bfb25b 100644
--- a/value-processor/src/org/immutables/value/processor/meta/SourceNames.java
+++ b/value-processor/src/org/immutables/value/processor/meta/SourceNames.java
@@ -46,7 +46,10 @@ final class SourceNames {
}
static String parentPackageName(PackageElement element) {
- String qualifiedName = element.getQualifiedName().toString();
+ return parentPackageName(element.getQualifiedName().toString());
+ }
+
+ static String parentPackageName(String qualifiedName) {
int lastIndexOfDot = qualifiedName.lastIndexOf('.');
if (lastIndexOfDot > 0) {
return qualifiedName.substring(0, lastIndexOfDot); | ['value-processor/src/org/immutables/value/processor/meta/SourceNames.java', 'value-processor/src/org/immutables/value/processor/meta/Proto.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,652,986 | 351,504 | 52,376 | 539 | 601 | 109 | 12 | 2 | 1,543 | 141 | 376 | 84 | 2 | 3 | 2018-12-18T20:39:12 | 3,300 | Java | {'Java': 3671759} | Apache License 2.0 |
333 | immutables/immutables/789/788 | immutables | immutables | https://github.com/immutables/immutables/issues/788 | https://github.com/immutables/immutables/pull/789 | https://github.com/immutables/immutables/pull/789 | 1 | resolves | Generation with javax.validation.NotNull annotation fails | Using immutables 2.6.1 (and 1.8.0_171 on macOS) , annotation processing of this code (using Validation API 2.0):
```java
import javax.validation.constraints.NotNull;
import org.immutables.value.Value;
@Value.Immutable
public interface Test {
@NotNull
String getTest();
}
```
Fails with this exception:
```java
error: org.immutables.value.internal.$processor$.$Processor threw java.lang.IllegalArgumentException: Cannot parse type from input string '(@javax.validation.constraints.NotNull :: java.lang.String)'. unexpected term '('
at org.immutables.value.internal.$processor$.encode.$Type$Parser$1Reader.type($Type.java:767)
at org.immutables.value.internal.$processor$.encode.$Type$Parser.doParse($Type.java:891)
at org.immutables.value.internal.$processor$.encode.$Type$Parser.parse($Type.java:715)
at org.immutables.value.internal.$processor$.meta.$FromSupertypesModel.isEligibleFromType($FromSupertypesModel.java:137)
at org.immutables.value.internal.$processor$.meta.$FromSupertypesModel.<init>($FromSupertypesModel.java:78)
at org.immutables.value.internal.$processor$.meta.$ValueType.getBuildFromTypes($ValueType.java:1358)
at org.immutables.value.internal.$processor$.$Generator_Immutables._t18__generateBuilder($Generator_Immutables.java:5008)
at org.immutables.value.internal.$processor$.$Generator_Immutables$FragmentDispatch.run($Generator_Immutables.java:19510)
at org.immutables.value.internal.$generator$.$Templates$Fragment.invoke($Templates.java:248)
at org.immutables.value.internal.$generator$.$Intrinsics.$($Intrinsics.java:96)
at org.immutables.value.internal.$processor$.$Generator_Immutables._t4__generateImmutable($Generator_Immutables.java:601)
at org.immutables.value.internal.$processor$.$Generator_Immutables$FragmentDispatch.run($Generator_Immutables.java:19496)
at org.immutables.value.internal.$generator$.$Templates$Fragment.invoke($Templates.java:248)
at org.immutables.value.internal.$generator$.$Intrinsics.$($Intrinsics.java:96)
at org.immutables.value.internal.$processor$.$Generator_Immutables$1.run($Generator_Immutables.java:23)
at org.immutables.value.internal.$generator$.$Templates$Fragment.invoke($Templates.java:248)
at org.immutables.value.internal.$generator$.$Output$7.invoke($Output.java:174)
at org.immutables.value.internal.$generator$.$Intrinsics.$($Intrinsics.java:96)
at org.immutables.value.internal.$processor$.$Generator_Immutables._t0__generate($Generator_Immutables.java:20)
at org.immutables.value.internal.$processor$.$Generator_Immutables$FragmentDispatch.run($Generator_Immutables.java:19492)
at org.immutables.value.internal.$generator$.$Templates$Fragment.invoke($Templates.java:248)
at org.immutables.value.internal.$generator$.$AbstractGenerator.invoke($AbstractGenerator.java:57)
at org.immutables.value.internal.$processor$.$Processor.process($Processor.java:63)
at org.immutables.value.internal.$generator$.$AbstractGenerator.process($AbstractGenerator.java:87)
at org.immutables.processor.ProxyProcessor.process(ProxyProcessor.java:72)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.java:91)
at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1035)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1176)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:856)
at com.sun.tools.javac.main.Main.compile(Main.java:523)
at com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:129)
at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:138)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:50)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:36)
at org.gradle.api.internal.tasks.compile.daemon.AbstractDaemonCompiler$CompilerCallable.call(AbstractDaemonCompiler.java:88)
at org.gradle.api.internal.tasks.compile.daemon.AbstractDaemonCompiler$CompilerCallable.call(AbstractDaemonCompiler.java:76)
at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:42)
at org.gradle.workers.internal.WorkerDaemonServer.execute(WorkerDaemonServer.java:46)
at org.gradle.workers.internal.WorkerDaemonServer.execute(WorkerDaemonServer.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.process.internal.worker.request.WorkerAction.run(WorkerAction.java:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:155)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:137)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
1 error
```
The Validation API 2.0 introduced `TYPE_USE` as a Annotation target for `NotNull`, annotating the return type for the method (instead of the method itself), which `Parser` can not handle. | 0ded2d7abacb33d8b11de42b25046fb608c09a39 | 9bce0fd862569a749cbcc801608cc734da8ea7cc | https://github.com/immutables/immutables/compare/0ded2d7abacb33d8b11de42b25046fb608c09a39...9bce0fd862569a749cbcc801608cc734da8ea7cc | diff --git a/value-processor/src/org/immutables/value/processor/encode/Type.java b/value-processor/src/org/immutables/value/processor/encode/Type.java
index 66bacb32..1d55d0a7 100644
--- a/value-processor/src/org/immutables/value/processor/encode/Type.java
+++ b/value-processor/src/org/immutables/value/processor/encode/Type.java
@@ -758,15 +758,25 @@ public interface Type {
} else if (t.is("@")) {
// just consume type annotation
terms.poll();
- named();
- consumeAnnotationParameters();
- consumeErraticTrailingComma();
+ consumeAnnotation();
// and try again, yep, recursively...
return type();
+ } else if (t.is("(")) {
+ return annotatedType();
}
throw new IllegalStateException("unexpected term '" + t + "'");
}
+ Type annotatedType() {
+ terms.poll();
+ consumeAnnotation();
+ expect(terms.poll(), ":");
+ expect(terms.poll(), ":");
+ Type type = type();
+ expect(terms.poll(), ")");
+ return type;
+ }
+
Wildcard wildcard() {
expect(terms.poll(), "?");
@@ -822,14 +832,12 @@ public interface Type {
List<String> segments = new ArrayList<>();
for (;;) {
- Term t = terms.poll();
- if (t.isWordOrNumber()) {
- segments.add(t.toString());
- } else if (t.is("@")) {
+ if (terms.peek().isWordOrNumber()) {
+ segments.add(terms.poll().toString());
+ } else if (terms.peek().is("@")) {
+ terms.poll();
// just consume type annotation
- named();
- consumeAnnotationParameters();
- consumeErraticTrailingComma();
+ consumeAnnotation();
continue;
} else {
break;
@@ -853,6 +861,12 @@ public interface Type {
return forName(JOINER.join(segments));
}
+ private void consumeAnnotation() {
+ named();
+ consumeAnnotationParameters();
+ consumeErraticTrailingComma();
+ }
+
private void consumeAnnotationParameters() {
consumeRecursiveUntil("(", ")");
}
diff --git a/value-processor/test/org/immutables/value/processor/encode/TypeTest.java b/value-processor/test/org/immutables/value/processor/encode/TypeTest.java
index 4175441d..c2e7e1db 100644
--- a/value-processor/test/org/immutables/value/processor/encode/TypeTest.java
+++ b/value-processor/test/org/immutables/value/processor/encode/TypeTest.java
@@ -64,6 +64,7 @@ public class TypeTest {
check(parser.parse("java.lang.@javax.validation.constraints.Size(max = 10)String")).is(Reference.STRING);
check(parser.parse("java.lang.@javax.validation.constraints.Size(max = 10, @A(a=@B(b=1))) String")).is(Reference.STRING);
check(parser.parse("@Ann(\\"b\\") int")).is(Primitive.INT);
+ check(parser.parse("(@javax.validation.constraints.NotNull :: java.lang.String)")).is(Reference.STRING);
}
@Test | ['value-processor/src/org/immutables/value/processor/encode/Type.java', 'value-processor/test/org/immutables/value/processor/encode/TypeTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,602,077 | 340,450 | 50,700 | 521 | 1,135 | 203 | 34 | 1 | 7,109 | 211 | 1,579 | 82 | 0 | 2 | 2018-06-09T08:46:41 | 3,300 | Java | {'Java': 3671759} | Apache License 2.0 |
334 | immutables/immutables/785/784 | immutables | immutables | https://github.com/immutables/immutables/issues/784 | https://github.com/immutables/immutables/pull/785 | https://github.com/immutables/immutables/pull/785 | 1 | resolve | -Werror compiler warning for unchecked casts for java.util.Optional | Issue #723 still occurs for java.util.Optional with using the -Werror compiler option. | 99256177286404c75bbfe56eed21fa3c469121f5 | ceab34a7288c946844bb522c420c7f87c78a2e38 | https://github.com/immutables/immutables/compare/99256177286404c75bbfe56eed21fa3c469121f5...ceab34a7288c946844bb522c420c7f87c78a2e38 | diff --git a/value-processor/src/org/immutables/value/processor/meta/ValueAttribute.java b/value-processor/src/org/immutables/value/processor/meta/ValueAttribute.java
index e061a57d..6eeaab53 100644
--- a/value-processor/src/org/immutables/value/processor/meta/ValueAttribute.java
+++ b/value-processor/src/org/immutables/value/processor/meta/ValueAttribute.java
@@ -1050,7 +1050,6 @@ public final class ValueAttribute extends TypeIntrospectionBase implements HasSt
public boolean isSafeUncheckedCovariantCast() {
return isOptionalType()
- && !isJdkOptional()
&& !getConsumedElementType().equals(getWrappedElementType());
}
| ['value-processor/src/org/immutables/value/processor/meta/ValueAttribute.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,602,105 | 340,458 | 50,701 | 521 | 28 | 8 | 1 | 1 | 86 | 12 | 18 | 1 | 0 | 0 | 2018-06-04T20:09:34 | 3,300 | Java | {'Java': 3671759} | Apache License 2.0 |
908 | roaringbitmap/roaringbitmap/593/592 | roaringbitmap | roaringbitmap | https://github.com/RoaringBitmap/RoaringBitmap/issues/592 | https://github.com/RoaringBitmap/RoaringBitmap/pull/593 | https://github.com/RoaringBitmap/RoaringBitmap/pull/593 | 1 | fixes | Result of Roaring64Bitmap::or is not right | **Describe the bug**
```java
public static void main(String[] args) throws IOException {
String s1 = FileUtils.readFileToString(new File("D:\\\\Documents\\\\Pictures\\\\base64.txt"), StandardCharsets.UTF_8);
byte[] decodedString = Base64.getDecoder().decode(new String(s1).getBytes(StandardCharsets.UTF_8));
Roaring64Bitmap b1 = BitMapUtil.toBitMap(decodedString);
Roaring64Bitmap b2 = BitMapUtil.toBitMap(decodedString);
System.out.println("b1 length " + b1.getLongCardinality() + ", and b1 contains 22110666752 " + b1.contains(22110666752L));
b1.or(b1);
System.out.println("b1 length " + b1.getLongCardinality() + ", and b1 contains 22110666752 " + b1.contains(22110666752L));
}
public static Roaring64Bitmap toBitMap(byte[] array){
if (array == null){
return new Roaring64Bitmap();
}
Roaring64Bitmap ret = new Roaring64Bitmap();
try {
ret.deserialize(ByteBuffer.wrap(array));
} catch(IOException ioe) {
ioe.printStackTrace(); // should not happen
}
return ret;
}
```
result is :
```
b1 length 85243, and b1 contains 22110666752 false
b1 length 85297, and b1 contains 22110666752 true
```
base64.txt file is
[base64.txt](https://github.com/RoaringBitmap/RoaringBitmap/files/9961308/base64.txt)
| 0e5734418719cacdf57e316ab509284b54e23420 | 6764dde246987d60c9665e911cc7b01ada8cacf0 | https://github.com/roaringbitmap/roaringbitmap/compare/0e5734418719cacdf57e316ab509284b54e23420...6764dde246987d60c9665e911cc7b01ada8cacf0 | diff --git a/RoaringBitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java b/RoaringBitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
index 27af9afe..a9e93eec 100644
--- a/RoaringBitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
+++ b/RoaringBitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
@@ -1212,6 +1212,7 @@ public class RoaringBitmap implements Cloneable, Serializable, Iterable<Integer>
* @param x2 other bitmap
*/
public void and(final RoaringBitmap x2) {
+ if(x2 == this) { return; }
int pos1 = 0, pos2 = 0, intersectionSize = 0;
final int length1 = highLowContainer.size(), length2 = x2.highLowContainer.size();
@@ -1285,6 +1286,10 @@ public class RoaringBitmap implements Cloneable, Serializable, Iterable<Integer>
* @param x2 other bitmap
*/
public void andNot(final RoaringBitmap x2) {
+ if(x2 == this) {
+ clear();
+ return;
+ }
int pos1 = 0, pos2 = 0, intersectionSize = 0;
final int length1 = highLowContainer.size(), length2 = x2.highLowContainer.size();
@@ -1366,6 +1371,9 @@ public class RoaringBitmap implements Cloneable, Serializable, Iterable<Integer>
* @param rangeEnd end point of the range (exclusive).
*/
public void orNot(final RoaringBitmap other, long rangeEnd) {
+ if(other == this) {
+ throw new UnsupportedOperationException("orNot between a bitmap and itself?");
+ }
rangeSanityCheck(0, rangeEnd);
int maxKey = (int)((rangeEnd - 1) >>> 16);
int lastRun = (rangeEnd & 0xFFFF) == 0 ? 0x10000 : (int)(rangeEnd & 0xFFFF);
@@ -2211,6 +2219,7 @@ public class RoaringBitmap implements Cloneable, Serializable, Iterable<Integer>
// don't forget to call repairAfterLazy() afterward
// important: x2 should not have been computed lazily
protected void lazyor(final RoaringBitmap x2) {
+ if(this == x2) { return; }
int pos1 = 0, pos2 = 0;
int length1 = highLowContainer.size();
final int length2 = x2.highLowContainer.size();
@@ -2258,6 +2267,7 @@ public class RoaringBitmap implements Cloneable, Serializable, Iterable<Integer>
// this method is like lazyor except that it will convert
// the current container to a bitset
protected void naivelazyor(RoaringBitmap x2) {
+ if(this == x2) { return; }
int pos1 = 0, pos2 = 0;
int length1 = highLowContainer.size();
final int length2 = x2.highLowContainer.size();
@@ -2333,6 +2343,7 @@ public class RoaringBitmap implements Cloneable, Serializable, Iterable<Integer>
* @param x2 other bitmap
*/
public void or(final RoaringBitmap x2) {
+ if(this == x2) { return; }
int pos1 = 0, pos2 = 0;
int length1 = highLowContainer.size();
final int length2 = x2.highLowContainer.size();
@@ -3089,6 +3100,10 @@ public class RoaringBitmap implements Cloneable, Serializable, Iterable<Integer>
* @param x2 other bitmap
*/
public void xor(final RoaringBitmap x2) {
+ if(x2 == this) {
+ clear();
+ return;
+ }
int pos1 = 0, pos2 = 0;
int length1 = highLowContainer.size();
final int length2 = x2.highLowContainer.size();
diff --git a/RoaringBitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringBitmap.java b/RoaringBitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringBitmap.java
index 878a0c42..7ef2ce04 100644
--- a/RoaringBitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringBitmap.java
+++ b/RoaringBitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringBitmap.java
@@ -850,6 +850,7 @@ public class MutableRoaringBitmap extends ImmutableRoaringBitmap
* @param array other bitmap
*/
public void and(final ImmutableRoaringBitmap array) {
+ if(array == this) { return; }
int pos1 = 0, pos2 = 0, intersectionSize = 0;
final int length1 = highLowContainer.size(), length2 = array.highLowContainer.size();
@@ -881,6 +882,10 @@ public class MutableRoaringBitmap extends ImmutableRoaringBitmap
* @param x2 other bitmap
*/
public void andNot(final ImmutableRoaringBitmap x2) {
+ if(x2 == this) {
+ clear();
+ return;
+ }
int pos1 = 0, pos2 = 0, intersectionSize = 0;
final int length1 = highLowContainer.size(), length2 = x2.highLowContainer.size();
@@ -921,6 +926,9 @@ public class MutableRoaringBitmap extends ImmutableRoaringBitmap
* @param rangeEnd end point of the range (exclusive).
*/
public void orNot(ImmutableRoaringBitmap other, long rangeEnd) {
+ if(other == this) {
+ throw new UnsupportedOperationException("orNot between a bitmap and itself?");
+ }
rangeSanityCheck(0, rangeEnd);
int maxKey = (int)((rangeEnd - 1) >>> 16);
int lastRun = (rangeEnd & 0xFFFF) == 0 ? 0x10000 : (int)(rangeEnd & 0xFFFF);
@@ -1254,6 +1262,7 @@ public class MutableRoaringBitmap extends ImmutableRoaringBitmap
// call repairAfterLazy on result, eventually
// important: x2 should not have been computed lazily
protected void lazyor(final ImmutableRoaringBitmap x2) {
+ if(this == x2) { return; }
int pos1 = 0, pos2 = 0;
int length1 = highLowContainer.size();
final int length2 = x2.highLowContainer.size();
@@ -1301,6 +1310,7 @@ public class MutableRoaringBitmap extends ImmutableRoaringBitmap
// this method is like lazyor except that it will convert
// the current container to a bitset
protected void naivelazyor(final ImmutableRoaringBitmap x2) {
+ if(this == x2) { return; }
int pos1 = 0, pos2 = 0;
int length1 = highLowContainer.size();
final int length2 = x2.highLowContainer.size();
@@ -1354,6 +1364,7 @@ public class MutableRoaringBitmap extends ImmutableRoaringBitmap
* @param x2 other bitmap
*/
public void or(final ImmutableRoaringBitmap x2) {
+ if(this == x2) { return; }
int pos1 = 0, pos2 = 0;
int length1 = highLowContainer.size();
final int length2 = x2.highLowContainer.size();
@@ -1617,6 +1628,10 @@ public class MutableRoaringBitmap extends ImmutableRoaringBitmap
* @param x2 other bitmap
*/
public void xor(final ImmutableRoaringBitmap x2) {
+ if(x2 == this) {
+ clear();
+ return;
+ }
int pos1 = 0, pos2 = 0;
int length1 = highLowContainer.size();
final int length2 = x2.highLowContainer.size();
diff --git a/RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64Bitmap.java b/RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64Bitmap.java
index 6f036d7f..36883093 100644
--- a/RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64Bitmap.java
+++ b/RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64Bitmap.java
@@ -294,6 +294,7 @@ public class Roaring64Bitmap implements Externalizable, LongBitmapDataProvider {
* @param x2 other bitmap
*/
public void or(final Roaring64Bitmap x2) {
+ if(this == x2) { return; }
KeyIterator highIte2 = x2.highLowContainer.highKeyIterator();
while (highIte2.hasNext()) {
byte[] high = highIte2.next();
@@ -316,6 +317,10 @@ public class Roaring64Bitmap implements Externalizable, LongBitmapDataProvider {
* @param x2 other bitmap
*/
public void xor(final Roaring64Bitmap x2) {
+ if(x2 == this) {
+ clear();
+ return;
+ }
KeyIterator keyIterator = x2.highLowContainer.highKeyIterator();
while (keyIterator.hasNext()) {
byte[] high = keyIterator.next();
@@ -338,6 +343,7 @@ public class Roaring64Bitmap implements Externalizable, LongBitmapDataProvider {
* @param x2 other bitmap
*/
public void and(final Roaring64Bitmap x2) {
+ if(x2 == this) { return; }
KeyIterator thisIterator = highLowContainer.highKeyIterator();
while (thisIterator.hasNext()) {
byte[] highKey = thisIterator.next();
@@ -364,6 +370,10 @@ public class Roaring64Bitmap implements Externalizable, LongBitmapDataProvider {
* @param x2 other bitmap
*/
public void andNot(final Roaring64Bitmap x2) {
+ if(x2 == this) {
+ clear();
+ return;
+ }
KeyIterator thisKeyIterator = highLowContainer.highKeyIterator();
while (thisKeyIterator.hasNext()) {
byte[] high = thisKeyIterator.next();
diff --git a/RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java b/RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
index 187c9c13..0461576e 100644
--- a/RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
+++ b/RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
@@ -708,6 +708,7 @@ public class Roaring64NavigableMap implements Externalizable, LongBitmapDataProv
* @param x2 other bitmap
*/
public void naivelazyor(final Roaring64NavigableMap x2) {
+ if(this == x2) { return; }
for (Entry<Integer, BitmapDataProvider> e2 : x2.highToBitmap.entrySet()) {
// Keep object to prevent auto-boxing
Integer high = e2.getKey();
@@ -750,6 +751,7 @@ public class Roaring64NavigableMap implements Externalizable, LongBitmapDataProv
* @param x2 other bitmap
*/
public void or(final Roaring64NavigableMap x2) {
+ if(this == x2) { return; }
boolean firstBucket = true;
for (Entry<Integer, BitmapDataProvider> e2 : x2.highToBitmap.entrySet()) {
@@ -806,6 +808,10 @@ public class Roaring64NavigableMap implements Externalizable, LongBitmapDataProv
* @param x2 other bitmap
*/
public void xor(final Roaring64NavigableMap x2) {
+ if(x2 == this) {
+ clear();
+ return;
+ }
boolean firstBucket = true;
for (Entry<Integer, BitmapDataProvider> e2 : x2.highToBitmap.entrySet()) {
@@ -861,6 +867,7 @@ public class Roaring64NavigableMap implements Externalizable, LongBitmapDataProv
* @param x2 other bitmap
*/
public void and(final Roaring64NavigableMap x2) {
+ if(x2 == this) { return; }
boolean firstBucket = true;
Iterator<Entry<Integer, BitmapDataProvider>> thisIterator = highToBitmap.entrySet().iterator();
@@ -906,6 +913,10 @@ public class Roaring64NavigableMap implements Externalizable, LongBitmapDataProv
* @param x2 other bitmap
*/
public void andNot(final Roaring64NavigableMap x2) {
+ if(x2 == this) {
+ clear();
+ return;
+ }
boolean firstBucket = true;
Iterator<Entry<Integer, BitmapDataProvider>> thisIterator = highToBitmap.entrySet().iterator();
diff --git a/RoaringBitmap/src/test/java/org/roaringbitmap/TestRoaringBitmap.java b/RoaringBitmap/src/test/java/org/roaringbitmap/TestRoaringBitmap.java
index 59e01b17..a1327195 100644
--- a/RoaringBitmap/src/test/java/org/roaringbitmap/TestRoaringBitmap.java
+++ b/RoaringBitmap/src/test/java/org/roaringbitmap/TestRoaringBitmap.java
@@ -5406,6 +5406,22 @@ public class TestRoaringBitmap {
assertTrue(bitmap.cardinalityExceeds(runLength - 1));
}
+
+ @Test
+ public void testWithYourself() {
+ RoaringBitmap b1 = RoaringBitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10);
+ b1.runOptimize();
+ b1.or(b1);
+ assertTrue(b1.equals(RoaringBitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10)));
+ b1.xor(b1);
+ assertTrue(b1.isEmpty());
+ b1 = RoaringBitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10);
+ b1.and(b1);
+ assertTrue(b1.equals(RoaringBitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10)));
+ b1.andNot(b1);
+ assertTrue(b1.isEmpty());
+ }
+
@Test
public void testIssue566() {
RoaringBitmap roaringBitMap = new RoaringBitmap();
diff --git a/RoaringBitmap/src/test/java/org/roaringbitmap/buffer/TestRoaringBitmap.java b/RoaringBitmap/src/test/java/org/roaringbitmap/buffer/TestRoaringBitmap.java
index 50cb2b22..f1371599 100644
--- a/RoaringBitmap/src/test/java/org/roaringbitmap/buffer/TestRoaringBitmap.java
+++ b/RoaringBitmap/src/test/java/org/roaringbitmap/buffer/TestRoaringBitmap.java
@@ -3916,6 +3916,21 @@ public class TestRoaringBitmap {
assertTrue(bitmap.cardinalityExceeds(runLength - 1));
}
+ @Test
+ public void testWithYourself() {
+ MutableRoaringBitmap b1 = MutableRoaringBitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10);
+ b1.runOptimize();
+ b1.or(b1);
+ assertTrue(b1.equals(MutableRoaringBitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10)));
+ b1.xor(b1);
+ assertTrue(b1.isEmpty());
+ b1 = MutableRoaringBitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10);
+ b1.and(b1);
+ assertTrue(b1.equals(MutableRoaringBitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10)));
+ b1.andNot(b1);
+ assertTrue(b1.isEmpty());
+ }
+
@Test
public void testPreviousValueRegression() {
// see https://github.com/RoaringBitmap/RoaringBitmap/issues/564
diff --git a/RoaringBitmap/src/test/java/org/roaringbitmap/longlong/TestRoaring64Bitmap.java b/RoaringBitmap/src/test/java/org/roaringbitmap/longlong/TestRoaring64Bitmap.java
index f0d0d52c..eeff115f 100644
--- a/RoaringBitmap/src/test/java/org/roaringbitmap/longlong/TestRoaring64Bitmap.java
+++ b/RoaringBitmap/src/test/java/org/roaringbitmap/longlong/TestRoaring64Bitmap.java
@@ -2172,6 +2172,20 @@ public class TestRoaring64Bitmap {
}
+ @Test
+ public void testWithYourself() {
+ Roaring64Bitmap b1 = Roaring64Bitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10);
+ b1.runOptimize();
+ b1.or(b1);
+ assertTrue(b1.equals(Roaring64Bitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10)));
+ b1.xor(b1);
+ assertTrue(b1.isEmpty());
+ b1 = Roaring64Bitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10);
+ b1.and(b1);
+ assertTrue(b1.equals(Roaring64Bitmap.bitmapOf(1,2,3,4,5,6,7,8,9,10)));
+ b1.andNot(b1);
+ assertTrue(b1.isEmpty());
+ }
@Test
public void testIssue580() { | ['RoaringBitmap/src/test/java/org/roaringbitmap/buffer/TestRoaringBitmap.java', 'RoaringBitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java', 'RoaringBitmap/src/test/java/org/roaringbitmap/TestRoaringBitmap.java', 'RoaringBitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringBitmap.java', 'RoaringBitmap/src/test/java/org/roaringbitmap/longlong/TestRoaring64Bitmap.java', 'RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java', 'RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64Bitmap.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 1,656,682 | 416,050 | 54,696 | 244 | 1,131 | 316 | 51 | 4 | 1,391 | 121 | 349 | 39 | 1 | 2 | 2022-11-08T15:58:22 | 3,158 | Java | {'Java': 3366271, 'Kotlin': 14705, 'Python': 2509, 'Shell': 1485} | Apache License 2.0 |
909 | roaringbitmap/roaringbitmap/587/586 | roaringbitmap | roaringbitmap | https://github.com/RoaringBitmap/RoaringBitmap/issues/586 | https://github.com/RoaringBitmap/RoaringBitmap/pull/587 | https://github.com/RoaringBitmap/RoaringBitmap/pull/587 | 2 | fixes | RangeBitmap can give wrong result when computing between on 2 values with different highest bit | **Describe the bug**
When setting the RangeBitmap to full range (`0xFFFFFFFFFFFFFFFFL`, used for computing double range), computing a between for 2 values with different highest bit won't return the expected matching value.
**To Reproduce**
```
public static void main(String[] args) {
RangeBitmap.Appender appender = RangeBitmap.appender(0xFFFFFFFFFFFFFFFFL);
appender.add(0xFFFFFFFFFFFFFFF0L);
RangeBitmap rangeBitmap = appender.build();
System.out.println(rangeBitmap.between(0x0FFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFF0L));
System.out.println(rangeBitmap.between(0x0FFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFF1L));
}
```
It returns empty bitmap in both operations.
**RoaringBitmap version:**
0.9.28
**Java version:**
11
| a307727d3a87fe89aa3d1a7328821b057717d4bf | f2b22f2c26588cb6228d67153728ab30f5a75411 | https://github.com/roaringbitmap/roaringbitmap/compare/a307727d3a87fe89aa3d1a7328821b057717d4bf...f2b22f2c26588cb6228d67153728ab30f5a75411 | diff --git a/RoaringBitmap/src/main/java/org/roaringbitmap/RangeBitmap.java b/RoaringBitmap/src/main/java/org/roaringbitmap/RangeBitmap.java
index b8e4320d..3b95471c 100644
--- a/RoaringBitmap/src/main/java/org/roaringbitmap/RangeBitmap.java
+++ b/RoaringBitmap/src/main/java/org/roaringbitmap/RangeBitmap.java
@@ -729,11 +729,15 @@ public final class RangeBitmap {
// most significant absent bit in the threshold for which there is no container;
// everything before this is wasted work, so we just skip over the containers
int skipLow = 64 - Long.numberOfLeadingZeros(((~lower & ~containerMask) & mask));
- if (skipLow > 0) {
+ if (skipLow == 64) {
+ lower = 0L;
+ } else if (skipLow > 0) {
lower &= -(1L << skipLow);
}
int skipHigh = 64 - Long.numberOfLeadingZeros(((~upper & ~containerMask) & mask));
- if (skipHigh > 0) {
+ if (skipHigh == 64) {
+ upper = 0L;
+ } else if (skipHigh > 0) {
upper &= -(1L << skipHigh);
}
setupFirstSlice(upper, high, (int) remaining, skipHigh == 0);
@@ -741,9 +745,12 @@ public final class RangeBitmap {
if ((containerMask & 1) == 1) {
skipContainer();
}
- for (int slice = 1; slice < Long.bitCount(mask); ++slice) {
- if ((containerMask >>> slice & 1) == 1) {
- int flags = (int) (((upper >>> slice) & 1) | (((lower >>> slice) & 1) << 1));
+ containerMask >>>= 1;
+ upper >>>= 1;
+ lower >>>= 1;
+ for (; containerMask != 0; containerMask >>>= 1, upper >>>= 1, lower >>>= 1) {
+ if ((containerMask & 1) == 1) {
+ int flags = (int) ((upper & 1) | ((lower & 1) << 1));
switch (flags) {
case 0: // both absent
andLowAndHigh();
diff --git a/RoaringBitmap/src/test/java/org/roaringbitmap/RangeBitmapTest.java b/RoaringBitmap/src/test/java/org/roaringbitmap/RangeBitmapTest.java
index 6a508ef8..e3120fd8 100644
--- a/RoaringBitmap/src/test/java/org/roaringbitmap/RangeBitmapTest.java
+++ b/RoaringBitmap/src/test/java/org/roaringbitmap/RangeBitmapTest.java
@@ -736,6 +736,25 @@ public class RangeBitmapTest {
assertEquals(accumulator.build().betweenCardinality(value, value), count);
}
+ @Test
+ public void regressionTestIssue586() {
+ // see https://github.com/RoaringBitmap/RoaringBitmap/issues/586
+ assertAll(
+ () -> regresssionTestIssue586(0x0FFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFF0L, 0xFFFFFFFFFFFFFF0L),
+ () -> regresssionTestIssue586(0x0FFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFF0L, 0xFFFFFFFFFFFFFFF0L),
+ () -> regresssionTestIssue586(0x0FFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFF1L, 0xFFFFFFFFFFFFFFF0L),
+ () -> regresssionTestIssue586(0, 10_000_000_000L, 10_000_000L)
+ );
+ }
+
+ private static void regresssionTestIssue586(long low, long high, long value) {
+ RangeBitmap.Appender appender = RangeBitmap.appender(0xFFFFFFFFFFFFFFFFL);
+ appender.add(value);
+ RangeBitmap rangeBitmap = appender.build();
+ assertEquals(rangeBitmap.gte(low, rangeBitmap.lte(high)), rangeBitmap.between(low, high));
+ assertEquals(1, rangeBitmap.between(low, high).getCardinality());
+ }
+
public static class ReferenceImplementation {
public static Builder builder() { | ['RoaringBitmap/src/main/java/org/roaringbitmap/RangeBitmap.java', 'RoaringBitmap/src/test/java/org/roaringbitmap/RangeBitmapTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,656,449 | 415,964 | 54,689 | 244 | 688 | 233 | 17 | 1 | 768 | 69 | 179 | 26 | 0 | 1 | 2022-10-16T11:09:00 | 3,158 | Java | {'Java': 3366271, 'Kotlin': 14705, 'Python': 2509, 'Shell': 1485} | Apache License 2.0 |
9,781 | helidon-io/helidon/502/477 | helidon-io | helidon | https://github.com/helidon-io/helidon/issues/477 | https://github.com/helidon-io/helidon/pull/502 | https://github.com/helidon-io/helidon/pull/502 | 1 | fixes | Config: Refactor usage of exceptions in optional sources | When we start Helidon SE and have logging set to "FINE", config logs a number of exceptions that should not be thrown, related to optional config sources.
When a config source is optional, there should be no exception thrown, instead we should gracefully ignore it.
Reasons:
1. Log is polluted with useless information
2. Debugging using Exception breakpoints is more complicated, as it stops on "false" positives
## Environment Details
* Helidon Version: 1.0.0
* Helidon SE
----------
Log output:
```
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource loadDataChangedSinceLastLoad
FINE: Source ClasspathConfig[meta-config.yaml]? has changed to Optional[1970-01-01T00:00:00Z] from Optional.empty.
Mar 06, 2019 7:22:19 PM io.helidon.config.internal.ClasspathConfigSource content
FINE: Error to get ClasspathConfig[meta-config.yaml]? using java.lang.ClassLoader@1043d64e8 CONTEXT ClassLoader.
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource processMissingData
CONFIG: Cannot load data from optional source ClasspathConfig[meta-config.yaml]?. Will not be used to load from. ClasspathConfig[meta-config.yaml]? does not exist. Used ClassLoader: java.lang.ClassLoader@1043d64e8
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource processMissingData
FINE: Load of 'ClasspathConfig[meta-config.yaml]?' source failed with an exception.
io.helidon.config.ConfigException: ClasspathConfig[meta-config.yaml]? does not exist. Used ClassLoader: java.lang.ClassLoader@1043d64e8
at io.helidon.config.internal.ClasspathConfigSource.content(ClasspathConfigSource.java:115)
at io.helidon.config.spi.AbstractParsableConfigSource.loadData(AbstractParsableConfigSource.java:58)
at io.helidon.config.RetryPolicies$JustCallRetryPolicyHolder$1.execute(RetryPolicies.java:77)
at io.helidon.config.spi.AbstractSource.loadDataChangedSinceLastLoad(AbstractSource.java:197)
at io.helidon.config.spi.AbstractSource.load(AbstractSource.java:177)
at io.helidon.config.UseFirstAvailableConfigSource.load(UseFirstAvailableConfigSource.java:58)
at io.helidon.config.ProviderImpl.newConfig(ProviderImpl.java:103)
at io.helidon.config.BuilderImpl.build(BuilderImpl.java:245)
at io.helidon.config.ConfigSources.load(ConfigSources.java:345)
at io.helidon.config.BuilderImpl.defaultConfigSource(BuilderImpl.java:348)
at io.helidon.config.BuilderImpl.targetConfigSource(BuilderImpl.java:309)
at io.helidon.config.BuilderImpl.buildProvider(BuilderImpl.java:278)
at io.helidon.config.BuilderImpl.build(BuilderImpl.java:245)
at io.helidon.config.Config.create(Config.java:358)
at io.helidon.examples.graalvm.GraalVMNativeImageMain.main(GraalVMNativeImageMain.java:76)
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource loadDataChangedSinceLastLoad
FINE: Source ClasspathConfig[meta-config.conf]? has changed to Optional[1970-01-01T00:00:00Z] from Optional.empty.
Mar 06, 2019 7:22:19 PM io.helidon.config.internal.ClasspathConfigSource content
FINE: Error to get ClasspathConfig[meta-config.conf]? using java.lang.ClassLoader@1043d64e8 CONTEXT ClassLoader.
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource processMissingData
CONFIG: Cannot load data from optional source ClasspathConfig[meta-config.conf]?. Will not be used to load from. ClasspathConfig[meta-config.conf]? does not exist. Used ClassLoader: java.lang.ClassLoader@1043d64e8
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource processMissingData
FINE: Load of 'ClasspathConfig[meta-config.conf]?' source failed with an exception.
io.helidon.config.ConfigException: ClasspathConfig[meta-config.conf]? does not exist. Used ClassLoader: java.lang.ClassLoader@1043d64e8
at io.helidon.config.internal.ClasspathConfigSource.content(ClasspathConfigSource.java:115)
at io.helidon.config.spi.AbstractParsableConfigSource.loadData(AbstractParsableConfigSource.java:58)
at io.helidon.config.RetryPolicies$JustCallRetryPolicyHolder$1.execute(RetryPolicies.java:77)
at io.helidon.config.spi.AbstractSource.loadDataChangedSinceLastLoad(AbstractSource.java:197)
at io.helidon.config.spi.AbstractSource.load(AbstractSource.java:177)
at io.helidon.config.UseFirstAvailableConfigSource.load(UseFirstAvailableConfigSource.java:58)
at io.helidon.config.ProviderImpl.newConfig(ProviderImpl.java:103)
at io.helidon.config.BuilderImpl.build(BuilderImpl.java:245)
at io.helidon.config.ConfigSources.load(ConfigSources.java:345)
at io.helidon.config.BuilderImpl.defaultConfigSource(BuilderImpl.java:348)
at io.helidon.config.BuilderImpl.targetConfigSource(BuilderImpl.java:309)
at io.helidon.config.BuilderImpl.buildProvider(BuilderImpl.java:278)
at io.helidon.config.BuilderImpl.build(BuilderImpl.java:245)
at io.helidon.config.Config.create(Config.java:358)
at io.helidon.examples.graalvm.GraalVMNativeImageMain.main(GraalVMNativeImageMain.java:76)
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource loadDataChangedSinceLastLoad
FINE: Source ClasspathConfig[meta-config.json]? has changed to Optional[1970-01-01T00:00:00Z] from Optional.empty.
Mar 06, 2019 7:22:19 PM io.helidon.config.internal.ClasspathConfigSource content
FINE: Error to get ClasspathConfig[meta-config.json]? using java.lang.ClassLoader@1043d64e8 CONTEXT ClassLoader.
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource processMissingData
CONFIG: Cannot load data from optional source ClasspathConfig[meta-config.json]?. Will not be used to load from. ClasspathConfig[meta-config.json]? does not exist. Used ClassLoader: java.lang.ClassLoader@1043d64e8
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource processMissingData
FINE: Load of 'ClasspathConfig[meta-config.json]?' source failed with an exception.
io.helidon.config.ConfigException: ClasspathConfig[meta-config.json]? does not exist. Used ClassLoader: java.lang.ClassLoader@1043d64e8
at io.helidon.config.internal.ClasspathConfigSource.content(ClasspathConfigSource.java:115)
at io.helidon.config.spi.AbstractParsableConfigSource.loadData(AbstractParsableConfigSource.java:58)
at io.helidon.config.RetryPolicies$JustCallRetryPolicyHolder$1.execute(RetryPolicies.java:77)
at io.helidon.config.spi.AbstractSource.loadDataChangedSinceLastLoad(AbstractSource.java:197)
at io.helidon.config.spi.AbstractSource.load(AbstractSource.java:177)
at io.helidon.config.UseFirstAvailableConfigSource.load(UseFirstAvailableConfigSource.java:58)
at io.helidon.config.ProviderImpl.newConfig(ProviderImpl.java:103)
at io.helidon.config.BuilderImpl.build(BuilderImpl.java:245)
at io.helidon.config.ConfigSources.load(ConfigSources.java:345)
at io.helidon.config.BuilderImpl.defaultConfigSource(BuilderImpl.java:348)
at io.helidon.config.BuilderImpl.targetConfigSource(BuilderImpl.java:309)
at io.helidon.config.BuilderImpl.buildProvider(BuilderImpl.java:278)
at io.helidon.config.BuilderImpl.build(BuilderImpl.java:245)
at io.helidon.config.Config.create(Config.java:358)
at io.helidon.examples.graalvm.GraalVMNativeImageMain.main(GraalVMNativeImageMain.java:76)
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource loadDataChangedSinceLastLoad
FINE: Source ClasspathConfig[meta-config.properties]? has changed to Optional[1970-01-01T00:00:00Z] from Optional.empty.
Mar 06, 2019 7:22:19 PM io.helidon.config.internal.ClasspathConfigSource content
FINE: Error to get ClasspathConfig[meta-config.properties]? using java.lang.ClassLoader@1043d64e8 CONTEXT ClassLoader.
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource processMissingData
CONFIG: Cannot load data from optional source ClasspathConfig[meta-config.properties]?. Will not be used to load from. ClasspathConfig[meta-config.properties]? does not exist. Used ClassLoader: java.lang.ClassLoader@1043d64e8
Mar 06, 2019 7:22:19 PM io.helidon.config.spi.AbstractSource processMissingData
FINE: Load of 'ClasspathConfig[meta-config.properties]?' source failed with an exception.
io.helidon.config.ConfigException: ClasspathConfig[meta-config.properties]? does not exist. Used ClassLoader: java.lang.ClassLoader@1043d64e8
at io.helidon.config.internal.ClasspathConfigSource.content(ClasspathConfigSource.java:115)
at io.helidon.config.spi.AbstractParsableConfigSource.loadData(AbstractParsableConfigSource.java:58)
at io.helidon.config.RetryPolicies$JustCallRetryPolicyHolder$1.execute(RetryPolicies.java:77)
at io.helidon.config.spi.AbstractSource.loadDataChangedSinceLastLoad(AbstractSource.java:197)
at io.helidon.config.spi.AbstractSource.load(AbstractSource.java:177)
at io.helidon.config.UseFirstAvailableConfigSource.load(UseFirstAvailableConfigSource.java:58)
at io.helidon.config.ProviderImpl.newConfig(ProviderImpl.java:103)
at io.helidon.config.BuilderImpl.build(BuilderImpl.java:245)
at io.helidon.config.ConfigSources.load(ConfigSources.java:345)
at io.helidon.config.BuilderImpl.defaultConfigSource(BuilderImpl.java:348)
at io.helidon.config.BuilderImpl.targetConfigSource(BuilderImpl.java:309)
at io.helidon.config.BuilderImpl.buildProvider(BuilderImpl.java:278)
at io.helidon.config.BuilderImpl.build(BuilderImpl.java:245)
at io.helidon.config.Config.create(Config.java:358)
at io.helidon.examples.graalvm.GraalVMNativeImageMain.main(GraalVMNativeImageMain.java:76)
``` | 01a88710f83e9293ee33fc411b0607aa83e09cb6 | 36aca6ba087c6a18a19920ba7259401956a744ff | https://github.com/helidon-io/helidon/compare/01a88710f83e9293ee33fc411b0607aa83e09cb6...36aca6ba087c6a18a19920ba7259401956a744ff | diff --git a/config/config/src/main/java/io/helidon/config/BuilderImpl.java b/config/config/src/main/java/io/helidon/config/BuilderImpl.java
index 33e7761d4d..a2f8b7762f 100644
--- a/config/config/src/main/java/io/helidon/config/BuilderImpl.java
+++ b/config/config/src/main/java/io/helidon/config/BuilderImpl.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2019 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package io.helidon.config;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -54,6 +55,7 @@ import static io.helidon.config.ConfigSources.classpath;
class BuilderImpl implements Config.Builder {
static final Executor DEFAULT_CHANGES_EXECUTOR = Executors.newCachedThreadPool(new ConfigThreadFactory("config"));
+ private static final List<String> DEFAULT_FILE_EXTENSIONS = Arrays.asList("yaml", "conf", "json", "properties");
private List<ConfigSource> sources;
private final MapperProviders mapperProviders;
@@ -342,21 +344,36 @@ class BuilderImpl implements Config.Builder {
// utils
//
- static ConfigSource defaultConfigSource() {
- return ConfigSources.create(
- new UseFirstAvailableConfigSource(
- ConfigSources.load(
- new UseFirstAvailableConfigSource(
- classpath("meta-config.yaml").optional().build(),
- classpath("meta-config.conf").optional().build(),
- classpath("meta-config.json").optional().build(),
- classpath("meta-config.properties").optional().build()
- )).build(),
- classpath("application.yaml").optional().build(),
- classpath("application.conf").optional().build(),
- classpath("application.json").optional().build(),
- classpath("application.properties").optional().build()
- )).build();
+ private static ConfigSource defaultConfigSource() {
+ final List<ConfigSource> sources = new ArrayList<>();
+ final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+ final List<ConfigSource> meta = defaultConfigSources(classLoader, "meta-config");
+ if (!meta.isEmpty()) {
+ sources.add(ConfigSources.load(toDefaultConfigSource(meta)).build());
+ }
+ sources.addAll(defaultConfigSources(classLoader, "application"));
+ return ConfigSources.create(toDefaultConfigSource(sources)).build();
+ }
+
+ private static List<ConfigSource> defaultConfigSources(final ClassLoader classLoader, final String baseResourceName) {
+ final List<ConfigSource> sources = new ArrayList<>();
+ for (final String extension : DEFAULT_FILE_EXTENSIONS) {
+ final String resource = baseResourceName + "." + extension;
+ if (classLoader.getResource(resource) != null) {
+ sources.add(classpath(resource).optional().build());
+ }
+ }
+ return sources;
+ }
+
+ private static ConfigSource toDefaultConfigSource(final List<ConfigSource> sources) {
+ if (sources.isEmpty()) {
+ return ConfigSources.empty();
+ } else if (sources.size() == 1) {
+ return sources.get(0);
+ } else {
+ return new UseFirstAvailableConfigSource(sources);
+ }
}
static List<ConfigParser> buildParsers(boolean servicesEnabled, List<ConfigParser> userDefinedParsers) { | ['config/config/src/main/java/io/helidon/config/BuilderImpl.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,331,989 | 873,821 | 118,766 | 848 | 2,749 | 479 | 49 | 1 | 9,759 | 542 | 2,431 | 117 | 0 | 1 | 2019-03-13T00:54:36 | 3,093 | Java | {'Java': 20926867, 'Mustache': 144743, 'Shell': 96781, 'Lua': 6617, 'Dockerfile': 1874, 'CSS': 1413, 'HTML': 15} | Apache License 2.0 |
9,783 | helidon-io/helidon/393/392 | helidon-io | helidon | https://github.com/helidon-io/helidon/issues/392 | https://github.com/helidon-io/helidon/pull/393 | https://github.com/helidon-io/helidon/pull/393 | 1 | fixes | Regression in JsonSupport | Reading content as JsonObject fails in 0.11.1, works in 0.11.0
```
request.content()
.as(JsonObject.class)
.thenAccept(json -> {
// this line is never reached
greeting.set(json.getString("greeting"));
sendGreeting(response);
});
```
## Environment Details
* Helidon Version: 0.11.1
* Helidon SE
* JDK version: 1.8
* OS: Mac
----------
When I upgrade to 0.11.1 (and change JsonSupport to new package), the PUT request never reaches the line that processes the JsonObject.
Downgrading to 0.11.0 (and changing the JsonSupport to old package), the PUT request works just fine.
Registration:
```
return Routing.builder()
.register(JsonSupport.create())
//.register("/greet", new GreetService(greeting, config))
.register("/greeting", new GreetingService(greeting))
.build();
```
GreetingService:
```
/*
* Copyright (c) 2019 Oracle and/or its affiliates. All rights reserved.
*/
package io.helidon.examples.screencast.se;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import javax.json.Json;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObject;
import io.helidon.webserver.Routing;
import io.helidon.webserver.ServerRequest;
import io.helidon.webserver.ServerResponse;
import io.helidon.webserver.Service;
/**
* Greeting management.
*/
public class GreetingService implements Service {
private static final JsonBuilderFactory JSON = Json.createBuilderFactory(Collections.emptyMap());
private final AtomicReference<String> greeting;
public GreetingService(AtomicReference<String> greeting) {
this.greeting = greeting;
}
@Override
public void update(Routing.Rules rules) {
rules.put("/", this::updateGreetingHandler);
}
private void greetingHandler(ServerRequest request, ServerResponse response) {
sendGreeting(response);
}
private void updateGreetingHandler(ServerRequest request, ServerResponse response) {
request.content()
.as(JsonObject.class)
.thenAccept(json -> {
greeting.set(json.getString("greeting"));
sendGreeting(response);
});
}
private void sendGreeting(ServerResponse response) {
response.send(JSON.createObjectBuilder()
.add("greeting", greeting.get())
.build());
}
}
``` | 7e7e09b8ab5e0b45e9d8ebf31567b0002df2d49b | f75a7beb6af4410d1059e8d2af3d08170d24858f | https://github.com/helidon-io/helidon/compare/7e7e09b8ab5e0b45e9d8ebf31567b0002df2d49b...f75a7beb6af4410d1059e8d2af3d08170d24858f | diff --git a/media/jsonp/server/src/main/java/io/helidon/media/jsonp/server/JsonSupport.java b/media/jsonp/server/src/main/java/io/helidon/media/jsonp/server/JsonSupport.java
index 2d9bd36777..a0d2f69d43 100644
--- a/media/jsonp/server/src/main/java/io/helidon/media/jsonp/server/JsonSupport.java
+++ b/media/jsonp/server/src/main/java/io/helidon/media/jsonp/server/JsonSupport.java
@@ -18,6 +18,7 @@ package io.helidon.media.jsonp.server;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
@@ -185,7 +186,7 @@ public final class JsonSupport implements Service, Handler {
* Returns a charset from {@code Content-Type} header parameter or {@code null} if not defined.
*
* @param headers parameters representing request or response headers
- * @return a charset or {@code null}
+ * @return a charset or {@code UTF-8} as default
* @throws RuntimeException if charset is not supported
*/
private Charset determineCharset(Parameters headers) {
@@ -199,7 +200,7 @@ public final class JsonSupport implements Service, Handler {
return null; // Do not need default charset. Can use JSON specification.
}
})
- .orElse(null);
+ .orElse(StandardCharsets.UTF_8);
}
/** | ['media/jsonp/server/src/main/java/io/helidon/media/jsonp/server/JsonSupport.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,340,929 | 875,695 | 119,049 | 853 | 220 | 49 | 5 | 1 | 2,651 | 207 | 520 | 88 | 0 | 3 | 2019-02-11T15:22:08 | 3,093 | Java | {'Java': 20926867, 'Mustache': 144743, 'Shell': 96781, 'Lua': 6617, 'Dockerfile': 1874, 'CSS': 1413, 'HTML': 15} | Apache License 2.0 |
9,782 | helidon-io/helidon/431/430 | helidon-io | helidon | https://github.com/helidon-io/helidon/issues/430 | https://github.com/helidon-io/helidon/pull/431 | https://github.com/helidon-io/helidon/pull/431 | 1 | fix | NPE in ForwardingHandler |
## Environment Details
* Helidon Version: 1.0.1-SNAPSHOT
* Helidon SE or Helidon MP
* JDK version: 1.8
* OS: n/a
* Docker version (if applicable): n/a
----------
## Problem Description
In `channelRead0()` the response completion handler accesses the requestContent field which will normally be `null` unless the response was completed without reading all of the request.
```
bareResponse.whenCompleted()
.thenRun(() -> {
RequestContext requestContext = this.requestContext;
requestContext.responseCompleted(true); // <<== NPE
```
This field is set to `null` in the same method when handling a `LastHttpContent` message.
## Steps to reproduce
Make any request that reads all of the content before responding.
| b11767fe9b4ade402eb66956f2dcb4aa8dceaf90 | 0bac1f75e65bb0310d1698216ec42e950770badd | https://github.com/helidon-io/helidon/compare/b11767fe9b4ade402eb66956f2dcb4aa8dceaf90...0bac1f75e65bb0310d1698216ec42e950770badd | diff --git a/webserver/webserver/src/main/java/io/helidon/webserver/ForwardingHandler.java b/webserver/webserver/src/main/java/io/helidon/webserver/ForwardingHandler.java
index 49510d73d0..b5a4e83e41 100644
--- a/webserver/webserver/src/main/java/io/helidon/webserver/ForwardingHandler.java
+++ b/webserver/webserver/src/main/java/io/helidon/webserver/ForwardingHandler.java
@@ -98,14 +98,16 @@ public class ForwardingHandler extends SimpleChannelInboundHandler<Object> {
long requestId = REQUEST_ID_GENERATOR.incrementAndGet();
BareRequestImpl bareRequest =
- new BareRequestImpl((HttpRequest) msg, requestContext.publisher(), webServer, ctx, sslEngine, requestId);
+ new BareRequestImpl((HttpRequest) msg, requestContext.publisher(), webServer, ctx, sslEngine, requestId);
BareResponseImpl bareResponse =
- new BareResponseImpl(ctx, request, publisherRef::isCompleted, Thread.currentThread(), requestId);
+ new BareResponseImpl(ctx, request, publisherRef::isCompleted, Thread.currentThread(), requestId);
bareResponse.whenCompleted()
.thenRun(() -> {
RequestContext requestContext = this.requestContext;
- requestContext.responseCompleted(true);
+ if (requestContext != null) {
+ requestContext.responseCompleted(true);
+ }
/*
* Cleanup for these queues is done in HttpInitializer. However,
* it may take a while for the event loop on the channel to
@@ -128,7 +130,7 @@ public class ForwardingHandler extends SimpleChannelInboundHandler<Object> {
if (msg instanceof HttpContent) {
if (requestContext == null) {
throw new IllegalStateException("There is no request context associated with this http content. "
- + "This is never expected to happen!");
+ + "This is never expected to happen!");
}
HttpContent httpContent = (HttpContent) msg; | ['webserver/webserver/src/main/java/io/helidon/webserver/ForwardingHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,346,832 | 876,948 | 119,216 | 856 | 901 | 133 | 10 | 1 | 819 | 100 | 172 | 25 | 0 | 1 | 2019-02-21T21:44:50 | 3,093 | Java | {'Java': 20926867, 'Mustache': 144743, 'Shell': 96781, 'Lua': 6617, 'Dockerfile': 1874, 'CSS': 1413, 'HTML': 15} | Apache License 2.0 |
114 | axonframework/axonframework/2756/2751 | axonframework | axonframework | https://github.com/AxonFramework/AxonFramework/issues/2751 | https://github.com/AxonFramework/AxonFramework/pull/2756 | https://github.com/AxonFramework/AxonFramework/pull/2756 | 2 | resolves | Duplicate initialization of TrackingEventProcessor worker threads | <!-- Please use markdown (https://guides.github.com/features/mastering-markdown/) semantics throughout the bug description. -->
### Basic information
* Axon Framework version: 4.7.1
* JDK version: Amazon Coretto 17
### Steps to reproduce
We build our applications using Spring Boot and we recently introduced a spring actuator `HealthIndicator` to monitor the health of all axon event processors. The health indicator starts as a spring component and injects the axon `EventProcessingConfiguration` to access the `.eventProcessors()` method to loop over all event processors checking their status.
After the introduction of our new `HealthIndicator` we started seeing random occurrences of duplicated events in our event processors. We spent the last few days tracking down the error and finally found a race condition in the initialization of the axon event processors. After looking at the axon source code we found that calling the `.eventProcessors()` was not a simple get operation (as we expected) but it actually initialized the event processors. In some rare occasions the `HealthIndicator` will call the `.eventProcessors()` method at the same time as it is being initialized by axon during startup. Since the `EventProcessingModule.initializeProcessors()` is not thread safe this will causes duplicate event processor threads being created for the same event processor and segment.
### Expected behaviour
The `.eventProcessors()` method looks like a simple getter, and should not have side effects. If the initialization side effects are unavoidable it should be thread safe.
### Actual behaviour
Race condition when calling `.eventProcessors()` from multiple locations simultaneously during startup.
| 62bae3f17614e66d919afbbda08da4cbd6235346 | 61efd48c72f49feaaecea2c8c01c120889b5aaf8 | https://github.com/axonframework/axonframework/compare/62bae3f17614e66d919afbbda08da4cbd6235346...61efd48c72f49feaaecea2c8c01c120889b5aaf8 | diff --git a/config/src/main/java/org/axonframework/config/EventProcessingModule.java b/config/src/main/java/org/axonframework/config/EventProcessingModule.java
index 092a993e6..535b70ac5 100644
--- a/config/src/main/java/org/axonframework/config/EventProcessingModule.java
+++ b/config/src/main/java/org/axonframework/config/EventProcessingModule.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2022. Axon Framework
+ * Copyright (c) 2010-2023. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,6 +65,7 @@
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -129,6 +130,7 @@
protected final Map<String, PooledStreamingProcessorConfiguration> psepConfigs = new HashMap<>();
protected final Map<String, DeadLetteringInvokerConfiguration> deadLetteringInvokerConfigs = new HashMap<>();
+ private final AtomicBoolean initialized = new AtomicBoolean(false);
private Configuration configuration;
private final Component<ListenerInvocationErrorHandler> defaultListenerInvocationErrorHandler = new Component<>(
@@ -209,7 +211,15 @@ public void initialize(Configuration configuration) {
* processors have already been initialized, this method does nothing.
*/
private void initializeProcessors() {
- if (eventProcessors.isEmpty()) {
+ if (initialized.get()) {
+ return;
+ }
+
+ synchronized (initialized) {
+ if (initialized.get()) {
+ return;
+ }
+
instanceSelectors.sort(comparing(InstanceProcessingGroupSelector::getPriority).reversed());
Map<String, List<Function<Configuration, EventHandlerInvoker>>> handlerInvokers = new HashMap<>();
@@ -217,12 +227,14 @@ private void initializeProcessors() {
registerSagaManagers(handlerInvokers);
handlerInvokers.forEach((processorName, invokers) -> {
- Component<EventProcessor> eventProcessorComponent =
- new Component<>(configuration, processorName, c -> buildEventProcessor(invokers, processorName));
+ Component<EventProcessor> eventProcessorComponent = new Component<>(
+ configuration, processorName, c -> buildEventProcessor(invokers, processorName)
+ );
eventProcessors.put(processorName, eventProcessorComponent);
});
eventProcessors.values().forEach(Component::get);
+ initialized.set(true);
}
}
| ['config/src/main/java/org/axonframework/config/EventProcessingModule.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 5,365,156 | 1,045,642 | 127,217 | 970 | 878 | 157 | 20 | 1 | 1,741 | 242 | 333 | 21 | 1 | 0 | 2023-06-16T11:23:16 | 3,085 | Java | {'Java': 10919624} | Apache License 2.0 |
444 | jabref/jabref/6511/6507 | jabref | jabref | https://github.com/JabRef/jabref/issues/6507 | https://github.com/JabRef/jabref/pull/6511 | https://github.com/JabRef/jabref/pull/6511 | 1 | fixes | InvalidPathException after right-click on entry with an eprint via arXiv fetcher | JabRef version JabRef 5.1--2020-05-21--950d9c0 on Windows 10
- [X] **Mandatory**: I have tested the latest development version from http://builds.jabref.org/master/ and the problem persists
<!-- Add a clear and concise description of what the bug is. -->
Steps to reproduce the behavior:
1. Go to the web search pane
2. Enter search keywords in the text field
3. Import entry
4. Right-click on the entry in the main table
<!-- If applicable, add excerpt of the bibliography file, screenshot, and excerpt of log (available in the error console) -->
<details>
<summary>Log File</summary>
```
java.nio.file.InvalidPathException: Illegal char <:> at index 4: http://arxiv.org/pdf/1911.01235v1
at java.base/sun.nio.fs.WindowsPathParser.normalize(Unknown Source)
at java.base/sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at java.base/sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at java.base/sun.nio.fs.WindowsPath.parse(Unknown Source)
at java.base/sun.nio.fs.WindowsFileSystem.getPath(Unknown Source)
at java.base/java.nio.file.Path.resolve(Unknown Source)
at org.jabref/org.jabref.model.util.FileHelper.find(Unknown Source)
at org.jabref/org.jabref.model.util.FileHelper.lambda$find$0(Unknown Source)
at java.base/java.util.stream.ReferencePipeline$7$1.accept(Unknown Source)
at java.base/java.util.ArrayList$ArrayListSpliterator.tryAdvance(Unknown Source)
at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.base/java.util.stream.ReferencePipeline.findFirst(Unknown Source)
at org.jabref/org.jabref.model.util.FileHelper.find(Unknown Source)
at org.jabref/org.jabref.model.util.FileHelper.find(Unknown Source)
at org.jabref/org.jabref.gui.actions.ActionHelper.lambda$isFilePresentForSelectedEntry$3(Unknown Source)
at java.base/java.util.Optional.map(Unknown Source)
at com.tobiasdiez.easybind/com.tobiasdiez.easybind.optional.PreboundOptionalBinding$1.computeValue(Unknown Source)
at com.tobiasdiez.easybind/com.tobiasdiez.easybind.optional.PreboundOptionalBinding$1.computeValue(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.ObjectBinding.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.ObjectExpression.getValue(Unknown Source)
at com.tobiasdiez.easybind/com.tobiasdiez.easybind.optional.PreboundOptionalBinding$3.computeValue(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.ObjectBinding.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.ObjectExpression.getValue(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanExpression$2.computeValue(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanBinding.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.Bindings$BooleanAndBinding.computeValue(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanBinding.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.ReadOnlyBooleanWrapper$ReadOnlyPropertyImpl.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.Bindings$52.computeValue(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanBinding.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase.get(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanExpression.getValue(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanExpression.getValue(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase.markInvalid(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase$Listener.invalidated(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase.markInvalid(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase$Listener.invalidated(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanBinding.invalidate(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.BindingHelperObserver.invalidated(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.ReadOnlyBooleanPropertyBase.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.ReadOnlyBooleanWrapper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase.markInvalid(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.property.BooleanPropertyBase$Listener.invalidated(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanBinding.invalidate(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.Bindings$ShortCircuitAndInvalidator.invalidated(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.BooleanBinding.invalidate(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.BindingHelperObserver.invalidated(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.ObjectBinding.invalidate(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.BindingHelperObserver.invalidated(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.beans.binding.ObjectBinding.invalidate(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.binding.BindingHelperObserver.invalidated(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ObservableListBase.fireChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ListChangeBuilder.commit(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ListChangeBuilder.endChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ObservableListBase.endChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ModifiableObservableListBase.setAll(Unknown Source)
at org.jabref/org.jabref.gui.StateManager.setSelectedEntries(Unknown Source)
at org.jabref/org.jabref.gui.BasePanel.lambda$createMainTable$1(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ObservableListBase.fireChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ListChangeBuilder.commit(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ListChangeBuilder.endChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ObservableListBase.endChange(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.scene.control.SelectedItemsReadOnlyObservableList.lambda$new$1(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ObservableListBase.fireChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ListChangeBuilder.commit(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ListChangeBuilder.endChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.collections.ObservableListBase.endChange(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList._endChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.scene.control.MultipleSelectionModelBase$SelectedIndicesList._endChange(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.scene.control.ControlUtils.updateSelectedIndices(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.scene.control.TableView$TableViewArrayListSelectionModel.fireCustomSelectedCellsListChangeEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.scene.control.TableView$TableViewArrayListSelectionModel.clearAndSelect(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.scene.control.TableView$TableViewSelectionModel.clearAndSelect(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.scene.control.behavior.TableCellBehaviorBase.simpleSelect(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.scene.control.behavior.TableCellBehaviorBase.doSelect(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.scene.control.inputmap.InputMap.handle(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.event.Event.fireEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.scene.Scene$MouseHandler.process(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.scene.Scene.processMouseEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.glass.ui.View.notifyMouse(Unknown Source)
at org.jabref.merged.module@5.1.423/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at org.jabref.merged.module@5.1.423/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
```
</details>
| ef2a31c91b052693550b29254aab6a94471b637e | 77489409d92abfeb4bbbb360172e12fb6f294b63 | https://github.com/jabref/jabref/compare/ef2a31c91b052693550b29254aab6a94471b637e...77489409d92abfeb4bbbb360172e12fb6f294b63 | diff --git a/src/main/java/org/jabref/gui/actions/ActionHelper.java b/src/main/java/org/jabref/gui/actions/ActionHelper.java
index bbb22b6022..dfad438f8c 100644
--- a/src/main/java/org/jabref/gui/actions/ActionHelper.java
+++ b/src/main/java/org/jabref/gui/actions/ActionHelper.java
@@ -55,6 +55,10 @@ public class ActionHelper {
List<LinkedFile> files = entry.getFiles();
if ((entry.getFiles().size() > 0) && stateManager.getActiveDatabase().isPresent()) {
+ if (files.get(0).isOnlineLink()) {
+ return true;
+ }
+
Optional<Path> filename = FileHelper.find(
stateManager.getActiveDatabase().get(),
files.get(0).getLink(), | ['src/main/java/org/jabref/gui/actions/ActionHelper.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,751,169 | 961,582 | 122,357 | 1,144 | 106 | 19 | 4 | 1 | 16,876 | 558 | 4,045 | 175 | 2 | 1 | 2020-05-22T15:08:27 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
452 | jabref/jabref/5048/5043 | jabref | jabref | https://github.com/JabRef/jabref/issues/5043 | https://github.com/JabRef/jabref/pull/5048 | https://github.com/JabRef/jabref/pull/5048 | 1 | fixes | Handling of umlaut while copy and paste of entries | Using `JabRef 5.0-dev--snapshot--2019-05-30--master--ef2ebe165` on Windows 10.
The bib-file is UTF-8 encoded (double checked! with extern editor) and in biblatex style. There are entries with umlauts in the abstract, title, etc.
- On entry has well formated umlauts and they are correctly displayed in JabRef editor and preview window.
- Copy such an entry (Ctrl+C)
- Paste it (Ctrl+V)
- All Umlauts are converted into `�`
Example of such a result (copied from the bib-file)
```
@Misc{Nordhausen2019c,
author = {Nordhausen, Thomas and Hirt, Julian},
title = {One size does not fit all-systematische Literaturrecherche in Fachdatenbanken. Schritt 6: Entwicklung des Suchstrings},
date = {2019},
language = {ger},
doi = {10.6094/KlinPfleg.5.21},
abstract = {In diesem Schritt werden die identifizierten Synonyme und Schlagw�rter entsprechend der Suchkomponenten mithilfe von Booleschen Operatoren miteinander verkn�pft. Diese Verkn�pfung wird als Suchstring bezeichnet und muss f�r jede Datenbank gesondert vorgenommen werden. Bei der Entwicklung ist auch der Einsatz von Wortabstandsoperatoren und/oder Platzhaltern f�r eines oder mehrere Zeichen zu ber�cksichtigen. Neben der Verwendung von Schlagw�rtern stellen die Suchbefehle f�r Suchbegriffe und Synonyme eine M�glichkeit dar, um die Suche einzugrenzen. Bei der Verwendung von Suchbefehlen ist deren Schreibweise (Syntax) in der jeweiligen Fachdatenbank zu beachten.},
file = {:1015-2668-1-PB.pdf:PDF},
groups = {Review, 2019-06},
keywords = {lesen, hirt},
publisher = {Albert-Ludwigs-Universit�t Freiburg},
year = {2019},
}
``` | eb42850f7853aff1f98459e533bc254217a2fa8d | 63e490ca7d11e68b0735f1360351e81d1d444820 | https://github.com/jabref/jabref/compare/eb42850f7853aff1f98459e533bc254217a2fa8d...63e490ca7d11e68b0735f1360351e81d1d444820 | diff --git a/src/main/java/org/jabref/gui/ClipBoardManager.java b/src/main/java/org/jabref/gui/ClipBoardManager.java
index c7c6ce2b9d..26bc331fbb 100644
--- a/src/main/java/org/jabref/gui/ClipBoardManager.java
+++ b/src/main/java/org/jabref/gui/ClipBoardManager.java
@@ -1,6 +1,8 @@
package org.jabref.gui;
+import java.io.ByteArrayInputStream;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@@ -28,13 +30,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClipBoardManager {
-
public static final DataFormat XML = new DataFormat("application/xml");
-
+
private static final Logger LOGGER = LoggerFactory.getLogger(ClipBoardManager.class);
private final Clipboard clipboard;
-
private final ImportFormatReader importFormatReader;
public ClipBoardManager() {
@@ -63,9 +63,8 @@ public class ClipBoardManager {
String result = clipboard.getString();
if (result == null) {
return "";
- } else {
- return result;
}
+ return result;
}
public void setHtmlContent(String html) {
@@ -89,40 +88,55 @@ public class ClipBoardManager {
clipboard.setContent(content);
}
- public List<BibEntry> extractEntries() {
+ public List<BibEntry> extractData() {
Object entries = clipboard.getContent(DragAndDropDataFormats.ENTRIES);
+ if (entries == null) {
+ return handleStringData(clipboard.getString());
+ }
+ return handleBibTeXData((String) entries);
+ }
+
+ private List<BibEntry> handleBibTeXData(String entries) {
BibtexParser parser = new BibtexParser(Globals.prefs.getImportFormatPreferences(), Globals.getFileUpdateMonitor());
- if (entries != null) {
- // We have determined that the clipboard data is a set of entries (serialized as a string).
- try {
- return parser.parseEntries((String) entries);
- } catch (ParseException ex) {
- LOGGER.error("Could not paste", ex);
- }
- } else {
- String data = clipboard.getString();
- if (data != null) {
- try {
- // fetch from doi
- Optional<DOI> doi = DOI.parse(data);
- if (doi.isPresent()) {
- LOGGER.info("Found DOI in clipboard");
- Optional<BibEntry> entry = new DoiFetcher(Globals.prefs.getImportFormatPreferences()).performSearchById(doi.get().getDOI());
- return OptionalUtil.toList(entry);
- } else {
- try {
- UnknownFormatImport unknownFormatImport = importFormatReader.importUnknownFormat(data);
- return unknownFormatImport.parserResult.getDatabase().getEntries();
- } catch (ImportException e) {
- // import failed and result will be empty
- }
- }
- } catch (FetcherException ex) {
- LOGGER.error("Error while fetching", ex);
- }
- }
+ try {
+ return parser.parseEntries(new ByteArrayInputStream(entries.getBytes(StandardCharsets.UTF_8)));
+ } catch (ParseException ex) {
+ LOGGER.error("Could not paste", ex);
+ return Collections.emptyList();
+ }
+ }
+
+ private List<BibEntry> handleStringData(String data) {
+ if (data == null || data.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ Optional<DOI> doi = DOI.parse(data);
+ if (doi.isPresent()) {
+ return fetchByDOI(doi.get());
+ }
+
+ return tryImportFormats(data);
+ }
+
+ private List<BibEntry> tryImportFormats(String data) {
+ try {
+ UnknownFormatImport unknownFormatImport = importFormatReader.importUnknownFormat(data);
+ return unknownFormatImport.parserResult.getDatabase().getEntries();
+ } catch (ImportException ignored) {
+ return Collections.emptyList();
+ }
+ }
+
+ private List<BibEntry> fetchByDOI(DOI doi) {
+ LOGGER.info("Found DOI in clipboard");
+ try {
+ Optional<BibEntry> entry = new DoiFetcher(Globals.prefs.getImportFormatPreferences()).performSearchById(doi.getDOI());
+ return OptionalUtil.toList(entry);
+ } catch (FetcherException ex) {
+ LOGGER.error("Error while fetching", ex);
+ return Collections.emptyList();
}
- return Collections.emptyList();
}
}
diff --git a/src/main/java/org/jabref/gui/maintable/MainTable.java b/src/main/java/org/jabref/gui/maintable/MainTable.java
index 892116fb33..6232d33a96 100644
--- a/src/main/java/org/jabref/gui/maintable/MainTable.java
+++ b/src/main/java/org/jabref/gui/maintable/MainTable.java
@@ -209,7 +209,7 @@ public class MainTable extends TableView<BibEntryTableViewModel> {
public void paste() {
// Find entries in clipboard
- List<BibEntry> entriesToAdd = Globals.clipboardManager.extractEntries();
+ List<BibEntry> entriesToAdd = Globals.clipboardManager.extractData();
if (!entriesToAdd.isEmpty()) {
// Add new entries | ['src/main/java/org/jabref/gui/ClipBoardManager.java', 'src/main/java/org/jabref/gui/maintable/MainTable.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 4,534,690 | 922,051 | 119,343 | 1,073 | 3,574 | 638 | 88 | 2 | 1,665 | 214 | 494 | 25 | 0 | 1 | 2019-06-12T00:06:10 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
451 | jabref/jabref/5224/5220 | jabref | jabref | https://github.com/JabRef/jabref/issues/5220 | https://github.com/JabRef/jabref/pull/5224 | https://github.com/JabRef/jabref/pull/5224 | 1 | fixes | Exception when adding field formatter in cleanup entries dialog | <!--
Note: Please use the GitHub issue tracker only for bug reports.
Feature requests, questions and general feedback is now handled at http://discourse.jabref.org.
Thanks!
-->
JabRef version **JabRef 5.0-dev (8f463e4)** on **Windows 10 10.0 amd64, Java 1.8.0_221**
<!-- IMPORTANT NOTE ->
<!--
Please always test if the bug is still reproducible in the latest development version.
We are constantly improving JabRef and some bugs may already be fixed.
You can download the development version at: http://builds.jabref.org/master/
Please make a backup of your library before you try out this version.
If you already use a development version, ensure that you use the latest one.
-->
- [x] I have tested the latest development version from http://builds.jabref.org/master/ and the problem persists
<!-- Add a clear and concise description of what the bug is. -->
Steps to reproduce the behavior:
1. Select an entry
2. Open *Quality->Cleanup entries*
3. Try to add new field formatter by selecting field and field formatter via combo boxes
This results with uncaught exception.
I checked that the bug was introduced in 4b39b78. Before that commit the bug was not present.
<!-- If applicable, add excerpt of the bibliography file, screenshot, and excerpt of log (available in the error console) -->
<details>
<summary>Log File</summary>
```
22:41:59.563 [JavaFX Application Thread] ERROR org.jabref.FallbackExceptionHandler - Uncaught exception occurred in Thread[JavaFX Application Thread,5,main]
java.lang.ClassCastException: java.lang.String cannot be cast to org.jabref.model.entry.field.Field
at org.jabref.gui.cleanup.FieldFormatterCleanupsPanel.getFieldFormatterCleanup(FieldFormatterCleanupsPanel.java:220) ~[main/:?]
at org.jabref.gui.cleanup.FieldFormatterCleanupsPanel.updateDescription(FieldFormatterCleanupsPanel.java:147) ~[main/:?]
at org.jabref.gui.cleanup.FieldFormatterCleanupsPanel.lambda$getSelectorPanel$276(FieldFormatterCleanupsPanel.java:176) ~[main/:?]
at org.fxmisc.easybind.EasyBind.lambda$subscribe$12(EasyBind.java:263) ~[easybind-1.0.3.jar:?]
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:361) ~[jfxrt.jar:?]
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81) ~[jfxrt.jar:?]
at javafx.beans.property.ObjectPropertyBase.fireValueChangedEvent(ObjectPropertyBase.java:105) ~[jfxrt.jar:?]
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112) ~[jfxrt.jar:?]
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146) ~[jfxrt.jar:?]
at javafx.scene.control.ComboBoxBase.setValue(ComboBoxBase.java:150) ~[jfxrt.jar:?]
at javafx.scene.control.ComboBox.updateValue(ComboBox.java:463) ~[jfxrt.jar:?]
at javafx.scene.control.ComboBox.access$200(ComboBox.java:192) ~[jfxrt.jar:?]
at javafx.scene.control.ComboBox$3.changed(ComboBox.java:446) ~[jfxrt.jar:?]
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:361) ~[jfxrt.jar:?]
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81) ~[jfxrt.jar:?]
at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74) ~[jfxrt.jar:?]
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102) ~[jfxrt.jar:?]
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112) ~[jfxrt.jar:?]
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146) ~[jfxrt.jar:?]
at javafx.scene.control.SelectionModel.setSelectedItem(SelectionModel.java:102) ~[jfxrt.jar:?]
at javafx.scene.control.ComboBox$ComboBoxSelectionModel.lambda$new$0(ComboBox.java:494) ~[jfxrt.jar:?]
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137) ~[jfxrt.jar:?]
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81) ~[jfxrt.jar:?]
at javafx.beans.property.ReadOnlyIntegerPropertyBase.fireValueChangedEvent(ReadOnlyIntegerPropertyBase.java:72) ~[jfxrt.jar:?]
at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:102) ~[jfxrt.jar:?]
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:113) ~[jfxrt.jar:?]
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:147) ~[jfxrt.jar:?]
at javafx.scene.control.SelectionModel.setSelectedIndex(SelectionModel.java:68) ~[jfxrt.jar:?]
at javafx.scene.control.SingleSelectionModel.updateSelectedIndex(SingleSelectionModel.java:215) ~[jfxrt.jar:?]
at javafx.scene.control.SingleSelectionModel.select(SingleSelectionModel.java:149) ~[jfxrt.jar:?]
at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.lambda$createListView$1(ComboBoxListViewSkin.java:484) ~[jfxrt.jar:?]
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:349) ~[jfxrt.jar:?]
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81) ~[jfxrt.jar:?]
at javafx.beans.property.ReadOnlyIntegerPropertyBase.fireValueChangedEvent(ReadOnlyIntegerPropertyBase.java:72) ~[jfxrt.jar:?]
at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:102) ~[jfxrt.jar:?]
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:113) ~[jfxrt.jar:?]
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:147) ~[jfxrt.jar:?]
at javafx.scene.control.SelectionModel.setSelectedIndex(SelectionModel.java:68) ~[jfxrt.jar:?]
at javafx.scene.control.MultipleSelectionModelBase.select(MultipleSelectionModelBase.java:404) ~[jfxrt.jar:?]
at javafx.scene.control.MultipleSelectionModelBase.clearAndSelect(MultipleSelectionModelBase.java:356) ~[jfxrt.jar:?]
at javafx.scene.control.ListView$ListViewBitSetSelectionModel.clearAndSelect(ListView.java:1403) ~[jfxrt.jar:?]
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.simpleSelect(CellBehaviorBase.java:256) ~[jfxrt.jar:?]
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.doSelect(CellBehaviorBase.java:220) ~[jfxrt.jar:?]
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(CellBehaviorBase.java:150) ~[jfxrt.jar:?]
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:95) ~[jfxrt.jar:?]
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89) ~[jfxrt.jar:?]
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) ~[jfxrt.jar:?]
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) ~[jfxrt.jar:?]
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) ~[jfxrt.jar:?]
at javafx.event.Event.fireEvent(Event.java:198) ~[jfxrt.jar:?]
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757) ~[jfxrt.jar:?]
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) ~[jfxrt.jar:?]
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) ~[jfxrt.jar:?]
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) ~[jfxrt.jar:?]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_221]
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431) ~[jfxrt.jar:?]
at com.sun.glass.ui.View.handleMouseEvent(View.java:555) ~[jfxrt.jar:?]
at com.sun.glass.ui.View.notifyMouse(View.java:937) ~[jfxrt.jar:?]
at com.sun.glass.ui.win.WinApplication._enterNestedEventLoopImpl(Native Method) ~[jfxrt.jar:?]
at com.sun.glass.ui.win.WinApplication._enterNestedEventLoop(WinApplication.java:204) ~[jfxrt.jar:?]
at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511) ~[jfxrt.jar:?]
at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:633) ~[jfxrt.jar:?]
at javafx.stage.Stage.showAndWait(Stage.java:474) ~[jfxrt.jar:?]
at javafx.scene.control.HeavyweightDialog.showAndWait(HeavyweightDialog.java:162) ~[jfxrt.jar:?]
at javafx.scene.control.Dialog.showAndWait(Dialog.java:341) ~[jfxrt.jar:?]
at org.jabref.gui.cleanup.CleanupAction.action(CleanupAction.java:46) ~[main/:?]
at org.jabref.gui.BasePanel.runCommand(BasePanel.java:609) ~[main/:?]
at org.jabref.gui.actions.OldDatabaseCommandWrapper.execute(OldDatabaseCommandWrapper.java:40) ~[main/:?]
at org.jabref.gui.actions.JabRefAction.lambda$new$110(JabRefAction.java:29) ~[main/:?]
at org.controlsfx.control.action.Action.handle(Action.java:419) ~[controlsfx-8.40.16-SNAPSHOT.jar:8.40.16.SNAPSHOT]
at org.controlsfx.control.action.Action.handle(Action.java:64) ~[controlsfx-8.40.16-SNAPSHOT.jar:8.40.16.SNAPSHOT]
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) ~[jfxrt.jar:?]
at javafx.event.Event.fireEvent(Event.java:198) ~[jfxrt.jar:?]
at javafx.scene.control.MenuItem.fire(MenuItem.java:462) ~[jfxrt.jar:?]
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405) ~[jfxrt.jar:?]
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$6(ContextMenuContent.java:1358) ~[jfxrt.jar:?]
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) ~[jfxrt.jar:?]
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) ~[jfxrt.jar:?]
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) ~[jfxrt.jar:?]
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54) ~[jfxrt.jar:?]
at javafx.event.Event.fireEvent(Event.java:198) ~[jfxrt.jar:?]
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757) ~[jfxrt.jar:?]
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) ~[jfxrt.jar:?]
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) ~[jfxrt.jar:?]
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) ~[jfxrt.jar:?]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_221]
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410) ~[jfxrt.jar:?]
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431) ~[jfxrt.jar:?]
at com.sun.glass.ui.View.handleMouseEvent(View.java:555) ~[jfxrt.jar:?]
at com.sun.glass.ui.View.notifyMouse(View.java:937) ~[jfxrt.jar:?]
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) ~[jfxrt.jar:?]
at com.sun.glass.ui.win.WinApplication.lambda$null$3(WinApplication.java:177) ~[jfxrt.jar:?]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_221]
```
</details>
| 46565336109deb8e0e3fc96335f20838a1bb9c24 | a0af540d7d0c6bbe8d855da157febce18a019642 | https://github.com/jabref/jabref/compare/46565336109deb8e0e3fc96335f20838a1bb9c24...a0af540d7d0c6bbe8d855da157febce18a019642 | diff --git a/src/main/java/org/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java b/src/main/java/org/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java
index 12cd47ccf9..23917990eb 100644
--- a/src/main/java/org/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java
+++ b/src/main/java/org/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java
@@ -4,6 +4,8 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
@@ -40,18 +42,17 @@ public class FieldFormatterCleanupsPanel extends GridPane {
private static final String DESCRIPTION = Localization.lang("Description") + ": ";
private final CheckBox cleanupEnabled;
+ private final FieldFormatterCleanups defaultFormatters;
+ private final List<Formatter> availableFormatters;
private FieldFormatterCleanups fieldFormatterCleanups;
private ListView<FieldFormatterCleanup> actionsList;
private ComboBox<Formatter> formattersCombobox;
- private ComboBox<Field> selectFieldCombobox;
+ private ComboBox<String> selectFieldCombobox;
private Button addButton;
private Label descriptionAreaText;
private Button removeButton;
private Button resetButton;
private Button recommendButton;
-
- private final FieldFormatterCleanups defaultFormatters;
- private final List<Formatter> availableFormatters;
private ObservableList<FieldFormatterCleanup> actions;
public FieldFormatterCleanupsPanel(String description, FieldFormatterCleanups defaultFormatters) {
@@ -104,7 +105,7 @@ public class FieldFormatterCleanupsPanel extends GridPane {
actionsList = new ListView<>(actions);
actionsList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
new ViewModelListCellFactory<FieldFormatterCleanup>()
- .withText(action -> action.getField() + ": " + action.getFormatter().getName())
+ .withText(action -> action.getField().getDisplayName() + ": " + action.getFormatter().getName())
.withStringTooltip(action -> action.getFormatter().getDescription())
.install(actionsList);
add(actionsList, 1, 1, 3, 1);
@@ -164,7 +165,8 @@ public class FieldFormatterCleanupsPanel extends GridPane {
GridPane builder = new GridPane();
Set<Field> fields = FieldFactory.getCommonFields();
fields.add(InternalField.KEY_FIELD);
- selectFieldCombobox = new ComboBox<>(FXCollections.observableArrayList(fields));
+ Set<String> fieldsString = fields.stream().map(Field::getDisplayName).sorted().collect(Collectors.toCollection(TreeSet::new));
+ selectFieldCombobox = new ComboBox<>(FXCollections.observableArrayList(fieldsString));
selectFieldCombobox.setEditable(true);
builder.add(selectFieldCombobox, 1, 1);
@@ -217,7 +219,7 @@ public class FieldFormatterCleanupsPanel extends GridPane {
private FieldFormatterCleanup getFieldFormatterCleanup() {
Formatter selectedFormatter = formattersCombobox.getValue();
- Field field = selectFieldCombobox.getValue();
+ Field field = FieldFactory.parseField(selectFieldCombobox.getSelectionModel().getSelectedItem());
return new FieldFormatterCleanup(field, selectedFormatter);
}
@@ -242,5 +244,4 @@ public class FieldFormatterCleanupsPanel extends GridPane {
setStatus(cleanupEnabled.isSelected());
}
}
-
} | ['src/main/java/org/jabref/gui/cleanup/FieldFormatterCleanupsPanel.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,553,334 | 924,090 | 118,667 | 1,098 | 1,097 | 202 | 17 | 1 | 15,075 | 624 | 3,847 | 170 | 3 | 1 | 2019-08-24T23:34:52 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
445 | jabref/jabref/6402/6430 | jabref | jabref | https://github.com/JabRef/jabref/issues/6430 | https://github.com/JabRef/jabref/pull/6402 | https://github.com/JabRef/jabref/pull/6402 | 2 | fixes | Menu View on empty file => Uncaught exception | JabRef 5.1--2020-05-04--b5599c9
Linux 4.9.0-12-amd64 amd64
Java 14.0.1
- [X] I have tested the latest development version from http://builds.jabref.org/master/ and the problem persists
When clicking on the menu item "View" with an empty library on focus, a message "Uncaught exception" is displayed.
Steps to reproduce the behavior:
1. Create a new BibTeX library
2. Click on menu View
A window pops-up, displaying the message "Uncaught exception occurred in Thread[JavaFX Application Thread,5,main]
Afterwards, To be able to display the menu View on another file, JabRef needs to be re-opened.
Note: All the other menus are working as expected.
<details>
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Unknown Source)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Unknown Source)
at java.base/jdk.internal.util.Preconditions.checkIndex(Unknown Source)
at java.base/java.util.Objects.checkIndex(Unknown Source)
at java.base/java.util.ArrayList.get(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ObservableListWrapper.get(Unknown Source)
at org.jabref/org.jabref.gui.actions.ActionHelper.isFilePresentForSelectedEntry(Unknown Source)
at org.jabref/org.jabref.gui.documentviewer.ShowDocumentViewerAction.<init>(Unknown Source)
at org.jabref/org.jabref.gui.JabRefFrame.lambda$createMenu$13(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at org.jabref.merged.module/javafx.event.Event.fireEvent(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.Menu.setShowing(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.Menu.show(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.skin.MenuBarSkin.showMenu(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.skin.MenuBarSkin.showMenu(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.skin.MenuBarSkin.lambda$rebuildUI$27(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at org.jabref.merged.module/javafx.event.Event.fireEvent(Unknown Source)
at org.jabref.merged.module/javafx.scene.Scene$MouseHandler.process(Unknown Source)
at org.jabref.merged.module/javafx.scene.Scene.processMouseEvent(Unknown Source)
at org.jabref.merged.module/javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at org.jabref.merged.module/com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at org.jabref.merged.module/com.sun.glass.ui.View.notifyMouse(Unknown Source)
at org.jabref.merged.module/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at org.jabref.merged.module/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
</details>
| e0baa6d2a5130097c33ecfe67df548075d850ca8 | a3eff0c49c0c63c626f2a6a324b4459000fc7fca | https://github.com/jabref/jabref/compare/e0baa6d2a5130097c33ecfe67df548075d850ca8...a3eff0c49c0c63c626f2a6a324b4459000fc7fca | diff --git a/src/main/java/org/jabref/gui/actions/ActionHelper.java b/src/main/java/org/jabref/gui/actions/ActionHelper.java
index 494c64f2fc..b6b0415f59 100644
--- a/src/main/java/org/jabref/gui/actions/ActionHelper.java
+++ b/src/main/java/org/jabref/gui/actions/ActionHelper.java
@@ -13,14 +13,15 @@ import org.jabref.gui.StateManager;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.entry.field.Field;
-import org.jabref.model.entry.field.StandardField;
import org.jabref.model.util.FileHelper;
import org.jabref.preferences.PreferencesService;
import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.monadic.MonadicBinding;
+import org.fxmisc.easybind.monadic.MonadicObservableValue;
public class ActionHelper {
+
public static BooleanExpression needsDatabase(StateManager stateManager) {
return stateManager.activeDatabaseProperty().isPresent();
}
@@ -30,9 +31,8 @@ public class ActionHelper {
}
public static BooleanExpression needsEntriesSelected(int numberOfEntries, StateManager stateManager) {
- return Bindings.createBooleanBinding(
- () -> stateManager.getSelectedEntries().size() == numberOfEntries,
- stateManager.getSelectedEntries());
+ return Bindings.createBooleanBinding(() -> stateManager.getSelectedEntries().size() == numberOfEntries,
+ stateManager.getSelectedEntries());
}
public static BooleanExpression isFieldSetForSelectedEntry(Field field, StateManager stateManager) {
@@ -50,18 +50,23 @@ public class ActionHelper {
}
public static BooleanExpression isFilePresentForSelectedEntry(StateManager stateManager, PreferencesService preferencesService) {
- return Bindings.createBooleanBinding(() -> {
- List<LinkedFile> files = stateManager.getSelectedEntries().get(0).getFiles();
- if ((files.size() > 0) && stateManager.getActiveDatabase().isPresent()) {
- Optional<Path> filename = FileHelper.find(
- stateManager.getActiveDatabase().get(),
- files.get(0).getLink(),
- preferencesService.getFilePreferences());
- return filename.isPresent();
- } else {
- return false;
- }
- }, stateManager.getSelectedEntries(),
- stateManager.getSelectedEntries().get(0).getFieldBinding(StandardField.FILE));
+
+ ObservableList<BibEntry> selectedEntries = stateManager.getSelectedEntries();
+ MonadicObservableValue<Boolean> fileIsPresent = EasyBind.monadic(Bindings.valueAt(selectedEntries, 0)).map(entry -> {
+ List<LinkedFile> files = entry.getFiles();
+
+ if ((entry.getFiles().size() > 0) && stateManager.getActiveDatabase().isPresent()) {
+ Optional<Path> filename = FileHelper.find(
+ stateManager.getActiveDatabase().get(),
+ files.get(0).getLink(),
+ preferencesService.getFilePreferences());
+ return filename.isPresent();
+ } else {
+ return false;
+ }
+
+ }).orElse(false);
+
+ return BooleanExpression.booleanExpression(fileIsPresent);
}
}
diff --git a/src/main/java/org/jabref/gui/documentviewer/ShowDocumentViewerAction.java b/src/main/java/org/jabref/gui/documentviewer/ShowDocumentViewerAction.java
index 444bf3840e..a9a94d52b1 100644
--- a/src/main/java/org/jabref/gui/documentviewer/ShowDocumentViewerAction.java
+++ b/src/main/java/org/jabref/gui/documentviewer/ShowDocumentViewerAction.java
@@ -5,10 +5,12 @@ import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.preferences.PreferencesService;
+import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected;
+
public class ShowDocumentViewerAction extends SimpleCommand {
public ShowDocumentViewerAction(StateManager stateManager, PreferencesService preferences) {
- this.executable.bind(ActionHelper.isFilePresentForSelectedEntry(stateManager, preferences));
+ this.executable.bind(needsEntriesSelected(stateManager).and(ActionHelper.isFilePresentForSelectedEntry(stateManager, preferences)));
}
@Override | ['src/main/java/org/jabref/gui/documentviewer/ShowDocumentViewerAction.java', 'src/main/java/org/jabref/gui/actions/ActionHelper.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 4,728,833 | 956,620 | 121,684 | 1,140 | 2,556 | 401 | 43 | 2 | 5,778 | 266 | 1,284 | 75 | 1 | 0 | 2020-05-03T14:13:03 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
447 | jabref/jabref/5497/5496 | jabref | jabref | https://github.com/JabRef/jabref/issues/5496 | https://github.com/JabRef/jabref/pull/5497 | https://github.com/JabRef/jabref/pull/5497 | 1 | fixes | Blank input editor - Uncaught exception occured in Thread[JavaFX Application Thread,5,main] | <!--
Note: Please use the GitHub issue tracker only for bug reports.
Feature requests, questions and general feedback is now handled at http://discourse.jabref.org.
Thanks!
-->
Ubuntu 18.04 with Gnome desktop:
Installed from .deb file downloaded from https://builds.jabref.org/master/jabref_5.0.0-1_amd64.deb
JabRef version:
JabRef 5.0.0-dev--2019-10-21----0f0dce621
Linux 5.0.0-32-generic amd64
Java 12.0.2
Steps to reproduce the behavior:
1. Open JabRef with .bib file
2. Exception is thrown
3. Entry editor is blank (Just a white field. I'm in dark mode)
4. Exception is thrown with statement:
```Uncaught exception occured in Thread[JavaFX Application Thread,5,main]``` and
```Invalid stylesheet URL```
5. Clicking other tabs such as: Optional Fields, Deprecated Fields etc. results in additional exceptions thrown with the ```invalid stylesheet URL``` error.
Here's the Log summary:
<details>
<summary>Log File</summary>
```
java.lang.IllegalArgumentException: Invalid stylesheet URL
at org.jabref.merged.module/javafx.scene.web.WebEngine$2.invalidated(Unknown Source)
at org.jabref.merged.module/javafx.beans.property.StringPropertyBase.markInvalid(Unknown Source)
at org.jabref.merged.module/javafx.beans.property.StringPropertyBase.set(Unknown Source)
at org.jabref.merged.module/javafx.beans.property.StringPropertyBase.set(Unknown Source)
at org.jabref.merged.module/javafx.scene.web.WebEngine.setUserStyleSheetLocation(Unknown Source)
at org.jabref/org.jabref.gui.preview.PreviewViewer.setTheme(Unknown Source)
at org.jabref/org.jabref.gui.preview.PreviewPanel.<init>(Unknown Source)
at org.jabref/org.jabref.gui.entryeditor.FieldsEditorTab.initPanel(Unknown Source)
at org.jabref/org.jabref.gui.entryeditor.FieldsEditorTab.bindToEntry(Unknown Source)
at org.jabref/org.jabref.gui.entryeditor.EntryEditorTab.notifyAboutFocus(Unknown Source)
at org.jabref/org.jabref.gui.entryeditor.EntryEditor.lambda$new$0(Unknown Source)
at org.jabref.merged.module/org.fxmisc.easybind.EasyBind.lambda$subscribe$12(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/javafx.beans.property.ObjectPropertyBase.markInvalid(Unknown Source)
at org.jabref.merged.module/javafx.beans.property.ObjectPropertyBase.set(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.SelectionModel.setSelectedItem(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.TabPane$TabPaneSelectionModel.select(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.TabPane$TabPaneSelectionModel.select(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.TabPane$TabPaneSelectionModel.findNearestAvailableTab(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.TabPane$TabPaneSelectionModel.lambda$new$0(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.fireChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.commit(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.endChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.endChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ModifiableObservableListBase.add(Unknown Source)
at org.jabref/org.jabref.gui.entryeditor.EntryEditor.recalculateVisibleTabs(Unknown Source)
at org.jabref/org.jabref.gui.entryeditor.EntryEditor.setEntry(Unknown Source)
at org.jabref/org.jabref.gui.BasePanel.lambda$createMainTable$22(Unknown Source)
at java.base/java.util.Optional.ifPresent(Unknown Source)
at org.jabref/org.jabref.gui.BasePanel.lambda$createMainTable$23(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.fireChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.commit(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.endChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.endChange(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.scene.control.SelectedItemsReadOnlyObservableList.lambda$new$1(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.fireChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.commit(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.endChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.endChange(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList._endChange(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.MultipleSelectionModelBase$SelectedIndicesList._endChange(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.ControlUtils.updateSelectedIndices(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.TableView$TableViewArrayListSelectionModel.fireCustomSelectedCellsListChangeEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.fireChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.commit(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.endChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.endChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.transformation.SortedList.sourceChanged(Unknown Source)
at org.jabref.merged.module/javafx.collections.transformation.TransformationList.lambda$getListener$0(Unknown Source)
at org.jabref.merged.module/javafx.collections.WeakListChangeListener.onChanged(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.fireChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.commit(Unknown Source)
at org.jabref.merged.module/javafx.collections.ListChangeBuilder.endChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ObservableListBase.endChange(Unknown Source)
at org.jabref.merged.module/javafx.collections.ModifiableObservableListBase.add(Unknown Source)
at java.base/java.util.AbstractList.add(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.scene.control.SelectedCellsMap.add(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(Unknown Source)
at org.jabref.merged.module/javafx.scene.control.TableView$TableViewArrayListSelectionModel.selectFirst(Unknown Source)
at org.jabref/org.jabref.gui.maintable.MainTable.clearAndSelectFirst(Unknown Source)
at org.jabref/org.jabref.gui.BasePanel.clearAndSelectFirst(Unknown Source)
at org.jabref/org.jabref.gui.BasePanel.lambda$new$0(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at org.jabref.merged.module/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(Unknown Source)
at org.jabref.merged.module/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at org.jabref.merged.module/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at org.jabref.merged.module/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
```
</details>
| f86944aae2bd6d4457ac958516c0ae901790606b | b97f58fec2daeafeb33fef7dcdbc932a06271ca0 | https://github.com/jabref/jabref/compare/f86944aae2bd6d4457ac958516c0ae901790606b...b97f58fec2daeafeb33fef7dcdbc932a06271ca0 | diff --git a/src/main/java/org/jabref/gui/preview/PreviewViewer.java b/src/main/java/org/jabref/gui/preview/PreviewViewer.java
index 4e1201b92d..937a16b987 100644
--- a/src/main/java/org/jabref/gui/preview/PreviewViewer.java
+++ b/src/main/java/org/jabref/gui/preview/PreviewViewer.java
@@ -1,5 +1,7 @@
package org.jabref.gui.preview;
+import java.net.URL;
+import java.util.Base64;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
@@ -27,6 +29,7 @@ import org.jabref.logic.l10n.Localization;
import org.jabref.logic.search.SearchQuery;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
+import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -116,9 +119,14 @@ public class PreviewViewer extends ScrollPane implements InvalidationListener {
public void setTheme(String theme) {
if (theme.equals(ThemeLoader.DARK_CSS)) {
- previewView.getEngine().setUserStyleSheetLocation(JabRefFrame.class.getResource(ThemeLoader.DARK_CSS).toString());
+ // We need to load the css file manually, due to a bug in the jdk
+ // TODO: Remove this workaround as soon as https://github.com/openjdk/jfx/pull/22 is merged
+ URL url = JabRefFrame.class.getResource(ThemeLoader.DARK_CSS);
+ String dataUrl = "data:text/css;charset=utf-8;base64," +
+ Base64.getEncoder().encodeToString(StringUtil.getResourceFileAsString(url).getBytes());
+
+ previewView.getEngine().setUserStyleSheetLocation(dataUrl);
}
-
}
private void highlightSearchPattern() {
diff --git a/src/main/java/org/jabref/model/strings/StringUtil.java b/src/main/java/org/jabref/model/strings/StringUtil.java
index af38b5f012..0551821493 100644
--- a/src/main/java/org/jabref/model/strings/StringUtil.java
+++ b/src/main/java/org/jabref/model/strings/StringUtil.java
@@ -1,5 +1,12 @@
package org.jabref.model.strings;
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -9,6 +16,7 @@ import java.util.Optional;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import org.jabref.architecture.ApacheCommonsLang3Allowed;
@@ -721,4 +729,19 @@ public class StringUtil {
public static String substringBetween(String str, String open, String close) {
return StringUtils.substringBetween(str, open, close);
}
+
+ public static String getResourceFileAsString(URL resource) {
+ try {
+ URLConnection conn = resource.openConnection();
+ conn.connect();
+
+ try (InputStream inputStream = new BufferedInputStream(conn.getInputStream());
+ InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
+ BufferedReader reader = new BufferedReader(inputStreamReader)) {
+ return reader.lines().collect(Collectors.joining(System.lineSeparator()));
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/src/test/java/org/jabref/model/strings/StringUtilTest.java b/src/test/java/org/jabref/model/strings/StringUtilTest.java
index 383b97c1cc..5f9569eaa5 100644
--- a/src/test/java/org/jabref/model/strings/StringUtilTest.java
+++ b/src/test/java/org/jabref/model/strings/StringUtilTest.java
@@ -21,7 +21,7 @@ class StringUtilTest {
Path path = Paths.get("src", "main", "java", StringUtil.class.getName().replace('.', '/') + ".java");
int lineCount = Files.readAllLines(path, StandardCharsets.UTF_8).size();
- assertTrue(lineCount <= 725, "StringUtil increased in size to " + lineCount + ". "
+ assertTrue(lineCount <= 749, "StringUtil increased in size to " + lineCount + ". "
+ "We try to keep this class as small as possible. "
+ "Thus think twice if you add something to StringUtil.");
} | ['src/main/java/org/jabref/gui/preview/PreviewViewer.java', 'src/test/java/org/jabref/model/strings/StringUtilTest.java', 'src/main/java/org/jabref/model/strings/StringUtil.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 4,658,004 | 946,373 | 120,785 | 1,128 | 1,638 | 289 | 35 | 2 | 9,267 | 376 | 2,012 | 115 | 2 | 4 | 2019-10-21T20:58:44 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
441 | jabref/jabref/8092/8087 | jabref | jabref | https://github.com/JabRef/jabref/issues/8087 | https://github.com/JabRef/jabref/pull/8092 | https://github.com/JabRef/jabref/pull/8092 | 1 | fixes | cannot open a file with invalid group search expressions | ### JabRef version
5.3 (latest release)
### Operating system
GNU / Linux
### Details on version and operating system
_No response_
### Checked with the latest development build
- [X] I made a backup of my libraries before testing the latest development version.
- [X] I have tested the latest development version and the problem persists
### Steps to reproduce the behaviour
JabRef 5.4--2021-09-17--3d7521c
Linux 5.13.16-200.fc34.x86_64 amd64
Java 16.0.2
JavaFX 17+18
1. ... I open JabRef; it starts up with two of my key libraries opened. Good.
2. ... I try to open a specific third library. That generates the exception
Visible effect: opening the third library generates a new tab; but no table is visible. Sometimes the exception is reoccuring in a loop; other times it only shows 2 times, then I can click it away. In the latter case, when I switch to the other libraries, their table columns are minimised, so I cannot see anything. But I can resize the column widths.
I test it with another third library. No problem.
Ok, so that means I have a library that generates that exception in interaction with JabRef. Happy to share the file confidentially.
### Appendix
...
<details>
<summary>Log File</summary>
```
java.lang.NullPointerException: Cannot invoke "java.util.List.stream()" because "this.searchResults" is null
at org.jabref@5.4.211/org.jabref.model.search.rules.GrammarBasedSearchRule.getFulltextResults(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.search.rules.GrammarBasedSearchRule.applyRule(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.search.GroupSearchQuery.isMatch(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.groups.SearchGroup.contains(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.groups.AbstractGroup.isMatch(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.search.matchers.OrMatcher.lambda$isMatch$0(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.util.ListUtil.anyMatch(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.search.matchers.OrMatcher.isMatch(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.search.matchers.OrMatcher.lambda$isMatch$0(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.util.ListUtil.anyMatch(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.search.matchers.OrMatcher.isMatch(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.groups.GroupTreeNode.getMatchingGroups(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.groups.GroupTreeNode.getMatchingGroups(Unknown Source)
at org.jabref@5.4.211/org.jabref.model.groups.GroupTreeNode.getMatchingGroups(Unknown Source)
at org.jabref@5.4.211/org.jabref.gui.maintable.BibEntryTableViewModel.lambda$createMatchedGroupsBinding$5(Unknown Source)
at java.base/java.util.Optional.map(Unknown Source)
at org.jabref@5.4.211/org.jabref.gui.maintable.BibEntryTableViewModel.lambda$createMatchedGroupsBinding$6(Unknown Source)
at com.tobiasdiez.easybind@2.2/com.tobiasdiez.easybind.EasyBind$4.computeValue(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.beans.binding.ObjectBinding.get(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.beans.binding.ObjectExpression.getValue(Unknown Source)
at org.jabref@5.4.211/org.jabref.gui.util.uithreadaware.UiThreadBinding.getValue(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.TableCell.updateItem(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.TableCell.indexChanged(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.IndexedCell.updateIndex(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.TableRowSkinBase.updateCells(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.TableRowSkinBase.<init>(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.TableRowSkin.<init>(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.TableRow.createDefaultSkin(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.Control.doProcessCSS(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.Control$1.doProcessCSS(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.scene.control.ControlHelper.processCSSImpl(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.scene.NodeHelper.processCSS(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Node.processCSS(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Node.applyCss(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.VirtualFlow.setCellIndex(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.VirtualFlow.getCell(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.VirtualFlow.getOrCreateCellSize(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.VirtualFlow.getOrCreateCellSize(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.VirtualFlow.recalculateAndImproveEstimatedSize(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.VirtualFlow.recalculateEstimatedSize(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.skin.VirtualFlow.layoutChildren(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Parent.layout(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Scene.doLayoutPass(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.Scene$ScenePulseListener.pulse(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.tk.Toolkit.lambda$runPulse$2(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.tk.Toolkit.runPulse(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.tk.Toolkit.firePulse(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.glass.ui.gtk.GtkApplication.enterNestedEventLoopImpl(Native Method)
at org.jabref.merged.module@5.4.211/com.sun.glass.ui.gtk.GtkApplication._enterNestedEventLoop(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.glass.ui.Application.enterNestedEventLoop(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.glass.ui.EventLoop.enter(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.stage.Stage.showAndWait(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.HeavyweightDialog.showAndWait(Unknown Source)
at org.jabref.merged.module@5.4.211/javafx.scene.control.Dialog.showAndWait(Unknown Source)
at org.jabref@5.4.211/org.jabref.gui.JabRefDialogService.showErrorDialogAndWait(Unknown Source)
at org.jabref@5.4.211/org.jabref.gui.FallbackExceptionHandler.lambda$uncaughtException$0(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at org.jabref.merged.module@5.4.211/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at org.jabref.merged.module@5.4.211/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
```
</details>
| a91420d6491db7c63c167e8345cddd1cfcda0acc | 2eb32fd21d2ad6551e9f2836e9fb3457ad18d07c | https://github.com/jabref/jabref/compare/a91420d6491db7c63c167e8345cddd1cfcda0acc...2eb32fd21d2ad6551e9f2836e9fb3457ad18d07c | diff --git a/src/main/java/org/jabref/model/groups/SearchGroup.java b/src/main/java/org/jabref/model/groups/SearchGroup.java
index 5e261c438b..c1df365bef 100644
--- a/src/main/java/org/jabref/model/groups/SearchGroup.java
+++ b/src/main/java/org/jabref/model/groups/SearchGroup.java
@@ -37,10 +37,10 @@ public class SearchGroup extends AbstractGroup {
return false;
}
SearchGroup other = (SearchGroup) o;
- return getName().equals(other.getName())
- && getSearchExpression().equals(other.getSearchExpression())
- && (getSearchFlags().equals(other.getSearchFlags()))
- && (getHierarchicalContext() == other.getHierarchicalContext());
+ return Objects.equals(getName(), other.getName())
+ && Objects.equals(getHierarchicalContext(), other.getHierarchicalContext())
+ && Objects.equals(getSearchExpression(), other.getSearchExpression())
+ && Objects.equals(getSearchFlags(), other.getSearchFlags());
}
@Override
@@ -65,6 +65,11 @@ public class SearchGroup extends AbstractGroup {
}
}
+ @Override
+ public String toString() {
+ return "SearchGroup [query=" + query + ", name=" + name + ", searchFlags=" + getSearchFlags() + ", context=" + context + ", color=" + color + ", isExpanded=" + isExpanded + ", description=" + description + ", iconName=" + iconName + "]";
+ }
+
@Override
public boolean isDynamic() {
return true;
diff --git a/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java b/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java
index 5b0b5c40ea..777cbb6ebf 100644
--- a/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java
+++ b/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java
@@ -1,6 +1,7 @@
package org.jabref.model.search.rules;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
@@ -51,7 +52,7 @@ public class GrammarBasedSearchRule implements SearchRule {
private ParseTree tree;
private String query;
- private List<SearchResult> searchResults;
+ private List<SearchResult> searchResults = new ArrayList<>();
private final BibDatabaseContext databaseContext;
@@ -99,7 +100,7 @@ public class GrammarBasedSearchRule implements SearchRule {
tree = parser.start();
this.query = query;
- if (!searchFlags.contains(SearchRules.SearchFlags.FULLTEXT) || databaseContext == null) {
+ if (!searchFlags.contains(SearchRules.SearchFlags.FULLTEXT) || (databaseContext == null)) {
return;
}
try {
diff --git a/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java b/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java
index 2e514eb6d0..29580b7be2 100644
--- a/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java
+++ b/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java
@@ -2,6 +2,7 @@ package org.jabref.logic.importer.util;
import java.nio.file.Path;
import java.util.Arrays;
+import java.util.EnumSet;
import java.util.List;
import javafx.scene.paint.Color;
@@ -17,8 +18,10 @@ import org.jabref.model.groups.AutomaticPersonsGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.groups.GroupTreeNode;
+import org.jabref.model.groups.SearchGroup;
import org.jabref.model.groups.TexGroup;
import org.jabref.model.metadata.MetaData;
+import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.jabref.model.util.FileUpdateMonitor;
@@ -130,4 +133,12 @@ class GroupsParserTest {
void fromStringUnknownGroupThrowsException() throws Exception {
assertThrows(ParseException.class, () -> GroupsParser.fromString("0 UnknownGroup:myUnknownGroup;0;;1;;;;", ',', fileMonitor, metaData));
}
+
+ @Test
+ void fromStringParsesSearchGroup() throws Exception {
+ SearchGroup expected = new SearchGroup("Data", GroupHierarchyType.INCLUDING, "project=data|number|quant*", EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
+ AbstractGroup parsed = GroupsParser.fromString("SearchGroup:Data;2;project=data|number|quant*;0;1;1;;;;;", ',', fileMonitor, metaData);
+ assertEquals(expected, parsed);
+
+ }
}
diff --git a/src/test/java/org/jabref/model/groups/SearchGroupTest.java b/src/test/java/org/jabref/model/groups/SearchGroupTest.java
index 9b499ccf6e..c5b2f6a68d 100644
--- a/src/test/java/org/jabref/model/groups/SearchGroupTest.java
+++ b/src/test/java/org/jabref/model/groups/SearchGroupTest.java
@@ -7,6 +7,7 @@ import org.jabref.model.search.rules.SearchRules;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SearchGroupTest {
@@ -19,4 +20,13 @@ public class SearchGroupTest {
assertTrue(group.contains(entry));
}
+
+ @Test
+ public void containsDoesNotFindsWordWithInvalidRegularExpression() {
+ SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "anyfield=*rev*", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
+ BibEntry entry = new BibEntry();
+ entry.addKeyword("review", ',');
+
+ assertFalse(group.contains(entry));
+ }
} | ['src/main/java/org/jabref/model/groups/SearchGroup.java', 'src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java', 'src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java', 'src/test/java/org/jabref/model/groups/SearchGroupTest.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 5,724,289 | 1,147,793 | 146,226 | 1,334 | 1,239 | 244 | 18 | 2 | 9,080 | 453 | 2,418 | 126 | 0 | 1 | 2021-09-20T17:50:41 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
437 | jabref/jabref/9806/9805 | jabref | jabref | https://github.com/JabRef/jabref/issues/9805 | https://github.com/JabRef/jabref/pull/9806 | https://github.com/JabRef/jabref/pull/9806 | 1 | fixes | Preferences / entry types doesn't register changes | ### JabRef version
Latest development branch build (please note build date below)
### Operating system
GNU / Linux
### Details on version and operating system
Linux Mint 21.1 with Cinnamon
### Checked with the latest development build
- [X] I made a backup of my libraries before testing the latest development version.
- [X] I have tested the latest development version and the problem persists
### Steps to reproduce the behaviour
JabRef 5.10--2023-04-24--b599690
Linux 5.15.0-71-generic amd64
Java 20.0.1
JavaFX 20+19
1. File / Preferences / Entry types
2. Select, e.g., "book"
3. Click "required" for "Address"; also add some required fields like DOI, eprint, etc.
4. Save.
5. Have a look, close open, check again. The selections at step 3 is forgotten.
### Appendix
_No response_ | f7fba247e26369437f237d91682f7c2b05e006a4 | d69c6e87daf976a04efdf0c2986966d36e997477 | https://github.com/jabref/jabref/compare/f7fba247e26369437f237d91682f7c2b05e006a4...d69c6e87daf976a04efdf0c2986966d36e997477 | diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java
index bbc182f949..962bec1143 100644
--- a/src/main/java/org/jabref/preferences/JabRefPreferences.java
+++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java
@@ -1206,8 +1206,8 @@ public class JabRefPreferences implements PreferencesService {
@Override
public void storeCustomEntryTypesRepository(BibEntryTypesManager entryTypesManager) {
clearAllBibEntryTypes();
- storeBibEntryTypes(entryTypesManager.getAllCustomTypes(BibDatabaseMode.BIBTEX), BibDatabaseMode.BIBTEX);
- storeBibEntryTypes(entryTypesManager.getAllCustomTypes(BibDatabaseMode.BIBLATEX), BibDatabaseMode.BIBLATEX);
+ storeBibEntryTypes(entryTypesManager.getAllTypes(BibDatabaseMode.BIBTEX), BibDatabaseMode.BIBTEX);
+ storeBibEntryTypes(entryTypesManager.getAllTypes(BibDatabaseMode.BIBLATEX), BibDatabaseMode.BIBLATEX);
}
private void storeBibEntryTypes(Collection<BibEntryType> bibEntryTypes, BibDatabaseMode bibDatabaseMode) { | ['src/main/java/org/jabref/preferences/JabRefPreferences.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 6,273,010 | 1,253,293 | 159,463 | 1,460 | 451 | 114 | 4 | 1 | 812 | 126 | 216 | 34 | 0 | 0 | 2023-04-26T17:12:05 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
455 | jabref/jabref/3709/3646 | jabref | jabref | https://github.com/JabRef/jabref/issues/3646 | https://github.com/JabRef/jabref/pull/3709 | https://github.com/JabRef/jabref/pull/3709 | 1 | fixes | JabRef doesn't start if AutomaticKeywordGroup uses a semicolon as separator | - [x] I have tested the latest master version from http://builds.jabref.org/master/ and the problem persists
JabRef version 4.1 on Windows 10
(JabRef 4.1, Windows 10 10.0 amd64, Java 1.8.0_144)
Steps to reproduce:
1. Open a bibtex-file ([test0.txt](https://github.com/JabRef/jabref/files/1643240/test0.txt)). Create Automatic keyword group. Use proposed standard values, only change "," to ";" as separator.
2. Close JabRef. The bibtex-file looks like this: [test.txt](https://github.com/JabRef/jabref/files/1643209/test.txt)
3. Start JabRef.
4. JabRef doesn't start: It appears in the task manager, using the CPU a short time and then stays at 0% CPU with a constant amount of RAM used. No window opens.
If within the test file the `\\;` which stands for the separator (the second one after `keywords`, I guess) is changed to `,` or `-` JabRef opens again. If this `\\;` is changed to `;` JabRef doesn't start.
Regards
| 9228285befd2b7f1524f7623a092b3b70a373fe5 | b9bfea97a6a451ea6a79601a5e5bd8ca881d493a | https://github.com/jabref/jabref/compare/9228285befd2b7f1524f7623a092b3b70a373fe5...b9bfea97a6a451ea6a79601a5e5bd8ca881d493a | diff --git a/src/main/java/org/jabref/logic/exporter/GroupSerializer.java b/src/main/java/org/jabref/logic/exporter/GroupSerializer.java
index e8ce0925c3..eed98ed454 100644
--- a/src/main/java/org/jabref/logic/exporter/GroupSerializer.java
+++ b/src/main/java/org/jabref/logic/exporter/GroupSerializer.java
@@ -171,9 +171,9 @@ public class GroupSerializer {
appendAutomaticGroupDetails(sb, group);
sb.append(StringUtil.quote(group.getField(), MetadataSerializationConfiguration.GROUP_UNIT_SEPARATOR, MetadataSerializationConfiguration.GROUP_QUOTE_CHAR));
sb.append(MetadataSerializationConfiguration.GROUP_UNIT_SEPARATOR);
- sb.append(group.getKeywordDelimiter());
+ sb.append(StringUtil.quote(group.getKeywordDelimiter().toString(), MetadataSerializationConfiguration.GROUP_UNIT_SEPARATOR, MetadataSerializationConfiguration.GROUP_QUOTE_CHAR));
sb.append(MetadataSerializationConfiguration.GROUP_UNIT_SEPARATOR);
- sb.append(group.getKeywordHierarchicalDelimiter());
+ sb.append(StringUtil.quote(group.getKeywordHierarchicalDelimiter().toString(), MetadataSerializationConfiguration.GROUP_UNIT_SEPARATOR, MetadataSerializationConfiguration.GROUP_QUOTE_CHAR));
sb.append(MetadataSerializationConfiguration.GROUP_UNIT_SEPARATOR);
appendGroupDetails(sb, group);
return sb.toString();
diff --git a/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java b/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java
index ef694fac9f..dd9385a736 100644
--- a/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java
+++ b/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java
@@ -42,6 +42,20 @@ public class GroupsParserTest {
assertEquals(expected, parsed);
}
+ @Test
+ public void KeywordDelimiterThatNeedsToBeEscaped() throws Exception {
+ AutomaticGroup expected = new AutomaticKeywordGroup("group1", GroupHierarchyType.INDEPENDENT, "keywords", ';', '>');
+ AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:group1;0;keywords;\\\\;;>;1;;;;;", ';', fileMonitor);
+ assertEquals(expected, parsed);
+ }
+
+ @Test
+ public void HierarchicalDelimiterThatNeedsToBeEscaped() throws Exception {
+ AutomaticGroup expected = new AutomaticKeywordGroup("group1", GroupHierarchyType.INDEPENDENT, "keywords", ',', ';');
+ AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:group1;0;keywords;,;\\\\;;1;;;;;", ';', fileMonitor);
+ assertEquals(expected, parsed);
+ }
+
@Test(expected = ParseException.class)
public void fromStringThrowsParseExceptionForNotEscapedGroupName() throws Exception {
GroupsParser.fromString("ExplicitGroup:slit\\\\\\\\;0\\\\;mertsch_slit2_2007\\\\;;", ',', fileMonitor); | ['src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java', 'src/main/java/org/jabref/logic/exporter/GroupSerializer.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 5,100,009 | 1,042,632 | 135,522 | 1,044 | 497 | 80 | 4 | 1 | 940 | 135 | 263 | 17 | 3 | 0 | 2018-02-07T17:52:51 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
456 | jabref/jabref/3588/3584 | jabref | jabref | https://github.com/JabRef/jabref/issues/3584 | https://github.com/JabRef/jabref/pull/3588 | https://github.com/JabRef/jabref/pull/3588 | 1 | fixes | Deleting an entry causes NPE exception | Delete an entry in the current master 64c774b
```
SEVERE: Exception thrown by subscriber method listen(org.jabref.model.database.event.EntryRemovedEvent) on subscriber org.jabref.gui.BasePanel$EntryRemovedListener@600cdad9 when dispatching event: org.jabref.model.database.event.EntryRemovedEvent@3850ee8f
java.lang.NullPointerException
at org.jabref.gui.BasePanel$EntryRemovedListener.listen(BasePanel.java:2092)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.google.common.eventbus.Subscriber.invokeSubscriberMethod(Subscriber.java:87)
at com.google.common.eventbus.Subscriber$SynchronizedSubscriber.invokeSubscriberMethod(Subscriber.java:144)
at com.google.common.eventbus.Subscriber$1.run(Subscriber.java:72)
at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:398)
at com.google.common.eventbus.Subscriber.dispatchEvent(Subscriber.java:67)
at com.google.common.eventbus.Dispatcher$PerThreadQueuedDispatcher.dispatch(Dispatcher.java:108)
at com.google.common.eventbus.EventBus.post(EventBus.java:212)
at org.jabref.model.database.BibDatabase.removeEntry(BibDatabase.java:252)
at org.jabref.model.database.BibDatabase.removeEntry(BibDatabase.java:236)
at org.jabref.gui.BasePanel.delete(BasePanel.java:803)
at org.jabref.gui.BasePanel.lambda$7(BasePanel.java:369)
``` | 1172ed493c6dce05fcb427b4e665f5de3a7b3fc3 | 0fbe7fa8c32293f431c24f68bbaedca172390c5a | https://github.com/jabref/jabref/compare/1172ed493c6dce05fcb427b4e665f5de3a7b3fc3...0fbe7fa8c32293f431c24f68bbaedca172390c5a | diff --git a/src/main/java/org/jabref/gui/BasePanel.java b/src/main/java/org/jabref/gui/BasePanel.java
index 806020c9bf..965675e5d2 100644
--- a/src/main/java/org/jabref/gui/BasePanel.java
+++ b/src/main/java/org/jabref/gui/BasePanel.java
@@ -221,6 +221,10 @@ public class BasePanel extends JPanel implements ClipboardOwner {
citationStyleCache = new CitationStyleCache(bibDatabaseContext);
annotationCache = new FileAnnotationCache(bibDatabaseContext);
+ this.preview = new PreviewPanel(this, getBibDatabaseContext());
+ DefaultTaskExecutor.runInJavaFXThread(() -> frame().getGlobalSearchBar().getSearchQueryHighlightObservable().addSearchListener(preview));
+ this.previewContainer = CustomJFXPanel.wrap(new Scene(preview));
+
setupMainPanel();
setupActions();
@@ -249,9 +253,6 @@ public class BasePanel extends JPanel implements ClipboardOwner {
entryEditor = new EntryEditor(this);
entryEditorContainer = setupEntryEditor(entryEditor);
- this.preview = new PreviewPanel(this, getBibDatabaseContext());
- DefaultTaskExecutor.runInJavaFXThread(() -> frame().getGlobalSearchBar().getSearchQueryHighlightObservable().addSearchListener(preview));
- this.previewContainer = CustomJFXPanel.wrap(new Scene(preview));
}
private static JFXPanel setupEntryEditor(EntryEditor entryEditor) {
@@ -2060,7 +2061,7 @@ public class BasePanel extends JPanel implements ClipboardOwner {
@Subscribe
public void listen(EntryRemovedEvent entryRemovedEvent) {
// if the entry that is displayed in the current entry editor is removed, close the entry editor
- if (mode == BasePanelMode.SHOWING_EDITOR && entryEditor.getEntry().equals(entryRemovedEvent.getBibEntry())) {
+ if ((mode == BasePanelMode.SHOWING_EDITOR) && entryEditor.getEntry().equals(entryRemovedEvent.getBibEntry())) {
entryEditor.close();
}
| ['src/main/java/org/jabref/gui/BasePanel.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 5,067,473 | 1,035,593 | 134,763 | 1,033 | 837 | 176 | 9 | 1 | 1,595 | 58 | 360 | 22 | 0 | 1 | 2017-12-29T09:47:22 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
460 | jabref/jabref/2774/2766 | jabref | jabref | https://github.com/JabRef/jabref/issues/2766 | https://github.com/JabRef/jabref/pull/2774 | https://github.com/JabRef/jabref/pull/2774 | 1 | fixes | File Annoation Tab gives NPE when PDF is not avaiable | Entry with linked PDF:
` file = {:Arellano2015 - Natural Language Processing of Textual Requirements.pdf:PDF},`
but the PDF is not available/existing in the folder.
Switch to Tab File Annotations: NPE exception comes:
```
java.lang.NullPointerException: null
at org.jabref.gui.entryeditor.FileAnnotationTab.updateShownAnnotations(FileAnnotationTab.java:130) ~[bin/:?]
at org.jabref.gui.entryeditor.FileAnnotationTab.addAnnotations(FileAnnotationTab.java:114) ~[bin/:?]
at org.jabref.gui.entryeditor.FileAnnotationTab.initializeTab(FileAnnotationTab.java:89) ~[bin/:?]
at org.jabref.gui.entryeditor.EntryEditor$TabListener.lambda$0(EntryEditor.java:1155) ~[bin/:?]
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) ~[?:1.8.0_121]
``` | a9e20660e07992b7f5739ce53c9156ae45623abf | 9b9b3c44ec60485384ba9d769f8a83afe2acc0b4 | https://github.com/jabref/jabref/compare/a9e20660e07992b7f5739ce53c9156ae45623abf...9b9b3c44ec60485384ba9d769f8a83afe2acc0b4 | diff --git a/src/main/java/org/jabref/gui/entryeditor/FileAnnotationTab.java b/src/main/java/org/jabref/gui/entryeditor/FileAnnotationTab.java
index 7c6901c310..14483cec7b 100644
--- a/src/main/java/org/jabref/gui/entryeditor/FileAnnotationTab.java
+++ b/src/main/java/org/jabref/gui/entryeditor/FileAnnotationTab.java
@@ -127,7 +127,7 @@ class FileAnnotationTab extends JPanel {
*/
private void updateShownAnnotations(List<FileAnnotation> annotations) {
listModel.clear();
- if (annotations.isEmpty()) {
+ if (annotations == null || annotations.isEmpty()) {
listModel.addElement(new FileAnnotation("", LocalDateTime.now(), 0, Localization.lang("File has no attached annotations"), NONE, Optional.empty()));
} else {
Comparator<FileAnnotation> byPage = Comparator.comparingInt(FileAnnotation::getPage); | ['src/main/java/org/jabref/gui/entryeditor/FileAnnotationTab.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 5,003,598 | 1,022,933 | 133,978 | 964 | 98 | 18 | 2 | 1 | 778 | 51 | 196 | 13 | 0 | 1 | 2017-04-20T15:38:53 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
458 | jabref/jabref/3401/3347 | jabref | jabref | https://github.com/JabRef/jabref/issues/3347 | https://github.com/JabRef/jabref/pull/3401 | https://github.com/JabRef/jabref/pull/3401 | 1 | fixes | NPE when saving new database with entries (DatabaseChangeMonitor is null) | Create a new database
Copy/Paste some bibtex entry
Hit CTRL +S
```
17:07:25.852 [AWT-EventQueue-0] ERROR org.jabref.gui.BasePanel - runCommand error: null
java.lang.NullPointerException: null
at org.jabref.gui.BasePanel.isUpdatedExternally(BasePanel.java:1823) ~[bin/:?]
at org.jabref.gui.exporter.SaveDatabaseAction.checkExternalModification(SaveDatabaseAction.java:403) ~[bin/:?]
at org.jabref.gui.exporter.SaveDatabaseAction.init(SaveDatabaseAction.java:90) ~[bin/:?]
at org.jabref.gui.BasePanel.runWorker(BasePanel.java:250) ~[bin/:?]
at org.jabref.gui.exporter.SaveDatabaseAction.runCommand(SaveDatabaseAction.java:285) ~[bin/:?]
at org.jabref.gui.exporter.SaveDatabaseAction.saveAs(SaveDatabaseAction.java:331) ~[bin/:?]
at org.jabref.gui.exporter.SaveDatabaseAction.saveAs(SaveDatabaseAction.java:305) ~[bin/:?]
at org.jabref.gui.exporter.SaveDatabaseAction.init(SaveDatabaseAction.java:100) ~[bin/:?]
at org.jabref.gui.BasePanel.runWorker(BasePanel.java:250) ~[bin/:?]
at org.jabref.gui.BasePanel.runCommand(BasePanel.java:1025) [bin/:?]
at org.jabref.gui.JabRefFrame$GeneralAction.actionPerformed(JabRefFrame.java:2052) [bin/:?]
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022) [?:1.8.0_152]
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348) [?:1.8.0_152]
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) [?:1.8.0_152]
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) [?:1.8.0_152]
at javax.swing.AbstractButton.doClick(AbstractButton.java:376) [?:1.8.0_152]
at javax.swing.AbstractButton.doClick(AbstractButton.java:356) [?:1.8.0_152]
at javax.swing.plaf.basic.BasicMenuItemUI$Actions.actionPerformed(BasicMenuItemUI.java:811) [?:1.8.0_152]
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1663) [?:1.8.0_152]
at javax.swing.JComponent.processKeyBinding(JComponent.java:2882) [?:1.8.0_152]
at javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:699) [?:1.8.0_152]
at javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:706) [?:1.8.0_152]
at javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:706) [?:1.8.0_152]
at javax.swing.JMenuBar.processKeyBinding(JMenuBar.java:677) [?:1.8.0_152]
at javax.swing.KeyboardManager.fireBinding(KeyboardManager.java:307) [?:1.8.0_152]
at javax.swing.KeyboardManager.fireKeyboardAction(KeyboardManager.java:293) [?:1.8.0_152]
at javax.swing.JComponent.processKeyBindingsForAllComponents(JComponent.java:2974) [?:1.8.0_152]
at javax.swing.JComponent.processKeyBindings(JComponent.java:2966) [?:1.8.0_152]
at javax.swing.JComponent.processKeyEvent(JComponent.java:2845) [?:1.8.0_152]
at java.awt.Component.processEvent(Component.java:6310) [?:1.8.0_152]
at java.awt.Container.processEvent(Container.java:2237) [?:1.8.0_152]
at java.awt.Component.dispatchEventImpl(Component.java:4889) [?:1.8.0_152]
at java.awt.Container.dispatchEventImpl(Container.java:2295) [?:1.8.0_152]
at java.awt.Component.dispatchEvent(Component.java:4711) [?:1.8.0_152]
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954) [?:1.8.0_152]
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:806) [?:1.8.0_152]
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1074) [?:1.8.0_152]
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:945) [?:1.8.0_152]
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:771) [?:1.8.0_152]
at java.awt.Component.dispatchEventImpl(Component.java:4760) [?:1.8.0_152]
at java.awt.Container.dispatchEventImpl(Container.java:2295) [?:1.8.0_152]
at java.awt.Window.dispatchEventImpl(Window.java:2746) [?:1.8.0_152]
at java.awt.Component.dispatchEvent(Component.java:4711) [?:1.8.0_152]
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) [?:1.8.0_152]
at java.awt.EventQueue.access$500(EventQueue.java:97) [?:1.8.0_152]
at java.awt.EventQueue$3.run(EventQueue.java:709) [?:1.8.0_152]
at java.awt.EventQueue$3.run(EventQueue.java:703) [?:1.8.0_152]
at java.security.AccessController.doPrivileged(Native Method) [?:1.8.0_152]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) [?:1.8.0_152]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90) [?:1.8.0_152]
at java.awt.EventQueue$4.run(EventQueue.java:731) [?:1.8.0_152]
at java.awt.EventQueue$4.run(EventQueue.java:729) [?:1.8.0_152]
at java.security.AccessController.doPrivileged(Native Method) [?:1.8.0_152]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) [?:1.8.0_152]
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) [?:1.8.0_152]
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) [?:1.8.0_152]
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) [?:1.8.0_152]
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) [?:1.8.0_152]
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) [?:1.8.0_152]
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) [?:1.8.0_152]
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) [?:1.8.0_152]
``` | f5842eff27cb16a41f8b6f1428ef27b177511be3 | 767818f21a8566ef282d7b12dcacc2dc00643e6a | https://github.com/jabref/jabref/compare/f5842eff27cb16a41f8b6f1428ef27b177511be3...767818f21a8566ef282d7b12dcacc2dc00643e6a | diff --git a/src/main/java/org/jabref/gui/BasePanel.java b/src/main/java/org/jabref/gui/BasePanel.java
index d536845048..c6668e2164 100644
--- a/src/main/java/org/jabref/gui/BasePanel.java
+++ b/src/main/java/org/jabref/gui/BasePanel.java
@@ -198,7 +198,7 @@ public class BasePanel extends JPanel implements ClipboardOwner {
// the query the user searches when this BasePanel is active
private Optional<SearchQuery> currentSearchQuery = Optional.empty();
- private DatabaseChangeMonitor changeMonitor;
+ private Optional<DatabaseChangeMonitor> changeMonitor = Optional.empty();
public BasePanel(JabRefFrame frame, BibDatabaseContext bibDatabaseContext) {
Objects.requireNonNull(frame);
@@ -228,7 +228,7 @@ public class BasePanel extends JPanel implements ClipboardOwner {
Optional<File> file = bibDatabaseContext.getDatabaseFile();
if (file.isPresent()) {
// Register so we get notifications about outside changes to the file.
- changeMonitor = new DatabaseChangeMonitor(bibDatabaseContext, Globals.getFileUpdateMonitor(), this);
+ changeMonitor = Optional.of(new DatabaseChangeMonitor(bibDatabaseContext, Globals.getFileUpdateMonitor(), this));
} else {
if (bibDatabaseContext.getDatabase().hasEntries()) {
// if the database is not empty and no file is assigned,
@@ -1796,7 +1796,7 @@ public class BasePanel extends JPanel implements ClipboardOwner {
* Perform necessary cleanup when this BasePanel is closed.
*/
public void cleanUp() {
- changeMonitor.unregister();
+ changeMonitor.ifPresent(DatabaseChangeMonitor::unregister);
// Check if there is a FileUpdatePanel for this BasePanel being shown. If so,
// remove it:
@@ -1823,11 +1823,11 @@ public class BasePanel extends JPanel implements ClipboardOwner {
}
public boolean isUpdatedExternally() {
- return changeMonitor.hasBeenModifiedExternally();
+ return changeMonitor.map(DatabaseChangeMonitor::hasBeenModifiedExternally).orElse(false);
}
public void markExternalChangesAsResolved() {
- changeMonitor.markExternalChangesAsResolved();
+ changeMonitor.ifPresent(DatabaseChangeMonitor::markExternalChangesAsResolved);
}
public SidePaneManager getSidePaneManager() {
@@ -1975,16 +1975,16 @@ public class BasePanel extends JPanel implements ClipboardOwner {
}
public void resetChangeMonitor() {
- changeMonitor.unregister();
- changeMonitor = new DatabaseChangeMonitor(bibDatabaseContext, Globals.getFileUpdateMonitor(), this);
+ changeMonitor.ifPresent(DatabaseChangeMonitor::unregister);
+ changeMonitor = Optional.of(new DatabaseChangeMonitor(bibDatabaseContext, Globals.getFileUpdateMonitor(), this));
}
public void updateTimeStamp() {
- changeMonitor.markAsSaved();
+ changeMonitor.ifPresent(DatabaseChangeMonitor::markAsSaved);
}
public Path getTempFile() {
- return changeMonitor.getTempFile();
+ return changeMonitor.map(DatabaseChangeMonitor::getTempFile).orElse(null);
}
private static class SearchAndOpenFile { | ['src/main/java/org/jabref/gui/BasePanel.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 5,050,144 | 1,031,459 | 134,561 | 1,025 | 1,353 | 236 | 18 | 1 | 5,568 | 208 | 1,594 | 70 | 0 | 1 | 2017-11-04T04:26:32 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
457 | jabref/jabref/3553/2852 | jabref | jabref | https://github.com/JabRef/jabref/issues/2852 | https://github.com/JabRef/jabref/pull/3553 | https://github.com/JabRef/jabref/pull/3553 | 1 | fixes | Performance problems with new groups search/filter and large databases | JabRef 4.0.0-dev--snapshot--2017-05-18--master--018173ebd
Windows 10 10.0 amd64
Java 1.8.0_131
The newly implemented groups filter/search (https://github.com/JabRef/jabref/pull/2588) exhibits massive performance problems when used on a large database (>10,000 entries, ~1,000 static groups).
1. Open large database
2. Start to enter any term you want to search for in the "Filter Groups" part of the groups panel.
3. You will immediately see a massive performance decrease. It takes minutes to just complete entering the word you want to search for (because the filtering starts immediately). The groups filtering itself also takes minutes to complete. During that time JabRef behaves as if it had crashed.
This issue has been reported before (https://github.com/JabRef/jabref/pull/2588#issuecomment-283042778, https://github.com/JabRef/jabref/pull/2588#issuecomment-302629336) but I have been advised to open a new ticket so that the issue is not forgotten. | 6d2ec481cdad6029b29a3b3d217f23ab47e92588 | 3092915214b958bb8a534a53f5438fa6e2e75c93 | https://github.com/jabref/jabref/compare/6d2ec481cdad6029b29a3b3d217f23ab47e92588...3092915214b958bb8a534a53f5438fa6e2e75c93 | diff --git a/src/main/java/org/jabref/gui/groups/GroupSidePane.java b/src/main/java/org/jabref/gui/groups/GroupSidePane.java
index 326685e0d1..86e4392c61 100644
--- a/src/main/java/org/jabref/gui/groups/GroupSidePane.java
+++ b/src/main/java/org/jabref/gui/groups/GroupSidePane.java
@@ -1,5 +1,6 @@
package org.jabref.gui.groups;
+import java.util.Collections;
import java.util.List;
import javafx.application.Platform;
@@ -16,6 +17,7 @@ import org.jabref.gui.SidePaneManager;
import org.jabref.gui.customjfx.CustomJFXPanel;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.maintable.MainTableDataModel;
+import org.jabref.logic.groups.DefaultGroupsFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.OS;
import org.jabref.model.entry.FieldName;
@@ -83,8 +85,8 @@ public class GroupSidePane extends SidePaneComponent {
private void updateShownEntriesAccordingToSelectedGroups(List<GroupTreeNode> selectedGroups) {
if ((selectedGroups == null) || selectedGroups.isEmpty()) {
- // No selected group, nothing to do
- return;
+ // No selected group, show all entries
+ selectedGroups = Collections.singletonList(new GroupTreeNode(DefaultGroupsFactory.getAllEntriesGroup()));
}
final MatcherSet searchRules = MatcherSets.build(
diff --git a/src/main/java/org/jabref/gui/groups/GroupTreeController.java b/src/main/java/org/jabref/gui/groups/GroupTreeController.java
index 357331789c..983bdb4c7e 100644
--- a/src/main/java/org/jabref/gui/groups/GroupTreeController.java
+++ b/src/main/java/org/jabref/gui/groups/GroupTreeController.java
@@ -2,6 +2,7 @@ package org.jabref.gui.groups;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -41,12 +42,15 @@ import org.jabref.gui.util.RecursiveTreeItem;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ViewModelTreeTableCellFactory;
import org.jabref.logic.l10n.Localization;
+import org.jabref.model.groups.AllEntriesGroup;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.controlsfx.control.textfield.CustomTextField;
import org.controlsfx.control.textfield.TextFields;
import org.fxmisc.easybind.EasyBind;
+import org.reactfx.util.FxTimer;
+import org.reactfx.util.Timer;
public class GroupTreeController extends AbstractController<GroupTreeViewModel> {
@@ -87,7 +91,13 @@ public class GroupTreeController extends AbstractController<GroupTreeViewModel>
this::updateSelection
);
- viewModel.filterTextProperty().bind(searchField.textProperty());
+ // We try to to prevent publishing changes in the search field directly to the search task that takes some time
+ // for larger group structures.
+ final Timer searchTask = FxTimer.create(Duration.ofMillis(400), () -> {
+ LOGGER.debug("Run group search " + searchField.getText());
+ viewModel.filterTextProperty().setValue(searchField.textProperty().getValue());
+ });
+ searchField.textProperty().addListener((observable, oldValue, newValue) -> searchTask.restart());
groupTree.rootProperty().bind(
EasyBind.map(viewModel.rootGroupProperty(),
@@ -241,12 +251,12 @@ public class GroupTreeController extends AbstractController<GroupTreeViewModel>
}
private void updateSelection(List<TreeItem<GroupNodeViewModel>> newSelectedGroups) {
- if (newSelectedGroups == null) {
+ if (newSelectedGroups == null || newSelectedGroups.isEmpty()) {
viewModel.selectedGroupsProperty().clear();
} else {
List<GroupNodeViewModel> list = new ArrayList<>();
for (TreeItem<GroupNodeViewModel> model : newSelectedGroups) {
- if (model != null && model.getValue() != null) {
+ if (model != null && model.getValue() != null && !(model.getValue().getGroupNode().getGroup() instanceof AllEntriesGroup)) {
list.add(model.getValue());
}
}
diff --git a/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java b/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java
index bc11a195de..a4e2889b9e 100644
--- a/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java
+++ b/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java
@@ -92,7 +92,7 @@ public class GroupTreeViewModel extends AbstractViewModel {
}
currentDatabase.ifPresent(database -> {
- if (newValue == null) {
+ if (newValue == null || newValue.isEmpty()) {
stateManager.clearSelectedGroups(database);
} else {
stateManager.setSelectedGroups(database, newValue.stream().map(GroupNodeViewModel::getGroupNode).collect(Collectors.toList()));
diff --git a/src/main/java/org/jabref/gui/util/BindingsHelper.java b/src/main/java/org/jabref/gui/util/BindingsHelper.java
index 22b26f2db8..716ca03b89 100644
--- a/src/main/java/org/jabref/gui/util/BindingsHelper.java
+++ b/src/main/java/org/jabref/gui/util/BindingsHelper.java
@@ -68,7 +68,7 @@ public class BindingsHelper {
* the items are converted when the are inserted (and at the initialization) instead of when they are accessed.
* Thus the initial CPU overhead and memory consumption is higher but the access to list items is quicker.
*/
- public static <A, B> MappedList mapBacked(ObservableList<A> source, Function<A, B> mapper) {
+ public static <A, B> MappedList<B, A> mapBacked(ObservableList<A> source, Function<A, B> mapper) {
return new MappedList<>(source, mapper);
}
diff --git a/src/main/java/org/jabref/gui/util/RecursiveTreeItem.java b/src/main/java/org/jabref/gui/util/RecursiveTreeItem.java
index 1117f9dad3..c8c1f9db4c 100644
--- a/src/main/java/org/jabref/gui/util/RecursiveTreeItem.java
+++ b/src/main/java/org/jabref/gui/util/RecursiveTreeItem.java
@@ -1,8 +1,6 @@
package org.jabref.gui.util;
-import java.util.List;
import java.util.function.Predicate;
-import java.util.stream.Collectors;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
@@ -24,7 +22,7 @@ public class RecursiveTreeItem<T> extends TreeItem<T> {
private final Callback<T, BooleanProperty> expandedProperty;
private Callback<T, ObservableList<T>> childrenFactory;
private ObjectProperty<Predicate<T>> filter = new SimpleObjectProperty<>();
- private FilteredList<T> children;
+ private FilteredList<RecursiveTreeItem<T>> children;
public RecursiveTreeItem(final T value, Callback<T, ObservableList<T>> func) {
this(value, func, null, null);
@@ -52,7 +50,7 @@ public class RecursiveTreeItem<T> extends TreeItem<T> {
bindExpandedProperty(value, expandedProperty);
}
- valueProperty().addListener((obs, oldValue, newValue)-> {
+ valueProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null) {
addChildrenListener(newValue);
bindExpandedProperty(newValue, expandedProperty);
@@ -67,44 +65,38 @@ public class RecursiveTreeItem<T> extends TreeItem<T> {
}
private void addChildrenListener(T value) {
- children = new FilteredList<>(childrenFactory.call(value));
+ children = new FilteredList<>(
+ BindingsHelper.mapBacked(childrenFactory.call(value),
+ child -> new RecursiveTreeItem<>(child, getGraphic(), childrenFactory, expandedProperty, filter)));
children.predicateProperty().bind(Bindings.createObjectBinding(() -> this::showNode, filter));
- addAsChildren(children, 0);
+ getChildren().addAll(0, children);
- children.addListener((ListChangeListener<T>) change -> {
+ children.addListener((ListChangeListener<RecursiveTreeItem<T>>) change -> {
while (change.next()) {
if (change.wasRemoved()) {
- change.getRemoved().forEach(t-> {
- final List<TreeItem<T>> itemsToRemove = getChildren().stream().filter(treeItem -> treeItem.getValue().equals(t)).collect(Collectors.toList());
- getChildren().removeAll(itemsToRemove);
- });
+ getChildren().removeAll(change.getRemoved());
}
if (change.wasAdded()) {
- addAsChildren(change.getAddedSubList(), change.getFrom());
+ getChildren().addAll(change.getFrom(), change.getAddedSubList());
}
}
});
}
- private void addAsChildren(List<? extends T> children, int startIndex) {
- List<RecursiveTreeItem<T>> treeItems = children.stream().map(child -> new RecursiveTreeItem<>(child, getGraphic(), childrenFactory, expandedProperty, filter)).collect(Collectors.toList());
- getChildren().addAll(startIndex, treeItems);
- }
-
- private boolean showNode(T t) {
+ private boolean showNode(RecursiveTreeItem<T> node) {
if (filter.get() == null) {
return true;
}
- if (filter.get().test(t)) {
+ if (filter.get().test(node.getValue())) {
// Node is directly matched -> so show it
return true;
}
// Are there children (or children of children...) that are matched? If yes we also need to show this node
- return childrenFactory.call(t).stream().anyMatch(this::showNode);
+ return node.children.getSource().stream().anyMatch(this::showNode);
}
} | ['src/main/java/org/jabref/gui/groups/GroupTreeController.java', 'src/main/java/org/jabref/gui/util/BindingsHelper.java', 'src/main/java/org/jabref/gui/util/RecursiveTreeItem.java', 'src/main/java/org/jabref/gui/groups/GroupSidePane.java', 'src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 5,089,097 | 1,039,411 | 135,384 | 1,032 | 3,739 | 736 | 58 | 5 | 973 | 125 | 250 | 11 | 3 | 0 | 2017-12-20T05:13:24 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
473 | jabref/jabref/600/599 | jabref | jabref | https://github.com/JabRef/jabref/issues/599 | https://github.com/JabRef/jabref/pull/600 | https://github.com/JabRef/jabref/pull/600 | 1 | fixes | Import from external database fails for 3.1 and PostgreSQL | Hi,
Just tried out 3.1. Thank you for all of the enhancements, especially the new look!.
I tried to import from an existing database but it failed with the following error in a pop-up window:
"Could not import from SQL database for the following reason:
java.util.ConcurrentModificationException"
There were no obvious command line messages. I used ./gradlew run to test.
Cheers,
Fred
| 0b588f52a9aa28b48ad451792481bf4217359926 | 548c797b6992f3bc784dca0e162d6cc3bfe6df5b | https://github.com/jabref/jabref/compare/0b588f52a9aa28b48ad451792481bf4217359926...548c797b6992f3bc784dca0e162d6cc3bfe6df5b | diff --git a/src/main/java/net/sf/jabref/sql/importer/DBImporter.java b/src/main/java/net/sf/jabref/sql/importer/DBImporter.java
index cf8d75355f..f5ff766ce1 100644
--- a/src/main/java/net/sf/jabref/sql/importer/DBImporter.java
+++ b/src/main/java/net/sf/jabref/sql/importer/DBImporter.java
@@ -21,6 +21,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
+import java.util.stream.Collectors;
import net.sf.jabref.bibtex.EntryTypes;
import net.sf.jabref.model.entry.*;
@@ -104,12 +105,7 @@ public abstract class DBImporter extends DBImporterExporter {
rsEntryType.getStatement().close();
}
- List<String> colNames = this.readColumnNames(conn);
- for (String next : colNames) {
- if (!columnsNotConsideredForEntries.contains(next)) {
- colNames.add(next);
- }
- }
+ List<String> colNames = this.readColumnNames(conn).stream().filter(column -> !columnsNotConsideredForEntries.contains(column)).collect(Collectors.toList());
String database_id = rsDatabase.getString("database_id");
// Read the entries and create BibEntry instances: | ['src/main/java/net/sf/jabref/sql/importer/DBImporter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,796,307 | 1,000,801 | 127,693 | 689 | 517 | 84 | 8 | 1 | 393 | 61 | 85 | 15 | 0 | 0 | 2015-12-28T15:35:39 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
465 | jabref/jabref/1460/1455 | jabref | jabref | https://github.com/JabRef/jabref/issues/1455 | https://github.com/JabRef/jabref/pull/1460 | https://github.com/JabRef/jabref/pull/1460 | 2 | fix | DOI Fetcher throws NPE if no result was found | JabRef dev version on Windows 10
<!-- Hint: If you use a development version (available at http://builds.jabref.org/master/), ensure that you use the latest one. -->
Steps to reproduce:
1. Entry with DOI for which the fetcher can't find bibtex data, for example: 10.2307/2372901
2. Click "Get BibTeX data from DOI"
3. Results in no warning but an NPE:
```
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at net.sf.jabref.importer.fetcher.DOItoBibTeXFetcher.getEntryFromDOI(DOItoBibTeXFetcher.java:90)
at net.sf.jabref.gui.mergeentries.MergeEntryDOIDialog.<init>(MergeEntryDOIDialog.java:75)
at net.sf.jabref.gui.entryeditor.FieldExtraComponents.lambda$getDoiExtraComponent$339(FieldExtraComponents.java:199)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
```
<!-- If applicable, excerpt of the bibliography file, screenshot, and excerpt of log (available in the error console) -->
| a14ad8e6b10bff8c129ffc7edd56ba0c33b1deda | b0352a18f04d34fe8738d025dde1906cce220ab5 | https://github.com/jabref/jabref/compare/a14ad8e6b10bff8c129ffc7edd56ba0c33b1deda...b0352a18f04d34fe8738d025dde1906cce220ab5 | diff --git a/src/main/java/net/sf/jabref/gui/ClipBoardManager.java b/src/main/java/net/sf/jabref/gui/ClipBoardManager.java
index 9071de0a38..fb16c131df 100644
--- a/src/main/java/net/sf/jabref/gui/ClipBoardManager.java
+++ b/src/main/java/net/sf/jabref/gui/ClipBoardManager.java
@@ -32,6 +32,7 @@ import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
+import java.util.Optional;
import net.sf.jabref.importer.fetcher.DOItoBibTeXFetcher;
import net.sf.jabref.importer.fileformat.BibtexParser;
@@ -105,10 +106,8 @@ public class ClipBoardManager implements ClipboardOwner {
// fetch from doi
if (DOI.build(data).isPresent()) {
LOGGER.info("Found DOI in clipboard");
- BibEntry entry = new DOItoBibTeXFetcher().getEntryFromDOI(new DOI(data).getDOI(), null);
- if (entry != null) {
- result.add(entry);
- }
+ Optional<BibEntry> entry = new DOItoBibTeXFetcher().getEntryFromDOI(new DOI(data).getDOI());
+ entry.ifPresent(result::add);
} else {
// parse bibtex string
BibtexParser bp = new BibtexParser(new StringReader(data));
diff --git a/src/main/java/net/sf/jabref/gui/desktop/JabRefDesktop.java b/src/main/java/net/sf/jabref/gui/desktop/JabRefDesktop.java
index c6606e12a7..8a577b8dba 100644
--- a/src/main/java/net/sf/jabref/gui/desktop/JabRefDesktop.java
+++ b/src/main/java/net/sf/jabref/gui/desktop/JabRefDesktop.java
@@ -80,7 +80,7 @@ public class JabRefDesktop {
} else if ("doi".equals(fieldName)) {
Optional<DOI> doiUrl = DOI.build(link);
if (doiUrl.isPresent()) {
- link = doiUrl.get().getURLAsASCIIString();
+ link = doiUrl.get().getURIAsASCIIString();
}
// should be opened in browser
fieldName = "url";
diff --git a/src/main/java/net/sf/jabref/gui/mergeentries/MergeEntryDOIDialog.java b/src/main/java/net/sf/jabref/gui/mergeentries/MergeEntryDOIDialog.java
index 8b7d19c96c..b3df25b126 100644
--- a/src/main/java/net/sf/jabref/gui/mergeentries/MergeEntryDOIDialog.java
+++ b/src/main/java/net/sf/jabref/gui/mergeentries/MergeEntryDOIDialog.java
@@ -40,9 +40,7 @@ import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
/**
- * @author Oscar
- *
- * Dialog for merging Bibtex entry with data fetched from DOI
+ * Dialog for merging Bibtex entry with data fetched from DOI
*/
public class MergeEntryDOIDialog extends JDialog {
@@ -72,7 +70,7 @@ public class MergeEntryDOIDialog extends JDialog {
this.originalEntry = panel.getSelectedEntries().get(0);
panel.output(Localization.lang("Fetching info based on DOI"));
- this.doiEntry = doiFetcher.getEntryFromDOI(this.originalEntry.getField("doi"), null);
+ this.doiEntry = doiFetcher.getEntryFromDOI(this.originalEntry.getField("doi")).orElse(null);
if (this.doiEntry == null) {
panel.output("");
diff --git a/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java b/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java
index d83c1c7719..5ad05a0eb6 100644
--- a/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java
+++ b/src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java
@@ -1,28 +1,10 @@
-/* Copyright (C) 2014 JabRef contributors.
- Copyright (C) 2015 Oliver Kopp
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
package net.sf.jabref.importer.fetcher;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
-import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
-import java.util.Objects;
import java.util.Optional;
import javax.swing.JPanel;
@@ -50,24 +32,21 @@ public class DOItoBibTeXFetcher implements EntryFetcher {
private final ProtectTermsFormatter protectTermsFormatter = new ProtectTermsFormatter();
private final UnitsToLatexFormatter unitsToLatexFormatter = new UnitsToLatexFormatter();
-
@Override
public void stopFetching() {
- // nothing needed as the fetching is a single HTTP GET
+ // not needed as the fetching is a single HTTP GET
}
@Override
public boolean processQuery(String query, ImportInspector inspector, OutputPrinter status) {
ParserResult parserResult = new ParserResult();
- BibEntry entry = getEntryFromDOI(query, parserResult);
- if(parserResult.hasWarnings()) {
+ Optional<BibEntry> entry = getEntryFromDOI(query, parserResult);
+ if (parserResult.hasWarnings()) {
status.showMessage(parserResult.getErrorMessage());
}
- if (entry != null) {
- inspector.addEntry(entry);
- return true;
- }
- return false;
+ entry.ifPresent(e -> inspector.addEntry(e));
+
+ return entry.isPresent();
}
@Override
@@ -86,67 +65,73 @@ public class DOItoBibTeXFetcher implements EntryFetcher {
return null;
}
- public BibEntry getEntryFromDOI(String doiStr, ParserResult parserResult) {
- Objects.requireNonNull(parserResult);
-
- DOI doi;
- try {
- doi = new DOI(doiStr);
- } catch (IllegalArgumentException e) {
- parserResult.addWarning(Localization.lang("Invalid DOI: '%0'.", doiStr));
- return null;
- }
+ public Optional<BibEntry> getEntryFromDOI(String doiStr) {
+ return getEntryFromDOI(doiStr, null);
+ }
- // Send the request
+ public Optional<BibEntry> getEntryFromDOI(String doiStr, ParserResult parserResult) {
+ Optional<DOI> doi = DOI.build(doiStr);
- // construct URL
- URL url;
- try {
- Optional<URI> uri = doi.getURI();
- if (uri.isPresent()) {
- url = uri.get().toURL();
- } else {
- return null;
+ if (!doi.isPresent()) {
+ if (parserResult != null) {
+ parserResult.addWarning(Localization.lang("Invalid DOI: '%0'.", doiStr));
}
- } catch (MalformedURLException e) {
- LOGGER.warn("Bad URL", e);
- return null;
+ return Optional.empty();
}
- String bibtexString = "";
try {
- URLDownload dl = new URLDownload(url);
- dl.addParameters("Accept", "application/x-bibtex");
- bibtexString = dl.downloadToString(StandardCharsets.UTF_8);
+ URL doiURL = new URL(doi.get().getURIAsASCIIString());
+
+ // BibTeX data
+ URLDownload download = new URLDownload(doiURL);
+ download.addParameters("Accept", "application/x-bibtex");
+ String bibtexString = download.downloadToString(StandardCharsets.UTF_8);
+ bibtexString = cleanupEncoding(bibtexString);
+
+ // BibTeX entry
+ BibEntry entry = BibtexParser.singleFromString(bibtexString);
+
+ if (entry == null) {
+ return Optional.empty();
+ }
+ // Optionally re-format BibTeX entry
+ formatTitleField(entry);
+
+ return Optional.of(entry);
+ } catch (MalformedURLException e) {
+ LOGGER.warn("Bad DOI URL", e);
+ return Optional.empty();
} catch (FileNotFoundException e) {
- parserResult.addWarning(Localization.lang("Unknown DOI: '%0'.", doi.getDOI()));
+ if (parserResult != null) {
+ parserResult.addWarning(Localization.lang("Unknown DOI: '%0'.", doi.get().getDOI()));
+ }
LOGGER.debug("Unknown DOI", e);
- return null;
+ return Optional.empty();
} catch (IOException e) {
LOGGER.warn("Communication problems", e);
- return null;
+ return Optional.empty();
}
+ }
- //Usually includes an en-dash in the page range. Char is in cp1252 but not
+ private void formatTitleField(BibEntry entry) {
+ // Optionally add curly brackets around key words to keep the case
+ entry.getFieldOptional("title").ifPresent(title -> {
+ // Unit formatting
+ if (Globals.prefs.getBoolean(JabRefPreferences.USE_UNIT_FORMATTER_ON_SEARCH)) {
+ title = unitsToLatexFormatter.format(title);
+ }
+
+ // Case keeping
+ if (Globals.prefs.getBoolean(JabRefPreferences.USE_CASE_KEEPER_ON_SEARCH)) {
+ title = protectTermsFormatter.format(title);
+ }
+ entry.setField("title", title);
+ });
+ }
+
+ private String cleanupEncoding(String bibtex) {
+ // Usually includes an en-dash in the page range. Char is in cp1252 but not
// ISO 8859-1 (which is what latex expects). For convenience replace here.
- bibtexString = bibtexString.replaceAll("(pages=\\\\{[0-9]+)\\u2013([0-9]+\\\\})", "$1--$2");
- BibEntry entry = BibtexParser.singleFromString(bibtexString);
-
- if (entry != null) {
- // Optionally add curly brackets around key words to keep the case
- entry.getFieldOptional("title").ifPresent(title -> {
- // Unit formatting
- if (Globals.prefs.getBoolean(JabRefPreferences.USE_UNIT_FORMATTER_ON_SEARCH)) {
- title = unitsToLatexFormatter.format(title);
- }
-
- // Case keeping
- if (Globals.prefs.getBoolean(JabRefPreferences.USE_CASE_KEEPER_ON_SEARCH)) {
- title = protectTermsFormatter.format(title);
- }
- entry.setField("title", title);
- });
- }
- return entry;
+ return bibtex.replaceAll("(pages=\\\\{[0-9]+)\\u2013([0-9]+\\\\})", "$1--$2");
}
}
diff --git a/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java b/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java
index a9a412ee97..08a8856998 100644
--- a/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java
+++ b/src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java
@@ -199,8 +199,8 @@ public class PdfContentImporter extends ImportFormat {
Optional<DOI> doi = DOI.findInText(firstPageContents);
if (doi.isPresent()) {
ParserResult parserResult = new ParserResult(result);
- BibEntry entry = DOI_TO_BIBTEX_FETCHER.getEntryFromDOI(doi.get().getDOI(), parserResult);
- parserResult.getDatabase().insertEntry(entry);
+ Optional<BibEntry> entry = DOI_TO_BIBTEX_FETCHER.getEntryFromDOI(doi.get().getDOI(), parserResult);
+ entry.ifPresent(e -> parserResult.getDatabase().insertEntry(e));
return parserResult;
}
diff --git a/src/main/java/net/sf/jabref/logic/fulltext/DoiResolution.java b/src/main/java/net/sf/jabref/logic/fulltext/DoiResolution.java
index 0ee73cfa7a..f4e3098fe7 100644
--- a/src/main/java/net/sf/jabref/logic/fulltext/DoiResolution.java
+++ b/src/main/java/net/sf/jabref/logic/fulltext/DoiResolution.java
@@ -48,7 +48,7 @@ public class DoiResolution implements FullTextFinder {
Optional<DOI> doi = DOI.build(entry.getField("doi"));
if(doi.isPresent()) {
- String sciLink = doi.get().getURLAsASCIIString();
+ String sciLink = doi.get().getURIAsASCIIString();
// follow all redirects and scan for a single pdf link
if (!sciLink.isEmpty()) {
diff --git a/src/main/java/net/sf/jabref/logic/layout/format/DOICheck.java b/src/main/java/net/sf/jabref/logic/layout/format/DOICheck.java
index d3c9d22cc4..4ac3f9ce7c 100644
--- a/src/main/java/net/sf/jabref/logic/layout/format/DOICheck.java
+++ b/src/main/java/net/sf/jabref/logic/layout/format/DOICheck.java
@@ -33,6 +33,6 @@ public class DOICheck implements LayoutFormatter {
if (result.startsWith("/")) {
result = result.substring(1);
}
- return DOI.build(result).map(DOI::getURLAsASCIIString).orElse(result);
+ return DOI.build(result).map(DOI::getURIAsASCIIString).orElse(result);
}
}
diff --git a/src/main/java/net/sf/jabref/logic/util/DOI.java b/src/main/java/net/sf/jabref/logic/util/DOI.java
index 55cbfc614f..08814fa5f4 100644
--- a/src/main/java/net/sf/jabref/logic/util/DOI.java
+++ b/src/main/java/net/sf/jabref/logic/util/DOI.java
@@ -163,7 +163,7 @@ public class DOI {
*
* @return an encoded URL representation of the DOI
*/
- public String getURLAsASCIIString() {
+ public String getURIAsASCIIString() {
return getURI().map(URI::toASCIIString).orElse("");
}
}
diff --git a/src/test/java/net/sf/jabref/logic/util/DOITest.java b/src/test/java/net/sf/jabref/logic/util/DOITest.java
index 859905ca87..b679ca5685 100644
--- a/src/test/java/net/sf/jabref/logic/util/DOITest.java
+++ b/src/test/java/net/sf/jabref/logic/util/DOITest.java
@@ -95,23 +95,23 @@ public class DOITest {
public void correctlyEncodeDOIs() {
// See http://www.doi.org/doi_handbook/2_Numbering.html#2.5.2.4
// % -> (%25)
- Assert.assertEquals("http://doi.org/10.1006/rwei.1999%25.0001", new DOI("http://doi.org/10.1006/rwei.1999%25.0001").getURLAsASCIIString());
+ Assert.assertEquals("http://doi.org/10.1006/rwei.1999%25.0001", new DOI("http://doi.org/10.1006/rwei.1999%25.0001").getURIAsASCIIString());
// " -> (%22)
- Assert.assertEquals("http://doi.org/10.1006/rwei.1999%22.0001", new DOI("http://doi.org/10.1006/rwei.1999%22.0001").getURLAsASCIIString());
+ Assert.assertEquals("http://doi.org/10.1006/rwei.1999%22.0001", new DOI("http://doi.org/10.1006/rwei.1999%22.0001").getURIAsASCIIString());
// # -> (%23)
- Assert.assertEquals("http://doi.org/10.1006/rwei.1999%23.0001", new DOI("http://doi.org/10.1006/rwei.1999%23.0001").getURLAsASCIIString());
+ Assert.assertEquals("http://doi.org/10.1006/rwei.1999%23.0001", new DOI("http://doi.org/10.1006/rwei.1999%23.0001").getURIAsASCIIString());
// SPACE -> (%20)
- Assert.assertEquals("http://doi.org/10.1006/rwei.1999%20.0001", new DOI("http://doi.org/10.1006/rwei.1999%20.0001").getURLAsASCIIString());
+ Assert.assertEquals("http://doi.org/10.1006/rwei.1999%20.0001", new DOI("http://doi.org/10.1006/rwei.1999%20.0001").getURIAsASCIIString());
// ? -> (%3F)
- Assert.assertEquals("http://doi.org/10.1006/rwei.1999%3F.0001", new DOI("http://doi.org/10.1006/rwei.1999%3F.0001").getURLAsASCIIString());
+ Assert.assertEquals("http://doi.org/10.1006/rwei.1999%3F.0001", new DOI("http://doi.org/10.1006/rwei.1999%3F.0001").getURIAsASCIIString());
}
@Test
public void constructCorrectURLForDoi() {
// add / to RESOLVER url if missing
- Assert.assertEquals("http://doi.org/10.1006/jmbi.1998.2354", new DOI("10.1006/jmbi.1998.2354").getURLAsASCIIString());
- Assert.assertEquals("http://doi.org/10.1006/jmbi.1998.2354", new DOI("http://doi.org/10.1006/jmbi.1998.2354").getURLAsASCIIString());
- Assert.assertEquals("http://doi.org/10.1109/VLHCC.2004.20", new DOI("doi:10.1109/VLHCC.2004.20").getURLAsASCIIString());
+ Assert.assertEquals("http://doi.org/10.1006/jmbi.1998.2354", new DOI("10.1006/jmbi.1998.2354").getURIAsASCIIString());
+ Assert.assertEquals("http://doi.org/10.1006/jmbi.1998.2354", new DOI("http://doi.org/10.1006/jmbi.1998.2354").getURIAsASCIIString());
+ Assert.assertEquals("http://doi.org/10.1109/VLHCC.2004.20", new DOI("doi:10.1109/VLHCC.2004.20").getURIAsASCIIString());
}
@Test | ['src/main/java/net/sf/jabref/gui/mergeentries/MergeEntryDOIDialog.java', 'src/main/java/net/sf/jabref/importer/fetcher/DOItoBibTeXFetcher.java', 'src/main/java/net/sf/jabref/logic/util/DOI.java', 'src/main/java/net/sf/jabref/gui/desktop/JabRefDesktop.java', 'src/test/java/net/sf/jabref/logic/util/DOITest.java', 'src/main/java/net/sf/jabref/logic/fulltext/DoiResolution.java', 'src/main/java/net/sf/jabref/importer/fileformat/PdfContentImporter.java', 'src/main/java/net/sf/jabref/logic/layout/format/DOICheck.java', 'src/main/java/net/sf/jabref/gui/ClipBoardManager.java'] | {'.java': 9} | 9 | 9 | 0 | 0 | 9 | 4,736,870 | 986,990 | 125,911 | 729 | 7,481 | 1,567 | 162 | 8 | 3,565 | 166 | 803 | 55 | 1 | 1 | 2016-05-30T12:52:52 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
467 | jabref/jabref/1168/1163 | jabref | jabref | https://github.com/JabRef/jabref/issues/1163 | https://github.com/JabRef/jabref/pull/1168 | https://github.com/JabRef/jabref/pull/1168 | 1 | fix | Year sorting doesn't work | Clicking on the year column doesn't affect the sorting of the table.
| cc2f992eacc88166fa95bd12f508f1962fbd3486 | a68daaaf575e23e05c35a9c976896e781c5251a3 | https://github.com/jabref/jabref/compare/cc2f992eacc88166fa95bd12f508f1962fbd3486...a68daaaf575e23e05c35a9c976896e781c5251a3 | diff --git a/src/main/java/net/sf/jabref/bibtex/comparator/FieldComparator.java b/src/main/java/net/sf/jabref/bibtex/comparator/FieldComparator.java
index c3058ec841..43cd246174 100644
--- a/src/main/java/net/sf/jabref/bibtex/comparator/FieldComparator.java
+++ b/src/main/java/net/sf/jabref/bibtex/comparator/FieldComparator.java
@@ -22,7 +22,6 @@ import net.sf.jabref.logic.config.SaveOrderConfig;
import net.sf.jabref.logic.util.strings.StringUtil;
import net.sf.jabref.model.entry.AuthorList;
import net.sf.jabref.model.entry.MonthUtil;
-import net.sf.jabref.model.entry.YearUtil;
import net.sf.jabref.model.entry.BibEntry;
import java.text.Collator;
@@ -57,8 +56,6 @@ public class FieldComparator implements Comparator<BibEntry> {
}
}
-
-
enum FieldType {
NAME, TYPE, YEAR, MONTH, OTHER;
}
@@ -139,7 +136,10 @@ public class FieldComparator implements Comparator<BibEntry> {
f1 = AuthorList.fixAuthorForAlphabetization(f1);
f2 = AuthorList.fixAuthorForAlphabetization(f2);
} else if (fieldType == FieldType.YEAR) {
- return Integer.compare(YearUtil.toFourDigitYearWithInts(f1), YearUtil.toFourDigitYearWithInts(f2)) * multiplier;
+ Integer f1year = StringUtil.intValueOfWithNull(f1);
+ Integer f2year = StringUtil.intValueOfWithNull(f2);
+ int comparisonResult = Integer.compare(f1year == null ? 0 : f1year, f2year == null ? 0 : f2year);
+ return comparisonResult * multiplier;
} else if (fieldType == FieldType.MONTH) {
return Integer.compare(MonthUtil.getMonth(f1).number, MonthUtil.getMonth(f2).number) * multiplier;
}
diff --git a/src/main/java/net/sf/jabref/model/entry/BibEntry.java b/src/main/java/net/sf/jabref/model/entry/BibEntry.java
index 3091ca2fd1..5ff8a809fa 100644
--- a/src/main/java/net/sf/jabref/model/entry/BibEntry.java
+++ b/src/main/java/net/sf/jabref/model/entry/BibEntry.java
@@ -497,7 +497,7 @@ public class BibEntry {
return null;
}
- String year = YearUtil.toFourDigitYear(getField("year"));
+ String year = getField("year");
if (hasField("month")) {
MonthUtil.Month month = MonthUtil.getMonth(getField("month"));
diff --git a/src/main/java/net/sf/jabref/model/entry/YearUtil.java b/src/main/java/net/sf/jabref/model/entry/YearUtil.java
deleted file mode 100644
index 23e1f3da1d..0000000000
--- a/src/main/java/net/sf/jabref/model/entry/YearUtil.java
+++ /dev/null
@@ -1,124 +0,0 @@
-package net.sf.jabref.model.entry;
-
-import java.util.Calendar;
-
-public class YearUtil {
-
- private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR);
-
- /**
- * Will convert a two digit year using the following scheme (describe at
- * http://www.filemaker.com/help/02-Adding%20and%20view18.html):
- * <p/>
- * If a two digit year is encountered they are matched against the last 69
- * years and future 30 years.
- * <p/>
- * For instance if it is the year 1992 then entering 23 is taken to be 1923
- * but if you enter 23 in 1993 then it will evaluate to 2023.
- *
- * @param year The year to convert to 4 digits.
- * @return
- */
- public static String toFourDigitYear(String year) {
- return YearUtil.toFourDigitYear(year, YearUtil.CURRENT_YEAR);
- }
-
- /**
- * Will convert a two digit year using the following scheme (describe at
- * http://www.filemaker.com/help/02-Adding%20and%20view18.html):
- * <p/>
- * If a two digit year is encountered they are matched against the last 69
- * years and future 30 years.
- * <p/>
- * For instance if it is the year 1992 then entering 23 is taken to be 1923
- * but if you enter 23 in 1993 then it will evaluate to 2023.
- *
- * @param year The year to convert to 4 digits.
- * @return
- */
- static String toFourDigitYear(String year, int thisYear) {
- if ((year == null) || (year.length() != 2)) {
- return year;
- }
-
- Integer yearNumber = intValueOfWithNull(year);
- if (yearNumber == null) {
- return year;
- }
-
- return String.valueOf(new Year(thisYear).toFourDigitYear(yearNumber));
- }
-
- public static int toFourDigitYearWithInts(String year) {
- return YearUtil.toFourDigitYearWithInts(year, YearUtil.CURRENT_YEAR);
- }
-
- private static int toFourDigitYearWithInts(String year, int thisYear) {
- if ((year == null) || (year.length() != 2)) {
- return 0;
- }
-
- Integer yearNumber = intValueOfWithNull(year);
- if (yearNumber == null) {
- return 0;
- }
-
- return new Year(thisYear).toFourDigitYear(yearNumber);
- }
-
- private static Integer intValueOfWithNull(String str) {
- int idx = 0;
- int end;
- boolean sign = false;
- char ch;
-
- if ((str == null) || ((end = str.length()) == 0) || ((((ch = str.charAt(0)) < '0') || (ch > '9')) && (!(sign = ch == '-') || (++idx == end) || ((ch = str.charAt(idx)) < '0') || (ch > '9')))) {
- return null;
- }
-
- int ival = 0;
- for (; ; ival *= 10) {
- ival += '0' - ch;
- if (++idx == end) {
- return sign ? ival : -ival;
- }
- if (((ch = str.charAt(idx)) < '0') || (ch > '9')) {
- return null;
- }
- }
- }
-
- private static class Year {
-
- private final int year;
- private final int century;
- private final int yearShort;
-
- public Year(int year) {
- this.year = year;
- this.yearShort = this.year % 100;
- this.century = (this.year / 100) * 100;
- }
-
- public int toFourDigitYear(int relativeYear) {
- if (relativeYear == yearShort) {
- return this.year;
- }
- // 20 , 90
- // 99 > 30
- if ((((relativeYear + 100) - yearShort) % 100) > 30) {
- if (relativeYear < yearShort) {
- return century + relativeYear;
- } else {
- return (century - 100) + relativeYear;
- }
- } else {
- if (relativeYear < yearShort) {
- return century + 100 + relativeYear;
- } else {
- return century + relativeYear;
- }
- }
- }
- }
-}
diff --git a/src/test/java/net/sf/jabref/model/entry/BibtexEntryTests.java b/src/test/java/net/sf/jabref/model/entry/BibtexEntryTests.java
index ac3708a80e..85389b8ba2 100644
--- a/src/test/java/net/sf/jabref/model/entry/BibtexEntryTests.java
+++ b/src/test/java/net/sf/jabref/model/entry/BibtexEntryTests.java
@@ -133,7 +133,7 @@ public class BibtexEntryTests {
(BibtexParser.singleFromString("@ARTICLE{HipKro03, author={bla}}")).getPublicationDate());
Assert.assertEquals("2003-12",
- (BibtexParser.singleFromString("@ARTICLE{HipKro03, year = {03}, month = #DEC# }"))
+ (BibtexParser.singleFromString("@ARTICLE{HipKro03, year = {2003}, month = #DEC# }"))
.getPublicationDate());
}
diff --git a/src/test/java/net/sf/jabref/model/entry/YearUtilTest.java b/src/test/java/net/sf/jabref/model/entry/YearUtilTest.java
deleted file mode 100644
index bb8c967bad..0000000000
--- a/src/test/java/net/sf/jabref/model/entry/YearUtilTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package net.sf.jabref.model.entry;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.text.DecimalFormat;
-import java.text.NumberFormat;
-import java.util.Calendar;
-
-public class YearUtilTest {
-
- @Test
- public void test2to4DigitsYear() {
- Assert.assertEquals("1990", YearUtil.toFourDigitYear("1990"));
- Assert.assertEquals("190", YearUtil.toFourDigitYear("190"));
- Assert.assertEquals("1990", YearUtil.toFourDigitYear("90", 1990));
- Assert.assertEquals("1990", YearUtil.toFourDigitYear("90", 1991));
- Assert.assertEquals("2020", YearUtil.toFourDigitYear("20", 1990));
- Assert.assertEquals("1921", YearUtil.toFourDigitYear("21", 1990));
- Assert.assertEquals("1922", YearUtil.toFourDigitYear("22", 1990));
- Assert.assertEquals("2022", YearUtil.toFourDigitYear("22", 1992));
- Assert.assertEquals("1999", YearUtil.toFourDigitYear("99", 2001));
- Assert.assertEquals("1931", YearUtil.toFourDigitYear("1931", 2001));
- Assert.assertEquals("2031", YearUtil.toFourDigitYear("31", 2001));
- Assert.assertEquals("1932", YearUtil.toFourDigitYear("32", 2001));
- Assert.assertEquals("1944", YearUtil.toFourDigitYear("44", 2001));
- Assert.assertEquals("2011", YearUtil.toFourDigitYear("11", 2001));
- Assert.assertEquals("2005a", YearUtil.toFourDigitYear("2005a"));
- Assert.assertEquals("2005b", YearUtil.toFourDigitYear("2005b"));
-
- int thisYear = Calendar.getInstance().get(Calendar.YEAR);
- int d2 = thisYear % 100;
-
- NumberFormat f = new DecimalFormat("00");
-
- for (int i = 0; i <= 30; i++) {
- Assert.assertTrue(String.valueOf(i), thisYear <= Integer.parseInt(YearUtil.toFourDigitYear(f.format((d2 + i) % 100))));
- }
- for (int i = 0; i < 70; i++) {
- Assert.assertTrue(String.valueOf(i), thisYear >= Integer.parseInt(YearUtil.toFourDigitYear(f.format((d2 - i + 100) % 100))));
- }
- }
-
-}
\\ No newline at end of file | ['src/test/java/net/sf/jabref/model/entry/YearUtilTest.java', 'src/main/java/net/sf/jabref/model/entry/BibEntry.java', 'src/main/java/net/sf/jabref/bibtex/comparator/FieldComparator.java', 'src/test/java/net/sf/jabref/model/entry/BibtexEntryTests.java', 'src/main/java/net/sf/jabref/model/entry/YearUtil.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 4,668,297 | 972,721 | 123,549 | 722 | 4,611 | 1,100 | 134 | 3 | 69 | 12 | 15 | 2 | 0 | 0 | 2016-04-11T19:40:05 | 3,074 | Java | {'Java': 8932171, 'TeX': 710947, 'XSLT': 151896, 'CSS': 54744, 'Ruby': 20199, 'Shell': 9437, 'Python': 9240, 'Groovy': 5264, 'ANTLR': 3775, 'PowerShell': 2028, 'AppleScript': 1622, 'GAP': 1470, 'Batchfile': 637} | MIT License |
535 | altbeacon/android-beacon-library/878/814 | altbeacon | android-beacon-library | https://github.com/AltBeacon/android-beacon-library/issues/814 | https://github.com/AltBeacon/android-beacon-library/pull/878 | https://github.com/AltBeacon/android-beacon-library/pull/878 | 2 | fix | ANRs due to the ScanState.restore being called on the main thread | In our app we listen to the bluetooth state changes when the app is in the foreground so that we can stop foreground beacon scans manually and start them again once the Bluetooth is on again.
Some time ago we started noticing ANRs happening on rare occasions, the relevant part of stackrace (not sure if this term is applicable to the ANRs though) looks like this:
```
"main" tid=1 Runnable Performing disk I/O
"main" prio=5 tid=1 Runnable
| group="main" sCount=0 dsCount=0 flags=0 obj=0x73fa1a78 self=0x7d37414c00
| sysTid=11757 nice=-10 cgrp=default sched=0/0 handle=0x7dbcde5548
| state=R schedstat=( 503793695236 32744365477 307265 ) utm=31364 stm=19014 core=3 HZ=100
| stack=0x7fea04b000-0x7fea04d000 stackSize=8MB
| held mutexes= "mutator lock"(shared held)
#00 pc 00000000003c8d04 /system/lib64/libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, int, BacktraceMap*, char const*, art::ArtMethod*, void*, bool)+220)
#01 pc 0000000000498b90 /system/lib64/libart.so (art::Thread::DumpStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool, BacktraceMap*, bool) const+352)
#02 pc 00000000004b29a4 /system/lib64/libart.so (art::DumpCheckpoint::Run(art::Thread*)+828)
#03 pc 0000000000499860 /system/lib64/libart.so (art::Thread::RunCheckpointFunction()+204)
#04 pc 00000000003776f8 /system/lib64/libart.so (art::JNI::GetByteArrayElements(_JNIEnv*, _jbyteArray*, unsigned char*)+1316)
#05 pc 000000000002f744 /system/lib64/libjavacore.so (Linux_readBytes(_JNIEnv*, _jobject*, _jobject*, _jobject*, int, int)+128)
at libcore.io.Linux.readBytes (Linux.java)
at libcore.io.Linux.read (Linux.java:184)
at libcore.io.BlockGuardOs.read (BlockGuardOs.java:254)
at libcore.io.IoBridge.read (IoBridge.java:501)
at java.io.FileInputStream.read (FileInputStream.java:307)
at java.io.FileInputStream.read (FileInputStream.java:245)
at java.io.ObjectInputStream$PeekInputStream.peek (ObjectInputStream.java:2312)
at java.io.ObjectInputStream$BlockDataInputStream.peek (ObjectInputStream.java:2605)
at java.io.ObjectInputStream$BlockDataInputStream.peekByte (ObjectInputStream.java:2615)
at java.io.ObjectInputStream.readClassDesc (ObjectInputStream.java:1508)
at java.io.ObjectInputStream.readOrdinaryObject (ObjectInputStream.java:1776)
at java.io.ObjectInputStream.readObject0 (ObjectInputStream.java:1353)
at java.io.ObjectInputStream.defaultReadFields (ObjectInputStream.java:2002)
at java.io.ObjectInputStream.readSerialData (ObjectInputStream.java:1926)
at java.io.ObjectInputStream.readOrdinaryObject (ObjectInputStream.java:1803)
at java.io.ObjectInputStream.readObject0 (ObjectInputStream.java:1353)
at java.io.ObjectInputStream.readObject (ObjectInputStream.java:373)
at java.util.HashSet.readObject (HashSet.java:333)
at java.lang.reflect.Method.invoke (Method.java)
at java.io.ObjectStreamClass.invokeReadObject (ObjectStreamClass.java:1067)
at java.io.ObjectInputStream.readSerialData (ObjectInputStream.java:1902)
at java.io.ObjectInputStream.readOrdinaryObject (ObjectInputStream.java:1803)
at java.io.ObjectInputStream.readObject0 (ObjectInputStream.java:1353)
at java.io.ObjectInputStream.defaultReadFields (ObjectInputStream.java:2002)
at java.io.ObjectInputStream.readSerialData (ObjectInputStream.java:1926)
at java.io.ObjectInputStream.readOrdinaryObject (ObjectInputStream.java:1803)
at java.io.ObjectInputStream.readObject0 (ObjectInputStream.java:1353)
at java.io.ObjectInputStream.readObject (ObjectInputStream.java:373)
at org.altbeacon.beacon.service.ScanState.restore (ScanState.java)
- locked <0x02c2bafd> (a java.lang.Class<org.altbeacon.beacon.service.ScanState>)
at org.altbeacon.beacon.service.ScanJobScheduler.applySettingsToScheduledJob (ScanJobScheduler.java)
at org.altbeacon.beacon.BeaconManager.applyChangesToServices (BeaconManager.java)
at org.altbeacon.beacon.BeaconManager.startMonitoringBeaconsInRegion (BeaconManager.java)
at org.altbeacon.beacon.startup.RegionBootstrap$InternalBeaconConsumer.onBeaconServiceConnect (RegionBootstrap.java)
at org.altbeacon.beacon.BeaconManager.bind (BeaconManager.java)
- locked <0x09cec503> (a java.util.concurrent.ConcurrentHashMap)
at org.altbeacon.beacon.startup.RegionBootstrap.<init> (RegionBootstrap.java)
```
This does not affect ALL devices though - we were not able to reproduce it on some Xiaomi devices we have and my own Nexus 5 does not seem to be affected either (I guess it could be related to the fact that ScanState.restore invocation is guarded by the `mScheduledScanJobsEnabled` and this variable is equal to true only if OS version >= Oreo).
### Expected behavior
The ANR does not occur.
### Actual behavior
The app literally hangs and stops responding to the user input. Sometimes it leads to the ANR, sometimes the app starts listening to user input within 2-3 seconds.
### Steps to reproduce this behavior
The way we're able to reproduce it is following:
1. Stand close to the ibeacon so that the app is able to see it.
2. Open the notifications drawer, turn Bluetooth off, then turn it on.
3. App hangs and does not respond. Sometimes it leads to ANR, sometimes the app is able to return to normal state.
### Mobile device model and OS version
Google Pixel
Google Pixel 2 XL
Samsung S8+
### Android Beacon Library version
2.15.4
IMPORTANT: This forum is reserved for feature requests or reproducible bugs with the library itself. If you need help with using the library with your project, please open a new question on StackOverflow.com.
| f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3 | d3c1490f0498fcd0cf49071391270f1544795a79 | https://github.com/altbeacon/android-beacon-library/compare/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3...d3c1490f0498fcd0cf49071391270f1544795a79 | diff --git a/lib/src/main/java/org/altbeacon/beacon/service/ScanJob.java b/lib/src/main/java/org/altbeacon/beacon/service/ScanJob.java
index 18b6665..b13e0e9 100644
--- a/lib/src/main/java/org/altbeacon/beacon/service/ScanJob.java
+++ b/lib/src/main/java/org/altbeacon/beacon/service/ScanJob.java
@@ -54,63 +54,71 @@ public class ScanJob extends JobService {
@Override
public boolean onStartJob(final JobParameters jobParameters) {
- if (!initialzeScanHelper()) {
- LogManager.e(TAG, "Cannot allocate a scanner to look for beacons. System resources are low.");
- return false;
- }
- ScanJobScheduler.getInstance().ensureNotificationProcessorSetup(getApplicationContext());
- if (jobParameters.getJobId() == getImmediateScanJobId(this)) {
- LogManager.i(TAG, "Running immediate scan job: instance is "+this);
- }
- else {
- LogManager.i(TAG, "Running periodic scan job: instance is "+this);
- }
-
- List<ScanResult> queuedScanResults = ScanJobScheduler.getInstance().dumpBackgroundScanResultQueue();
- LogManager.d(TAG, "Processing %d queued scan resuilts", queuedScanResults.size());
- for (ScanResult result : queuedScanResults) {
- ScanRecord scanRecord = result.getScanRecord();
- if (scanRecord != null) {
- mScanHelper.processScanResult(result.getDevice(), result.getRssi(), scanRecord.getBytes());
- }
- }
- LogManager.d(TAG, "Done processing queued scan resuilts");
+ // We start off on the main UI thread here.
+ // But the ScanState restore from storage sometimes hangs, so we start new thread here just
+ // to kick that off. This way if the restore hangs, we don't hang the UI thread.
+ new Thread(new Runnable() {
+ public void run() {
+ if (!initialzeScanHelper()) {
+ LogManager.e(TAG, "Cannot allocate a scanner to look for beacons. System resources are low.");
+ ScanJob.this.jobFinished(jobParameters , false);
+ }
+ ScanJobScheduler.getInstance().ensureNotificationProcessorSetup(getApplicationContext());
+ if (jobParameters.getJobId() == getImmediateScanJobId(ScanJob.this)) {
+ LogManager.i(TAG, "Running immediate scan job: instance is "+this);
+ }
+ else {
+ LogManager.i(TAG, "Running periodic scan job: instance is "+this);
+ }
- boolean startedScan;
- if (mInitialized) {
- LogManager.d(TAG, "Scanning already started. Resetting for current parameters");
- startedScan = restartScanning();
- }
- else {
- startedScan = startScanning();
- }
- mStopHandler.removeCallbacksAndMessages(null);
+ List<ScanResult> queuedScanResults = ScanJobScheduler.getInstance().dumpBackgroundScanResultQueue();
+ LogManager.d(TAG, "Processing %d queued scan resuilts", queuedScanResults.size());
+ for (ScanResult result : queuedScanResults) {
+ ScanRecord scanRecord = result.getScanRecord();
+ if (scanRecord != null) {
+ mScanHelper.processScanResult(result.getDevice(), result.getRssi(), scanRecord.getBytes());
+ }
+ }
+ LogManager.d(TAG, "Done processing queued scan resuilts");
- if (startedScan) {
- LogManager.i(TAG, "Scan job running for "+mScanState.getScanJobRuntimeMillis()+" millis");
- mStopHandler.postDelayed(new Runnable() {
- @Override
- public void run() {
- LogManager.i(TAG, "Scan job runtime expired: " + ScanJob.this);
- stopScanning();
- mScanState.save();
- ScanJob.this.jobFinished(jobParameters , false);
+ boolean startedScan;
+ if (mInitialized) {
+ LogManager.d(TAG, "Scanning already started. Resetting for current parameters");
+ startedScan = restartScanning();
+ }
+ else {
+ startedScan = startScanning();
+ }
+ mStopHandler.removeCallbacksAndMessages(null);
- // need to execute this after the current block or Android stops this job prematurely
- mStopHandler.post(new Runnable() {
+ if (startedScan) {
+ LogManager.i(TAG, "Scan job running for "+mScanState.getScanJobRuntimeMillis()+" millis");
+ mStopHandler.postDelayed(new Runnable() {
@Override
public void run() {
- scheduleNextScan();
- }
- });
+ LogManager.i(TAG, "Scan job runtime expired: " + ScanJob.this);
+ stopScanning();
+ mScanState.save();
+ ScanJob.this.jobFinished(jobParameters , false);
+ // need to execute this after the current block or Android stops this job prematurely
+ mStopHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ scheduleNextScan();
+ }
+ });
+
+ }
+ }, mScanState.getScanJobRuntimeMillis());
}
- }, mScanState.getScanJobRuntimeMillis());
- }
- else {
- LogManager.i(TAG, "Scanning not started so Scan job is complete.");
- ScanJob.this.jobFinished(jobParameters , false);
- }
+ else {
+ LogManager.i(TAG, "Scanning not started so Scan job is complete.");
+ ScanJob.this.jobFinished(jobParameters , false);
+ }
+ }
+ }).start();
+
return true;
}
| ['lib/src/main/java/org/altbeacon/beacon/service/ScanJob.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 526,953 | 109,811 | 13,463 | 76 | 5,689 | 980 | 108 | 1 | 5,684 | 497 | 1,467 | 80 | 0 | 1 | 2019-05-15T18:26:42 | 2,758 | Java | {'Java': 766605, 'Kotlin': 17054} | Apache License 2.0 |
536 | altbeacon/android-beacon-library/381/143 | altbeacon | android-beacon-library | https://github.com/AltBeacon/android-beacon-library/issues/143 | https://github.com/AltBeacon/android-beacon-library/pull/381 | https://github.com/AltBeacon/android-beacon-library/pull/381 | 2 | fix | getInstanceForApplication should be renamed & is prone to context leaks | getInstanceForApplication or the BeaconManager class should probably call getApplicationContext on the application context to prevent leaks.
The suggested use for the BeaconManager is from an activity, like so:
`private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);`
To prevent the activity being leaked, the beaconmanager should really make sure it calls `getApplicationContext` on the passed context.
Secondly `getInstanceForApplication` implies you should be passing an application to the method, simply `getInstance` might be better
| 1c091d8f6bb0bc5c36969cc95536b5ec7aa438f4 | 2e3b396fbef2d929376c18acd8835316e7d9b75e | https://github.com/altbeacon/android-beacon-library/compare/1c091d8f6bb0bc5c36969cc95536b5ec7aa438f4...2e3b396fbef2d929376c18acd8835316e7d9b75e | diff --git a/src/main/java/org/altbeacon/beacon/BeaconManager.java b/src/main/java/org/altbeacon/beacon/BeaconManager.java
index 35b7df6..657d03b 100644
--- a/src/main/java/org/altbeacon/beacon/BeaconManager.java
+++ b/src/main/java/org/altbeacon/beacon/BeaconManager.java
@@ -246,7 +246,7 @@ public class BeaconManager {
}
protected BeaconManager(Context context) {
- mContext = context;
+ mContext = context.getApplicationContext();
if (!sManifestCheckingDisabled) {
verifyServiceDeclaration();
} | ['src/main/java/org/altbeacon/beacon/BeaconManager.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 360,659 | 76,063 | 9,482 | 63 | 77 | 12 | 2 | 1 | 573 | 69 | 102 | 10 | 0 | 0 | 2016-06-01T13:29:38 | 2,758 | Java | {'Java': 766605, 'Kotlin': 17054} | Apache License 2.0 |
532 | altbeacon/android-beacon-library/317/270 | altbeacon | android-beacon-library | https://github.com/AltBeacon/android-beacon-library/issues/270 | https://github.com/AltBeacon/android-beacon-library/pull/317 | https://github.com/AltBeacon/android-beacon-library/pull/317#issuecomment-157298324 | 2 | fixes | Switching from monitoring to ranging during active scan cycle breaks scanning | Hi David,
thanks for your work on this library! I've been using it for a while but I ran into a small issue lately.
So my app monitors beacons with a specific UUID and as soon as it receives a `didEnterRegion` callback, it stops monitoring and starts ranging that same UUID. The problem is that ranging stops within seconds after it has been started.
The relevant code basically looks like this:
``` java
@Override
public void didEnterRegion(Region region) {
mBeaconManager.stopMonitoringBeaconsInRegion(region);
mBeaconManager.startRangingBeaconsInRegion(region);
}
```
I did some debugging and these are the steps that lead to the issue:
1. App calls `startMonitoringBeaconsInRegion()`
2. Starting monitoring calls `mCycledScanner.start()` which sets `mScanningEnabled=true` and calls `scanLeDevice(true)`
3. `scanLeDevice(true)` then sets `mScanCyclerStarted=true`, `mScanning=true` and starts a scan cycle
4. App calls `stopMonitoringBeaconsInRegion()`
5. Stopping monitoring calls `mCycledScanner.stop()` which sets `mScanningEnabled=false` and calls `scanLeDevice(false)`
6. `scanLeDevice(false)` then sets `mScanning=false`
7. App calls `startRangingBeaconsInRegion()`
8. Starting ranging calls `mCycledScanner.start()` which sets `mScanningEnabled=true` but does not call `scanLeDevice(true)` as `mScanCyclerStarted` is still `true`
9. At some point in the future `finishScanCycle()` is called as the scan cycle started earlier for monitoring ends
10. `finishScanCycle()` does nothing as `mScanning=false` and `mScanningEnabled=true`
At this point no new scan has been scheduled so scanning stops. It's also impossible to start a new scan as `mScanCyclerStarted=true` and this guards the call to `scanLeDevice(true)` in `start()`. `mScanCyclerStarted` is only reset to `false` in `finishScanCycle()` if `mScanning=true` and `mScanningEnabled=true`, which - if I'm not mistaken - can't be achieved in this situation. Looks like a deadlock.
A workaround for an app is waiting for the scan cycle to finish after calling `stopMonitoringBeaconsInRegion()` and only then call `startRangingBeaconsInRegion()`.
The device I observed this on was a Moto G (2nd gen) with Android 5.0.2 and AndroidLScanning disabled. Library version was 2.5.1.
This is the relevant debug log for reference:
```
BeaconService I start monitoring received
D startMonitoring called
D Currently monitoring 1 regions.
CycledLeScanner D start called
D starting a new scan cycle
D starting a new bluetooth le scan
D Waiting to stop scan cycle for another 1100 milliseconds
D Scan started
D Set scan periods called with 2500, 500 Background mode must have changed.
D We are not in the background. Cancelling wakeup alarm
D cancel wakeup alarm: null
eScannerForJellyBeanMr2 D got record
D got record
BeaconParser D Ignoring pdu type 01
D Processing pdu type FF: 02010617ff4c000512000000000000000001b11468c100000000000000000000000000000000000000000000000000000000000000000000000000000000 with startIndex: 5, endIndex: 26
D This is not a matching Beacon advertisement. (Was expecting 02 15. The bytes I see are: 02010617ff4c000512000000000000000001b11468c100000000000000000000000000000000000000000000000000000000000000000000000000000000
D Ignoring pdu type 01
D Processing pdu type FF: 02011a17ff4c000512000000000000000001b11468c1000000000014ff4c0001000000000000000000000004000000000000000000000000000000000000 with startIndex: 5, endIndex: 26
D This is not a matching Beacon advertisement. (Was expecting 02 15. The bytes I see are: 02011a17ff4c000512000000000000000001b11468c1000000000014ff4c0001000000000000000000000004000000000000000000000000000000000000
CycledLeScanner D Waiting to stop scan cycle for another 98 milliseconds
D Done with scan cycle
D stopping bluetooth le scan
D Normalizing between scan period from 500 to -1781
D starting a new scan cycle
D starting a new bluetooth le scan
D Waiting to stop scan cycle for another 2500 milliseconds
[...]
eScannerForJellyBeanMr2 D got record
BeaconParser D Ignoring pdu type 01
D Processing pdu type FF: 0201061aff4c000215xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx02d2920cc609095069426561636f6e00000000000000000000000000000000000000000000 with startIndex: 5, endIndex: 29
D This is a recognized beacon advertisement -- 02 15 seen
BeaconService D beacon detected : id1: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx id2: 722 id3: 37388
BeaconIntentProcessor D got an intent to process
D got monitoring data
D Calling monitoring notifier: com.dummy.MyBeaconManager@227351d4
BeaconManager D callback packageName: com.dummy
BeaconService I stop monitoring received
D stopMonitoring called
D Currently monitoring 0 regions.
CycledLeScanner D stop called
D disabling scan
D Set scan periods called with 2500, 500 Background mode must have changed.
D We are not in the background. Cancelling wakeup alarm
D cancel wakeup alarm: PendingIntent{7b19601: android.os.BinderProxy@28175ca6}
D Set a wakeup alarm to go off in 9223372036854775807 ms: PendingIntent{7b19601: android.os.BinderProxy@28175ca6}
tartupBroadcastReceiver D onReceive called in startup broadcast receiver
D got wake up intent
BeaconManager D callback packageName: com.dummy
BeaconService I start ranging received
D Currently ranging 1 regions.
CycledLeScanner D start called
D scanning already started
D Set scan periods called with 2500, 500 Background mode must have changed.
D We are not in the background. Cancelling wakeup alarm
D cancel wakeup alarm: PendingIntent{7b19601: android.os.BinderProxy@28175ca6}
D Set a wakeup alarm to go off in 9223372036854775807 ms: PendingIntent{7b19601: android.os.BinderProxy@28175ca6}
tartupBroadcastReceiver D onReceive called in startup broadcast receiver
D got wake up intent
BeaconService D looking for ranging region matches for this beacon
D matches ranging region: id1: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx id2: null id3: null
RangeState D adding id1: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx id2: 722 id3: 37388 to new rangedBeacon
CycledLeScanner D Waiting to stop scan cycle for another 1500 milliseconds
D Waiting to stop scan cycle for another 498 milliseconds
D Done with scan cycle
BeaconService D Calling ranging callback
unningAverageRssiFilter D Running average mRssi based on 1 measurements: -67.0
RangedBeacon D calculated new runningAverageRssi: -67.0
RangingData D writing RangingData
Beacon D serializing identifiers of size 3
ittedDistanceCalculator D calculating distance based on mRssi of -67.0 and txPower of -58
D avg mRssi: -67.0 distance: 1.6966333022995579
Beacon D writing 0 extra data fields to parcel
RangingData D done writing RangingData
BeaconIntentProcessor D got an intent to process
RangingData D parsing RangingData
Beacon D reading 0 extra data fields from parcel
RangingData D parsing RangingData
Beacon D reading 0 extra data fields from parcel
BeaconIntentProcessor D got ranging data
Beacon D Not using running average RSSI because it is null
ittedDistanceCalculator D calculating distance based on mRssi of -67.0 and txPower of -58
D avg mRssi: -67.0 distance: 1.6966333022995579
```
| 4a28c6fc3b0287d24fe28fe1119d04d09ed90b82 | 05e07096c0e2d505bca20e2a2837338522ca0ca3 | https://github.com/altbeacon/android-beacon-library/compare/4a28c6fc3b0287d24fe28fe1119d04d09ed90b82...05e07096c0e2d505bca20e2a2837338522ca0ca3 | diff --git a/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java b/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java
index 573981b..e228de8 100644
--- a/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java
+++ b/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java
@@ -208,7 +208,7 @@ public abstract class CycledLeScanner {
} else {
LogManager.d(TAG, "disabling scan");
mScanning = false;
-
+ mScanCyclerStarted = false;
stopScan();
mLastScanCycleEndTime = new Date().getTime();
} | ['src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 346,634 | 73,212 | 9,095 | 61 | 42 | 10 | 2 | 1 | 8,653 | 914 | 2,074 | 121 | 0 | 2 | 2015-11-17T07:22:17 | 2,758 | Java | {'Java': 766605, 'Kotlin': 17054} | Apache License 2.0 |
537 | altbeacon/android-beacon-library/199/185 | altbeacon | android-beacon-library | https://github.com/AltBeacon/android-beacon-library/issues/185 | https://github.com/AltBeacon/android-beacon-library/pull/199 | https://github.com/AltBeacon/android-beacon-library/pull/199 | 1 | fixes | Stackoverflow error | After updating the library.
I get Stackoverflow error at java.util.Collections
Checking DDMS shows that java.util.Collections are allocated when in writeToParcel:
```
at java.util.Collections$UnmodifiableCollection.iterator(Collections.java:952)
at java.util.Collections$UnmodifiableCollection$1.<init>(Collections.java:953)
at java.util.Collections$UnmodifiableCollection.iterator(Collections.java:952)
at java.util.Collections$UnmodifiableCollection$1.<init>(Collections.java:953)
at java.util.Collections$UnmodifiableCollection.iterator(Collections.java:952)
at java.util.Collections$UnmodifiableCollection$1.<init>(Collections.java:953)
at java.util.Collections$UnmodifiableCollection.iterator(Collections.java:952)
at org.altbeacon.beacon.Beacon.writeToParcel(Beacon.java:524)
at org.altbeacon.beacon.AltBeacon.writeToParcel(AltBeacon.java:115)
at android.os.Parcel.writeParcelable(Parcel.java:1285)
at android.os.Parcel.writeParcelableArray(Parcel.java:1984)
at org.altbeacon.beacon.service.RangingData.writeToParcel(RangingData.java:62)
at android.os.Parcel.writeParcelable(Parcel.java:1285)
at android.os.Parcel.writeValue(Parcel.java:1204)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:618)
at android.os.Bundle.writeToParcel(Bundle.java:1692)
```
It crashed in Emulator, also on Galaxy S5, 4.4.4
| b7536cc79061e8e3091e29ea4980743f28a43c88 | c7affe1438d007b6e0d89af244d7baccdc6e88cb | https://github.com/altbeacon/android-beacon-library/compare/b7536cc79061e8e3091e29ea4980743f28a43c88...c7affe1438d007b6e0d89af244d7baccdc6e88cb | diff --git a/src/main/java/org/altbeacon/beacon/Beacon.java b/src/main/java/org/altbeacon/beacon/Beacon.java
index 7944ae9..6d4dc3c 100644
--- a/src/main/java/org/altbeacon/beacon/Beacon.java
+++ b/src/main/java/org/altbeacon/beacon/Beacon.java
@@ -25,6 +25,7 @@ package org.altbeacon.beacon;
import android.os.Parcel;
import android.os.Parcelable;
+import android.util.Log;
import org.altbeacon.beacon.client.BeaconDataFactory;
import org.altbeacon.beacon.client.NullBeaconDataFactory;
@@ -57,6 +58,11 @@ import java.util.List;
public class Beacon implements Parcelable {
private static final String TAG = "Beacon";
+ private static final List<Long> UNMODIFIABLE_LIST_OF_LONG =
+ Collections.unmodifiableList(new ArrayList<Long>());
+ private static final List<Identifier> UNMODIFIABLE_LIST_OF_IDENTIFIER =
+ Collections.unmodifiableList(new ArrayList<Identifier>());
+
/**
* Determines whether a the bluetoothAddress (mac address) must be the same for two Beacons
* to be configured equal.
@@ -137,7 +143,7 @@ public class Beacon implements Parcelable {
* beacon, this field will be -1
*/
- protected int mServiceUuid;
+ protected int mServiceUuid = -1;
/**
* The Bluetooth device name. This is a field transmitted by the remote beacon device separate
@@ -329,7 +335,12 @@ public class Beacon implements Parcelable {
* @return dataFields
*/
public List<Long> getDataFields() {
- return Collections.unmodifiableList(mDataFields);
+ if (mDataFields.getClass().isInstance(UNMODIFIABLE_LIST_OF_LONG)) {
+ return mDataFields;
+ }
+ else {
+ return Collections.unmodifiableList(mDataFields);
+ }
}
/**
@@ -337,7 +348,12 @@ public class Beacon implements Parcelable {
* @return dataFields
*/
public List<Long> getExtraDataFields() {
- return Collections.unmodifiableList(mExtraDataFields);
+ if (mExtraDataFields.getClass().isInstance(UNMODIFIABLE_LIST_OF_LONG)) {
+ return mExtraDataFields;
+ }
+ else {
+ return Collections.unmodifiableList(mExtraDataFields);
+ }
}
/**
@@ -353,7 +369,12 @@ public class Beacon implements Parcelable {
* @return identifier
*/
public List<Identifier> getIdentifiers() {
- return Collections.unmodifiableList(mIdentifiers);
+ if (mIdentifiers.getClass().isInstance(UNMODIFIABLE_LIST_OF_IDENTIFIER)) {
+ return mIdentifiers;
+ }
+ else {
+ return Collections.unmodifiableList(mIdentifiers);
+ }
}
@@ -754,4 +775,6 @@ public class Beacon implements Parcelable {
}
}
+
+
}
diff --git a/src/test/java/org/altbeacon/beacon/BeaconTest.java b/src/test/java/org/altbeacon/beacon/BeaconTest.java
index 8f78d4f..e77b664 100644
--- a/src/test/java/org/altbeacon/beacon/BeaconTest.java
+++ b/src/test/java/org/altbeacon/beacon/BeaconTest.java
@@ -15,6 +15,8 @@ import org.robolectric.annotation.Config;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
@Config(emulateSdk = 18)
@@ -183,5 +185,16 @@ public class BeaconTest {
assertEquals("data field 0 is the same after deserialization", beacon.getDataFields().get(0), beacon2.getDataFields().get(0));
assertEquals("data field 0 is the right value", beacon.getDataFields().get(0), (Long) 100l);
}
+ @Test
+ public void noDoubleWrappingOfExtraDataFields() {
+ org.robolectric.shadows.ShadowLog.stream = System.err;
+ Beacon beacon = new AltBeacon.Builder().setId1("1").setId2("2").setId3("3").setRssi(4)
+ .setBeaconTypeCode(5).setTxPower(6).setBluetoothName("xx")
+ .setBluetoothAddress("1:2:3:4:5:6").setDataFields(Arrays.asList(100l)).build();
+ List<Long> list = beacon.getExtraDataFields();
+ beacon.setExtraDataFields(list);
+ assertTrue("getter should return same object after first wrap ", beacon.getExtraDataFields() == list);
+ }
+
}
\\ No newline at end of file | ['src/test/java/org/altbeacon/beacon/BeaconTest.java', 'src/main/java/org/altbeacon/beacon/Beacon.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 311,819 | 65,774 | 8,365 | 59 | 1,222 | 235 | 31 | 1 | 1,403 | 63 | 331 | 26 | 0 | 1 | 2015-06-01T21:04:28 | 2,758 | Java | {'Java': 766605, 'Kotlin': 17054} | Apache License 2.0 |
534 | altbeacon/android-beacon-library/886/876 | altbeacon | android-beacon-library | https://github.com/AltBeacon/android-beacon-library/issues/876 | https://github.com/AltBeacon/android-beacon-library/pull/886 | https://github.com/AltBeacon/android-beacon-library/pull/886 | 2 | fix | CycledLeScanner crashes on setWakeUpAlarm | ### Expected behavior
No crash
### Actual behavior
Fatal Exception: java.lang.SecurityException
get application info: Neither user 1010129 nor current process has android.permission.INTERACT_ACROSS_USERS.
Fatal Exception: java.lang.SecurityException
Permission Denial: getIntentForIntentSender() from pid=20646, uid=10159 requires android.permission.GET_INTENT_SENDER_INTENT
Fatal Exception: java.lang.NullPointerException
println needs a message
### Steps to reproduce this behavior
Not sure about the reproduction, we noticed these crashes on Firebase. Here's the stack trace for LENOVO VIBE X3 Lite, Android 5.1:
```
Fatal Exception: java.lang.SecurityException: get application info: Neither user 1010129 nor current process has android.permission.INTERACT_ACROSS_USERS.
at android.os.Parcel.readException(Parcel.java:1546)
at android.os.Parcel.readException(Parcel.java:1499)
at android.app.IAlarmManager$Stub$Proxy.set(IAlarmManager.java:244)
at android.app.AlarmManager.setImpl(AlarmManager.java:425)
at android.app.AlarmManager.set(AlarmManager.java:224)
at org.altbeacon.beacon.service.scanner.CycledLeScanner.setWakeUpAlarm(CycledLeScanner.java:489)
at org.altbeacon.beacon.service.scanner.CycledLeScanner.scheduleScanCycleStop(CycledLeScanner.java:368)
at org.altbeacon.beacon.service.scanner.CycledLeScanner$2.run(CycledLeScanner.java:374)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
```
There was another similar crash on Galaxy S5 Neo (6.0.1):
```
Fatal Exception: java.lang.SecurityException: Permission Denial: getIntentForIntentSender() from pid=20646, uid=10159 requires android.permission.GET_INTENT_SENDER_INTENT
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at android.app.IAlarmManager$Stub$Proxy.set(IAlarmManager.java:217)
at android.app.AlarmManager.setImpl(AlarmManager.java:484)
at android.app.AlarmManager.set(AlarmManager.java:260)
at org.altbeacon.beacon.service.scanner.CycledLeScanner.setWakeUpAlarm(CycledLeScanner.java:489)
at org.altbeacon.beacon.service.scanner.CycledLeScanner.scheduleScanCycleStop(CycledLeScanner.java:368)
at org.altbeacon.beacon.service.scanner.CycledLeScanner$2.run(CycledLeScanner.java:374)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7230)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
```
And another one on LENOVO A6010 (5.0.2):
```
Fatal Exception: java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Log.java)
at android.util.Slog.v(Slog.java:28)
at android.app.AlarmManager.setImpl(AlarmManager.java:429)
at android.app.AlarmManager.set(AlarmManager.java:228)
at org.altbeacon.beacon.service.scanner.CycledLeScanner.setWakeUpAlarm(CycledLeScanner.java:489)
at org.altbeacon.beacon.service.scanner.CycledLeScanner.scheduleScanCycleStop(CycledLeScanner.java:368)
at org.altbeacon.beacon.service.scanner.CycledLeScanner.scanLeDevice(CycledLeScanner.java:338)
at org.altbeacon.beacon.service.scanner.CycledLeScannerForLollipop$1.run(CycledLeScannerForLollipop.java:153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5233)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
```
### Mobile device model and OS version
LENOVO VIBE X3 Lite (5.1)
Galaxy S5 Neo (6.0.1)
LENOVO A6010 (5.0.2)
### Android Beacon Library version
2.15.4
| a5ba01bbb44f6033009e122280a54002599eb98c | 967c58de6a3af7194fc39267a21a71330edd8b87 | https://github.com/altbeacon/android-beacon-library/compare/a5ba01bbb44f6033009e122280a54002599eb98c...967c58de6a3af7194fc39267a21a71330edd8b87 | diff --git a/lib/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java b/lib/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java
index 0089b18..399f107 100644
--- a/lib/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java
+++ b/lib/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java
@@ -6,13 +6,16 @@ import android.app.AlarmManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
+import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
+import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
+import android.os.PowerManager;
import android.os.SystemClock;
import android.support.annotation.AnyThread;
import android.support.annotation.MainThread;
@@ -52,6 +55,7 @@ public abstract class CycledLeScanner {
// avoid doing too many scans in a limited time on Android 7.0 or because we are capable of
// multiple detections. If true, it indicates scanning needs to be stopped when we finish.
private boolean mScanningLeftOn = false;
+ private BroadcastReceiver mCancelAlarmOnUserSwitchBroadcastReceiver = null;
protected long mBetweenScanPeriod;
@@ -260,7 +264,6 @@ public abstract class CycledLeScanner {
// Remove any postDelayed Runnables queued for the next scan cycle
mHandler.removeCallbacksAndMessages(null);
-
// We cannot quit the thread used by the handler until queued Runnables have been processed,
// because the handler is what stops scanning, and we do not want scanning left on.
// So we stop the thread using the handler, so we make sure it happens after all other
@@ -273,6 +276,7 @@ public abstract class CycledLeScanner {
mScanThread.quit();
}
});
+ cleanupCancelAlarmOnUserSwitch();
}
protected abstract void stopScan();
@@ -484,12 +488,37 @@ public abstract class CycledLeScanner {
if (milliseconds < mScanPeriod) {
milliseconds = mScanPeriod;
}
-
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + milliseconds, getWakeUpOperation());
LogManager.d(TAG, "Set a wakeup alarm to go off in %s ms: %s", milliseconds, getWakeUpOperation());
+ cancelAlarmOnUserSwitch();
}
+ // Added to prevent crash on switching users. See #876
+ protected void cancelAlarmOnUserSwitch() {
+ if (mCancelAlarmOnUserSwitchBroadcastReceiver == null) {
+ IntentFilter filter = new IntentFilter();
+ filter.addAction( Intent.ACTION_USER_BACKGROUND );
+ filter.addAction( Intent.ACTION_USER_FOREGROUND );
+
+ mCancelAlarmOnUserSwitchBroadcastReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ LogManager.w(TAG, "User switch detected. Cancelling alarm to prevent potential crash.");
+ cancelWakeUpAlarm();
+ }
+ };
+ mContext.registerReceiver(mCancelAlarmOnUserSwitchBroadcastReceiver, filter);
+ }
+ }
+ protected void cleanupCancelAlarmOnUserSwitch() {
+ if (mCancelAlarmOnUserSwitchBroadcastReceiver != null) {
+ mContext.unregisterReceiver(mCancelAlarmOnUserSwitchBroadcastReceiver);
+ mCancelAlarmOnUserSwitchBroadcastReceiver = null;
+ }
+ }
+
+
protected PendingIntent getWakeUpOperation() {
if (mWakeUpOperation == null) {
Intent wakeupIntent = new Intent(mContext, StartupBroadcastReceiver.class); | ['lib/src/main/java/org/altbeacon/beacon/service/scanner/CycledLeScanner.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 527,153 | 109,850 | 13,466 | 76 | 1,408 | 249 | 33 | 1 | 4,790 | 242 | 1,140 | 80 | 0 | 3 | 2019-05-29T18:02:23 | 2,758 | Java | {'Java': 766605, 'Kotlin': 17054} | Apache License 2.0 |
989 | tng/archunit/744/739 | tng | archunit | https://github.com/TNG/ArchUnit/issues/739 | https://github.com/TNG/ArchUnit/pull/744 | https://github.com/TNG/ArchUnit/pull/744 | 1 | resolves | Layeredarchitecture problem with three layers A,B,C - The access check fails for A->B, but the violation comes up when allowing access B->C | We came across an issue with `layeredarchitecture` where we have three layers A, B and C: A may access B, B may access C.
As soon as we allow the access from B to C with `.whereLayer(layerB).mayOnlyAccessLayers(layerC)` , the architecture tests fails because of a violation by the access from layer A to layer B (which is even explicitely allowed). What are we doing wrong?
We are using ArchUnit V0.22.0 (but the same issue occurs with older versions, as we tried a few like 0.11 or 0.19 to 0.21).
# Our scenario: Three layers A, B, C
We put some minimal sample code to a separate Github repo https://github.com/mrtnlhmnn/archunit-layeredarchitecture-problem
We have a component `mycomponent` and want to check the access rules between these technical layers. Originally, we were checking an onion architecture with its technical layers (like application, domain, infrastructure).
- We stripped that down to a very minimum with three layers, named `layerA` and `layerB` and `layerC`, see [here](https://github.com/mrtnlhmnn/archunit-layeredarchitecture-problem/tree/main/src/main/java/mycomponent)
- Each layer is a separate package.
- Each package contains one class `A` and `B` and `C` (where class `A` has a dependency to class `B` and class `B` has one to class `C`).
- Our ArchUnit test fails as soon as we allow `.whereLayer(layerB).mayOnlyAccessLayers(layerC)`, but the violation says that there is a problem with the access from `layerA` to `layerB`, though we have this explictely allowed.
- If we commented that `whereLayer...` out, the test is OK. This looks weird to us, as this `mayOnlyAccessLayers` is "outgoing from B" while the violation is for an "incoming to B".
# Violation
```
java.lang.AssertionError: Architecture Violation [Priority: MEDIUM] - Rule 'Layered architecture consisting of
layer 'LayerA' ('mycomponent.layerA..')
layer 'LayerB' ('mycomponent.layerB..')
layer 'LayerC' ('mycomponent.layerC..')
where layer 'LayerA' may not be accessed by any layer
where layer 'LayerA' may only access layers ['LayerB']
where layer 'LayerB' may only be accessed by layers ['LayerA']
where layer 'LayerC' may only be accessed by layers ['LayerB']
where layer 'LayerB' may only access layers ['LayerC']' was violated (1 times):
Field <mycomponent.layerA.A.b> has type <mycomponent.layerB.B> in (A.java:0)
```
# ArchUnit test
Whole class see [here](https://github.com/mrtnlhmnn/archunit-layeredarchitecture-problem/blob/main/src/test/java/ArchUnit_LayeredArchitectureProblem.java)
```
String PKG = "mycomponent";
JavaClasses myClasses = new ClassFileImporter().importPackages(PKG);
String layerA = "LayerA";
String layerB = "LayerB";
String layerC = "LayerC";
Architectures.LayeredArchitecture layeredArchitecture = Architectures.layeredArchitecture()
.layer(layerA).definedBy(PKG+".layerA..")
.layer(layerB).definedBy(PKG+".layerB..")
.layer(layerC).definedBy(PKG+".layerC..")
// ignore any dependencies to java.. Not sure if this ignore could be avoided
.ignoreDependency(isMyClass, isJavaClass)
// no access to A
.whereLayer(layerA).mayNotBeAccessedByAnyLayer()
// A --can access--> B
.whereLayer(layerA).mayOnlyAccessLayers(layerB)
.whereLayer(layerB).mayOnlyBeAccessedByLayers(layerA)
// B --can access--> C
.whereLayer(layerC).mayOnlyBeAccessedByLayers(layerB)
/* .whereLayer(layerB).mayOnlyAccessLayers(layerC) */ // <== problem occurs when this line is commented in
;
// the check is ok, when the last whereLayer() is commented out but fails with the line commented in
layeredArchitecture.check(myClasses);
```
# We ignore accesses to Java standard classes
Note that in the test code above we are explicitely ignoring any dependencies to `java..` by saying `.ignoreDependency(isMyClass, isJavaClass)`. For that we wrote two `DescribePredicate`s which look as follows:
```
DescribedPredicate<JavaClass> isMyClass = new DescribedPredicate<>("is in mycomponent") {
@Override
public boolean apply(JavaClass input) {
return input.getPackageName().startsWith(PKG);
}
};
DescribedPredicate<JavaClass> isJavaClass = new DescribedPredicate<>("is Java class") {
@Override
public boolean apply(JavaClass input) {
return input.getPackageName().startsWith("java");
}
};
``` | d6b03207653d14c2bd2a0d9df8b5d5cf7e741b72 | 1a805cb51b14dceada9a2fbcaaf8650631fb76be | https://github.com/tng/archunit/compare/d6b03207653d14c2bd2a0d9df8b5d5cf7e741b72...1a805cb51b14dceada9a2fbcaaf8650631fb76be | diff --git a/archunit/src/main/java/com/tngtech/archunit/base/PackageMatcher.java b/archunit/src/main/java/com/tngtech/archunit/base/PackageMatcher.java
index 67fa4871..a2afb391 100644
--- a/archunit/src/main/java/com/tngtech/archunit/base/PackageMatcher.java
+++ b/archunit/src/main/java/com/tngtech/archunit/base/PackageMatcher.java
@@ -28,7 +28,7 @@ import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;
/**
* Matches packages with a syntax similar to AspectJ. In particular '*' stands for any sequence of
- * characters, '..' stands for any sequence of packages, including zero packages.<br>
+ * characters but not the dot '.', while '..' stands for any sequence of packages, including zero packages.<br>
* For example
* <ul>
* <li><b>{@code '..pack..'}</b> matches <b>{@code 'a.pack'}</b>, <b>{@code 'a.pack.b'}</b> or <b>{@code 'a.b.pack.c.d'}</b>,
@@ -38,7 +38,7 @@ import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;
* <li><b>{@code '*.*.pack*..'}</b> matches <b>{@code 'a.b.packfix.c.d'}</b>,
* but neither <b>{@code 'a.packfix.b'}</b> nor <b>{@code 'a.b.prepack.d'}</b></li>
* </ul>
- * Furthermore the use of capturing groups is supported. In this case '(*)' matches any sequence of characters,
+ * Furthermore, the use of capturing groups is supported. In this case '(*)' matches any sequence of characters,
* but not the dot '.', while '(**)' matches any sequence including the dot. <br>
* For example
* <ul>
diff --git a/archunit/src/main/java/com/tngtech/archunit/core/domain/Dependency.java b/archunit/src/main/java/com/tngtech/archunit/core/domain/Dependency.java
index 225fa021..7f086eb3 100644
--- a/archunit/src/main/java/com/tngtech/archunit/core/domain/Dependency.java
+++ b/archunit/src/main/java/com/tngtech/archunit/core/domain/Dependency.java
@@ -39,12 +39,16 @@ import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;
* following:
* <ul>
* <li>a class accesses a field of another class</li>
- * <li>a class calls a method of another class</li>
- * <li>a class calls a constructor of another class</li>
- * <li>a class inherits from another class (which is in fact a special case of constructor call)</li>
+ * <li>a class calls a method/constructor of another class</li>
+ * <li>a class inherits from another class</li>
* <li>a class implements an interface</li>
* <li>a class has a field with type of another class</li>
* <li>a class has a method/constructor with parameter/return type of another class</li>
+ * <li>a class (or method/constructor of this class) declares a type parameter referencing another class</li>
+ * <li>a class (or method/constructor of this class) is annotated with an annotation of a certain type or referencing another class as annotation parameter</li>
+ * <li>a method/constructor of a class references another class in a throws declaration</li>
+ * <li>a class references another class object (e.g. {@code Example.class})</li>
+ * <li>a class references another class in an {@code instanceof} check</li>
* </ul>
* Note that a {@link Dependency} will by definition never be a self-reference,
* i.e. <code>origin</code> will never be equal to <code>target</code>.
diff --git a/archunit/src/main/java/com/tngtech/archunit/core/domain/JavaClass.java b/archunit/src/main/java/com/tngtech/archunit/core/domain/JavaClass.java
index 9160fccf..f5e9efca 100644
--- a/archunit/src/main/java/com/tngtech/archunit/core/domain/JavaClass.java
+++ b/archunit/src/main/java/com/tngtech/archunit/core/domain/JavaClass.java
@@ -1221,18 +1221,8 @@ public class JavaClass
}
/**
- * Returns all dependencies originating directly from this class (i.e. not just from a superclass),
- * where a dependency can be
- * <ul>
- * <li>field access</li>
- * <li>method call</li>
- * <li>constructor call</li>
- * <li>extending a class</li>
- * <li>implementing an interface</li>
- * <li>referencing in throws declaration</li>
- * </ul>
- *
- * @return All dependencies originating directly from this class (i.e. where this class is the origin)
+ * @return All dependencies originating directly from this class (i.e. where this class is the origin).
+ * For further details about dependencies refer to {@link Dependency}.
*/
@PublicAPI(usage = ACCESS)
public Set<Dependency> getDirectDependenciesFromSelf() {
diff --git a/archunit/src/main/java/com/tngtech/archunit/library/Architectures.java b/archunit/src/main/java/com/tngtech/archunit/library/Architectures.java
index a64e3570..3bfbf6ce 100644
--- a/archunit/src/main/java/com/tngtech/archunit/library/Architectures.java
+++ b/archunit/src/main/java/com/tngtech/archunit/library/Architectures.java
@@ -30,6 +30,7 @@ import com.google.common.base.Joiner;
import com.tngtech.archunit.PublicAPI;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.base.Optional;
+import com.tngtech.archunit.base.PackageMatcher;
import com.tngtech.archunit.core.domain.Dependency;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaClasses;
@@ -226,12 +227,9 @@ public final class Architectures {
}
private EvaluationResult evaluateDependenciesShouldBeSatisfied(JavaClasses classes, LayerDependencySpecification specification) {
- ArchCondition<JavaClass> satisfyLayerDependenciesCondition =
- onlyHaveDependentsWhere(originMatchesIfDependencyIsRelevant(specification.layerName, specification.allowedAccessors));
- if (!specification.allowedTargets.isEmpty()) {
- satisfyLayerDependenciesCondition = satisfyLayerDependenciesCondition
- .and(onlyHaveDependenciesWhere(targetMatchesIfDependencyIsRelevant(specification.layerName, specification.allowedTargets)));
- }
+ ArchCondition<JavaClass> satisfyLayerDependenciesCondition = specification.constraint == LayerDependencyConstraint.ORIGIN
+ ? onlyHaveDependentsWhere(originMatchesIfDependencyIsRelevant(specification.layerName, specification.allowedLayers))
+ : onlyHaveDependenciesWhere(targetMatchesIfDependencyIsRelevant(specification.layerName, specification.allowedLayers));
return classes().that(layerDefinitions.containsPredicateFor(specification.layerName))
.should(satisfyLayerDependenciesCondition)
.evaluate(classes);
@@ -305,16 +303,30 @@ public final class Architectures {
irrelevantDependenciesPredicate, Optional.of(newDescription), optionalLayers);
}
+ /**
+ * Configures the rule to ignore any violation from a specific {@code origin} class to a specific {@code target} class.
+ * @param origin A {@link Class} object specifying the origin of a {@link Dependency} to ignore
+ * @param target A {@link Class} object specifying the target of a {@link Dependency} to ignore
+ * @return a {@link LayeredArchitecture} to be used as an {@link ArchRule} or further restricted through a fluent API.
+ */
@PublicAPI(usage = ACCESS)
public LayeredArchitecture ignoreDependency(Class<?> origin, Class<?> target) {
return ignoreDependency(equivalentTo(origin), equivalentTo(target));
}
+ /**
+ * Same as {@link #ignoreDependency(Class, Class)} but allows specifying origin and target as fully qualified class names.
+ */
@PublicAPI(usage = ACCESS)
- public LayeredArchitecture ignoreDependency(String origin, String target) {
- return ignoreDependency(name(origin), name(target));
+ public LayeredArchitecture ignoreDependency(String originFullyQualifiedClassName, String targetFullyQualifiedClassName) {
+ return ignoreDependency(name(originFullyQualifiedClassName), name(targetFullyQualifiedClassName));
}
+ /**
+ * Same as {@link #ignoreDependency(Class, Class)} but allows specifying origin and target by freely defined predicates.
+ * Any dependency where the {@link Dependency#getOriginClass()} matches the {@code origin} predicate
+ * and the {@link Dependency#getTargetClass()} matches the {@code target} predicate will be ignored.
+ */
@PublicAPI(usage = ACCESS)
public LayeredArchitecture ignoreDependency(
DescribedPredicate<? super JavaClass> origin, DescribedPredicate<? super JavaClass> target) {
@@ -323,6 +335,12 @@ public final class Architectures {
irrelevantDependenciesPredicate.add(dependency(origin, target)), overriddenDescription, optionalLayers);
}
+ /**
+ * Allows restricting accesses to or from this layer. Note that "access" in the context of a layer refers to
+ * any dependency as defined by {@link Dependency}.
+ * @param name a layer name as specified before via {@link #layer(String)}
+ * @return a specification to fluently define further restrictions
+ */
@PublicAPI(usage = ACCESS)
public LayerDependencySpecification whereLayer(String name) {
checkLayerNamesExist(name);
@@ -383,6 +401,9 @@ public final class Architectures {
this.optional = optional;
}
+ /**
+ * Defines a layer by a predicate, i.e. any {@link JavaClass} that will match the predicate will belong to this layer.
+ */
@PublicAPI(usage = ACCESS)
public LayeredArchitecture definedBy(DescribedPredicate<? super JavaClass> predicate) {
checkNotNull(predicate, "Supplied predicate must not be null");
@@ -390,6 +411,9 @@ public final class Architectures {
return LayeredArchitecture.this.addLayerDefinition(this);
}
+ /**
+ * Defines a layer by package identifiers (compare {@link PackageMatcher})
+ */
@PublicAPI(usage = ACCESS)
public LayeredArchitecture definedBy(String... packageIdentifiers) {
String description = String.format("'%s'", Joiner.on("', '").join(packageIdentifiers));
@@ -410,38 +434,72 @@ public final class Architectures {
}
}
+ private enum LayerDependencyConstraint {
+ ORIGIN,
+ TARGET
+ }
+
public final class LayerDependencySpecification {
private final String layerName;
- private final Set<String> allowedAccessors = new LinkedHashSet<>();
- private final Set<String> allowedTargets = new LinkedHashSet<>();
+ private final Set<String> allowedLayers = new LinkedHashSet<>();
+ private LayerDependencyConstraint constraint;
private String descriptionSuffix;
private LayerDependencySpecification(String layerName) {
this.layerName = layerName;
}
+ /**
+ * Forbids any {@link Dependency dependency} from another layer to this layer.
+ * @return a {@link LayeredArchitecture} to be used as an {@link ArchRule} or further restricted through a fluent API.
+ */
@PublicAPI(usage = ACCESS)
public LayeredArchitecture mayNotBeAccessedByAnyLayer() {
- descriptionSuffix = "may not be accessed by any layer";
- return LayeredArchitecture.this.addDependencySpecification(this);
+ return denyLayerAccess(LayerDependencyConstraint.ORIGIN, "may not be accessed by any layer");
}
+ /**
+ * Restricts this layer to only allow the specified layers to have {@link Dependency dependencies} to this layer.
+ * @param layerNames the names of other layers (as specified by {@link #layer(String)}) that may access this layer
+ * @return a {@link LayeredArchitecture} to be used as an {@link ArchRule} or further restricted through a fluent API.
+ */
@PublicAPI(usage = ACCESS)
public LayeredArchitecture mayOnlyBeAccessedByLayers(String... layerNames) {
- checkLayerNamesExist(layerNames);
- allowedAccessors.addAll(asList(layerNames));
- descriptionSuffix = String.format("may only be accessed by layers ['%s']",
- Joiner.on("', '").join(allowedAccessors));
- return LayeredArchitecture.this.addDependencySpecification(this);
+ return restrictLayers(LayerDependencyConstraint.ORIGIN, layerNames, "may only be accessed by layers ['%s']");
+ }
+
+ /**
+ * Forbids any {@link Dependency dependency} from this layer to any other layer.
+ * @return a {@link LayeredArchitecture} to be used as an {@link ArchRule} or further restricted through a fluent API.
+ */
+ @PublicAPI(usage = ACCESS)
+ public LayeredArchitecture mayNotAccessAnyLayer() {
+ return denyLayerAccess(LayerDependencyConstraint.TARGET, "may not access any layer");
}
+ /**
+ * Restricts this layer to only allow {@link Dependency dependencies} to the specified layers.
+ * @param layerNames the only names of other layers (as specified by {@link #layer(String)}) that this layer may access
+ * @return a {@link LayeredArchitecture} to be used as an {@link ArchRule} or further restricted through a fluent API.
+ */
@PublicAPI(usage = ACCESS)
public LayeredArchitecture mayOnlyAccessLayers(String... layerNames) {
- checkArgument(layerNames.length > 0, "At least 1 layer name should be provided.");
+ return restrictLayers(LayerDependencyConstraint.TARGET, layerNames, "may only access layers ['%s']");
+ }
+
+ private LayeredArchitecture denyLayerAccess(LayerDependencyConstraint constraint, String description) {
+ allowedLayers.clear();
+ this.constraint = constraint;
+ descriptionSuffix = description;
+ return LayeredArchitecture.this.addDependencySpecification(this);
+ }
+
+ private LayeredArchitecture restrictLayers(LayerDependencyConstraint constraint, String[] layerNames, String descriptionTemplate) {
+ checkArgument(layerNames.length > 0, "At least 1 layer name must be provided.");
checkLayerNamesExist(layerNames);
- allowedTargets.addAll(asList(layerNames));
- descriptionSuffix = String.format("may only access layers ['%s']",
- Joiner.on("', '").join(allowedTargets));
+ allowedLayers.addAll(asList(layerNames));
+ this.constraint = constraint;
+ descriptionSuffix = String.format(descriptionTemplate, Joiner.on("', '").join(layerNames));
return LayeredArchitecture.this.addDependencySpecification(this);
}
diff --git a/archunit/src/test/java/com/tngtech/archunit/library/ArchitecturesTest.java b/archunit/src/test/java/com/tngtech/archunit/library/ArchitecturesTest.java
index 439894f7..23cd7e54 100644
--- a/archunit/src/test/java/com/tngtech/archunit/library/ArchitecturesTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/library/ArchitecturesTest.java
@@ -275,18 +275,20 @@ public class ArchitecturesTest {
.layer("Allowed").definedBy("..library.testclasses.mayonlyaccesslayers.allowed..")
.layer("Forbidden").definedBy("..library.testclasses.mayonlyaccesslayers.forbidden..")
.layer("Origin").definedBy("..library.testclasses.mayonlyaccesslayers.origin..")
- .whereLayer("Origin").mayOnlyAccessLayers("Allowed"),
+ .whereLayer("Origin").mayOnlyAccessLayers("Allowed")
+ .whereLayer("Forbidden").mayNotAccessAnyLayer(),
layeredArchitecture()
.layer("Allowed").definedBy(
- resideInAnyPackage("..library.testclasses.mayonlyaccesslayers.allowed..")
- .as("'..library.testclasses.mayonlyaccesslayers.allowed..'"))
+ resideInAnyPackage("..library.testclasses.mayonlyaccesslayers.allowed..")
+ .as("'..library.testclasses.mayonlyaccesslayers.allowed..'"))
.layer("Forbidden").definedBy(
- resideInAnyPackage("..library.testclasses.mayonlyaccesslayers.forbidden..")
- .as("'..library.testclasses.mayonlyaccesslayers.forbidden..'"))
+ resideInAnyPackage("..library.testclasses.mayonlyaccesslayers.forbidden..")
+ .as("'..library.testclasses.mayonlyaccesslayers.forbidden..'"))
.layer("Origin").definedBy(
- resideInAnyPackage("..library.testclasses.mayonlyaccesslayers.origin..")
- .as("'..library.testclasses.mayonlyaccesslayers.origin..'"))
- .whereLayer("Origin").mayOnlyAccessLayers("Allowed"));
+ resideInAnyPackage("..library.testclasses.mayonlyaccesslayers.origin..")
+ .as("'..library.testclasses.mayonlyaccesslayers.origin..'"))
+ .whereLayer("Origin").mayOnlyAccessLayers("Allowed")
+ .whereLayer("Forbidden").mayNotAccessAnyLayer());
}
@Test
@@ -297,7 +299,8 @@ public class ArchitecturesTest {
"layer 'Allowed' ('..library.testclasses.mayonlyaccesslayers.allowed..')" + lineSeparator() +
"layer 'Forbidden' ('..library.testclasses.mayonlyaccesslayers.forbidden..')" + lineSeparator() +
"layer 'Origin' ('..library.testclasses.mayonlyaccesslayers.origin..')" + lineSeparator() +
- "where layer 'Origin' may only access layers ['Allowed']");
+ "where layer 'Origin' may only access layers ['Allowed']" + lineSeparator() +
+ "where layer 'Forbidden' may not access any layer");
}
@Test
@@ -312,7 +315,10 @@ public class ArchitecturesTest {
expectedAccessViolationPattern(
MayOnlyAccessLayersOriginClass.class, "call", MayOnlyAccessLayersForbiddenClass.class, "callMe"),
expectedAccessViolationPattern(MayOnlyAccessLayersOriginClass.class, CONSTRUCTOR_NAME, Object.class, CONSTRUCTOR_NAME),
+ expectedAccessViolationPattern(MayOnlyAccessLayersForbiddenClass.class, CONSTRUCTOR_NAME, Object.class, CONSTRUCTOR_NAME),
+ expectedAccessViolationPattern(MayOnlyAccessLayersForbiddenClass.class, "callMe", MayOnlyAccessLayersOriginClass.class, CONSTRUCTOR_NAME),
expectedInheritancePattern(MayOnlyAccessLayersOriginClass.class, Object.class),
+ expectedInheritancePattern(MayOnlyAccessLayersForbiddenClass.class, Object.class),
expectedFieldTypePattern(MayOnlyAccessLayersOriginClass.class, "illegalTarget", MayOnlyAccessLayersForbiddenClass.class)));
}
@@ -322,7 +328,9 @@ public class ArchitecturesTest {
JavaClasses classes = new ClassFileImporter().importPackages(absolute("mayonlyaccesslayers"));
architecture = architecture.ignoreDependency(MayOnlyAccessLayersOriginClass.class, MayOnlyAccessLayersForbiddenClass.class)
- .ignoreDependency(MayOnlyAccessLayersOriginClass.class, Object.class);
+ .ignoreDependency(MayOnlyAccessLayersOriginClass.class, Object.class)
+ .ignoreDependency(MayOnlyAccessLayersForbiddenClass.class, Object.class)
+ .ignoreDependency(MayOnlyAccessLayersForbiddenClass.class, MayOnlyAccessLayersOriginClass.class);
assertThat(architecture.evaluate(classes).hasViolation()).as("result has violation").isFalse();
}
diff --git a/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java b/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java
index f34e80ad..3eca4882 100644
--- a/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java
+++ b/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java
@@ -1,6 +1,9 @@
package com.tngtech.archunit.library.testclasses.mayonlyaccesslayers.allowed;
+import com.tngtech.archunit.library.testclasses.mayonlyaccesslayers.origin.MayOnlyAccessLayersOriginClass;
+
public class MayOnlyAccessLayersAllowedClass {
public void callMe() {
+ new MayOnlyAccessLayersOriginClass();
}
}
diff --git a/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/forbidden/MayOnlyAccessLayersForbiddenClass.java b/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/forbidden/MayOnlyAccessLayersForbiddenClass.java
index 461f57d3..ad488a99 100644
--- a/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/forbidden/MayOnlyAccessLayersForbiddenClass.java
+++ b/archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/forbidden/MayOnlyAccessLayersForbiddenClass.java
@@ -1,6 +1,9 @@
package com.tngtech.archunit.library.testclasses.mayonlyaccesslayers.forbidden;
+import com.tngtech.archunit.library.testclasses.mayonlyaccesslayers.origin.MayOnlyAccessLayersOriginClass;
+
public class MayOnlyAccessLayersForbiddenClass {
public void callMe() {
+ new MayOnlyAccessLayersOriginClass();
}
} | ['archunit/src/main/java/com/tngtech/archunit/core/domain/JavaClass.java', 'archunit/src/main/java/com/tngtech/archunit/core/domain/Dependency.java', 'archunit/src/test/java/com/tngtech/archunit/library/ArchitecturesTest.java', 'archunit/src/main/java/com/tngtech/archunit/base/PackageMatcher.java', 'archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/allowed/MayOnlyAccessLayersAllowedClass.java', 'archunit/src/test/java/com/tngtech/archunit/library/testclasses/mayonlyaccesslayers/forbidden/MayOnlyAccessLayersForbiddenClass.java', 'archunit/src/main/java/com/tngtech/archunit/library/Architectures.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 1,908,988 | 391,375 | 48,591 | 449 | 9,018 | 1,722 | 128 | 4 | 4,495 | 522 | 1,097 | 80 | 3 | 3 | 2021-12-20T21:54:14 | 2,751 | Java | {'Java': 5207204, 'Shell': 1522, 'Groovy': 512, 'Dockerfile': 367} | Apache License 2.0 |
992 | tng/archunit/35/29 | tng | archunit | https://github.com/TNG/ArchUnit/issues/29 | https://github.com/TNG/ArchUnit/pull/35 | https://github.com/TNG/ArchUnit/pull/35 | 1 | resolves | @ArchIgnore is ignored on ArchRules fields | ArchRule suites ignore the `@ArchIgnore` annotation, e.g.:
```
public class MyRules {
@ArchTest
public static final ArchRule someRule = ...
}
```
```
@RunWith(ArchUnitRunner.class)
// ...
public class MyArchTest {
@ArchTest
@ArchIgnore // This is ignored
public static final ArchRules rules = ArchRules.in(MyRules.class);
}
```
Expected behavior when running `MyArchTest`:
All rules within `MyRules` are skipped
Actual behavior:
Rules within `MyRules` run anyway. | 3af1a803ca42280debd1562276faef44dea1b880 | a2d952f5ddec4a13ef9b7d9d89bed4cdd2f884ad | https://github.com/tng/archunit/compare/3af1a803ca42280debd1562276faef44dea1b880...a2d952f5ddec4a13ef9b7d9d89bed4cdd2f884ad | diff --git a/archunit-integration-test/src/test/java/com/tngtech/archunit/junit/ArchUnitIntegrationTestRunner.java b/archunit-integration-test/src/test/java/com/tngtech/archunit/junit/ArchUnitIntegrationTestRunner.java
index 29714924..9629f4f5 100644
--- a/archunit-integration-test/src/test/java/com/tngtech/archunit/junit/ArchUnitIntegrationTestRunner.java
+++ b/archunit-integration-test/src/test/java/com/tngtech/archunit/junit/ArchUnitIntegrationTestRunner.java
@@ -1,6 +1,7 @@
package com.tngtech.archunit.junit;
import java.lang.annotation.Annotation;
+import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -14,6 +15,7 @@ import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import static com.google.common.base.Preconditions.checkNotNull;
+import static org.mockito.Mockito.mock;
public class ArchUnitIntegrationTestRunner extends ArchUnitRunner {
public ArchUnitIntegrationTestRunner(Class<?> testClass) throws InitializationError {
@@ -113,7 +115,7 @@ public class ArchUnitIntegrationTestRunner extends ArchUnitRunner {
private JavaClasses classes;
ClassesCaptor() {
- super(Object.class);
+ super(Object.class, mock(AnnotatedElement.class), false);
}
@Override
diff --git a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRuleExecution.java b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRuleExecution.java
index 0cfe4218..51e5e28e 100644
--- a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRuleExecution.java
+++ b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRuleExecution.java
@@ -30,8 +30,8 @@ class ArchRuleExecution extends ArchTestExecution {
@VisibleForTesting
final ArchRule rule;
- ArchRuleExecution(Class<?> testClass, Field ruleField) {
- super(testClass);
+ ArchRuleExecution(Class<?> testClass, Field ruleField, boolean forceIgnore) {
+ super(testClass, ruleField, forceIgnore);
validatePublicStatic(ruleField);
checkArgument(ArchRule.class.isAssignableFrom(ruleField.getType()),
diff --git a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRules.java b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRules.java
index 1f4ea221..f139d4f9 100644
--- a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRules.java
+++ b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRules.java
@@ -29,6 +29,7 @@ import com.tngtech.archunit.junit.ReflectionUtils.Predicate;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;
+import static com.tngtech.archunit.junit.ArchTestExecution.elementShouldBeIgnored;
import static com.tngtech.archunit.junit.ReflectionUtils.getAllFields;
import static com.tngtech.archunit.junit.ReflectionUtils.getAllMethods;
@@ -56,21 +57,21 @@ public final class ArchRules {
return new ArchRules(definitionLocation);
}
- Set<ArchTestExecution> asTestExecutions() {
+ Set<ArchTestExecution> asTestExecutions(boolean forceIgnore) {
ImmutableSet.Builder<ArchTestExecution> result = ImmutableSet.builder();
for (Field field : fields) {
- result.addAll(archRuleExecutionsOf(field));
+ result.addAll(archRuleExecutionsOf(field, forceIgnore));
}
for (Method method : methods) {
- result.add(new ArchTestMethodExecution(method.getDeclaringClass(), method));
+ result.add(new ArchTestMethodExecution(method.getDeclaringClass(), method, forceIgnore));
}
return result.build();
}
- private Set<ArchTestExecution> archRuleExecutionsOf(Field field) {
+ private Set<ArchTestExecution> archRuleExecutionsOf(Field field, boolean forceIgnore) {
return ArchRules.class.isAssignableFrom(field.getType()) ?
- getArchRulesIn(field).asTestExecutions() :
- Collections.<ArchTestExecution>singleton(new ArchRuleExecution(field.getDeclaringClass(), field));
+ getArchRulesIn(field).asTestExecutions(forceIgnore || elementShouldBeIgnored(field)) :
+ Collections.<ArchTestExecution>singleton(new ArchRuleExecution(field.getDeclaringClass(), field, forceIgnore));
}
private ArchRules getArchRulesIn(Field field) {
diff --git a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestExecution.java b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestExecution.java
index 163ecb1d..8db416e2 100644
--- a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestExecution.java
+++ b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestExecution.java
@@ -16,6 +16,8 @@
package com.tngtech.archunit.junit;
import java.lang.annotation.Annotation;
+import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
@@ -28,9 +30,11 @@ import static com.google.common.base.Preconditions.checkArgument;
abstract class ArchTestExecution {
final Class<?> testClass;
+ private final boolean ignore;
- ArchTestExecution(Class<?> testClass) {
+ ArchTestExecution(Class<?> testClass, AnnotatedElement ruleDeclaration, boolean forceIgnore) {
this.testClass = testClass;
+ this.ignore = forceIgnore || elementShouldBeIgnored(testClass, ruleDeclaration);
}
static <T extends Member> T validatePublicStatic(T member) {
@@ -53,7 +57,16 @@ abstract class ArchTestExecution {
abstract <T extends Annotation> T getAnnotation(Class<T> type);
boolean ignore() {
- return testClass.getAnnotation(ArchIgnore.class) != null || getAnnotation(ArchIgnore.class) != null;
+ return ignore;
+ }
+
+ static boolean elementShouldBeIgnored(Field field) {
+ return elementShouldBeIgnored(field.getDeclaringClass(), field);
+ }
+
+ private static boolean elementShouldBeIgnored(Class<?> testClass, AnnotatedElement ruleDeclaration) {
+ return testClass.getAnnotation(ArchIgnore.class) != null ||
+ ruleDeclaration.getAnnotation(ArchIgnore.class) != null;
}
abstract static class Result {
diff --git a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestMethodExecution.java b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestMethodExecution.java
index 0750688e..2bf674d6 100644
--- a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestMethodExecution.java
+++ b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestMethodExecution.java
@@ -26,8 +26,8 @@ import org.junit.runners.model.FrameworkMethod;
class ArchTestMethodExecution extends ArchTestExecution {
private final Method testMethod;
- ArchTestMethodExecution(Class<?> testClass, Method testMethod) {
- super(testClass);
+ ArchTestMethodExecution(Class<?> testClass, Method testMethod, boolean forceIgnore) {
+ super(testClass, testMethod, forceIgnore);
this.testMethod = validatePublicStatic(testMethod);
}
diff --git a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchUnitRunner.java b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchUnitRunner.java
index b3892a75..270e4aea 100644
--- a/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchUnitRunner.java
+++ b/archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchUnitRunner.java
@@ -33,6 +33,7 @@ import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;
+import static com.tngtech.archunit.junit.ArchTestExecution.elementShouldBeIgnored;
/**
* Evaluates {@link ArchRule ArchRules} against the classes inside of the packages specified via
@@ -80,9 +81,10 @@ public class ArchUnitRunner extends ParentRunner<ArchTestExecution> {
private Set<ArchTestExecution> findArchRulesIn(FrameworkField ruleField) {
if (ruleField.getType() == ArchRules.class) {
- return getArchRules(ruleField).asTestExecutions();
+ boolean ignore = elementShouldBeIgnored(ruleField.getField());
+ return getArchRules(ruleField).asTestExecutions(ignore);
}
- return Collections.<ArchTestExecution>singleton(new ArchRuleExecution(getTestClass().getJavaClass(), ruleField.getField()));
+ return Collections.<ArchTestExecution>singleton(new ArchRuleExecution(getTestClass().getJavaClass(), ruleField.getField(), false));
}
private ArchRules getArchRules(FrameworkField ruleField) {
@@ -97,7 +99,7 @@ public class ArchUnitRunner extends ParentRunner<ArchTestExecution> {
private Collection<ArchTestExecution> findArchRuleMethods() {
List<ArchTestExecution> result = new ArrayList<>();
for (FrameworkMethod testMethod : getTestClass().getAnnotatedMethods(ArchTest.class)) {
- result.add(new ArchTestMethodExecution(getTestClass().getJavaClass(), testMethod.getMethod()));
+ result.add(new ArchTestMethodExecution(getTestClass().getJavaClass(), testMethod.getMethod(), false));
}
return result;
}
diff --git a/archunit-junit/src/test/java/com/tngtech/archunit/junit/ArchUnitRunnerRunsRuleSetsTest.java b/archunit-junit/src/test/java/com/tngtech/archunit/junit/ArchUnitRunnerRunsRuleSetsTest.java
index 1ab6eb87..e9ddf172 100644
--- a/archunit-junit/src/test/java/com/tngtech/archunit/junit/ArchUnitRunnerRunsRuleSetsTest.java
+++ b/archunit-junit/src/test/java/com/tngtech/archunit/junit/ArchUnitRunnerRunsRuleSetsTest.java
@@ -25,12 +25,17 @@ import org.mockito.junit.MockitoRule;
import static com.google.common.base.Preconditions.checkState;
import static com.tngtech.archunit.core.domain.TestUtils.importClassesWithContext;
import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.ArchTestWithRuleLibrary.someOtherMethodRuleName;
+import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.IgnoredRules.someIgnoredFieldRuleName;
+import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.IgnoredRules.someIgnoredMethodRuleName;
+import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.IgnoredSubRules.someIgnoredSubFieldRuleName;
+import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.IgnoredSubRules.someIgnoredSubMethodRuleName;
+import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.IgnoredSubRules.someNonIgnoredSubFieldRuleName;
+import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.IgnoredSubRules.someNonIgnoredSubMethodRuleName;
import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.Rules.someFieldRuleName;
import static com.tngtech.archunit.junit.ArchUnitRunnerRunsRuleSetsTest.Rules.someMethodRuleName;
import static com.tngtech.archunit.junit.ArchUnitRunnerTestUtils.getRule;
import static com.tngtech.archunit.junit.ArchUnitRunnerTestUtils.newRunnerFor;
-import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.all;
-import static com.tngtech.archunit.lang.syntax.ClassesIdentityTransformer.classes;
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.testutil.TestUtils.invoke;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
@@ -55,9 +60,15 @@ public class ArchUnitRunnerRunsRuleSetsTest {
@InjectMocks
private ArchUnitRunner runnerForRuleSet = newRunnerFor(ArchTestWithRuleSet.class);
+ @InjectMocks
+ private ArchUnitRunner runnerForIgnoredRuleSet = newRunnerFor(ArchTestWithIgnoredRuleSet.class);
+
@InjectMocks
private ArchUnitRunner runnerForRuleLibrary = newRunnerFor(ArchTestWithRuleLibrary.class);
+ @InjectMocks
+ private ArchUnitRunner runnerForIgnoredRuleLibrary = newRunnerFor(ArchTestWithIgnoredRuleLibrary.class);
+
private JavaClasses cachedClasses = importClassesWithContext(ArchUnitRunnerRunsRuleSetsTest.class);
@Before
@@ -86,12 +97,81 @@ public class ArchUnitRunnerRunsRuleSetsTest {
@Test
public void can_run_rule_field() throws Exception {
- run(someFieldRuleName);
+ run(someFieldRuleName, runnerForRuleSet, verifyTestRan());
}
@Test
public void can_run_rule_method() throws Exception {
- run(someMethodRuleName);
+ run(someMethodRuleName, runnerForRuleSet, verifyTestRan());
+ }
+
+ @Test
+ public void ignores_field_rule_of_ignored_rule_set() {
+ run(someFieldRuleName, runnerForIgnoredRuleSet, verifyTestIgnored());
+ }
+
+ @Test
+ public void ignores_method_rule_of_ignored_rule_set() {
+ run(someMethodRuleName, runnerForIgnoredRuleSet, verifyTestIgnored());
+ }
+
+ @Test
+ public void ignores_nested_field_rule() {
+ run(someIgnoredFieldRuleName, runnerForIgnoredRuleLibrary, verifyTestIgnored());
+ }
+
+ @Test
+ public void ignores_nested_method_rule() {
+ run(someIgnoredMethodRuleName, runnerForIgnoredRuleLibrary, verifyTestIgnored());
+ }
+
+ @Test
+ public void ignores_double_nested_field_rule() {
+ run(someIgnoredSubFieldRuleName, runnerForIgnoredRuleLibrary, verifyTestIgnored());
+ }
+
+ @Test
+ public void ignores_double_nested_method_rule() {
+ run(someIgnoredSubMethodRuleName, runnerForIgnoredRuleLibrary, verifyTestIgnored());
+ }
+
+ @Test
+ public void runs_double_nested_field_method_rule() {
+ run(someNonIgnoredSubFieldRuleName, runnerForIgnoredRuleLibrary, verifyTestRan());
+ }
+
+ @Test
+ public void runs_double_nested_method_rule() {
+ run(someNonIgnoredSubMethodRuleName, runnerForIgnoredRuleLibrary, verifyTestRan());
+ }
+
+ @Test
+ public void ignores_double_nested_field_rule_in_ignored_rule_set() {
+ run(someFieldRuleName, runnerForIgnoredRuleLibrary, verifyTestIgnored());
+ }
+
+ @Test
+ public void ignores_double_nested_method_rule_in_ignored_rule_set() {
+ run(someMethodRuleName, runnerForIgnoredRuleLibrary, verifyTestIgnored());
+ }
+
+ private Runnable verifyTestIgnored() {
+ return new Runnable() {
+ @Override
+ public void run() {
+ verify(runNotifier).fireTestIgnored(descriptionCaptor.capture());
+ }
+ };
+ }
+
+ private Runnable verifyTestRan() {
+ return new Runnable() {
+ @Override
+ public void run() {
+ verify(runNotifier).fireTestStarted(any(Description.class));
+ verify(runNotifier).fireTestFinished(descriptionCaptor.capture());
+ }
+ };
}
// extractingResultOf(..) only looks for public methods
@@ -113,13 +193,12 @@ public class ArchUnitRunnerRunsRuleSetsTest {
};
}
- private void run(String ruleName) {
- ArchTestExecution rule = getRule(ruleName, runnerForRuleSet);
+ private void run(String ruleName, ArchUnitRunner runner, Runnable testVerification) {
+ ArchTestExecution rule = getRule(ruleName, runner);
- runnerForRuleSet.runChild(rule, runNotifier);
+ runner.runChild(rule, runNotifier);
- verify(runNotifier).fireTestStarted(any(Description.class));
- verify(runNotifier).fireTestFinished(descriptionCaptor.capture());
+ testVerification.run();
assertThat(descriptionCaptor.getValue().toString()).contains(ruleName);
}
@@ -141,20 +220,80 @@ public class ArchUnitRunnerRunsRuleSetsTest {
public static final ArchRules rules = ArchRules.in(Rules.class);
}
+ @AnalyzeClasses(packages = "some.pkg")
+ public static class ArchTestWithIgnoredRuleSet {
+ @ArchTest
+ @ArchIgnore
+ public static final ArchRules rules = ArchRules.in(Rules.class);
+ }
+
+ @AnalyzeClasses(packages = "some.pkg")
+ public static class ArchTestWithIgnoredRuleLibrary {
+ @ArchTest
+ public static final ArchRules rules = ArchRules.in(IgnoredRules.class);
+ }
+
public static class Rules {
static final String someFieldRuleName = "someFieldRule";
static final String someMethodRuleName = "someMethodRule";
@ArchTest
- public static final ArchRule someFieldRule = all(classes())
- .should(new ArchCondition<JavaClass>("satisfy something") {
- @Override
- public void check(JavaClass item, ConditionEvents events) {
- }
- });
+ public static final ArchRule someFieldRule = classes().should(satisfySomething());
@ArchTest
public static void someMethodRule(JavaClasses classes) {
}
}
+
+ public static class IgnoredRules {
+ static final String someIgnoredFieldRuleName = "someIgnoredFieldRule";
+ static final String someIgnoredMethodRuleName = "someIgnoredMethodRule";
+
+ @ArchTest
+ @ArchIgnore
+ public static final ArchRule someIgnoredFieldRule = classes().should(satisfySomething());
+
+ @ArchTest
+ @ArchIgnore
+ public static void someIgnoredMethodRule(JavaClasses classes) {
+ }
+
+ @ArchTest
+ public static final ArchRules subRules = ArchRules.in(IgnoredSubRules.class);
+
+ @ArchTest
+ @ArchIgnore
+ public static final ArchRules ignoredSubRules = ArchRules.in(Rules.class);
+ }
+
+ public static class IgnoredSubRules {
+ static final String someIgnoredSubFieldRuleName = "someIgnoredSubFieldRule";
+ static final String someNonIgnoredSubFieldRuleName = "someNonIgnoredSubFieldRule";
+ static final String someIgnoredSubMethodRuleName = "someIgnoredSubMethodRule";
+ static final String someNonIgnoredSubMethodRuleName = "someNonIgnoredSubMethodRule";
+
+ @ArchTest
+ @ArchIgnore
+ public static final ArchRule someIgnoredSubFieldRule = classes().should(satisfySomething());
+
+ @ArchTest
+ public static final ArchRule someNonIgnoredSubFieldRule = classes().should(satisfySomething());
+
+ @ArchTest
+ @ArchIgnore
+ public static void someIgnoredSubMethodRule(JavaClasses classes) {
+ }
+
+ @ArchTest
+ public static void someNonIgnoredSubMethodRule(JavaClasses classes) {
+ }
+ }
+
+ private static ArchCondition<JavaClass> satisfySomething() {
+ return new ArchCondition<JavaClass>("satisfy something") {
+ @Override
+ public void check(JavaClass item, ConditionEvents events) {
+ }
+ };
+ }
}
\\ No newline at end of file | ['archunit-junit/src/test/java/com/tngtech/archunit/junit/ArchUnitRunnerRunsRuleSetsTest.java', 'archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRuleExecution.java', 'archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestExecution.java', 'archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchUnitRunner.java', 'archunit-integration-test/src/test/java/com/tngtech/archunit/junit/ArchUnitIntegrationTestRunner.java', 'archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchRules.java', 'archunit-junit/src/main/java/com/tngtech/archunit/junit/ArchTestMethodExecution.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 757,918 | 153,243 | 20,178 | 218 | 3,228 | 641 | 46 | 5 | 510 | 63 | 122 | 24 | 0 | 2 | 2017-10-18T03:40:25 | 2,751 | Java | {'Java': 5207204, 'Shell': 1522, 'Groovy': 512, 'Dockerfile': 367} | Apache License 2.0 |
991 | tng/archunit/220/219 | tng | archunit | https://github.com/TNG/ArchUnit/issues/219 | https://github.com/TNG/ArchUnit/pull/220 | https://github.com/TNG/ArchUnit/pull/220 | 1 | resolves | Modifier "static" of nested classes is not recognized | Currently, interfaces that are declared within another class and don't have the static keyword, are not considered as static. But those interfaces are implicitly static.
See [JLS, 8.5.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.5.1):
> A member interface is implicitly static (§9.1.1). It is permitted for the declaration of a member interface to redundantly specify the static modifier.
Test:
```java
class ExampleTest {
@Test
void modifierOfInterface() {
JavaClass javaClass = new ClassFileImporter().importClass(NestedInterface.class);
System.out.println(Predicates.modifier(STATIC).apply(javaClass)); // ArchUnit
System.out.println(Modifier.isStatic(NestedInterface.class.getModifiers())); // JDK
}
interface NestedInterface {}
}
```
Output:
```
false
true
``` | 3cf73f47be8af9dcdc9358cc46dfe8fc5d2623db | 0402a3b24bfa172c952d763c64a30ad8191e384c | https://github.com/tng/archunit/compare/3cf73f47be8af9dcdc9358cc46dfe8fc5d2623db...0402a3b24bfa172c952d763c64a30ad8191e384c | diff --git a/archunit/src/main/java/com/tngtech/archunit/core/domain/JavaModifier.java b/archunit/src/main/java/com/tngtech/archunit/core/domain/JavaModifier.java
index 20989635..b5b47556 100644
--- a/archunit/src/main/java/com/tngtech/archunit/core/domain/JavaModifier.java
+++ b/archunit/src/main/java/com/tngtech/archunit/core/domain/JavaModifier.java
@@ -34,7 +34,7 @@ public enum JavaModifier {
@PublicAPI(usage = ACCESS)
PRIVATE(EnumSet.allOf(ApplicableType.class), Opcodes.ACC_PRIVATE),
@PublicAPI(usage = ACCESS)
- STATIC(EnumSet.of(ApplicableType.FIELD, ApplicableType.METHOD), Opcodes.ACC_STATIC),
+ STATIC(EnumSet.allOf(ApplicableType.class), Opcodes.ACC_STATIC),
@PublicAPI(usage = ACCESS)
FINAL(EnumSet.allOf(ApplicableType.class), Opcodes.ACC_FINAL),
@PublicAPI(usage = ACCESS)
diff --git a/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java b/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java
index 01d8c01c..126c7a25 100644
--- a/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java
@@ -306,9 +306,22 @@ public class ClassFileImporterTest {
ClassWithNestedClass.class,
ClassWithNestedClass.NestedClass.class,
ClassWithNestedClass.StaticNestedClass.class,
+ ClassWithNestedClass.NestedInterface.class,
+ ClassWithNestedClass.StaticNestedInterface.class,
Class.forName(ClassWithNestedClass.class.getName() + "$PrivateNestedClass"));
}
+ @Test
+ public void handles_static_modifier_of_nested_classes() throws Exception {
+ JavaClasses classes = classesIn("testexamples/nestedimport").classes;
+
+ assertThat(classes.get(ClassWithNestedClass.class).getModifiers()).as("modifiers of ClassWithNestedClass").doesNotContain(STATIC);
+ assertThat(classes.get(ClassWithNestedClass.NestedClass.class).getModifiers()).as("modifiers of ClassWithNestedClass.NestedClass").doesNotContain(STATIC);
+ assertThat(classes.get(ClassWithNestedClass.StaticNestedClass.class).getModifiers()).as("modifiers of ClassWithNestedClass.StaticNestedClass").contains(STATIC);
+ assertThat(classes.get(ClassWithNestedClass.NestedInterface.class).getModifiers()).as("modifiers of ClassWithNestedClass.NestedInterface").contains(STATIC);
+ assertThat(classes.get(ClassWithNestedClass.StaticNestedInterface.class).getModifiers()).as("modifiers of ClassWithNestedClass.StaticNestedInterface").contains(STATIC);
+ }
+
@Test
public void imports_jdk_classes() {
JavaClasses classes = new ClassFileImporter().importClasses(File.class);
diff --git a/archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/nestedimport/ClassWithNestedClass.java b/archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/nestedimport/ClassWithNestedClass.java
index 5b717958..ee2f3f4e 100644
--- a/archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/nestedimport/ClassWithNestedClass.java
+++ b/archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/nestedimport/ClassWithNestedClass.java
@@ -10,4 +10,10 @@ public class ClassWithNestedClass {
public static class StaticNestedClass {
}
+
+ public interface NestedInterface {
+ }
+
+ public static interface StaticNestedInterface {
+ }
} | ['archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java', 'archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/nestedimport/ClassWithNestedClass.java', 'archunit/src/main/java/com/tngtech/archunit/core/domain/JavaModifier.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 1,444,515 | 295,881 | 37,820 | 386 | 159 | 39 | 2 | 1 | 861 | 83 | 199 | 26 | 1 | 2 | 2019-08-24T09:41:53 | 2,751 | Java | {'Java': 5207204, 'Shell': 1522, 'Groovy': 512, 'Dockerfile': 367} | Apache License 2.0 |
990 | tng/archunit/688/683 | tng | archunit | https://github.com/TNG/ArchUnit/issues/683 | https://github.com/TNG/ArchUnit/pull/688 | https://github.com/TNG/ArchUnit/pull/688 | 1 | resolves | Can't handle spaces in dependencies | We use ArchUnit 0.21.0 on an OSGi system. To load our java classes we just point to a rootdir, pretty much like this:
```java
private static JavaClasses getJavaClasses() {
return new ClassFileImporter()
.withImportOption(DO_NOT_INCLUDE_ARCHIVES)
.importPath("rootPath");
}
```
OSGi being OSGi, the code above will only find the class files for our product. The dependencies reside in different directories such as `~/.m2/` or `$workspace/.metadata.plugins/`. When loading a dependency class the OSGi classloader will know to check such directories.
The stacktrace we're encountering is the following:
```
ClassResolverFromClasspath.tryGetUriOf(String) line: 62
ClassResolverFromClasspath.tryResolve(String) line: 49
ImportedClasses.getOrResolve(String) line: 57
ImportedClasses.ensurePresent(String) line: 69
ClassGraphCreator.ensureMemberTypesArePresent() line: 117
ClassGraphCreator.complete() line: 106
ClassFileProcessor.process(ClassFileSource) line: 63
ClassFileImporter.importLocations(Collection<Location>) line: 336
ClassFileImporter.importPaths(Collection<Path>) line: 158
ClassFileImporter.importPaths(String...) line: 133
ClassFileImporter.importPath(String) line: 112
BaseArchUnitTest.getJavaClasses() line: 56
```
Line 56 in `BaseArchUnitTest` being the `.importPath("rootPath");` in the code above.
For most of our `typeName`s in `ImportedClasses.getOrResolve(String)`, the javaClass != null and thus we have no need to resolve it. However, for dependencies such as OSGi's `Version.class` (org.osgi.framework.Version.class) we need to go look into the directories mentioned above.
This results in `resource` in `ClassResolverFromClasspath.tryGetUriOf(String)` being of the form `C:/Users/David Name/sigasi-development-project-master/ws/.metadata/.plugins/org.eclipse.pde.core/.bundle_pool/plugins/org.eclipse.osgi_3.16.300.v20210525-1715.jar!/org/osgi/framework/Version.class`. Note the space in the user name.
When we then try to do `resource.toURI()`, we get the error below.
Conclusion: The URL received from the classloader should first be encoded, and only then transformed into a URI
```
java.net.URISyntaxException: Illegal character in opaque part at index 24: jar:file:/C:/Users/David Name/sigasi-development-project-master/ws/.metadata/.plugins/org.eclipse.pde.core/.bundle_pool/plugins/org.eclipse.osgi_3.16.300.v20210525-1715.jar!/org/osgi/framework/Version.class
``` | a1b7c6765fa865bdf298104ff5a8dbf275e83a84 | fea8b8c4164e8c20c3ad276bd6537f70753617c0 | https://github.com/tng/archunit/compare/a1b7c6765fa865bdf298104ff5a8dbf275e83a84...fea8b8c4164e8c20c3ad276bd6537f70753617c0 | diff --git a/archunit/src/jdk9test/java/com/tngtech/archunit/core/importer/ModuleLocationFactoryTest.java b/archunit/src/jdk9test/java/com/tngtech/archunit/core/importer/ModuleLocationFactoryTest.java
index a8e402bc..1b2f6d86 100644
--- a/archunit/src/jdk9test/java/com/tngtech/archunit/core/importer/ModuleLocationFactoryTest.java
+++ b/archunit/src/jdk9test/java/com/tngtech/archunit/core/importer/ModuleLocationFactoryTest.java
@@ -5,7 +5,6 @@ import java.io.FileReader;
import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReference;
import java.net.URI;
-import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
@@ -13,15 +12,15 @@ import java.util.stream.StreamSupport;
import org.junit.Test;
-import static com.tngtech.archunit.core.domain.SourceTest.urlOf;
import static com.tngtech.archunit.core.importer.ClassFileSourceTest.MODULE_INFO_FILE_NAME;
+import static com.tngtech.archunit.testutil.TestUtils.uriOf;
import static org.assertj.core.api.Assertions.assertThat;
public class ModuleLocationFactoryTest {
private ModuleLocationFactory locationFactory = new ModuleLocationFactory();
@Test
- public void reads_single_entry_of_jrt() throws URISyntaxException {
+ public void reads_single_entry_of_jrt() {
URI jrtJavaIoFile = uriOf(File.class);
Location jrtJavaIo = locationFactory.create(jrtJavaIoFile);
@@ -30,7 +29,7 @@ public class ModuleLocationFactoryTest {
}
@Test
- public void iterates_package_of_jrt() throws URISyntaxException {
+ public void iterates_package_of_jrt() {
URI jrtJavaIoFile = uriOf(File.class);
Location jrtJavaIo = locationFactory.create(parentOf(jrtJavaIoFile));
@@ -39,7 +38,7 @@ public class ModuleLocationFactoryTest {
}
@Test
- public void iterates_entire_jrt() throws URISyntaxException {
+ public void iterates_entire_jrt() {
Location jrtContainingFile = locationFactory.create(createModuleUriContaining(File.class));
assertThat(jrtContainingFile.iterateEntries())
@@ -47,7 +46,7 @@ public class ModuleLocationFactoryTest {
}
@Test
- public void respects_import_options() throws URISyntaxException {
+ public void respects_import_options() {
Location jrtContainingFile = locationFactory.create(createModuleUriContaining(File.class));
ClassFileSource fileSource = jrtContainingFile.asClassFileSource(new ImportOptions()
@@ -76,7 +75,7 @@ public class ModuleLocationFactoryTest {
}
@SuppressWarnings("SameParameterValue")
- private URI createModuleUriContaining(Class<?> clazz) throws URISyntaxException {
+ private URI createModuleUriContaining(Class<?> clazz) {
URI someJrt = uriOf(clazz);
String moduleUri = someJrt.toString().replaceAll("(jrt:/[^/]+).*", "$1");
return URI.create(moduleUri);
@@ -85,8 +84,4 @@ public class ModuleLocationFactoryTest {
private URI parentOf(URI uri) {
return URI.create(uri.toString().replaceAll("/[^/]+$", ""));
}
-
- private URI uriOf(Class<?> clazz) throws URISyntaxException {
- return urlOf(clazz).toURI();
- }
}
diff --git a/archunit/src/main/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClasspath.java b/archunit/src/main/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClasspath.java
index a2f60ed1..3cf36df6 100644
--- a/archunit/src/main/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClasspath.java
+++ b/archunit/src/main/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClasspath.java
@@ -57,9 +57,19 @@ public final class ClassResolverFromClasspath implements ClassResolver {
return Optional.empty();
}
try {
- return Optional.of(resource.toURI());
+ return Optional.of(toUri(resource));
} catch (URISyntaxException e) {
throw new ArchUnitException.LocationException(e);
}
}
+
+ private URI toUri(URL resource) throws URISyntaxException {
+ try {
+ return resource.toURI();
+ } catch (URISyntaxException e) {
+ // In case the ClassLoader returns a URL with unencoded characters (e.g. spaces), this will correctly encode them.
+ // This was added to solve https://github.com/TNG/ArchUnit/issues/683 where some OSGI ClassLoader would not encode spaces correctly.
+ return new URI(resource.getProtocol(), resource.getHost(), resource.getPath(), null);
+ }
+ }
}
diff --git a/archunit/src/test/java/com/tngtech/archunit/ArchConfigurationTest.java b/archunit/src/test/java/com/tngtech/archunit/ArchConfigurationTest.java
index 3ace2f8c..81d785ca 100644
--- a/archunit/src/test/java/com/tngtech/archunit/ArchConfigurationTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/ArchConfigurationTest.java
@@ -17,13 +17,12 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.tngtech.archunit.testutil.Assertions.assertThat;
import static com.tngtech.archunit.testutil.ReflectionTestUtils.constructor;
-import static com.tngtech.archunit.testutil.TestUtils.properties;
-import static com.tngtech.archunit.testutil.TestUtils.singleProperty;
+import static com.tngtech.archunit.testutil.TestUtils.*;
import static org.assertj.core.api.Assertions.entry;
public class ArchConfigurationTest {
private static final String PROPERTIES_FILE_NAME = "archconfigtest.properties";
- private final File testPropsFile = new File(getClass().getResource("/").getFile(), PROPERTIES_FILE_NAME);
+ private final File testPropsFile = new File(new File(toUri(getClass().getResource("/"))), PROPERTIES_FILE_NAME);
@Rule
public final ExpectedException thrown = ExpectedException.none();
diff --git a/archunit/src/test/java/com/tngtech/archunit/core/domain/SourceTest.java b/archunit/src/test/java/com/tngtech/archunit/core/domain/SourceTest.java
index aca2e267..cadc9c93 100644
--- a/archunit/src/test/java/com/tngtech/archunit/core/domain/SourceTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/core/domain/SourceTest.java
@@ -24,8 +24,9 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import static com.google.common.base.Preconditions.checkNotNull;
import static com.tngtech.archunit.testutil.Assertions.assertThat;
+import static com.tngtech.archunit.testutil.TestUtils.uriOf;
+import static com.tngtech.archunit.testutil.TestUtils.urlOf;
import static com.tngtech.java.junit.dataprovider.DataProviders.$;
import static com.tngtech.java.junit.dataprovider.DataProviders.$$;
import static java.nio.charset.StandardCharsets.UTF_8;
@@ -38,11 +39,11 @@ public class SourceTest {
}
@Test
- public void source_file_name() throws URISyntaxException {
- Source source = new Source(urlOf(Object.class).toURI(), Optional.of("SomeClass.java"), false);
+ public void source_file_name() {
+ Source source = new Source(uriOf(Object.class), Optional.of("SomeClass.java"), false);
assertThat(source.getFileName()).as("source file name").contains("SomeClass.java");
- source = new Source(urlOf(Object.class).toURI(), Optional.<String>empty(), false);
+ source = new Source(uriOf(Object.class), Optional.<String>empty(), false);
assertThat(source.getFileName()).as("source file name").isAbsent();
}
@@ -150,10 +151,10 @@ public class SourceTest {
@Test
public void disables_md5_calculation_via_parameter() throws Exception {
- Source source = new Source(urlOf(getClass()).toURI(), Optional.of("any.java"), false);
+ Source source = new Source(uriOf(getClass()), Optional.of("any.java"), false);
assertThat(source.getMd5sum()).isEqualTo(Md5sum.DISABLED);
- source = new Source(urlOf(getClass()).toURI(), Optional.of("any.java"), true);
+ source = new Source(uriOf(getClass()), Optional.of("any.java"), true);
assertThat(source.getMd5sum().asBytes()).isEqualTo(expectedMd5BytesAt(source.getUri().toURL()));
}
@@ -185,9 +186,4 @@ public class SourceTest {
private static Object jarUrl() {
return urlOf(Rule.class);
}
-
- public static URL urlOf(Class<?> clazz) {
- return checkNotNull(clazz.getResource("/" + clazz.getName().replace('.', '/') + ".class"),
- "Can't determine url of %s", clazz.getName());
- }
}
diff --git a/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterSlowTest.java b/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterSlowTest.java
index 9685e8e8..f22fcd3a 100644
--- a/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterSlowTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterSlowTest.java
@@ -1,7 +1,6 @@
package com.tngtech.archunit.core.importer;
import java.io.File;
-import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
@@ -21,13 +20,13 @@ import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
-import static com.tngtech.archunit.core.domain.SourceTest.urlOf;
import static com.tngtech.archunit.core.importer.ClassFileImporterTestUtils.jarFileOf;
import static com.tngtech.archunit.core.importer.ImportOption.Predefined.DO_NOT_INCLUDE_TESTS;
import static com.tngtech.archunit.core.importer.UrlSourceTest.JAVA_CLASS_PATH_PROP;
import static com.tngtech.archunit.testutil.Assertions.assertThat;
import static com.tngtech.archunit.testutil.Assertions.assertThatType;
import static com.tngtech.archunit.testutil.Assertions.assertThatTypes;
+import static com.tngtech.archunit.testutil.TestUtils.urlOf;
import static java.util.jar.Attributes.Name.CLASS_PATH;
@Category(Slow.class)
@@ -99,7 +98,7 @@ public class ClassFileImporterSlowTest {
}
@Test
- public void imports_duplicate_classes() throws IOException {
+ public void imports_duplicate_classes() {
String existingClass = urlOf(JavaClass.class).getFile();
copyRule.copy(
new File(existingClass),
diff --git a/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java b/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java
index 71a9cec6..7c23c171 100644
--- a/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java
@@ -6,7 +6,6 @@ import java.io.PrintStream;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.net.MalformedURLException;
-import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -87,7 +86,6 @@ import static com.tngtech.archunit.core.domain.JavaModifier.BRIDGE;
import static com.tngtech.archunit.core.domain.JavaModifier.STATIC;
import static com.tngtech.archunit.core.domain.JavaModifier.SYNTHETIC;
import static com.tngtech.archunit.core.domain.SourceTest.bytesAt;
-import static com.tngtech.archunit.core.domain.SourceTest.urlOf;
import static com.tngtech.archunit.core.domain.TestUtils.MD5_SUM_DISABLED;
import static com.tngtech.archunit.core.domain.TestUtils.md5sumOf;
import static com.tngtech.archunit.core.domain.properties.HasName.Utils.namesOf;
@@ -100,6 +98,8 @@ import static com.tngtech.archunit.testutil.Assertions.assertThatTypes;
import static com.tngtech.archunit.testutil.ReflectionTestUtils.constructor;
import static com.tngtech.archunit.testutil.ReflectionTestUtils.field;
import static com.tngtech.archunit.testutil.ReflectionTestUtils.method;
+import static com.tngtech.archunit.testutil.TestUtils.uriOf;
+import static com.tngtech.archunit.testutil.TestUtils.urlOf;
import static com.tngtech.java.junit.dataprovider.DataProviders.$;
import static com.tngtech.java.junit.dataprovider.DataProviders.$$;
import static com.tngtech.java.junit.dataprovider.DataProviders.testForEach;
@@ -654,7 +654,7 @@ public class ClassFileImporterTest {
@Test
public void imports_urls_of_folders() throws Exception {
- File testexamplesFolder = new File(new File(urlOf(getClass()).toURI()).getParentFile(), "testexamples");
+ File testexamplesFolder = new File(new File(uriOf(getClass())).getParentFile(), "testexamples");
JavaClasses javaClasses = new ClassFileImporter().importUrl(testexamplesFolder.toURI().toURL());
@@ -797,19 +797,19 @@ public class ClassFileImporterTest {
JavaClass clazzFromFile = new ClassFileImporter().importClass(ClassToImportOne.class);
Source source = clazzFromFile.getSource().get();
- assertThat(source.getUri()).isEqualTo(urlOf(ClassToImportOne.class).toURI());
+ assertThat(source.getUri()).isEqualTo(uriOf(ClassToImportOne.class));
assertThat(source.getFileName()).contains(ClassToImportOne.class.getSimpleName() + ".java");
assertThat(source.getMd5sum()).isEqualTo(md5sumOf(bytesAt(urlOf(ClassToImportOne.class))));
clazzFromFile = new ClassFileImporter().importClass(ClassWithInnerClass.Inner.class);
source = clazzFromFile.getSource().get();
- assertThat(source.getUri()).isEqualTo(urlOf(ClassWithInnerClass.Inner.class).toURI());
+ assertThat(source.getUri()).isEqualTo(uriOf(ClassWithInnerClass.Inner.class));
assertThat(source.getFileName()).contains(ClassWithInnerClass.class.getSimpleName() + ".java");
assertThat(source.getMd5sum()).isEqualTo(md5sumOf(bytesAt(urlOf(ClassWithInnerClass.Inner.class))));
JavaClass clazzFromJar = new ClassFileImporter().importClass(Rule.class);
source = clazzFromJar.getSource().get();
- assertThat(source.getUri()).isEqualTo(urlOf(Rule.class).toURI());
+ assertThat(source.getUri()).isEqualTo(uriOf(Rule.class));
assertThat(source.getFileName()).contains(Rule.class.getSimpleName() + ".java");
assertThat(source.getMd5sum()).isEqualTo(md5sumOf(bytesAt(urlOf(Rule.class))));
@@ -850,8 +850,8 @@ public class ClassFileImporterTest {
}
@Test
- public void imports_paths() throws Exception {
- File exampleFolder = new File(new File(urlOf(getClass()).toURI()).getParentFile(), "testexamples");
+ public void imports_paths() {
+ File exampleFolder = new File(new File(uriOf(getClass())).getParentFile(), "testexamples");
File folderOne = new File(exampleFolder, "pathone");
File folderTwo = new File(exampleFolder, "pathtwo");
@@ -876,7 +876,7 @@ public class ClassFileImporterTest {
public void ImportOptions_are_respected() throws Exception {
ClassFileImporter importer = new ClassFileImporter().withImportOption(importOnly(getClass(), Rule.class));
- assertThatTypes(importer.importPath(Paths.get(urlOf(getClass()).toURI()))).matchExactly(getClass());
+ assertThatTypes(importer.importPath(Paths.get(uriOf(getClass())))).matchExactly(getClass());
assertThatTypes(importer.importUrl(urlOf(getClass()))).matchExactly(getClass());
assertThatTypes(importer.importJar(jarFileOf(Rule.class))).matchExactly(Rule.class);
}
@@ -898,8 +898,8 @@ public class ClassFileImporterTest {
assertThat(classes.get(clazz.getName())).hasSimpleName(clazz.getSimpleName());
}
- private void copyClassFile(Class<?> clazz, File targetFolder) throws IOException, URISyntaxException {
- Files.copy(Paths.get(urlOf(clazz).toURI()), new File(targetFolder, clazz.getSimpleName() + ".class").toPath());
+ private void copyClassFile(Class<?> clazz, File targetFolder) throws IOException {
+ Files.copy(Paths.get(uriOf(clazz)), new File(targetFolder, clazz.getSimpleName() + ".class").toPath());
}
private ImportOption importOnly(final Class<?>... classes) {
diff --git a/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTestUtils.java b/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTestUtils.java
index 2e57347f..9f2b1e7b 100644
--- a/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTestUtils.java
+++ b/archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTestUtils.java
@@ -16,7 +16,7 @@ import com.tngtech.archunit.core.domain.properties.HasName;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getFirst;
-import static com.tngtech.archunit.core.domain.SourceTest.urlOf;
+import static com.tngtech.archunit.testutil.TestUtils.urlOf;
class ClassFileImporterTestUtils {
diff --git a/archunit/src/test/java/com/tngtech/archunit/core/importer/LocationTest.java b/archunit/src/test/java/com/tngtech/archunit/core/importer/LocationTest.java
index 8f901042..095fcff4 100644
--- a/archunit/src/test/java/com/tngtech/archunit/core/importer/LocationTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/core/importer/LocationTest.java
@@ -1,5 +1,18 @@
package com.tngtech.archunit.core.importer;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import com.tngtech.archunit.ArchConfiguration;
+import com.tngtech.archunit.base.DescribedPredicate;
+import com.tngtech.archunit.core.InitialConfigurationTest;
+import com.tngtech.archunit.core.importer.resolvers.ClassResolverFactoryTest;
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+import com.tngtech.java.junit.dataprovider.UseDataProvider;
+import org.assertj.core.api.Condition;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -15,19 +28,6 @@ import java.util.Set;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Sets;
-import com.tngtech.archunit.ArchConfiguration;
-import com.tngtech.archunit.base.DescribedPredicate;
-import com.tngtech.archunit.core.InitialConfigurationTest;
-import com.tngtech.archunit.core.importer.resolvers.ClassResolverFactoryTest;
-import com.tngtech.java.junit.dataprovider.DataProvider;
-import com.tngtech.java.junit.dataprovider.DataProviderRunner;
-import com.tngtech.java.junit.dataprovider.UseDataProvider;
-import org.assertj.core.api.Condition;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
import static com.google.common.base.Functions.toStringFunction;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.transform;
@@ -283,7 +283,7 @@ public class LocationTest {
@Test
public void location_of_path() throws URISyntaxException {
URL url = getClass().getResource(".");
- assertThat(Location.of(Paths.get(url.toURI())).asURI().getPath()).isEqualTo(url.getFile());
+ assertThat(Location.of(Paths.get(url.toURI())).asURI()).isEqualTo(url.toURI());
}
@DataProvider
diff --git a/archunit/src/test/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClassPathTest.java b/archunit/src/test/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClassPathTest.java
index 681eda80..89e41636 100644
--- a/archunit/src/test/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClassPathTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClassPathTest.java
@@ -1,22 +1,37 @@
package com.tngtech.archunit.core.importer.resolvers;
+import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.net.URL;
+import com.tngtech.archunit.base.Function;
import com.tngtech.archunit.base.Optional;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.importer.resolvers.ClassResolver.ClassUriImporter;
+import com.tngtech.archunit.testutil.TestUtils;
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+import com.tngtech.java.junit.dataprovider.UseDataProvider;
+import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import static com.tngtech.archunit.core.domain.TestUtils.importClassWithContext;
import static com.tngtech.archunit.testutil.Assertions.assertThat;
+import static com.tngtech.java.junit.dataprovider.DataProviders.$;
+import static com.tngtech.java.junit.dataprovider.DataProviders.$$;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
+@RunWith(DataProviderRunner.class)
public class ClassResolverFromClassPathTest {
@Rule
public final MockitoRule mockitoRule = MockitoJUnit.rule();
@@ -24,14 +39,17 @@ public class ClassResolverFromClassPathTest {
@Mock
private ClassUriImporter uriImporter;
- private ClassResolverFromClasspath resolver = new ClassResolverFromClasspath();
+ private final ClassResolverFromClasspath resolver = new ClassResolverFromClasspath();
+
+ @Before
+ public void setUp() {
+ resolver.setClassUriImporter(uriImporter);
+ }
@Test
- public void finds_uri_of_class_on_classpath() throws URISyntaxException {
+ public void finds_uri_of_class_on_classpath() {
JavaClass expectedJavaClass = importClassWithContext(Object.class);
- when(uriImporter.tryImport(uriOf(Object.class))).thenReturn(Optional.of(expectedJavaClass));
-
- resolver.setClassUriImporter(uriImporter);
+ when(uriImporter.tryImport(TestUtils.uriOf(Object.class))).thenReturn(Optional.of(expectedJavaClass));
Optional<JavaClass> result = resolver.tryResolve(Object.class.getName());
@@ -39,16 +57,62 @@ public class ClassResolverFromClassPathTest {
}
@Test
- public void is_resilient_if_URI_cant_be_located() throws URISyntaxException {
- resolver.setClassUriImporter(uriImporter);
-
+ public void is_resilient_if_URI_cant_be_located() {
Optional<JavaClass> result = resolver.tryResolve("sooo.Wrong");
assertThat(result).isAbsent();
verifyNoMoreInteractions(uriImporter);
}
- private URI uriOf(Class<?> clazz) throws URISyntaxException {
- return getClass().getResource("/" + clazz.getName().replace('.', '/') + ".class").toURI();
+ @DataProvider
+ public static Object[][] urls_with_spaces() throws MalformedURLException, URISyntaxException {
+ return $$(
+ $(new URL("file:/C:/Some Windows/URL with spaces 123/any.jar"), new URI("file:/C:/Some%20Windows/URL%20with%20spaces%20123/any.jar")),
+ $(new URL("file:/Some Unix/URL with spaces 123/any.jar"), new URI("file:/Some%20Unix/URL%20with%20spaces%20123/any.jar"))
+ );
+ }
+
+ @Test
+ @UseDataProvider("urls_with_spaces")
+ public void is_resilient_against_wrongly_encoded_ClassLoader_resource_URLs(final URL urlReturnedByClassLoader, URI expectedUriDerivedFromUrl) {
+ // it seems like some OSGI ClassLoaders incorrectly return URLs with unencoded spaces.
+ // This lead to `url.toURI()` throwing an exception -> https://github.com/TNG/ArchUnit/issues/683
+ verifyUrlCannotBeConvertedToUriInTheCurrentForm(urlReturnedByClassLoader);
+
+ final JavaClass expectedJavaClass = importClassWithContext(Object.class);
+ when(uriImporter.tryImport(expectedUriDerivedFromUrl)).thenReturn(Optional.of(expectedJavaClass));
+
+ Optional<JavaClass> resolvedClass = withMockedContextClassLoader(new Function<ClassLoader, Optional<JavaClass>>() {
+ @Override
+ public Optional<JavaClass> apply(ClassLoader classLoaderMock) {
+ String typeNameFromUrlWithSpaces = "some.TypeFromUrlWithSpaces";
+ String typeResourceFromUrlWithSpaces = typeNameFromUrlWithSpaces.replace(".", "/") + ".class";
+ when(classLoaderMock.getResource(typeResourceFromUrlWithSpaces)).thenReturn(urlReturnedByClassLoader);
+
+ return resolver.tryResolve(typeNameFromUrlWithSpaces);
+ }
+ });
+
+ assertThat(resolvedClass).contains(expectedJavaClass);
+ }
+
+ private <T> T withMockedContextClassLoader(Function<ClassLoader, T> doWithClassLoader) {
+ ClassLoader classLoaderMock = mock(ClassLoader.class);
+ ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
+ try {
+ Thread.currentThread().setContextClassLoader(classLoaderMock);
+ return doWithClassLoader.apply(classLoaderMock);
+ } finally {
+ Thread.currentThread().setContextClassLoader(originalContextClassLoader);
+ }
+ }
+
+ private void verifyUrlCannotBeConvertedToUriInTheCurrentForm(final URL url) {
+ assertThatThrownBy(new ThrowingCallable() {
+ @Override
+ public void call() throws Throwable {
+ url.toURI();
+ }
+ }).isInstanceOf(URISyntaxException.class);
}
}
\\ No newline at end of file
diff --git a/archunit/src/test/java/com/tngtech/archunit/lang/ArchRuleTest.java b/archunit/src/test/java/com/tngtech/archunit/lang/ArchRuleTest.java
index 410bdd3f..b2ef9506 100644
--- a/archunit/src/test/java/com/tngtech/archunit/lang/ArchRuleTest.java
+++ b/archunit/src/test/java/com/tngtech/archunit/lang/ArchRuleTest.java
@@ -1,12 +1,5 @@
package com.tngtech.archunit.lang;
-import java.io.File;
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.io.Files;
@@ -23,6 +16,13 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
+import java.io.File;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
import static com.google.common.collect.Lists.newArrayList;
import static com.tngtech.archunit.core.domain.TestUtils.importClasses;
import static com.tngtech.archunit.core.domain.TestUtils.importClassesWithContext;
@@ -30,6 +30,7 @@ import static com.tngtech.archunit.lang.ArchRule.Assertions.ARCHUNIT_IGNORE_PATT
import static com.tngtech.archunit.lang.Priority.HIGH;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.all;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
+import static com.tngtech.archunit.testutil.TestUtils.toUri;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
@@ -178,7 +179,7 @@ public class ArchRuleTest {
}
private File ignoreFile() {
- return new File(new File(getClass().getResource("/").getFile()), ARCHUNIT_IGNORE_PATTERNS_FILE_NAME);
+ return new File(new File(toUri(getClass().getResource("/"))), ARCHUNIT_IGNORE_PATTERNS_FILE_NAME);
}
private void expectAssertionErrorWithMessages(final String... messages) {
diff --git a/archunit/src/test/java/com/tngtech/archunit/lang/extension/TestServicesFile.java b/archunit/src/test/java/com/tngtech/archunit/lang/extension/TestServicesFile.java
index 3bac1548..df6fec66 100644
--- a/archunit/src/test/java/com/tngtech/archunit/lang/extension/TestServicesFile.java
+++ b/archunit/src/test/java/com/tngtech/archunit/lang/extension/TestServicesFile.java
@@ -1,12 +1,13 @@
package com.tngtech.archunit.lang.extension;
-import java.io.File;
-
import com.tngtech.archunit.testutil.ReplaceFileRule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
+import java.io.File;
+
+import static com.tngtech.archunit.testutil.TestUtils.toUri;
import static java.nio.charset.StandardCharsets.UTF_8;
public class TestServicesFile implements TestRule {
@@ -18,7 +19,7 @@ public class TestServicesFile implements TestRule {
}
public void addService(Class<? extends ArchUnitExtension> extensionClass) {
- File root = new File(getClass().getResource("/").getFile());
+ File root = new File(toUri(getClass().getResource("/")));
File metaInfServices = new File(new File(root, "META-INF"), "services");
File extensionSPI = new File(metaInfServices, ArchUnitExtension.class.getName());
replaceFile.appendLine(extensionSPI, extensionClass.getName(), UTF_8);
diff --git a/archunit/src/test/java/com/tngtech/archunit/testutil/OutsideOfClassPathRule.java b/archunit/src/test/java/com/tngtech/archunit/testutil/OutsideOfClassPathRule.java
index a8e76406..0946aa24 100644
--- a/archunit/src/test/java/com/tngtech/archunit/testutil/OutsideOfClassPathRule.java
+++ b/archunit/src/test/java/com/tngtech/archunit/testutil/OutsideOfClassPathRule.java
@@ -1,14 +1,5 @@
package com.tngtech.archunit.testutil;
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.SimpleFileVisitor;
-import java.nio.file.attribute.BasicFileAttributes;
-
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
@@ -18,8 +9,18 @@ import org.junit.rules.TemporaryFolder;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+
import static com.google.common.base.Preconditions.checkState;
import static com.tngtech.archunit.testutil.TestUtils.newTemporaryFolder;
+import static com.tngtech.archunit.testutil.TestUtils.toUri;
public class OutsideOfClassPathRule extends ExternalResource {
private final TemporaryFolder temporaryFolder = new TemporaryFolder(newTemporaryFolder());
@@ -39,7 +40,7 @@ public class OutsideOfClassPathRule extends ExternalResource {
}
public Path setUp(URL folder) throws IOException {
- this.originFolder = new File(folder.getFile()).toPath();
+ this.originFolder = new File(toUri(folder)).toPath();
return moveOutOfClassPath();
}
diff --git a/archunit/src/test/java/com/tngtech/archunit/testutil/TestUtils.java b/archunit/src/test/java/com/tngtech/archunit/testutil/TestUtils.java
index 6cfbf470..0636c734 100644
--- a/archunit/src/test/java/com/tngtech/archunit/testutil/TestUtils.java
+++ b/archunit/src/test/java/com/tngtech/archunit/testutil/TestUtils.java
@@ -2,6 +2,9 @@ package com.tngtech.archunit.testutil;
import java.io.File;
import java.lang.reflect.Method;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Properties;
@@ -11,6 +14,7 @@ import com.tngtech.archunit.core.domain.properties.HasName;
import org.assertj.core.util.Files;
import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
import static org.assertj.core.util.Files.temporaryFolderPath;
import static org.assertj.core.util.Strings.concat;
@@ -63,4 +67,21 @@ public class TestUtils {
}
});
}
+
+ public static URI toUri(URL url) {
+ try {
+ return url.toURI();
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static URL urlOf(Class<?> clazz) {
+ return requireNonNull(clazz.getResource("/" + clazz.getName().replace('.', '/') + ".class"),
+ String.format("Can't determine url of %s", clazz.getName()));
+ }
+
+ public static URI uriOf(Class<?> clazz) {
+ return toUri(urlOf(clazz));
+ }
} | ['archunit/src/main/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClasspath.java', 'archunit/src/jdk9test/java/com/tngtech/archunit/core/importer/ModuleLocationFactoryTest.java', 'archunit/src/test/java/com/tngtech/archunit/ArchConfigurationTest.java', 'archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTestUtils.java', 'archunit/src/test/java/com/tngtech/archunit/core/importer/resolvers/ClassResolverFromClassPathTest.java', 'archunit/src/test/java/com/tngtech/archunit/lang/extension/TestServicesFile.java', 'archunit/src/test/java/com/tngtech/archunit/core/importer/LocationTest.java', 'archunit/src/test/java/com/tngtech/archunit/testutil/OutsideOfClassPathRule.java', 'archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterSlowTest.java', 'archunit/src/test/java/com/tngtech/archunit/testutil/TestUtils.java', 'archunit/src/test/java/com/tngtech/archunit/lang/ArchRuleTest.java', 'archunit/src/test/java/com/tngtech/archunit/core/importer/ClassFileImporterTest.java', 'archunit/src/test/java/com/tngtech/archunit/core/domain/SourceTest.java'] | {'.java': 13} | 13 | 13 | 0 | 0 | 13 | 1,836,919 | 376,808 | 47,027 | 439 | 653 | 125 | 12 | 1 | 2,454 | 232 | 589 | 43 | 0 | 3 | 2021-10-09T12:44:02 | 2,751 | Java | {'Java': 5207204, 'Shell': 1522, 'Groovy': 512, 'Dockerfile': 367} | Apache License 2.0 |
1,084 | springdoc/springdoc-openapi/258/248 | springdoc | springdoc-openapi | https://github.com/springdoc/springdoc-openapi/issues/248 | https://github.com/springdoc/springdoc-openapi/pull/258 | https://github.com/springdoc/springdoc-openapi/pull/258 | 1 | fixes | Commit 80bc5a75361d1689fa72099963db84bcd95b2068 breaks project with JDK 11 + Kotlin | The commit 80bc5a75361d1689fa72099963db84bcd95b2068 is breaking again our project built with JDK 11 and Kotlin.
Can you please revert this? Additionally, what is the purpose of using `LocalVariableTableParameterNameDiscoverer` just to get the name of the parameters that you can get from `java.lang.reflect.Parameter` array that you already have at that point?
I've removed this `LocalVariableTableParameterNameDiscoverer` and no test is breaking.
I hope you can remove this again. Thanks!
Best regards,
João Dias
| 41c131ce45754558d3489268b94dfb9d7c0f173e | 41b61fd702b3f1d9925b58133e57ac3a05ce7b7b | https://github.com/springdoc/springdoc-openapi/compare/41c131ce45754558d3489268b94dfb9d7c0f173e...41b61fd702b3f1d9925b58133e57ac3a05ce7b7b | diff --git a/springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java b/springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java
index 8063e23b..e18b05dd 100644
--- a/springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java
+++ b/springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java
@@ -59,8 +59,9 @@ public abstract class AbstractRequestBuilder {
LocalVariableTableParameterNameDiscoverer d = parameterBuilder.getLocalSpringDocParameterNameDiscoverer();
String[] pNames = d.getParameterNames(handlerMethod.getMethod());
java.lang.reflect.Parameter[] parameters = handlerMethod.getMethod().getParameters();
+ String[] reflectionParametersNames = Arrays.stream(parameters).map(java.lang.reflect.Parameter::getName).toArray(String[]::new);
if (pNames == null) {
- pNames = Arrays.stream(parameters).map(java.lang.reflect.Parameter::getName).toArray(String[]::new);
+ pNames = reflectionParametersNames;
}
RequestBodyInfo requestBodyInfo = new RequestBodyInfo(methodAttributes);
List<Parameter> operationParameters = (operation.getParameters() != null) ? operation.getParameters()
@@ -70,7 +71,7 @@ public abstract class AbstractRequestBuilder {
for (int i = 0; i < pNames.length; i++) {
// check if query param
Parameter parameter = null;
- final String pName = pNames[i];
+ final String pName = pNames[i] == null ? reflectionParametersNames[i] : pNames[i];
io.swagger.v3.oas.annotations.Parameter parameterDoc = parameterBuilder.getParameterAnnotation(
handlerMethod, parameters[i], i, io.swagger.v3.oas.annotations.Parameter.class);
if (parameterDoc == null) { | ['springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 172,746 | 31,827 | 4,121 | 39 | 441 | 88 | 5 | 1 | 522 | 70 | 124 | 8 | 0 | 0 | 2019-12-12T18:15:38 | 2,717 | Java | {'Java': 4514044, 'Kotlin': 27895, 'Groovy': 9494, 'HTML': 223} | Apache License 2.0 |
1,083 | springdoc/springdoc-openapi/313/312 | springdoc | springdoc-openapi | https://github.com/springdoc/springdoc-openapi/issues/312 | https://github.com/springdoc/springdoc-openapi/pull/313 | https://github.com/springdoc/springdoc-openapi/pull/313 | 1 | fixes | Wrong server url with when grouped api name contains special charater | When the name of the grouped API contains a character which gets URL encoded the server url is generated wrong. When calculating the server URL the request URL should be decoded. | 168c4c9ca6a7c7f8a5e55b29b8da50366e4ff21b | e7c10c4788c64a0b6404b7ea3e114ee3e561f8d3 | https://github.com/springdoc/springdoc-openapi/compare/168c4c9ca6a7c7f8a5e55b29b8da50366e4ff21b...e7c10c4788c64a0b6404b7ea3e114ee3e561f8d3 | diff --git a/springdoc-openapi-common/src/main/java/org/springdoc/api/AbstractOpenApiResource.java b/springdoc-openapi-common/src/main/java/org/springdoc/api/AbstractOpenApiResource.java
index 87e61a7b..8df235e3 100644
--- a/springdoc-openapi-common/src/main/java/org/springdoc/api/AbstractOpenApiResource.java
+++ b/springdoc-openapi-common/src/main/java/org/springdoc/api/AbstractOpenApiResource.java
@@ -6,6 +6,7 @@ import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.PathItem.HttpMethod;
import io.swagger.v3.oas.models.responses.ApiResponses;
+import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.*;
@@ -18,7 +19,12 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
+import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
@@ -290,4 +296,12 @@ public abstract class AbstractOpenApiResource {
protected boolean isPathToMatch(String operationPath) {
return CollectionUtils.isEmpty(pathsToMatch) || pathsToMatch.stream().anyMatch(pattern -> antPathMatcher.match(pattern, operationPath));
}
+
+ protected static String decode(String requestURI) {
+ try {
+ return URLDecoder.decode(requestURI, StandardCharsets.UTF_8.toString());
+ } catch (UnsupportedEncodingException e) {
+ return requestURI;
+ }
+ }
}
diff --git a/springdoc-openapi-webflux-core/src/main/java/org/springdoc/api/OpenApiResource.java b/springdoc-openapi-webflux-core/src/main/java/org/springdoc/api/OpenApiResource.java
index 253e105a..19843c12 100644
--- a/springdoc-openapi-webflux-core/src/main/java/org/springdoc/api/OpenApiResource.java
+++ b/springdoc-openapi-webflux-core/src/main/java/org/springdoc/api/OpenApiResource.java
@@ -82,7 +82,7 @@ public class OpenApiResource extends AbstractOpenApiResource {
}
private void calculateServerUrl(ServerHttpRequest serverHttpRequest, String apiDocsUrl) {
- String requestUrl = serverHttpRequest.getURI().toString();
+ String requestUrl = decode(serverHttpRequest.getURI().toString());
String serverBaseUrl = requestUrl.substring(0, requestUrl.length() - apiDocsUrl.length());
openAPIBuilder.setServerBaseUrl(serverBaseUrl);
}
diff --git a/springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/MultipleOpenApiResource.java b/springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/MultipleOpenApiResource.java
index 1f7bc9d6..7707294f 100644
--- a/springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/MultipleOpenApiResource.java
+++ b/springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/MultipleOpenApiResource.java
@@ -3,6 +3,7 @@ package org.springdoc.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.v3.oas.annotations.Operation;
import org.springdoc.core.*;
+import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
@@ -21,14 +22,36 @@ import static org.springdoc.core.Constants.*;
import static org.springframework.util.AntPathMatcher.DEFAULT_PATH_SEPARATOR;
@RestController
-public class MultipleOpenApiResource {
+public class MultipleOpenApiResource implements InitializingBean {
- private final Map<String, OpenApiResource> groupedOpenApiResources;
+ private Map<String, OpenApiResource> groupedOpenApiResources;
+ private final List<GroupedOpenApi> groupedOpenApis;
+ private final ObjectFactory<OpenAPIBuilder> defaultOpenAPIBuilder;
+ private final AbstractRequestBuilder requestBuilder;
+ private final AbstractResponseBuilder responseBuilder;
+ private final OperationBuilder operationParser;
+ private final RequestMappingInfoHandlerMapping requestMappingHandlerMapping;
+ private final Optional<ActuatorProvider> servletContextProvider;
+
+ @Value(SPRINGDOC_SHOW_ACTUATOR_VALUE)
+ private boolean showActuator;
public MultipleOpenApiResource(List<GroupedOpenApi> groupedOpenApis,
ObjectFactory<OpenAPIBuilder> defaultOpenAPIBuilder, AbstractRequestBuilder requestBuilder,
AbstractResponseBuilder responseBuilder, OperationBuilder operationParser,
RequestMappingInfoHandlerMapping requestMappingHandlerMapping, Optional<ActuatorProvider> servletContextProvider) {
+
+ this.groupedOpenApis = groupedOpenApis;
+ this.defaultOpenAPIBuilder = defaultOpenAPIBuilder;
+ this.requestBuilder = requestBuilder;
+ this.responseBuilder = responseBuilder;
+ this.operationParser = operationParser;
+ this.requestMappingHandlerMapping = requestMappingHandlerMapping;
+ this.servletContextProvider = servletContextProvider;
+ }
+
+ @Override
+ public void afterPropertiesSet() throws Exception {
this.groupedOpenApiResources = groupedOpenApis.stream()
.collect(Collectors.toMap(GroupedOpenApi::getGroup, item ->
new OpenApiResource(
@@ -38,7 +61,8 @@ public class MultipleOpenApiResource {
operationParser,
requestMappingHandlerMapping,
servletContextProvider,
- Optional.of(item.getOpenApiCustomisers()), item.getPathsToMatch(), item.getPackagesToScan()
+ Optional.of(item.getOpenApiCustomisers()), item.getPathsToMatch(), item.getPackagesToScan(),
+ showActuator
)
));
}
@@ -67,4 +91,4 @@ public class MultipleOpenApiResource {
}
return openApiResource;
}
-}
\\ No newline at end of file
+}
diff --git a/springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/OpenApiResource.java b/springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/OpenApiResource.java
index aeec5584..0fab2447 100644
--- a/springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/OpenApiResource.java
+++ b/springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/OpenApiResource.java
@@ -53,12 +53,15 @@ public class OpenApiResource extends AbstractOpenApiResource {
public OpenApiResource(OpenAPIBuilder openAPIBuilder, AbstractRequestBuilder requestBuilder,
AbstractResponseBuilder responseBuilder, OperationBuilder operationParser,
RequestMappingInfoHandlerMapping requestMappingHandlerMapping, Optional<ActuatorProvider> servletContextProvider,
- Optional<List<OpenApiCustomiser>> openApiCustomisers, List<String> pathsToMatch, List<String> packagesToScan) {
+ Optional<List<OpenApiCustomiser>> openApiCustomisers, List<String> pathsToMatch, List<String> packagesToScan,
+ boolean showActuator) {
super(openAPIBuilder, requestBuilder, responseBuilder, operationParser, openApiCustomisers, pathsToMatch, packagesToScan);
this.requestMappingHandlerMapping = requestMappingHandlerMapping;
this.servletContextProvider = servletContextProvider;
+ this.showActuator = showActuator;
}
+
@Operation(hidden = true)
@GetMapping(value = API_DOCS_URL, produces = MediaType.APPLICATION_JSON_VALUE)
public String openapiJson(HttpServletRequest request, @Value(API_DOCS_URL) String apiDocsUrl)
@@ -126,8 +129,8 @@ public class OpenApiResource extends AbstractOpenApiResource {
}
private void calculateServerUrl(HttpServletRequest request, String apiDocsUrl) {
- StringBuffer requestUrl = request.getRequestURL();
- String serverBaseUrl = requestUrl.substring(0, requestUrl.length() - apiDocsUrl.length());
- openAPIBuilder.setServerBaseUrl(serverBaseUrl);
+ String requestUrl = decode(request.getRequestURL().toString());
+ String calculatedUrl = requestUrl.substring(0, requestUrl.length() - apiDocsUrl.length());
+ openAPIBuilder.setServerBaseUrl(calculatedUrl);
}
}
diff --git a/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocApp68Test.java b/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocApp68Test.java
index 88d500c4..087e2a64 100644
--- a/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocApp68Test.java
+++ b/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocApp68Test.java
@@ -57,7 +57,7 @@ public class SpringDocApp68Test {
@Test
public void testApp4() throws Exception {
- mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL + "/groups"))
+ mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL + "/groups test"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.openapi", is("3.0.1")))
.andExpect(content().json(getContent("results/app684.json"), true));
diff --git a/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocTestApp.java b/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocTestApp.java
index 1b245552..81d06752 100644
--- a/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocTestApp.java
+++ b/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocTestApp.java
@@ -43,7 +43,7 @@ public class SpringDocTestApp {
@Bean
public GroupedOpenApi groupOpenApi() {
return GroupedOpenApi.builder()
- .setGroup("groups")
+ .setGroup("groups test")
.pathsToMatch("/v1/**")
.packagesToScan("test.org.springdoc.api.app68.api.user", "test.org.springdoc.api.app68.api.store")
.build(); | ['springdoc-openapi-common/src/main/java/org/springdoc/api/AbstractOpenApiResource.java', 'springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocApp68Test.java', 'springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/OpenApiResource.java', 'springdoc-openapi-webflux-core/src/main/java/org/springdoc/api/OpenApiResource.java', 'springdoc-openapi-webmvc-core/src/main/java/org/springdoc/api/MultipleOpenApiResource.java', 'springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app68/SpringDocTestApp.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 206,740 | 38,115 | 4,910 | 53 | 3,066 | 558 | 59 | 4 | 178 | 31 | 33 | 1 | 0 | 0 | 2020-01-02T12:35:49 | 2,717 | Java | {'Java': 4514044, 'Kotlin': 27895, 'Groovy': 9494, 'HTML': 223} | Apache License 2.0 |
1,082 | springdoc/springdoc-openapi/518/517 | springdoc | springdoc-openapi | https://github.com/springdoc/springdoc-openapi/issues/517 | https://github.com/springdoc/springdoc-openapi/pull/518 | https://github.com/springdoc/springdoc-openapi/pull/518 | 2 | fixes | Commit 2594a276d97c8f4168f6f7aa22a00f8438f38dd5 broke Kotlin Coroutines support | This commit has changed the usage of `java.lang.reflect.Parameter` to `org.springframework.core.MethodParameter` and this broke Kotlin Coroutines support since with the second no parameter name is successfully retrieved. | 55b4d7fee8e3dc2c5b3a2000000fdc1e587b97b6 | 154d38d9caabcaed22b5cff48fcc11ea7a0cda76 | https://github.com/springdoc/springdoc-openapi/compare/55b4d7fee8e3dc2c5b3a2000000fdc1e587b97b6...154d38d9caabcaed22b5cff48fcc11ea7a0cda76 | diff --git a/springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java b/springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java
index adc9b904..62c168a4 100644
--- a/springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java
+++ b/springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java
@@ -160,8 +160,8 @@ public abstract class AbstractRequestBuilder {
// requests
String[] pNames = this.localSpringDocParameterNameDiscoverer.getParameterNames(handlerMethod.getMethod());
MethodParameter[] parameters = handlerMethod.getMethodParameters();
- String[] reflectionParametersNames = Arrays.stream(parameters).map(MethodParameter::getParameterName).toArray(String[]::new);
- if (pNames == null)
+ String[] reflectionParametersNames = Arrays.stream(handlerMethod.getMethod().getParameters()).map(java.lang.reflect.Parameter::getName).toArray(String[]::new);
+ if (pNames == null || Arrays.stream(pNames).anyMatch(Objects::isNull))
pNames = reflectionParametersNames;
parameters = DelegatingMethodParameter.customize(pNames, parameters);
RequestBodyInfo requestBodyInfo = new RequestBodyInfo(); | ['springdoc-openapi-common/src/main/java/org/springdoc/core/AbstractRequestBuilder.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 305,515 | 65,277 | 8,301 | 69 | 388 | 82 | 4 | 1 | 220 | 26 | 39 | 1 | 0 | 0 | 2020-03-30T00:53:12 | 2,717 | Java | {'Java': 4514044, 'Kotlin': 27895, 'Groovy': 9494, 'HTML': 223} | Apache License 2.0 |
1,080 | springdoc/springdoc-openapi/1002/996 | springdoc | springdoc-openapi | https://github.com/springdoc/springdoc-openapi/issues/996 | https://github.com/springdoc/springdoc-openapi/pull/1002 | https://github.com/springdoc/springdoc-openapi/pull/1002 | 1 | fixes | Minimal project with `use-management-port` set causes NPE on api-docs endpoint | **Describe the bug**
In a minimal example, use-management-port is generating NPEs when accessing v3/api-docs.
```
java.lang.NullPointerException: null
at org.springdoc.core.ActuatorProvider.getApplicationPort(ActuatorProvider.java:185) ~[springdoc-openapi-common-1.5.2.jar:1.5.2]
at org.springdoc.api.AbstractOpenApiResource.getActuatorURI(AbstractOpenApiResource.java:1061) ~[springdoc-openapi-common-1.5.2.jar:1.5.2]
at org.springdoc.webmvc.api.OpenApiActuatorResource.getServerUrl(OpenApiActuatorResource.java:152) ~[springdoc-openapi-webmvc-core-1.5.2.jar:1.5.2]
at org.springdoc.webmvc.api.OpenApiResource.calculateServerUrl(OpenApiResource.java:295) ~[springdoc-openapi-webmvc-core-1.5.2.jar:1.5.2]
at org.springdoc.webmvc.api.OpenApiResource.openapiJson(OpenApiResource.java:171) ~[springdoc-openapi-webmvc-core-1.5.2.jar:1.5.2]
at org.springdoc.webmvc.api.OpenApiActuatorResource.openapiJson(OpenApiActuatorResource.java:131) ~[springdoc-openapi-webmvc-core-1.5.2.jar:1.5.2]
```
This appears to be because the ActuatorProvider is trying to access a port from a null `applicationWebServer`. However the previous call's if statement in AbstractOpenApiResource might also be taking the wrong path. It could also be that my example is too minimal and I am missing some configuration.
**To Reproduce**
* Steps to reproduce the behavior:
* Created a simple project with one api endpoint, no groupings.
* Add Springdoc, v3/api-docs returns valid apis.
* Enable use-management-port, and set a management port.
* actuator/openapi produces NPE
What version of spring-boot you are using?
- 2.4.1
What modules and versions of springdoc-openapi are you using?
- 1.5.2
**Expected behavior**
- The same response I get when accessing without using the management port.
| 6dd01aa74e6d3cdab8b0018fd6964d5233321ef3 | 27e3541bb0d4e6e2d1cab5bd0b7b0cec7d3c2555 | https://github.com/springdoc/springdoc-openapi/compare/6dd01aa74e6d3cdab8b0018fd6964d5233321ef3...27e3541bb0d4e6e2d1cab5bd0b7b0cec7d3c2555 | diff --git a/springdoc-openapi-common/src/main/java/org/springdoc/core/ActuatorProvider.java b/springdoc-openapi-common/src/main/java/org/springdoc/core/ActuatorProvider.java
index 89fad675..c246d72f 100644
--- a/springdoc-openapi-common/src/main/java/org/springdoc/core/ActuatorProvider.java
+++ b/springdoc-openapi-common/src/main/java/org/springdoc/core/ActuatorProvider.java
@@ -30,6 +30,7 @@ import org.springdoc.api.AbstractOpenApiResource;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
+import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.boot.web.server.WebServer;
import org.springframework.context.ApplicationContext;
@@ -102,12 +103,11 @@ public abstract class ActuatorProvider implements ApplicationListener<WebServer
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
- if ("application".equals(event.getApplicationContext().getId())) {
- applicationWebServer = event.getWebServer();
- }
- else if ("application:management".equals(event.getApplicationContext().getId())) {
+ if (WebServerApplicationContext.hasServerNamespace(event.getApplicationContext(), "management")) {
managementApplicationContext = event.getApplicationContext();
actuatorWebServer = event.getWebServer();
+ } else {
+ applicationWebServer = event.getWebServer();
}
}
| ['springdoc-openapi-common/src/main/java/org/springdoc/core/ActuatorProvider.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 915,540 | 205,571 | 29,198 | 152 | 446 | 86 | 8 | 1 | 1,799 | 157 | 478 | 29 | 0 | 1 | 2020-12-29T15:53:40 | 2,717 | Java | {'Java': 4514044, 'Kotlin': 27895, 'Groovy': 9494, 'HTML': 223} | Apache License 2.0 |
264 | mybatis/spring/818/780 | mybatis | spring | https://github.com/mybatis/spring/issues/780 | https://github.com/mybatis/spring/pull/818 | https://github.com/mybatis/spring/pull/818 | 1 | fixes | Bean definition overridden when spring.aot.enabled=true in spring boot 3.0 | [original discussion](https://github.com/spring-projects/spring-boot/issues/33926)
The project is compiled with native profile and started with -Dspring.aot.enabled=true, and I got following exception.
```
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'l1ServiceA' defined in com.xmbsmdsj.springbootdemo.NativeConfiguration: @Bean definition illegally overridden by existing bean definition: Root bean: class [com.xmbsmdsj.springbootdemo.L1ServiceA]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=l1ServiceA; initMethodNames=null; destroyMethodNames=null
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.isOverriddenByExistingDefinition(ConfigurationClassBeanDefinitionReader.java:319) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:204) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:144) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:120) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:410) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:283) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:344) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:145) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:745) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:565) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.1.jar:3.0.1]
at com.xmbsmdsj.springbootdemo.SpringBootDemoApplication.main(SpringBootDemoApplication.java:11) ~[classes/:na]
```
I dropped a breakpoint in following method of ClassPathBeanDefinitionScanner, observing that @Configuration classes seem to be scanned even if bean definition registrations are generated at build-time.
```
public int scan(String... basePackages) {
int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
doScan(basePackages);
// It looks like the issue was due to this block
if (this.includeAnnotationConfig) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}
```
Heres the code to reproduce
https://github.com/spring-projects/spring-boot/files/10471672/spring-boot-demo.zip
| 40bb6939fdecbb5b523ad9c27197e8ab873f3f38 | 76c1766c8d3a9ef4e55664ce9f47963da277ff2c | https://github.com/mybatis/spring/compare/40bb6939fdecbb5b523ad9c27197e8ab873f3f38...76c1766c8d3a9ef4e55664ce9f47963da277ff2c | diff --git a/src/main/java/org/mybatis/spring/mapper/ClassPathMapperScanner.java b/src/main/java/org/mybatis/spring/mapper/ClassPathMapperScanner.java
index 617095f7..626cba99 100644
--- a/src/main/java/org/mybatis/spring/mapper/ClassPathMapperScanner.java
+++ b/src/main/java/org/mybatis/spring/mapper/ClassPathMapperScanner.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2022 the original author or authors.
+ * Copyright 2010-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,6 +27,7 @@ import org.mybatis.logging.LoggerFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.aop.scope.ScopedProxyFactoryBean;
import org.springframework.aop.scope.ScopedProxyUtils;
+import org.springframework.aot.AotDetector;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
@@ -87,7 +88,7 @@ public class ClassPathMapperScanner extends ClassPathBeanDefinitionScanner {
public ClassPathMapperScanner(BeanDefinitionRegistry registry) {
super(registry, false);
- setIncludeAnnotationConfig(!NativeDetector.inNativeImage());
+ setIncludeAnnotationConfig(!AotDetector.useGeneratedArtifacts());
setPrintWarnLogIfNotFoundMappers(!NativeDetector.inNativeImage());
}
| ['src/main/java/org/mybatis/spring/mapper/ClassPathMapperScanner.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 169,906 | 35,861 | 4,937 | 34 | 293 | 63 | 5 | 1 | 4,167 | 169 | 937 | 43 | 2 | 2 | 2023-05-13T12:54:00 | 2,681 | Java | {'Java': 424209, 'CSS': 6360, 'Shell': 1196} | Apache License 2.0 |
566 | square/keywhiz/250/170 | square | keywhiz | https://github.com/square/keywhiz/issues/170 | https://github.com/square/keywhiz/pull/250 | https://github.com/square/keywhiz/pull/250#issuecomment-240580226 | 1 | fix | Keywhiz has inconsistencies in filename enforcement | As evidenced by this output:
```
keywhiz.cli describe secret --name shh.2016-01-26T23:49:27Z.key
Exception in thread "main" java.lang.IllegalArgumentException: Invalid name, must match ^[a-zA-Z_0-9\\-.]+$
at keywhiz.cli.commands.DescribeAction.run(DescribeAction.java:58)
at keywhiz.cli.CommandExecutor.executeCommand(CommandExecutor.java:141)
at keywhiz.cli.CliMain.main(CliMain.java:68)
```
This secret was added via the automation API and otherwise is served and is displayed correctly.
| f17cf9d4988f55c01a4bf58d53d403c1fff37c91 | 3890f23c52cc48797062a1200d8566b06479447b | https://github.com/square/keywhiz/compare/f17cf9d4988f55c01a4bf58d53d403c1fff37c91...3890f23c52cc48797062a1200d8566b06479447b | diff --git a/cli/src/main/java/keywhiz/cli/Utilities.java b/cli/src/main/java/keywhiz/cli/Utilities.java
index 0871d598..2e1e6895 100644
--- a/cli/src/main/java/keywhiz/cli/Utilities.java
+++ b/cli/src/main/java/keywhiz/cli/Utilities.java
@@ -17,7 +17,7 @@ package keywhiz.cli;
public class Utilities {
- public static final String VALID_NAME_PATTERN = "^[a-zA-Z_0-9\\\\-.]+$";
+ public static final String VALID_NAME_PATTERN = "^[a-zA-Z_0-9\\\\-.:]+$";
public static boolean validName(String name) {
// "." is allowed at any position but the first.
diff --git a/cli/src/test/java/keywhiz/cli/UtilitiesTest.java b/cli/src/test/java/keywhiz/cli/UtilitiesTest.java
index 9788e8c1..d61d3a17 100644
--- a/cli/src/test/java/keywhiz/cli/UtilitiesTest.java
+++ b/cli/src/test/java/keywhiz/cli/UtilitiesTest.java
@@ -46,7 +46,7 @@ public class UtilitiesTest {
assertThat(validName("bad\\tI-am-secret.yml")).isFalse();
List<String> specialCharacters = Arrays.asList("&", "|", "(", ")", "[", "]", "{", "}", "^",
- ";", ",", "\\\\", "/", "<", ">", "\\t", "\\n", "\\r", "`", "'", "\\"", "?", ":", "#", "%",
+ ";", ",", "\\\\", "/", "<", ">", "\\t", "\\n", "\\r", "`", "'", "\\"", "?", "#", "%",
"*", "+", "=", "\\0", "\\u0002", "\\000");
for (String name : specialCharacters) { | ['cli/src/main/java/keywhiz/cli/Utilities.java', 'cli/src/test/java/keywhiz/cli/UtilitiesTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 533,393 | 116,615 | 15,180 | 154 | 148 | 45 | 2 | 1 | 503 | 44 | 133 | 12 | 0 | 1 | 2016-08-17T23:09:20 | 2,601 | Java | {'Java': 1652033, 'Ruby': 9423, 'Shell': 5836, 'Dockerfile': 3341, 'Smarty': 2334} | Apache License 2.0 |
522 | docker-java/docker-java/1218/532 | docker-java | docker-java | https://github.com/docker-java/docker-java/issues/532 | https://github.com/docker-java/docker-java/pull/1218 | https://github.com/docker-java/docker-java/pull/1218 | 1 | closes | Build command fails when symlinks in docker folder are used | My Docker image includes some files, which are symlinks pointing outside of docker folder, e.g.
```
$ ls -l include/
total 0
lrwxrwxrwx 1 dmitry dmitry 29 Mar 30 17:25 python3.5m -> /usr/local/include/python3.5m
```
Native docker client handles this correctly. Java `File.getCanonicalFile()` follows symlinks, so TAR archive sent to Docker daemon contains `usr/local/include/python3.5m/**` instead of expected `include/python3.5m/**`, and as a result I get confusing errors about non-existent files.
I guess replacing `FilePathUtil.relativize(File, File)` with the following code would work, but please check if this behavior does not break other usages.
```
public static String relativize(File baseDir, File file) {
try {
return baseDir.toPath()
.toRealPath(LinkOption.NOFOLLOW_LINKS)
.relativize(file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS))
.toString();
} catch (IOException e) {
throw new DockerClientException(e.getMessage(), e);
}
}
```
| 098f74d42bd44cd559d21ef278c984a5e8524a49 | 5f7349f0615f6f65ac06df20a4d46849f8668c74 | https://github.com/docker-java/docker-java/compare/098f74d42bd44cd559d21ef278c984a5e8524a49...5f7349f0615f6f65ac06df20a4d46849f8668c74 | diff --git a/src/main/java/com/github/dockerjava/core/util/CompressArchiveUtil.java b/src/main/java/com/github/dockerjava/core/util/CompressArchiveUtil.java
index 97471d7f..4590abb1 100644
--- a/src/main/java/com/github/dockerjava/core/util/CompressArchiveUtil.java
+++ b/src/main/java/com/github/dockerjava/core/util/CompressArchiveUtil.java
@@ -1,7 +1,6 @@
package com.github.dockerjava.core.util;
import static com.github.dockerjava.core.util.FilePathUtil.relativize;
-import static java.nio.file.FileVisitOption.FOLLOW_LINKS;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -13,7 +12,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.EnumSet;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
@@ -28,14 +26,26 @@ public class CompressArchiveUtil {
// utility class
}
- static void putTarEntry(TarArchiveOutputStream tarOutputStream, TarArchiveEntry tarEntry, Path file)
+ static void addFileToTar(TarArchiveOutputStream tarArchiveOutputStream, Path file, String entryName)
throws IOException {
- tarEntry.setSize(Files.size(file));
- tarOutputStream.putArchiveEntry(tarEntry);
- try (InputStream input = new BufferedInputStream(Files.newInputStream(file))) {
- ByteStreams.copy(input, tarOutputStream);
- tarOutputStream.closeArchiveEntry();
+ if (Files.isSymbolicLink(file)) {
+ TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(entryName, TarArchiveEntry.LF_SYMLINK);
+ tarArchiveEntry.setLinkName(Files.readSymbolicLink(file).toString());
+ tarArchiveOutputStream.putArchiveEntry(tarArchiveEntry);
+ } else {
+ TarArchiveEntry tarArchiveEntry = (TarArchiveEntry) tarArchiveOutputStream.createArchiveEntry(file.toFile(),
+ entryName);
+ if (file.toFile().canExecute()) {
+ tarArchiveEntry.setMode(tarArchiveEntry.getMode() | 0755);
+ }
+ tarArchiveOutputStream.putArchiveEntry(tarArchiveEntry);
+ if (file.toFile().isFile()) {
+ try (InputStream input = new BufferedInputStream(Files.newInputStream(file))) {
+ ByteStreams.copy(input, tarArchiveOutputStream);
+ }
+ }
}
+ tarArchiveOutputStream.closeArchiveEntry();
}
private static TarArchiveOutputStream buildTarStream(Path outputPath, boolean gZipped) throws IOException {
@@ -69,19 +79,14 @@ public class CompressArchiveUtil {
try (TarArchiveOutputStream tarArchiveOutputStream = buildTarStream(outputPath, gZipped)) {
if (!Files.isDirectory(inputPath)) {
- TarArchiveEntry tarEntry = new TarArchiveEntry(inputPath.getFileName().toString());
- if (inputPath.toFile().canExecute()) {
- tarEntry.setMode(tarEntry.getMode() | 0755);
- }
- putTarEntry(tarArchiveOutputStream, tarEntry, inputPath);
+ addFileToTar(tarArchiveOutputStream, inputPath, inputPath.getFileName().toString());
} else {
Path sourcePath = inputPath;
if (!childrenOnly) {
// In order to have the dossier as the root entry
sourcePath = inputPath.getParent();
}
- Files.walkFileTree(inputPath, EnumSet.of(FOLLOW_LINKS), Integer.MAX_VALUE,
- new TarDirWalker(sourcePath, tarArchiveOutputStream));
+ Files.walkFileTree(inputPath, new TarDirWalker(sourcePath, tarArchiveOutputStream));
}
tarArchiveOutputStream.flush();
}
@@ -95,19 +100,10 @@ public class CompressArchiveUtil {
new FileOutputStream(tarFile))))) {
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
for (File file : files) {
- TarArchiveEntry tarEntry = new TarArchiveEntry(file);
- tarEntry.setName(relativize(base, file));
-
- if (!file.isDirectory() && file.canExecute()) {
- tarEntry.setMode(tarEntry.getMode() | 0755);
- }
-
- tos.putArchiveEntry(tarEntry);
-
- if (!file.isDirectory()) {
- FileUtils.copyFile(file, tos);
- }
- tos.closeArchiveEntry();
+ // relativize with method using Path otherwise method with File resolves the symlinks
+ // and this is not want we want. If the file is a symlink, the relativized path should
+ // keep the symlink name and not the target it points to.
+ addFileToTar(tos, file.toPath(), relativize(base.toPath(), file.toPath()));
}
}
diff --git a/src/main/java/com/github/dockerjava/core/util/TarDirWalker.java b/src/main/java/com/github/dockerjava/core/util/TarDirWalker.java
index ec390611..a2b87d7b 100644
--- a/src/main/java/com/github/dockerjava/core/util/TarDirWalker.java
+++ b/src/main/java/com/github/dockerjava/core/util/TarDirWalker.java
@@ -33,14 +33,7 @@ public class TarDirWalker extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
- if (attrs.isSymbolicLink()) { // symbolic link to folder
- return FileVisitResult.CONTINUE;
- }
- TarArchiveEntry tarEntry = new TarArchiveEntry(FilePathUtil.relativize(basePath, file));
- if (file.toFile().canExecute()) {
- tarEntry.setMode(tarEntry.getMode() | 0755);
- }
- CompressArchiveUtil.putTarEntry(tarArchiveOutputStream, tarEntry, file);
+ CompressArchiveUtil.addFileToTar(tarArchiveOutputStream, file, FilePathUtil.relativize(basePath, file));
return FileVisitResult.CONTINUE;
}
diff --git a/src/test/java/com/github/dockerjava/core/util/CompressArchiveUtilTest.java b/src/test/java/com/github/dockerjava/core/util/CompressArchiveUtilTest.java
index c2b4a6f4..e8d88d24 100644
--- a/src/test/java/com/github/dockerjava/core/util/CompressArchiveUtilTest.java
+++ b/src/test/java/com/github/dockerjava/core/util/CompressArchiveUtilTest.java
@@ -2,7 +2,6 @@ package com.github.dockerjava.core.util;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
-import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
@@ -69,7 +68,6 @@ public class CompressArchiveUtilTest {
}
@Test
- @Ignore("Symlink creation is broken so test do not pass")
public void tarWithSymbolicLinkFileAsInput() throws IOException {
Path archiveSourceFile = tempFolder.getRoot().toPath().resolve("symlinkFile");
Path linkTargetFile = tempFolder.newFile("link-target").toPath();
@@ -140,7 +138,6 @@ public class CompressArchiveUtilTest {
}
@Test
- @Ignore("Symlink creation is broken so test do not pass")
public void tarWithfolderAsInputAndNestedSymbolicLinkFile() throws Exception {
Path archiveSourceDir = tempFolder.newFolder("archive-source").toPath();
Path linkTargetFile = tempFolder.newFile("link-target").toPath();
@@ -162,7 +159,6 @@ public class CompressArchiveUtilTest {
}
@Test
- @Ignore("Symlink creation is broken so test do not pass")
public void tarWithfolderAsInputAndNestedSymbolicLinkDir() throws Exception {
Path archiveSourceDir = tempFolder.newFolder("archive-source").toPath();
Path linkTargetDir = tempFolder.newFolder("link-target").toPath();
@@ -207,7 +203,6 @@ public class CompressArchiveUtilTest {
}
@Test
- @Ignore("Symlink creation is broken so test do not pass")
public void archiveTARFilesWithSymbolicLinkFile() throws Exception {
Path linkTargetFile = tempFolder.newFile("link-target").toPath();
Path symlinkFile = tempFolder.getRoot().toPath().resolve("symlinkFile");
@@ -219,7 +214,6 @@ public class CompressArchiveUtilTest {
}
@Test
- @Ignore("Symlink creation is broken so test do not pass")
public void archiveTARFilesWithSymbolicLinkDir() throws Exception {
Path linkTargetDir = tempFolder.newFolder("link-target").toPath();
Path symlinkFile = tempFolder.getRoot().toPath().resolve("symlinkFile"); | ['src/main/java/com/github/dockerjava/core/util/TarDirWalker.java', 'src/main/java/com/github/dockerjava/core/util/CompressArchiveUtil.java', 'src/test/java/com/github/dockerjava/core/util/CompressArchiveUtilTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 1,215,155 | 254,492 | 44,118 | 538 | 3,656 | 725 | 61 | 2 | 1,089 | 118 | 259 | 25 | 0 | 2 | 2019-07-11T01:50:42 | 2,597 | Java | {'Java': 1789504, 'Shell': 12612, 'Dockerfile': 4471} | Apache License 2.0 |
1,079 | real-logic/agrona/121/120 | real-logic | agrona | https://github.com/real-logic/agrona/issues/120 | https://github.com/real-logic/agrona/pull/121 | https://github.com/real-logic/agrona/pull/121 | 1 | fix | ObjectHashSet does not implement equals in a compatible fashion to HashSet/AbstractSet | In essence, it does not accommodate other implementations of the Set interface, such that a HashSet and an ObjectHashSet of the same contents are not equal. This blocks the adoption of ObjectHashSet as a drop in replacement. Happy to provide a PR if we agree this is desirable to be fixed. | 7b72974ef76c4aee7e1ae544127d622e0cefcc80 | 814a5bfd5d5b546bf63613ad6ce99f5120f39183 | https://github.com/real-logic/agrona/compare/7b72974ef76c4aee7e1ae544127d622e0cefcc80...814a5bfd5d5b546bf63613ad6ce99f5120f39183 | diff --git a/agrona/src/main/java/org/agrona/collections/IntHashSet.java b/agrona/src/main/java/org/agrona/collections/IntHashSet.java
index c29d0af1..552dc4be 100644
--- a/agrona/src/main/java/org/agrona/collections/IntHashSet.java
+++ b/agrona/src/main/java/org/agrona/collections/IntHashSet.java
@@ -652,7 +652,29 @@ public final class IntHashSet extends AbstractSet<Integer> implements Serializab
containsAll(otherSet);
}
- return false;
+ if (!(other instanceof Set))
+ {
+ return false;
+ }
+
+ final Set<?> c = (Set<?>)other;
+ if (c.size() != size())
+ {
+ return false;
+ }
+
+ try
+ {
+ return containsAll(c);
+ }
+ catch (final ClassCastException unused)
+ {
+ return false;
+ }
+ catch (final @DoNotSub NullPointerException unused)
+ {
+ return false;
+ }
}
/**
diff --git a/agrona/src/main/java/org/agrona/collections/ObjectHashSet.java b/agrona/src/main/java/org/agrona/collections/ObjectHashSet.java
index 5917d007..26654871 100644
--- a/agrona/src/main/java/org/agrona/collections/ObjectHashSet.java
+++ b/agrona/src/main/java/org/agrona/collections/ObjectHashSet.java
@@ -566,7 +566,29 @@ public final class ObjectHashSet<T> extends AbstractSet<T> implements Serializab
return otherSet.size == size && containsAll(otherSet);
}
- return false;
+ if (!(other instanceof Set))
+ {
+ return false;
+ }
+
+ final Set<?> c = (Set<?>)other;
+ if (c.size() != size())
+ {
+ return false;
+ }
+
+ try
+ {
+ return containsAll(c);
+ }
+ catch (final ClassCastException unused)
+ {
+ return false;
+ }
+ catch (final NullPointerException unused)
+ {
+ return false;
+ }
}
/**
diff --git a/agrona/src/test/java/org/agrona/collections/IntHashSetTest.java b/agrona/src/test/java/org/agrona/collections/IntHashSetTest.java
index 4ac0d2ea..23ecadfc 100644
--- a/agrona/src/test/java/org/agrona/collections/IntHashSetTest.java
+++ b/agrona/src/test/java/org/agrona/collections/IntHashSetTest.java
@@ -626,63 +626,6 @@ public class IntHashSetTest
assertThat(testSet, hasSize(1));
}
- private static void addTwoElements(final IntHashSet obj)
- {
- obj.add(1);
- obj.add(1001);
- }
-
- private static void addTwoElements(final HashSet<Integer> obj)
- {
- obj.add(1);
- obj.add(1001);
- }
-
- private void assertIteratorHasElements()
- {
- final Iterator<Integer> iter = testSet.iterator();
-
- final Set<Integer> values = new HashSet<>();
-
- assertTrue(iter.hasNext());
- values.add(iter.next());
- assertTrue(iter.hasNext());
- values.add(iter.next());
- assertFalse(iter.hasNext());
-
- assertContainsElements(values);
- }
-
- private void assertIteratorHasElementsWithoutHasNext()
- {
- final Iterator<Integer> iter = testSet.iterator();
-
- final Set<Integer> values = new HashSet<>();
-
- values.add(iter.next());
- values.add(iter.next());
-
- assertContainsElements(values);
- }
-
- private static void assertArrayContainingElements(final Integer[] result)
- {
- assertThat(result, arrayContainingInAnyOrder(1, 1001));
- }
-
- private static void assertContainsElements(final Set<Integer> other)
- {
- assertThat(other, containsInAnyOrder(1, 1001));
- }
-
- private void exhaustIterator()
- {
- final IntIterator iterator = testSet.iterator();
- iterator.next();
- iterator.next();
- iterator.next();
- }
-
@Test
public void shouldNotContainMissingValueInitially()
{
@@ -861,4 +804,84 @@ public class IntHashSetTest
assertFalse(testSet.contains(MISSING_VALUE));
}
+
+ @Test
+ public void shouldHaveCompatibleEqualsAndHashcode()
+ {
+ final HashSet compatibleSet = new HashSet();
+ final long seed = System.nanoTime();
+ final Random r = new Random(seed);
+ for (int i = 0; i < 1024; i++)
+ {
+ final int value = r.nextInt();
+ compatibleSet.add(value);
+ testSet.add(value);
+ }
+
+ if (r.nextBoolean())
+ {
+ compatibleSet.add(MISSING_VALUE);
+ testSet.add(MISSING_VALUE);
+ }
+ assertEquals("Fail with seed:" + seed, testSet, compatibleSet);
+ assertEquals("Fail with seed:" + seed, compatibleSet, testSet);
+ assertEquals("Fail with seed:" + seed, compatibleSet.hashCode(), testSet.hashCode());
+ }
+
+ private static void addTwoElements(final IntHashSet obj)
+ {
+ obj.add(1);
+ obj.add(1001);
+ }
+
+ private static void addTwoElements(final HashSet<Integer> obj)
+ {
+ obj.add(1);
+ obj.add(1001);
+ }
+
+ private void assertIteratorHasElements()
+ {
+ final Iterator<Integer> iter = testSet.iterator();
+
+ final Set<Integer> values = new HashSet<>();
+
+ assertTrue(iter.hasNext());
+ values.add(iter.next());
+ assertTrue(iter.hasNext());
+ values.add(iter.next());
+ assertFalse(iter.hasNext());
+
+ assertContainsElements(values);
+ }
+
+ private void assertIteratorHasElementsWithoutHasNext()
+ {
+ final Iterator<Integer> iter = testSet.iterator();
+
+ final Set<Integer> values = new HashSet<>();
+
+ values.add(iter.next());
+ values.add(iter.next());
+
+ assertContainsElements(values);
+ }
+
+ private static void assertArrayContainingElements(final Integer[] result)
+ {
+ assertThat(result, arrayContainingInAnyOrder(1, 1001));
+ }
+
+ private static void assertContainsElements(final Set<Integer> other)
+ {
+ assertThat(other, containsInAnyOrder(1, 1001));
+ }
+
+ private void exhaustIterator()
+ {
+ final IntIterator iterator = testSet.iterator();
+ iterator.next();
+ iterator.next();
+ iterator.next();
+ }
}
diff --git a/agrona/src/test/java/org/agrona/collections/ObjectHashSetIntegerTest.java b/agrona/src/test/java/org/agrona/collections/ObjectHashSetIntegerTest.java
index 43ce0a91..acded0a2 100644
--- a/agrona/src/test/java/org/agrona/collections/ObjectHashSetIntegerTest.java
+++ b/agrona/src/test/java/org/agrona/collections/ObjectHashSetIntegerTest.java
@@ -615,6 +615,24 @@ public class ObjectHashSetIntegerTest
assertFalse(iter.hasNext());
}
+ @Test
+ public void shouldHaveCompatibleEqualsAndHashcode()
+ {
+ final HashSet compatibleSet = new HashSet();
+ final long seed = System.nanoTime();
+ final Random r = new Random(seed);
+ for (int i = 0; i < 1024; i++)
+ {
+ final int value = r.nextInt();
+ compatibleSet.add(value);
+ testSet.add(value);
+ }
+
+ assertEquals("Fail with seed:" + seed, testSet, compatibleSet);
+ assertEquals("Fail with seed:" + seed, compatibleSet, testSet);
+ assertEquals("Fail with seed:" + seed, compatibleSet.hashCode(), testSet.hashCode());
+ }
+
private static void addTwoElements(final ObjectHashSet<Integer> obj)
{
obj.add(1); | ['agrona/src/main/java/org/agrona/collections/ObjectHashSet.java', 'agrona/src/test/java/org/agrona/collections/IntHashSetTest.java', 'agrona/src/main/java/org/agrona/collections/IntHashSet.java', 'agrona/src/test/java/org/agrona/collections/ObjectHashSetIntegerTest.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 732,189 | 156,397 | 25,619 | 138 | 1,020 | 188 | 48 | 2 | 289 | 51 | 58 | 1 | 0 | 0 | 2017-12-18T07:57:01 | 2,592 | Java | {'Java': 2048302, 'Shell': 687} | Apache License 2.0 |
540 | xerial/sqlite-jdbc/190/145 | xerial | sqlite-jdbc | https://github.com/xerial/sqlite-jdbc/issues/145 | https://github.com/xerial/sqlite-jdbc/pull/190 | https://github.com/xerial/sqlite-jdbc/pull/190 | 1 | fixes | Usage of sqlite-jdbc together with the relocation feature of the Maven shade plugin | I would like to use the sqlite in a project where I have to use the relocation feature of the Maven shade plugin to avoid clashes with different versions of the same library being loaded. The Maven shade plugin can relocate all Java classes to a different package name (e.g., org.sqlite to test.org.sqlite).
Unfortunately, sqlite-jdbc seems to load some of its classes dynamically at runtime in such a way that it is impossible for the Maven shade plugin to adjust the references accordingly. Therefore, all projects that use sqlilte, for example [cqengine](https://github.com/npgall/cqengine/issues/86), cannot be "shaded" entirely.
I created a small standalone test that demonstrates the issue. The test runs the example code of sqlite-jdbc. The JUnit test runs successfull, but when executing the shaded artifact: sqlite[...]-shaded.jar I get the following error:
> java -jar target/sqlite-shade-test-0.0.1-SNAPSHOT-shaded.jar
> java.sql.SQLException: No suitable driver found for jdbc:sqlite:C:\\Users[...]AppData\\Loca\\Temp\\test_8871362628708427569.db
> at java.sql.DriverManager.getConnection(Unknown Source)
> at java.sql.DriverManager.getConnection(Unknown Source)
> at test.SQLite.open(SQLite.java:21)
> at test.SQLite.main(SQLite.java:28)`
I tried to load the correct shaded driver with:
```
try {
Class.forName("test.org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
}
```
but that leads to a ClassNotFoundException.
Would it be possible to support this use case?
[sqlite-shade-test.zip](https://github.com/xerial/sqlite-jdbc/files/454772/sqlite-shade-test.zip)
| de738f7a49985e1a8c00274d6a407332f9ac1c83 | 27e3d90eba05fddaa01951112c06a9e1ed4f649e | https://github.com/xerial/sqlite-jdbc/compare/de738f7a49985e1a8c00274d6a407332f9ac1c83...27e3d90eba05fddaa01951112c06a9e1ed4f649e | diff --git a/src/main/java/org/sqlite/SQLiteJDBCLoader.java b/src/main/java/org/sqlite/SQLiteJDBCLoader.java
index 1878e04..fc06a88 100644
--- a/src/main/java/org/sqlite/SQLiteJDBCLoader.java
+++ b/src/main/java/org/sqlite/SQLiteJDBCLoader.java
@@ -19,7 +19,7 @@
// SQLite.java
// Since: 2007/05/10
//
-// $URL$
+// $URL$
// $Author$
//--------------------------------------
package org.sqlite;
@@ -308,7 +308,8 @@ public class SQLiteJDBCLoader {
}
// Load the os-dependent library from the jar file
- sqliteNativeLibraryPath = "/org/sqlite/native/" + OSInfo.getNativeLibFolderPathForCurrentOS();
+ String packagePath = SQLiteJDBCLoader.class.getPackage().getName().replaceAll("\\\\.", "/");
+ sqliteNativeLibraryPath = String.format("/%s/native/%s", packagePath, OSInfo.getNativeLibFolderPathForCurrentOS());
boolean hasNativeLib = hasResource(sqliteNativeLibraryPath + "/" + sqliteNativeLibraryName);
@@ -325,12 +326,12 @@ public class SQLiteJDBCLoader {
if(!hasNativeLib) {
extracted = false;
- throw new Exception(String.format("No native library is found for os.name=%s and os.arch=%s", OSInfo.getOSName(), OSInfo.getArchName()));
+ throw new Exception(String.format("No native library is found for os.name=%s and os.arch=%s. path=%s", OSInfo.getOSName(), OSInfo.getArchName(), sqliteNativeLibraryPath));
}
// temporary library folder
String tempFolder = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
- // Try extracting the library from jar
+ // Try extracting the library from jar
if(extractAndLoadLibraryFile(sqliteNativeLibraryPath, sqliteNativeLibraryName, tempFolder)) {
extracted = true;
return; | ['src/main/java/org/sqlite/SQLiteJDBCLoader.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 510,627 | 108,090 | 14,998 | 47 | 782 | 178 | 9 | 1 | 1,650 | 193 | 372 | 27 | 2 | 1 | 2017-01-05T22:57:46 | 2,470 | Java | {'Java': 1020238, 'C++': 211104, 'C': 108528, 'Shell': 96790, 'Makefile': 11178} | Apache License 2.0 |
539 | xerial/sqlite-jdbc/279/278 | xerial | sqlite-jdbc | https://github.com/xerial/sqlite-jdbc/issues/278 | https://github.com/xerial/sqlite-jdbc/pull/279 | https://github.com/xerial/sqlite-jdbc/pull/279 | 1 | fixes | DatabaseMetaData getExportedKeys does not escape PK_NAME for named primary keys | DatabaseMetaData `getExportedKeys` does not escape `PK_NAME`, resulting in a SQLException for named primary keys. | 9bbb62adc083fe1938e4c1bc6eb698b258631563 | 890c2cf41774ff77f8818442f052a4d582b3126a | https://github.com/xerial/sqlite-jdbc/compare/9bbb62adc083fe1938e4c1bc6eb698b258631563...890c2cf41774ff77f8818442f052a4d582b3126a | diff --git a/src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java b/src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java
index 4b453ec..cad9326 100644
--- a/src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java
+++ b/src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java
@@ -1434,6 +1434,7 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
StringBuilder exportedKeysQuery = new StringBuilder(512);
+ String target = null;
int count = 0;
if (pkColumns != null) {
// retrieve table list
@@ -1441,13 +1442,18 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
ArrayList<String> tableList = new ArrayList<String>();
while (rs.next()) {
- tableList.add(rs.getString(1));
+ String tblname = rs.getString(1);
+ tableList.add(tblname);
+ if (tblname.equalsIgnoreCase(table)) {
+ // get the correct case as in the database
+ // (not uppercase nor lowercase)
+ target = tblname;
+ }
}
rs.close();
ResultSet fk = null;
- String target = table.toLowerCase();
// find imported keys for each table
for (String tbl : tableList) {
try {
@@ -1465,20 +1471,20 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
while(fk.next()) {
int keySeq = fk.getInt(2) + 1;
- String PKTabName = fk.getString(3).toLowerCase();
+ String PKTabName = fk.getString(3);
- if (PKTabName == null || !PKTabName.equals(target)) {
+ if (PKTabName == null || !PKTabName.equalsIgnoreCase(target)) {
continue;
}
String PKColName = fk.getString(5);
- PKColName = (PKColName == null) ? pkColumns[0] : PKColName.toLowerCase();
+ PKColName = (PKColName == null) ? pkColumns[0] : PKColName;
exportedKeysQuery
.append(count > 0 ? " union all select " : "select ")
- .append(Integer.toString(keySeq)).append(" as ks, lower('")
- .append(escape(tbl)).append("') as fkt, lower('")
- .append(escape(fk.getString(4))).append("') as fcn, '")
+ .append(Integer.toString(keySeq)).append(" as ks, '")
+ .append(escape(tbl)).append("' as fkt, '")
+ .append(escape(fk.getString(4))).append("' as fcn, '")
.append(escape(PKColName)).append("' as pcn, ")
.append(RULE_MAP.get(fk.getString(6))).append(" as ur, ")
.append(RULE_MAP.get(fk.getString(7))).append(" as dr, ");
@@ -1490,7 +1496,7 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
Matcher matcher = FK_NAMED_PATTERN.matcher(rs.getString(1));
if (matcher.find()){
- exportedKeysQuery.append("'").append(escape(matcher.group(1).toLowerCase())).append("' as fkn");
+ exportedKeysQuery.append("'").append(escape(matcher.group(1))).append("' as fkn");
}
else {
exportedKeysQuery.append("'' as fkn");
@@ -1520,7 +1526,7 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
sql.append("select ")
.append(catalog).append(" as PKTABLE_CAT, ")
.append(schema).append(" as PKTABLE_SCHEM, ")
- .append(quote(table)).append(" as PKTABLE_NAME, ")
+ .append(quote(target)).append(" as PKTABLE_NAME, ")
.append(hasImportedKey ? "pcn" : "''").append(" as PKCOLUMN_NAME, ")
.append(catalog).append(" as FKTABLE_CAT, ")
.append(schema).append(" as FKTABLE_SCHEM, ")
@@ -1530,7 +1536,7 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
.append(hasImportedKey ? "ur" : "3").append(" as UPDATE_RULE, ")
.append(hasImportedKey ? "dr" : "3").append(" as DELETE_RULE, ")
.append(hasImportedKey ? "fkn" : "''").append(" as FK_NAME, ")
- .append(pkFinder.getName() != null ? pkFinder.getName() : "''").append(" as PK_NAME, ")
+ .append(pkFinder.getName() != null ? quote(pkFinder.getName()) : "''").append(" as PK_NAME, ")
.append(Integer.toString(DatabaseMetaData.importedKeyInitiallyDeferred)) // FIXME: Check for pragma foreign_keys = true ?
.append(" as DEFERRABILITY ");
diff --git a/src/test/java/org/sqlite/DBMetaDataTest.java b/src/test/java/org/sqlite/DBMetaDataTest.java
index ff416d2..e613b39 100644
--- a/src/test/java/org/sqlite/DBMetaDataTest.java
+++ b/src/test/java/org/sqlite/DBMetaDataTest.java
@@ -260,13 +260,6 @@ public class DBMetaDataTest
importedKeys.close();
}
-/* @Test
- public void columnOrderOfgetExportedKeys() throws SQLException {
-
- exportedKeys.close();
-
- }*/
-
@Test
public void numberOfgetExportedKeysCols() throws SQLException {
@@ -316,6 +309,50 @@ public class DBMetaDataTest
exportedKeys.close();
}
+ @Test
+ public void getExportedKeysColsForNamedKeys() throws SQLException {
+
+ ResultSet exportedKeys;
+
+ // 1. Check for named primary keys
+ // SQL is deliberately in uppercase, to make sure case-sensitivity is maintained
+ stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT PRIMARY KEY (ID1))");
+ stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, DATA2 INTEGER, FOREIGN KEY(ID1) REFERENCES PARENT1(ID1))");
+
+ exportedKeys = meta.getExportedKeys(null, null, "PARENT1");
+
+ assertTrue(exportedKeys.next());
+ assertEquals("PARENT1", exportedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID1", exportedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("PK_PARENT", exportedKeys.getString("PK_NAME"));
+ assertEquals("", exportedKeys.getString("FK_NAME"));
+ assertEquals("CHILD1", exportedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID1", exportedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(exportedKeys.next());
+
+ exportedKeys.close();
+
+ // 2. Check for named foreign keys
+ // SQL is deliberately in mixed case, to make sure case-sensitivity is maintained
+ stat.executeUpdate("CREATE TABLE Parent2 (Id1 INTEGER, DATA1 INTEGER, PRIMARY KEY (Id1))");
+ stat.executeUpdate("CREATE TABLE Child2 (Id1 INTEGER, DATA2 INTEGER, CONSTRAINT FK_Child2 FOREIGN KEY(Id1) REFERENCES Parent2(Id1))");
+
+ exportedKeys = meta.getExportedKeys(null, null, "Parent2");
+
+ assertTrue(exportedKeys.next());
+ assertEquals("Parent2", exportedKeys.getString("PKTABLE_NAME"));
+ assertEquals("Id1", exportedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("", exportedKeys.getString("PK_NAME"));
+ assertEquals("FK_Child2", exportedKeys.getString("FK_NAME"));
+ assertEquals("Child2", exportedKeys.getString("FKTABLE_NAME"));
+ assertEquals("Id1", exportedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(exportedKeys.next());
+
+ exportedKeys.close();
+ }
+
@Test
public void columnOrderOfgetTables() throws SQLException {
ResultSet rs = meta.getTables(null, null, null, null);
@@ -770,8 +807,8 @@ public class DBMetaDataTest
stat.executeUpdate("create table REFERRING (ID integer, RID integer, constraint fk\\r\\n foreign\\tkey\\r\\n(RID) references REFERRED(id))");
exportedKeys = meta.getExportedKeys(null, null, "referred");
- assertEquals("referred", exportedKeys.getString("PKTABLE_NAME"));
- assertEquals("referring", exportedKeys.getString("FKTABLE_NAME"));
+ assertEquals("REFERRED", exportedKeys.getString("PKTABLE_NAME"));
+ assertEquals("REFERRING", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("fk", exportedKeys.getString("FK_NAME"));
exportedKeys.close();
} | ['src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java', 'src/test/java/org/sqlite/DBMetaDataTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 512,803 | 108,607 | 15,049 | 47 | 2,005 | 411 | 28 | 1 | 113 | 14 | 24 | 1 | 0 | 0 | 2017-10-14T02:20:48 | 2,470 | Java | {'Java': 1020238, 'C++': 211104, 'C': 108528, 'Shell': 96790, 'Makefile': 11178} | Apache License 2.0 |
538 | xerial/sqlite-jdbc/284/280 | xerial | sqlite-jdbc | https://github.com/xerial/sqlite-jdbc/issues/280 | https://github.com/xerial/sqlite-jdbc/pull/284 | https://github.com/xerial/sqlite-jdbc/pull/284 | 1 | fixes | DatabaseMetaData getImportedKeys does not return primary keys or foreign key names | DatabaseMetaData `getImportedKeys` does not return primary keys or foreign key names | 9bbb62adc083fe1938e4c1bc6eb698b258631563 | ec67764b380e556244d7153fa51a174ee3bda222 | https://github.com/xerial/sqlite-jdbc/compare/9bbb62adc083fe1938e4c1bc6eb698b258631563...ec67764b380e556244d7153fa51a174ee3bda222 | diff --git a/src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java b/src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java
index 4b453ec..fb2d658 100644
--- a/src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java
+++ b/src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java
@@ -10,8 +10,10 @@ import java.sql.Statement;
import java.sql.Struct;
import java.sql.Types;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
@@ -20,6 +22,7 @@ import java.util.regex.Pattern;
import org.sqlite.SQLiteConnection;
import org.sqlite.core.Codes;
import org.sqlite.core.CoreStatement;
+import org.sqlite.jdbc3.JDBC3DatabaseMetaData.ImportedKeyFinder.ForeignKey;
import org.sqlite.util.StringUtils;
public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabaseMetaData {
@@ -1417,7 +1420,7 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
* Pattern used to extract a named primary key.
*/
protected final static Pattern FK_NAMED_PATTERN =
- Pattern.compile(".*\\\\sCONSTRAINT\\\\s+(.*?)\\\\s*FOREIGN\\\\s+KEY\\\\s*\\\\((.*?)\\\\).*",
+ Pattern.compile("\\\\sCONSTRAINT\\\\s+(.*?)\\\\s*FOREIGN\\\\s+KEY\\\\s*\\\\((.*?)\\\\)",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
/**
@@ -1434,6 +1437,7 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
StringBuilder exportedKeysQuery = new StringBuilder(512);
+ String target = null;
int count = 0;
if (pkColumns != null) {
// retrieve table list
@@ -1441,13 +1445,18 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
ArrayList<String> tableList = new ArrayList<String>();
while (rs.next()) {
- tableList.add(rs.getString(1));
+ String tblname = rs.getString(1);
+ tableList.add(tblname);
+ if (tblname.equalsIgnoreCase(table)) {
+ // get the correct case as in the database
+ // (not uppercase nor lowercase)
+ target = tblname;
+ }
}
rs.close();
ResultSet fk = null;
- String target = table.toLowerCase();
// find imported keys for each table
for (String tbl : tableList) {
try {
@@ -1459,45 +1468,52 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
throw e;
}
- Statement stat2 = null;
try {
- stat2 = conn.createStatement();
-
+ final ImportedKeyFinder impFkFinder = new ImportedKeyFinder(tbl);
+ List<ForeignKey> fkNames = impFkFinder.getFkList();
+
+ int i = 0;
while(fk.next()) {
int keySeq = fk.getInt(2) + 1;
- String PKTabName = fk.getString(3).toLowerCase();
+ String PKTabName = fk.getString(3);
- if (PKTabName == null || !PKTabName.equals(target)) {
+ if (PKTabName == null || !PKTabName.equalsIgnoreCase(target)) {
continue;
}
String PKColName = fk.getString(5);
- PKColName = (PKColName == null) ? pkColumns[0] : PKColName.toLowerCase();
-
+ PKColName = (PKColName == null) ? "" : PKColName;
+
+ boolean usePkName = false;
+ for (int j = 0; j < pkColumns.length; j++) {
+ if (pkColumns[j] != null && pkColumns[j].equalsIgnoreCase(PKColName)) {
+ usePkName = true;
+ break;
+ }
+ }
+ String pkName = (usePkName && pkFinder.getName() != null)? pkFinder.getName(): "";
+
exportedKeysQuery
.append(count > 0 ? " union all select " : "select ")
- .append(Integer.toString(keySeq)).append(" as ks, lower('")
- .append(escape(tbl)).append("') as fkt, lower('")
- .append(escape(fk.getString(4))).append("') as fcn, '")
- .append(escape(PKColName)).append("' as pcn, ")
+ .append(Integer.toString(keySeq)).append(" as ks, '")
+ .append(escape(tbl)).append("' as fkt, '")
+ .append(escape(fk.getString(4))).append("' as fcn, '")
+ .append(escape(PKColName)).append("' as pcn, '")
+ .append(escape(pkName)).append("' as pkn, ")
.append(RULE_MAP.get(fk.getString(6))).append(" as ur, ")
.append(RULE_MAP.get(fk.getString(7))).append(" as dr, ");
- rs = stat2.executeQuery("select sql from sqlite_master where" +
- " lower(name) = lower('" + escape(tbl) + "')");
-
- if (rs.next()) {
- Matcher matcher = FK_NAMED_PATTERN.matcher(rs.getString(1));
-
- if (matcher.find()){
- exportedKeysQuery.append("'").append(escape(matcher.group(1).toLowerCase())).append("' as fkn");
- }
- else {
- exportedKeysQuery.append("'' as fkn");
- }
+ String fkName = null;
+ if (fkNames.size() > i) fkName = fkNames.get(i).getFkName();
+
+ if (fkName != null){
+ exportedKeysQuery.append("'").append(escape(fkName)).append("' as fkn");
}
-
- rs.close();
+ else {
+ exportedKeysQuery.append("'' as fkn");
+ }
+
+ i++;
count++;
}
}
@@ -1505,9 +1521,6 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
try{
if (rs != null) rs.close();
}catch(SQLException e) {}
- try{
- if (stat2 != null) stat2.close();
- }catch(SQLException e) {}
try{
if (fk != null) fk.close();
}catch(SQLException e) {}
@@ -1517,10 +1530,10 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
boolean hasImportedKey = (count > 0);
StringBuilder sql = new StringBuilder(512);
- sql.append("select ")
+ sql.append("select ")
.append(catalog).append(" as PKTABLE_CAT, ")
.append(schema).append(" as PKTABLE_SCHEM, ")
- .append(quote(table)).append(" as PKTABLE_NAME, ")
+ .append(quote(target)).append(" as PKTABLE_NAME, ")
.append(hasImportedKey ? "pcn" : "''").append(" as PKCOLUMN_NAME, ")
.append(catalog).append(" as FKTABLE_CAT, ")
.append(schema).append(" as FKTABLE_SCHEM, ")
@@ -1530,12 +1543,12 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
.append(hasImportedKey ? "ur" : "3").append(" as UPDATE_RULE, ")
.append(hasImportedKey ? "dr" : "3").append(" as DELETE_RULE, ")
.append(hasImportedKey ? "fkn" : "''").append(" as FK_NAME, ")
- .append(pkFinder.getName() != null ? pkFinder.getName() : "''").append(" as PK_NAME, ")
+ .append(hasImportedKey ? "pkn" : "''").append(" as PK_NAME, ")
.append(Integer.toString(DatabaseMetaData.importedKeyInitiallyDeferred)) // FIXME: Check for pragma foreign_keys = true ?
.append(" as DEFERRABILITY ");
if (hasImportedKey) {
- sql.append("from (").append(exportedKeysQuery).append(") order by fkt");
+ sql.append("from (").append(exportedKeysQuery).append(") ORDER BY FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, KEY_SEQ");
}
else {
sql.append("limit 0");
@@ -1547,7 +1560,10 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
private StringBuilder appendDummyForeignKeyList(StringBuilder sql) {
sql.append("select -1 as ks, '' as ptn, '' as fcn, '' as pcn, ")
.append(DatabaseMetaData.importedKeyNoAction).append(" as ur, ")
- .append(DatabaseMetaData.importedKeyNoAction).append(" as dr) limit 0;");
+ .append(DatabaseMetaData.importedKeyNoAction).append(" as dr, ")
+ .append(" '' as fkn, ")
+ .append(" '' as pkn ")
+ .append(") limit 0;");
return sql;
}
@@ -1566,7 +1582,7 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
.append(quote(catalog)).append(" as FKTABLE_CAT, ")
.append(quote(schema)).append(" as FKTABLE_SCHEM, ")
.append(quote(table)).append(" as FKTABLE_NAME, ")
- .append("fcn as FKCOLUMN_NAME, ks as KEY_SEQ, ur as UPDATE_RULE, dr as DELETE_RULE, '' as FK_NAME, '' as PK_NAME, ")
+ .append("fcn as FKCOLUMN_NAME, ks as KEY_SEQ, ur as UPDATE_RULE, dr as DELETE_RULE, fkn as FK_NAME, pkn as PK_NAME, ")
.append(Integer.toString(DatabaseMetaData.importedKeyInitiallyDeferred)).append(" as DEFERRABILITY from (");
// Use a try catch block to avoid "query does not return ResultSet" error
@@ -1577,6 +1593,9 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
sql = appendDummyForeignKeyList(sql);
return ((CoreStatement)stat).executeQuery(sql.toString(), true);
}
+
+ final ImportedKeyFinder impFkFinder = new ImportedKeyFinder(table);
+ List<ForeignKey> fkNames = impFkFinder.getFkList();
int i = 0;
for (; rs.next(); i++) {
@@ -1585,8 +1604,10 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
String FKColName = rs.getString(4);
String PKColName = rs.getString(5);
+ PrimaryKeyFinder pkFinder = new PrimaryKeyFinder(PKTabName);
+ String pkName = pkFinder.getName();
if (PKColName == null) {
- PKColName = new PrimaryKeyFinder(PKTabName).getColumns()[0];
+ PKColName = pkFinder.getColumns()[0];
}
String updateRule = rs.getString(6);
@@ -1596,6 +1617,9 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
sql.append(" union all ");
}
+ String fkName = null;
+ if (fkNames.size() > i) fkName = fkNames.get(i).getFkName();
+
sql.append("select ").append(keySeq).append(" as ks,")
.append("'").append(escape(PKTabName)).append("' as ptn, '")
.append(escape(FKColName)).append("' as fcn, '")
@@ -1611,15 +1635,18 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
.append(" when 'CASCADE' then ").append(DatabaseMetaData.importedKeyCascade)
.append(" when 'RESTRICT' then ").append(DatabaseMetaData.importedKeyRestrict)
.append(" when 'SET NULL' then ").append(DatabaseMetaData.importedKeySetNull)
- .append(" when 'SET DEFAULT' then ").append(DatabaseMetaData.importedKeySetDefault).append(" end as dr");
+ .append(" when 'SET DEFAULT' then ").append(DatabaseMetaData.importedKeySetDefault).append(" end as dr, ")
+ .append(fkName == null? "''": quote(fkName)).append(" as fkn, ")
+ .append(pkName == null? "''": quote(pkName)).append(" as pkn");
}
rs.close();
if(i == 0) {
sql = appendDummyForeignKeyList(sql);
}
-
- return ((CoreStatement)stat).executeQuery(sql.append(");").toString(), true);
+ sql.append(") ORDER BY PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME, KEY_SEQ;");
+
+ return ((CoreStatement)stat).executeQuery(sql.toString(), true);
}
/**
@@ -2008,6 +2035,164 @@ public abstract class JDBC3DatabaseMetaData extends org.sqlite.core.CoreDatabase
return pkColumns;
}
}
+
+ class ImportedKeyFinder {
+
+ private String fkTableName;
+ private List<ForeignKey> fkList = new ArrayList<ForeignKey>();
+
+ public ImportedKeyFinder(String table) throws SQLException {
+
+ if (table == null || table.trim().length() == 0) {
+ throw new SQLException("Invalid table name: '" + table + "'");
+ }
+
+ this.fkTableName = table;
+
+ List<String> fkNames = getForeignKeyNames(this.fkTableName);
+
+ Statement stat = null;
+ ResultSet rs = null;
+
+ try {
+ stat = conn.createStatement();
+ rs = stat.executeQuery("pragma foreign_key_list("+ this.fkTableName.toLowerCase()
+ + ")");
+
+ int prevFkId = -1;
+ int count = 0;
+ ForeignKey fk = null;
+ while(rs.next()) {
+ int fkId = rs.getInt(1);
+ int colSeq = rs.getInt(2);
+ String pkTableName = rs.getString(3);
+ String fkColName = rs.getString(4);
+ String pkColName = rs.getString(5);
+ String onUpdate = rs.getString(6);
+ String onDelete = rs.getString(7);
+ String match = rs.getString(8);
+
+ String fkName = null;
+ if (fkNames.size() > count) fkName = fkNames.get(count);
+
+ if (fkId != prevFkId) {
+ fk = new ForeignKey(fkName, pkTableName, pkTableName, onUpdate, onDelete, match);
+ fkList.add(fk);
+ prevFkId = fkId;
+ count++;
+ }
+ fk.addColumnMapping(fkColName, pkColName);
+ }
+ }
+ finally {
+ try {
+ if (rs != null) rs.close();
+ } catch (Exception e) {}
+ try {
+ if (stat != null) stat.close();
+ } catch (Exception e) {}
+ }
+ }
+
+ private List<String> getForeignKeyNames(String tbl) throws SQLException {
+ List<String> fkNames = new ArrayList<String>();
+ if (tbl==null) {
+ return fkNames;
+ }
+ Statement stat2 = null;
+ ResultSet rs = null;
+ try {
+ stat2 = conn.createStatement();
+
+ rs = stat2.executeQuery(
+ "select sql from sqlite_master where" + " lower(name) = lower('" + escape(tbl) + "')");
+ if (rs.next()) {
+ Matcher matcher = FK_NAMED_PATTERN.matcher(rs.getString(1));
+
+ while (matcher.find()) {
+ fkNames.add(matcher.group(1));
+ }
+ }
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (SQLException e) {
+ }
+ try {
+ if (stat2 != null)
+ stat2.close();
+ } catch (SQLException e) {
+ }
+ }
+ Collections.reverse(fkNames);
+ return fkNames;
+ }
+
+ public String getFkTableName() {
+ return fkTableName;
+ }
+
+ public List<ForeignKey> getFkList() {
+ return fkList;
+ }
+
+ class ForeignKey {
+
+ private String fkName;
+ private String pkTableName;
+ private String fkTableName;
+ private List<String> fkColNames = new ArrayList<String>();
+ private List<String> pkColNames = new ArrayList<String>();
+ private String onUpdate;
+ private String onDelete;
+ private String match;
+
+ ForeignKey(String fkName, String pkTableName, String fkTableName, String onUpdate, String onDelete, String match) {
+ this.fkName = fkName;
+ this.pkTableName = pkTableName;
+ this.fkTableName = fkTableName;
+ this.onUpdate = onUpdate;
+ this.onDelete = onDelete;
+ this.match = match;
+ }
+
+
+ public String getFkName() {
+ return fkName;
+ }
+
+ void addColumnMapping(String fkColName, String pkColName) {
+ fkColNames.add(fkColName);
+ pkColNames.add(pkColName);
+ }
+
+ public String[] getColumnMapping(int colSeq) {
+ return new String[] {fkColNames.get(colSeq), pkColNames.get(colSeq)};
+ }
+
+ public String getPkTableName() {
+ return pkTableName;
+ }
+
+ public String getFkTableName() {
+ return fkTableName;
+ }
+
+ public String getOnUpdate() {
+ return onUpdate;
+ }
+
+ public String getOnDelete() {
+ return onDelete;
+ }
+
+ public String getMatch() {
+ return match;
+ }
+ }
+
+ }
/**
* @see java.lang.Object#finalize()
diff --git a/src/test/java/org/sqlite/DBMetaDataTest.java b/src/test/java/org/sqlite/DBMetaDataTest.java
index ff416d2..35c665f 100644
--- a/src/test/java/org/sqlite/DBMetaDataTest.java
+++ b/src/test/java/org/sqlite/DBMetaDataTest.java
@@ -260,13 +260,6 @@ public class DBMetaDataTest
importedKeys.close();
}
-/* @Test
- public void columnOrderOfgetExportedKeys() throws SQLException {
-
- exportedKeys.close();
-
- }*/
-
@Test
public void numberOfgetExportedKeysCols() throws SQLException {
@@ -316,6 +309,215 @@ public class DBMetaDataTest
exportedKeys.close();
}
+ @Test
+ public void getExportedKeysColsForNamedKeys() throws SQLException {
+
+ ResultSet exportedKeys;
+
+ // 1. Check for named primary keys
+ // SQL is deliberately in uppercase, to make sure case-sensitivity is maintained
+ stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT PRIMARY KEY (ID1))");
+ stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, DATA2 INTEGER, FOREIGN KEY(ID1) REFERENCES PARENT1(ID1))");
+
+ exportedKeys = meta.getExportedKeys(null, null, "PARENT1");
+
+ assertTrue(exportedKeys.next());
+ assertEquals("PARENT1", exportedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID1", exportedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("PK_PARENT", exportedKeys.getString("PK_NAME"));
+ assertEquals("", exportedKeys.getString("FK_NAME"));
+ assertEquals("CHILD1", exportedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID1", exportedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(exportedKeys.next());
+
+ exportedKeys.close();
+
+ // 2. Check for named foreign keys
+ // SQL is deliberately in mixed case, to make sure case-sensitivity is maintained
+ stat.executeUpdate("CREATE TABLE Parent2 (Id1 INTEGER, DATA1 INTEGER, PRIMARY KEY (Id1))");
+ stat.executeUpdate("CREATE TABLE Child2 (Id1 INTEGER, DATA2 INTEGER, CONSTRAINT FK_Child2 FOREIGN KEY(Id1) REFERENCES Parent2(Id1))");
+
+ exportedKeys = meta.getExportedKeys(null, null, "Parent2");
+
+ assertTrue(exportedKeys.next());
+ assertEquals("Parent2", exportedKeys.getString("PKTABLE_NAME"));
+ assertEquals("Id1", exportedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("", exportedKeys.getString("PK_NAME"));
+ assertEquals("FK_Child2", exportedKeys.getString("FK_NAME"));
+ assertEquals("Child2", exportedKeys.getString("FKTABLE_NAME"));
+ assertEquals("Id1", exportedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(exportedKeys.next());
+
+ exportedKeys.close();
+ }
+
+ @Test
+ public void getImportedKeysColsForNamedKeys() throws SQLException {
+
+ ResultSet importedKeys;
+
+ // 1. Check for named primary keys
+ // SQL is deliberately in uppercase, to make sure case-sensitivity is maintained
+ stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT PRIMARY KEY (ID1))");
+ stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, DATA2 INTEGER, FOREIGN KEY(ID1) REFERENCES PARENT1(ID1))");
+
+ importedKeys = meta.getImportedKeys(null, null, "CHILD1");
+
+ assertTrue(importedKeys.next());
+ assertEquals("PARENT1", importedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID1", importedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("PK_PARENT", importedKeys.getString("PK_NAME"));
+ assertEquals("", importedKeys.getString("FK_NAME"));
+ assertEquals("CHILD1", importedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID1", importedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(importedKeys.next());
+
+ importedKeys.close();
+
+ // 2. Check for named foreign keys
+ // SQL is deliberately in mixed case, to make sure case-sensitivity is maintained
+ stat.executeUpdate("CREATE TABLE Parent2 (Id1 INTEGER, DATA1 INTEGER, PRIMARY KEY (Id1))");
+ stat.executeUpdate("CREATE TABLE Child2 (Id1 INTEGER, DATA2 INTEGER, "
+ + "CONSTRAINT FK_Child2 FOREIGN KEY(Id1) REFERENCES Parent2(Id1))");
+
+ importedKeys = meta.getImportedKeys(null, null, "Child2");
+
+ assertTrue(importedKeys.next());
+ assertEquals("Parent2", importedKeys.getString("PKTABLE_NAME"));
+ assertEquals("Id1", importedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("", importedKeys.getString("PK_NAME"));
+ assertEquals("FK_Child2", importedKeys.getString("FK_NAME"));
+ assertEquals("Child2", importedKeys.getString("FKTABLE_NAME"));
+ assertEquals("Id1", importedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(importedKeys.next());
+
+ importedKeys.close();
+ }
+
+ @Test
+ public void getImportedKeysColsForMixedCaseDefinition() throws SQLException {
+
+ ResultSet importedKeys;
+
+ // SQL is deliberately in mixed-case, to make sure case-sensitivity is maintained
+ stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT PRIMARY KEY (ID1))");
+ stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, DATA2 INTEGER, "
+ + "CONSTRAINT FK_Parent1 FOREIGN KEY(ID1) REFERENCES Parent1(Id1))");
+
+ importedKeys = meta.getImportedKeys(null, null, "CHILD1");
+
+ assertTrue(importedKeys.next());
+ assertEquals("Parent1", importedKeys.getString("PKTABLE_NAME"));
+ assertEquals("Id1", importedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("PK_PARENT", importedKeys.getString("PK_NAME"));
+ assertEquals("FK_Parent1", importedKeys.getString("FK_NAME"));
+ assertEquals("CHILD1", importedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID1", importedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(importedKeys.next());
+
+ importedKeys.close();
+ }
+
+ @Test
+ public void getImportedKeysColsForMultipleImports() throws SQLException {
+
+ ResultSet importedKeys;
+
+ stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT1 PRIMARY KEY (ID1))");
+ stat.executeUpdate("CREATE TABLE PARENT2 (ID2 INTEGER, DATA2 INTEGER, CONSTRAINT PK_PARENT2 PRIMARY KEY (ID2))");
+ stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, ID2 INTEGER, "
+ + "CONSTRAINT FK_PARENT1 FOREIGN KEY(ID1) REFERENCES PARENT1(ID1), "
+ + "CONSTRAINT FK_PARENT2 FOREIGN KEY(ID2) REFERENCES PARENT2(ID2))");
+
+ importedKeys = meta.getImportedKeys(null, null, "CHILD1");
+
+ assertTrue(importedKeys.next());
+ assertEquals("PARENT1", importedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID1", importedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("PK_PARENT1", importedKeys.getString("PK_NAME"));
+ assertEquals("FK_PARENT1", importedKeys.getString("FK_NAME"));
+ assertEquals("CHILD1", importedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID1", importedKeys.getString("FKCOLUMN_NAME"));
+
+ assertTrue(importedKeys.next());
+ assertEquals("PARENT2", importedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID2", importedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("PK_PARENT2", importedKeys.getString("PK_NAME"));
+ assertEquals("FK_PARENT2", importedKeys.getString("FK_NAME"));
+ assertEquals("CHILD1", importedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID2", importedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(importedKeys.next());
+
+ importedKeys.close();
+
+ // Unnamed foreign keys and unnamed primary keys
+ stat.executeUpdate("CREATE TABLE PARENT3 (ID3 INTEGER, DATA3 INTEGER, PRIMARY KEY (ID3))");
+ stat.executeUpdate("CREATE TABLE PARENT4 (ID4 INTEGER, DATA4 INTEGER, CONSTRAINT PK_PARENT4 PRIMARY KEY (ID4))");
+ stat.executeUpdate("CREATE TABLE CHILD2 (ID3 INTEGER, ID4 INTEGER, "
+ + "FOREIGN KEY(ID3) REFERENCES PARENT3(ID3), "
+ + "CONSTRAINT FK_PARENT4 FOREIGN KEY(ID4) REFERENCES PARENT4(ID4))");
+
+ importedKeys = meta.getImportedKeys(null, null, "CHILD2");
+
+ assertTrue(importedKeys.next());
+ assertEquals("PARENT3", importedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID3", importedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("", importedKeys.getString("PK_NAME"));
+ assertEquals("", importedKeys.getString("FK_NAME"));
+ assertEquals("CHILD2", importedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID3", importedKeys.getString("FKCOLUMN_NAME"));
+
+ assertTrue(importedKeys.next());
+ assertEquals("PARENT4", importedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID4", importedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("PK_PARENT4", importedKeys.getString("PK_NAME"));
+ assertEquals("FK_PARENT4", importedKeys.getString("FK_NAME"));
+ assertEquals("CHILD2", importedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID4", importedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(importedKeys.next());
+
+ importedKeys.close();
+ }
+
+ @Test
+ public void getExportedKeysColsForMultipleImports() throws SQLException {
+
+ ResultSet exportedKeys;
+
+ stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, ID2 INTEGER, CONSTRAINT PK_PARENT1 PRIMARY KEY (ID1))");
+ stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, CONSTRAINT FK_PARENT1 FOREIGN KEY(ID1) REFERENCES PARENT1(ID1))");
+ stat.executeUpdate("CREATE TABLE CHILD2 (ID2 INTEGER, CONSTRAINT FK_PARENT2 FOREIGN KEY(ID2) REFERENCES PARENT1(ID2))");
+
+ exportedKeys = meta.getExportedKeys(null, null, "PARENT1");
+
+ assertTrue(exportedKeys.next());
+ assertEquals("PARENT1", exportedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID1", exportedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("PK_PARENT1", exportedKeys.getString("PK_NAME"));
+ assertEquals("FK_PARENT1", exportedKeys.getString("FK_NAME"));
+ assertEquals("CHILD1", exportedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID1", exportedKeys.getString("FKCOLUMN_NAME"));
+
+ assertTrue(exportedKeys.next());
+ assertEquals("PARENT1", exportedKeys.getString("PKTABLE_NAME"));
+ assertEquals("ID2", exportedKeys.getString("PKCOLUMN_NAME"));
+ assertEquals("", exportedKeys.getString("PK_NAME"));
+ assertEquals("FK_PARENT2", exportedKeys.getString("FK_NAME"));
+ assertEquals("CHILD2", exportedKeys.getString("FKTABLE_NAME"));
+ assertEquals("ID2", exportedKeys.getString("FKCOLUMN_NAME"));
+
+ assertFalse(exportedKeys.next());
+
+ exportedKeys.close();
+ }
+
@Test
public void columnOrderOfgetTables() throws SQLException {
ResultSet rs = meta.getTables(null, null, null, null);
@@ -770,8 +972,8 @@ public class DBMetaDataTest
stat.executeUpdate("create table REFERRING (ID integer, RID integer, constraint fk\\r\\n foreign\\tkey\\r\\n(RID) references REFERRED(id))");
exportedKeys = meta.getExportedKeys(null, null, "referred");
- assertEquals("referred", exportedKeys.getString("PKTABLE_NAME"));
- assertEquals("referring", exportedKeys.getString("FKTABLE_NAME"));
+ assertEquals("REFERRED", exportedKeys.getString("PKTABLE_NAME"));
+ assertEquals("REFERRING", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("fk", exportedKeys.getString("FK_NAME"));
exportedKeys.close();
} | ['src/main/java/org/sqlite/jdbc3/JDBC3DatabaseMetaData.java', 'src/test/java/org/sqlite/DBMetaDataTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 512,803 | 108,607 | 15,049 | 47 | 10,835 | 2,332 | 267 | 1 | 84 | 11 | 17 | 1 | 0 | 0 | 2017-10-19T01:10:57 | 2,470 | Java | {'Java': 1020238, 'C++': 211104, 'C': 108528, 'Shell': 96790, 'Makefile': 11178} | Apache License 2.0 |
9,719 | assertj/assertj/613/611 | assertj | assertj | https://github.com/assertj/assertj/issues/611 | https://github.com/assertj/assertj/pull/613 | https://github.com/assertj/assertj/pull/613 | 1 | fixes | Assert "isCloseTo(double expected, Percentage p)" doesn't work for negative expected values | I have two tests whether an actual value is within a given percentage of the expected value.
The test for a positive expected value works without problems.
The test for a negative expected value throws `IllegalArgumentException`
My test methods are:
```
@Test
public void checkPositiveNumber() {
assertThat(11d).isCloseTo(10d, withinPercentage(10));
}
@Test
public void checkNegativeNumber() {
assertThat(-11d).isCloseTo(-10d, withinPercentage(10));
}
```
I've tested only for doubles but I suspect the same problem exists for all numeric types.
| 3118bf043099fba418bc908388afc0fbd25cf772 | 7f3af3a9e9e331a04fff2f375d3545e54a7a9145 | https://github.com/assertj/assertj/compare/3118bf043099fba418bc908388afc0fbd25cf772...7f3af3a9e9e331a04fff2f375d3545e54a7a9145 | diff --git a/src/main/java/org/assertj/core/internal/Longs.java b/src/main/java/org/assertj/core/internal/Longs.java
index 8ff43a76e..72c74ded4 100644
--- a/src/main/java/org/assertj/core/internal/Longs.java
+++ b/src/main/java/org/assertj/core/internal/Longs.java
@@ -73,7 +73,7 @@ public class Longs extends Numbers<Long> {
checkPercentageIsNotNull(percentage);
checkNumberIsNotNull(other);
- Offset<Double> calculatedOffset = offset(percentage.value * other / 100d);
+ Offset<Double> calculatedOffset = offset(abs(percentage.value * other / 100d));
Long absDiff = abs(other - actual);
if (absDiff > calculatedOffset.value)
diff --git a/src/main/java/org/assertj/core/internal/Numbers.java b/src/main/java/org/assertj/core/internal/Numbers.java
index 924bd3030..d2a1d9030 100644
--- a/src/main/java/org/assertj/core/internal/Numbers.java
+++ b/src/main/java/org/assertj/core/internal/Numbers.java
@@ -184,7 +184,7 @@ public abstract class Numbers<NUMBER extends Number & Comparable<NUMBER>> extend
}
private Offset<Double> computeOffset(NUMBER referenceValue, Percentage percentage) {
- return offset(percentage.value * referenceValue.doubleValue() / 100d);
+ return offset(abs(percentage.value * referenceValue.doubleValue() / 100d));
}
}
\\ No newline at end of file
diff --git a/src/main/java/org/assertj/core/internal/Shorts.java b/src/main/java/org/assertj/core/internal/Shorts.java
index 4e7fb9866..6204fd779 100644
--- a/src/main/java/org/assertj/core/internal/Shorts.java
+++ b/src/main/java/org/assertj/core/internal/Shorts.java
@@ -73,7 +73,7 @@ public class Shorts extends Numbers<Short> {
assertNotNull(info, actual);
checkPercentageIsNotNull(percentage);
checkNumberIsNotNull(other);
- Offset<Double> calculatedOffset = offset(percentage.value * other / 100d);
+ Offset<Double> calculatedOffset = offset(abs(percentage.value * other / 100d));
short absDiff = (short) abs(other - actual);
if (absDiff > calculatedOffset.value)
throw failures.failure(info, shouldBeEqualWithinPercentage(actual, other, percentage, absDiff));
diff --git a/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsCloseToPercentage_Test.java b/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsCloseToPercentage_Test.java
index 3ab6b35d9..ad6c11526 100644
--- a/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsCloseToPercentage_Test.java
+++ b/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsCloseToPercentage_Test.java
@@ -28,10 +28,13 @@ import java.math.BigDecimal;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.BigDecimalsBaseTest;
import org.junit.Test;
+import org.junit.runner.RunWith;
-public class BigDecimals_assertIsCloseToPercentage_Test extends BigDecimalsBaseTest {
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
- private static final BigDecimal TWO = new BigDecimal(2);
+@RunWith(DataProviderRunner.class)
+public class BigDecimals_assertIsCloseToPercentage_Test extends BigDecimalsBaseTest {
@Test
public void should_fail_if_actual_is_null() {
@@ -59,16 +62,32 @@ public class BigDecimals_assertIsCloseToPercentage_Test extends BigDecimalsBaseT
bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, ZERO, withPercentage(101));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_less_than_given_percentage() {
- bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(1));
- bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(100));
+ @DataProvider({
+ "1, 1, 1",
+ "1, 2, 100",
+ "-1, -1, 1",
+ "-1, -2, 100"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_less_than_given_percentage(BigDecimal actual, BigDecimal other, Integer percentage) {
+ bigDecimals.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_equal_to_given_percentage() {
- bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(0));
- bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(50));
+ @DataProvider({
+ "1, 1, 0",
+ "2, 1, 100",
+ "1, 2, 50",
+ "-1, -1, 0",
+ "-2, -1, 100",
+ "-1, -2, 50"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_equal_to_given_percentage(BigDecimal actual, BigDecimal other, Integer percentage) {
+ bigDecimals.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@Test
diff --git a/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsCloseToPercentage_Test.java b/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsCloseToPercentage_Test.java
index 155411553..f1fda1b68 100644
--- a/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsCloseToPercentage_Test.java
+++ b/src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsCloseToPercentage_Test.java
@@ -23,12 +23,16 @@ import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.BytesBaseTest;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+
+@RunWith(DataProviderRunner.class)
public class Bytes_assertIsCloseToPercentage_Test extends BytesBaseTest {
private static final Byte ZERO = 0;
private static final Byte ONE = 1;
- private static final Byte TWO = 2;
private static final Byte TEN = 10;
@Test
@@ -57,16 +61,32 @@ public class Bytes_assertIsCloseToPercentage_Test extends BytesBaseTest {
bytes.assertIsCloseToPercentage(someInfo(), ONE, ZERO, withPercentage(101));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_less_than_given_percentage() {
- bytes.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(1));
- bytes.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(100));
+ @DataProvider({
+ "1, 1, 1",
+ "1, 2, 100",
+ "-1, -1, 1",
+ "-1, -2, 100"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_less_than_given_percentage(Byte actual, Byte other, Byte percentage) {
+ bytes.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_equal_to_given_percentage() {
- bytes.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(0));
- bytes.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(50));
+ @DataProvider({
+ "1, 1, 0",
+ "2, 1, 100",
+ "1, 2, 50",
+ "-1, -1, 0",
+ "-2, -1, 100",
+ "-1, -2, 50"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_equal_to_given_percentage(Byte actual, Byte other, Byte percentage) {
+ bytes.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@Test
diff --git a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsCloseToPercentage_Test.java b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsCloseToPercentage_Test.java
index c9075f126..4fd18d764 100644
--- a/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsCloseToPercentage_Test.java
+++ b/src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsCloseToPercentage_Test.java
@@ -23,12 +23,16 @@ import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.DoublesBaseTest;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+
+@RunWith(DataProviderRunner.class)
public class Doubles_assertIsCloseToPercentage_Test extends DoublesBaseTest {
private static final Double ZERO = 0d;
private static final Double ONE = 1d;
- private static final Double TWO = 2d;
private static final Double TEN = 10d;
@Test
@@ -57,16 +61,32 @@ public class Doubles_assertIsCloseToPercentage_Test extends DoublesBaseTest {
doubles.assertIsCloseToPercentage(someInfo(), ONE, ZERO, withPercentage(101.0));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_less_than_given_percentage() {
- doubles.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(0.1));
- doubles.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(100.0));
+ @DataProvider({
+ "1, 1, 1",
+ "1, 2, 100",
+ "-1, -1, 1",
+ "-1, -2, 100"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_less_than_given_percentage(Double actual, Double other, Double percentage) {
+ doubles.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_equal_to_given_percentage() {
- doubles.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(ZERO));
- doubles.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(50.0));
+ @DataProvider({
+ "1, 1, 0",
+ "2, 1, 100",
+ "1, 2, 50",
+ "-1, -1, 0",
+ "-2, -1, 100",
+ "-1, -2, 50"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_equal_to_given_percentage(Double actual, Double other, Double percentage) {
+ doubles.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@Test
diff --git a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsCloseToPercentage_Test.java b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsCloseToPercentage_Test.java
index 372ab1ac8..b7a2fb891 100644
--- a/src/test/java/org/assertj/core/internal/floats/Floats_assertIsCloseToPercentage_Test.java
+++ b/src/test/java/org/assertj/core/internal/floats/Floats_assertIsCloseToPercentage_Test.java
@@ -23,12 +23,16 @@ import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.FloatsBaseTest;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+
+@RunWith(DataProviderRunner.class)
public class Floats_assertIsCloseToPercentage_Test extends FloatsBaseTest {
private static final Float ZERO = 0f;
private static final Float ONE = 1f;
- private static final Float TWO = 2f;
private static final Float TEN = 10f;
@Test
@@ -57,16 +61,32 @@ public class Floats_assertIsCloseToPercentage_Test extends FloatsBaseTest {
floats.assertIsCloseToPercentage(someInfo(), ONE, ZERO, withPercentage(101.0f));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_less_than_given_percentage() {
- floats.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(0.1f));
- floats.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(100.0f));
+ @DataProvider({
+ "1, 1, 1",
+ "1, 2, 100",
+ "-1, -1, 1",
+ "-1, -2, 100"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_less_than_given_percentage(Float actual, Float other, Float percentage) {
+ floats.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_equal_to_given_percentage() {
- floats.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(ZERO));
- floats.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(50.0f));
+ @DataProvider({
+ "1, 1, 0",
+ "2, 1, 100",
+ "1, 2, 50",
+ "-1, -1, 0",
+ "-2, -1, 100",
+ "-1, -2, 50"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_equal_to_given_percentage(Float actual, Float other, Float percentage) {
+ floats.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@Test
diff --git a/src/test/java/org/assertj/core/internal/integers/Integers_assertIsCloseToPercentage_Test.java b/src/test/java/org/assertj/core/internal/integers/Integers_assertIsCloseToPercentage_Test.java
index 804c9358d..6f36220b7 100644
--- a/src/test/java/org/assertj/core/internal/integers/Integers_assertIsCloseToPercentage_Test.java
+++ b/src/test/java/org/assertj/core/internal/integers/Integers_assertIsCloseToPercentage_Test.java
@@ -23,12 +23,16 @@ import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.IntegersBaseTest;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+
+@RunWith(DataProviderRunner.class)
public class Integers_assertIsCloseToPercentage_Test extends IntegersBaseTest {
private static final Integer ZERO = 0;
private static final Integer ONE = 1;
- private static final Integer TWO = 2;
private static final Integer TEN = 10;
@Test
@@ -57,16 +61,32 @@ public class Integers_assertIsCloseToPercentage_Test extends IntegersBaseTest {
integers.assertIsCloseToPercentage(someInfo(), ONE, ZERO, withPercentage(101));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_less_than_given_percentage() {
- integers.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(1));
- integers.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(100));
+ @DataProvider({
+ "1, 1, 1",
+ "1, 2, 100",
+ "-1, -1, 1",
+ "-1, -2, 100"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_less_than_given_percentage(Integer actual, Integer other, Integer percentage) {
+ integers.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_equal_to_given_percentage() {
- integers.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(ZERO));
- integers.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(50));
+ @DataProvider({
+ "1, 1, 0",
+ "2, 1, 100",
+ "1, 2, 50",
+ "-1, -1, 0",
+ "-2, -1, 100",
+ "-1, -2, 50"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_equal_to_given_percentage(Integer actual, Integer other, Integer percentage) {
+ integers.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@Test
diff --git a/src/test/java/org/assertj/core/internal/longs/Longs_assertIsCloseToPercentage_Test.java b/src/test/java/org/assertj/core/internal/longs/Longs_assertIsCloseToPercentage_Test.java
index ff10611c3..1092fd1d8 100644
--- a/src/test/java/org/assertj/core/internal/longs/Longs_assertIsCloseToPercentage_Test.java
+++ b/src/test/java/org/assertj/core/internal/longs/Longs_assertIsCloseToPercentage_Test.java
@@ -15,6 +15,10 @@ package org.assertj.core.internal.longs;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.LongsBaseTest;
import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import static org.assertj.core.api.Assertions.withinPercentage;
import static org.assertj.core.data.Percentage.withPercentage;
@@ -24,11 +28,11 @@ import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErr
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;
+@RunWith(DataProviderRunner.class)
public class Longs_assertIsCloseToPercentage_Test extends LongsBaseTest {
private static final Long ZERO = 0L;
private static final Long ONE = 1L;
- private static final Long TWO = 2L;
private static final Long TEN = 10L;
@Test
@@ -57,16 +61,32 @@ public class Longs_assertIsCloseToPercentage_Test extends LongsBaseTest {
longs.assertIsCloseToPercentage(someInfo(), ONE, ZERO, withPercentage(101L));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_less_than_given_percentage() {
- longs.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(1L));
- longs.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(100L));
+ @DataProvider({
+ "1, 1, 1",
+ "1, 2, 100",
+ "-1, -1, 1",
+ "-1, -2, 100"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_less_than_given_percentage(Long actual, Long other, Long percentage) {
+ longs.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_equal_to_given_percentage() {
- longs.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(ZERO));
- longs.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(50L));
+ @DataProvider({
+ "1, 1, 0",
+ "2, 1, 100",
+ "1, 2, 50",
+ "-1, -1, 0",
+ "-2, -1, 100",
+ "-1, -2, 50"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_equal_to_given_percentage(Long actual, Long other, Long percentage) {
+ longs.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@Test
diff --git a/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsCloseToPercentage_Test.java b/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsCloseToPercentage_Test.java
index 539542042..fb34811f0 100644
--- a/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsCloseToPercentage_Test.java
+++ b/src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsCloseToPercentage_Test.java
@@ -23,12 +23,16 @@ import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.ShortsBaseTest;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.tngtech.java.junit.dataprovider.DataProvider;
+import com.tngtech.java.junit.dataprovider.DataProviderRunner;
+
+@RunWith(DataProviderRunner.class)
public class Shorts_assertIsCloseToPercentage_Test extends ShortsBaseTest {
private static final Short ZERO = (short) 0;
private static final Short ONE = (short) 1;
- private static final Short TWO = (short) 2;
private static final Short TEN = (short) 10;
@Test
@@ -57,16 +61,32 @@ public class Shorts_assertIsCloseToPercentage_Test extends ShortsBaseTest {
shorts.assertIsCloseToPercentage(someInfo(), ONE, ZERO, withPercentage((short) 101));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_less_than_given_percentage() {
- shorts.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage((short) 1));
- shorts.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage((short) 100));
+ @DataProvider({
+ "1, 1, 1",
+ "1, 2, 100",
+ "-1, -1, 1",
+ "-1, -2, 100"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_less_than_given_percentage(Short actual, Short other, Short percentage) {
+ shorts.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
+ // @format:off
@Test
- public void should_pass_if_difference_is_equal_to_given_percentage() {
- shorts.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(ZERO));
- shorts.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage((short) 50));
+ @DataProvider({
+ "1, 1, 0",
+ "2, 1, 100",
+ "1, 2, 50",
+ "-1, -1, 0",
+ "-2, -1, 100",
+ "-1, -2, 50"
+ })
+ // @format:on
+ public void should_pass_if_difference_is_equal_to_given_percentage(Short actual, Short other, Short percentage) {
+ shorts.assertIsCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@Test | ['src/test/java/org/assertj/core/internal/longs/Longs_assertIsCloseToPercentage_Test.java', 'src/main/java/org/assertj/core/internal/Shorts.java', 'src/test/java/org/assertj/core/internal/integers/Integers_assertIsCloseToPercentage_Test.java', 'src/test/java/org/assertj/core/internal/bytes/Bytes_assertIsCloseToPercentage_Test.java', 'src/test/java/org/assertj/core/internal/doubles/Doubles_assertIsCloseToPercentage_Test.java', 'src/test/java/org/assertj/core/internal/shorts/Shorts_assertIsCloseToPercentage_Test.java', 'src/main/java/org/assertj/core/internal/Numbers.java', 'src/test/java/org/assertj/core/internal/floats/Floats_assertIsCloseToPercentage_Test.java', 'src/main/java/org/assertj/core/internal/Longs.java', 'src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsCloseToPercentage_Test.java'] | {'.java': 10} | 10 | 10 | 0 | 0 | 10 | 2,241,003 | 527,686 | 56,682 | 413 | 484 | 109 | 6 | 3 | 559 | 74 | 123 | 21 | 0 | 1 | 2016-02-06T11:44:56 | 2,399 | Java | {'Java': 18477327, 'Shell': 39277, 'Kotlin': 8052, 'Groovy': 3774} | Apache License 2.0 |
9,420 | apache/incubator-hugegraph/1803/1794 | apache | incubator-hugegraph | https://github.com/apache/incubator-hugegraph/issues/1794 | https://github.com/apache/incubator-hugegraph/pull/1803 | https://github.com/apache/incubator-hugegraph/pull/1803 | 1 | fix | [Bug]within do not return the correct result | ### Bug Type (问题类型)
gremlin (结果不合预期)
### Before submit
- [X] 我已经确认现有的 [Issues](https://github.com/hugegraph/hugegraph/issues) 与 [FAQ](https://hugegraph.github.io/hugegraph-doc/guides/faq.html) 中没有相同 / 重复问题
### Environment (环境信息)
- Server Version: v0.11.x
- Backend: RocksDB x nodes, HDD or SSD
- OS: xx CPUs, xx G RAM, Centos 7.x
- Data Size: xx vertices, xx edges <!-- (like 1000W 点, 9000W 边) -->
### Expected & Actual behavior (期望与实际表现)
使用within直接查询能起作用,但是多次拼接查询,没数据
gremlin> :> g.V().has('name',Text.contains('诚信')).has('type', 0).where(values('confirmType').is(neq(1))).valueMap('name','confirmType').limit(1)
==>[name:[诚信],confirmType:[0]]
gremlin> :> g.V().has('name',Text.contains('诚信')).has('type', 0).has('confirmType',within(0,2,3)).valueMap('name','confirmType').limit(1)
gremlin>
gremlin> :> g.V().has('type', 0).has('confirmType',within(0,2,3)).has('name',Text.contains('诚信')).valueMap('name','confirmType').limit(1)
gremlin>
gremlin> :> g.V().has('type', 0).has('name',Text.contains('诚信')).has('confirmType',within(3,2,0)).valueMap('name','confirmType').limit(1)
==>[name:[诚信],confirmType:[0]]
gremlin> :> g.V().has('type', 0).has('name',Text.contains('诚信')).valueMap('name','confirmType').limit(1)
==>[name:[诚信],confirmType:[0]]
gremlin> :> g.V().has('type', 0).has('name',Text.contains('诚信')).has('confirmType',0).valueMap('name','confirmType').limit(1)
==>[name:[诚信],confirmType:[0]]
### Vertex/Edge example (问题点 / 边数据举例)
_No response_
### Schema [VertexLabel, EdgeLabel, IndexLabel] (元数据结构)
schema.propertyKey("type").asInt().ifNotExist().create();
schema.propertyKey("kid").asInt().ifNotExist().create();
schema.propertyKey("name").asText().ifNotExist().create();
schema.propertyKey("confirmType").asInt().ifNotExist().create();
schema.vertexLabel("test").properties("confirmType","name","kid","type").nullableKeys("confirmType","name","type").primaryKeys("kid").ifNotExist().create();
g.addVertex(T.label, "tets", "name", "诚信", "confirmType", 0, "type", 1,"kid",1);
g.V().has('type', 1).has('confirmType',within(0,2,3)).has('name',Text.contains('诚信'));
g.V().has('type', 1).has('confirmType',within(3,2,0)).has('name',Text.contains('诚信'));
_No response_ | 0cc02e47b02eca90f22fdb1132a4b1b89520fbb9 | 3e1e0acc4720eb1a0ecef2917089926aa673c1c3 | https://github.com/apache/incubator-hugegraph/compare/0cc02e47b02eca90f22fdb1132a4b1b89520fbb9...3e1e0acc4720eb1a0ecef2917089926aa673c1c3 | diff --git a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/page/QueryList.java b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/page/QueryList.java
index 9739e329..4e209458 100644
--- a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/page/QueryList.java
+++ b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/page/QueryList.java
@@ -219,6 +219,7 @@ public final class QueryList<R> {
private QueryResults<R> each(IdHolder holder) {
assert !holder.paging();
Query bindQuery = holder.query();
+ this.updateResultsFilter(bindQuery);
this.updateOffsetIfNeeded(bindQuery);
// Iterate by all
@@ -267,6 +268,8 @@ public final class QueryList<R> {
E.checkArgument(0 <= index && index <= this.holders.size(),
"Invalid page index %s", index);
IdHolder holder = this.holders.get(index);
+ Query bindQuery = holder.query();
+ this.updateResultsFilter(bindQuery);
PageIds pageIds = holder.fetchNext(page, pageSize);
if (pageIds.empty()) {
return PageResults.emptyIterator();
@@ -298,6 +301,16 @@ public final class QueryList<R> {
query.copyOffset(parent);
}
+ private void updateResultsFilter(Query query) {
+ while (query != null) {
+ if (query instanceof ConditionQuery) {
+ ((ConditionQuery) query).updateResultsFilter();
+ return;
+ }
+ query = query.originQuery();
+ }
+ }
+
private QueryResults<R> queryByIndexIds(Set<Id> ids) {
return this.queryByIndexIds(ids, false);
}
diff --git a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/Condition.java b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/Condition.java
index ecf7ac87..6be1b6eb 100644
--- a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/Condition.java
+++ b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/Condition.java
@@ -74,6 +74,7 @@ public abstract class Condition {
((Id) v1).asBytes());
}),
TEXT_CONTAINS("textcontains", String.class, String.class, (v1, v2) -> {
+ // TODO: support collection-property textcontains
return v1 != null && ((String) v1).contains((String) v2);
}),
TEXT_CONTAINS_ANY("textcontainsany", String.class, Collection.class,
diff --git a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/ConditionQuery.java b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/ConditionQuery.java
index a2fda90d..fcb2fe95 100644
--- a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/ConditionQuery.java
+++ b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/ConditionQuery.java
@@ -47,7 +47,6 @@ import com.baidu.hugegraph.util.E;
import com.baidu.hugegraph.util.InsertionOrderUtil;
import com.baidu.hugegraph.util.LongEncoding;
import com.baidu.hugegraph.util.NumericUtil;
-import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
@@ -79,7 +78,7 @@ public class ConditionQuery extends IdQuery {
private List<Condition> conditions = EMPTY_CONDITIONS;
private OptimizedType optimizedType = OptimizedType.NONE;
- private Function<HugeElement, Boolean> resultsFilter = null;
+ private ResultsFilter resultsFilter = null;
private Element2IndexValueMap element2IndexValueMap = null;
public ConditionQuery(HugeType resultType) {
@@ -173,20 +172,11 @@ public class ConditionQuery extends IdQuery {
}
public void recordIndexValue(Id propertyId, Id id, Object indexValue) {
- this.ensureElement2IndexValueMap();
- this.element2IndexValueMap.addIndexValue(propertyId, id, indexValue);
+ this.element2IndexValueMap().addIndexValue(propertyId, id, indexValue);
}
public void selectedIndexField(Id indexField) {
- this.ensureElement2IndexValueMap();
- this.element2IndexValueMap.selectedIndexField(indexField);
- }
-
- public Set<LeftIndex> getElementLeftIndex(Id elementId) {
- if (this.element2IndexValueMap == null) {
- return null;
- }
- return this.element2IndexValueMap.getLeftIndex(elementId);
+ this.element2IndexValueMap().selectedIndexField(indexField);
}
public void removeElementLeftIndex(Id elementId) {
@@ -197,7 +187,21 @@ public class ConditionQuery extends IdQuery {
}
public boolean existLeftIndex(Id elementId) {
- return this.getElementLeftIndex(elementId) != null;
+ return this.getLeftIndexOfElement(elementId) != null;
+ }
+
+ public Set<LeftIndex> getLeftIndexOfElement(Id elementId) {
+ if (this.element2IndexValueMap == null) {
+ return null;
+ }
+ return this.element2IndexValueMap.getLeftIndex(elementId);
+ }
+
+ private Element2IndexValueMap element2IndexValueMap() {
+ if (this.element2IndexValueMap == null) {
+ this.element2IndexValueMap = new Element2IndexValueMap();
+ }
+ return this.element2IndexValueMap;
}
public List<Condition.Relation> relations() {
@@ -548,14 +552,26 @@ public class ConditionQuery extends IdQuery {
return false;
}
- if (this.resultsFilter != null) {
- return this.resultsFilter.apply(element);
+ /*
+ * Currently results-filter is used to filter unmatched results returned
+ * by search index, and there may be multiple results-filter for every
+ * sub-query like within() + Text.contains().
+ * We can't use sub-query results-filter here for fresh element which is
+ * not committed to backend store, because it's not from a sub-query.
+ */
+ if (this.resultsFilter != null && !element.fresh()) {
+ return this.resultsFilter.test(element);
}
+
+ /*
+ * NOTE: seems need to keep call checkRangeIndex() for each condition,
+ * so don't break early even if test() return false.
+ */
boolean valid = true;
for (Condition cond : this.conditions) {
valid &= cond.test(element);
- valid &= (this.element2IndexValueMap == null ||
- this.element2IndexValueMap.validRangeIndex(element, cond));
+ valid &= this.element2IndexValueMap == null ||
+ this.element2IndexValueMap.checkRangeIndex(element, cond);
}
return valid;
}
@@ -615,14 +631,29 @@ public class ConditionQuery extends IdQuery {
return this.optimizedType;
}
- public void registerResultsFilter(Function<HugeElement, Boolean> filter) {
+ public void registerResultsFilter(ResultsFilter filter) {
assert this.resultsFilter == null;
this.resultsFilter = filter;
+ }
+ public void updateResultsFilter() {
Query originQuery = this.originQuery();
if (originQuery instanceof ConditionQuery) {
- ConditionQuery cq = ((ConditionQuery) originQuery);
- cq.registerResultsFilter(filter);
+ ConditionQuery originCQ = ((ConditionQuery) originQuery);
+ if (this.resultsFilter != null) {
+ originCQ.updateResultsFilter(this.resultsFilter);
+ } else {
+ originCQ.updateResultsFilter();
+ }
+ }
+ }
+
+ protected void updateResultsFilter(ResultsFilter filter) {
+ this.resultsFilter = filter;
+ Query originQuery = this.originQuery();
+ if (originQuery instanceof ConditionQuery) {
+ ConditionQuery originCQ = ((ConditionQuery) originQuery);
+ originCQ.updateResultsFilter(filter);
}
}
@@ -638,12 +669,6 @@ public class ConditionQuery extends IdQuery {
return (ConditionQuery) originQuery;
}
- private void ensureElement2IndexValueMap() {
- if (this.element2IndexValueMap == null) {
- this.element2IndexValueMap = new Element2IndexValueMap();
- }
- }
-
public static String concatValues(List<?> values) {
assert !values.isEmpty();
List<Object> newValues = new ArrayList<>(values.size());
@@ -717,7 +742,7 @@ public class ConditionQuery extends IdQuery {
public void addIndexValue(Id indexField, Id elementId,
Object indexValue) {
if (!this.filed2IndexValues.containsKey(indexField)) {
- this.filed2IndexValues.put(indexField, new HashMap<>());
+ this.filed2IndexValues.putIfAbsent(indexField, new HashMap<>());
}
Map<Id, Set<Object>> element2IndexValueMap =
this.filed2IndexValues.get(indexField);
@@ -733,15 +758,15 @@ public class ConditionQuery extends IdQuery {
this.selectedIndexField = indexField;
}
- public Set<Object> removeIndexValues(Id indexField, Id elementId) {
+ public Set<Object> toRemoveIndexValues(Id indexField, Id elementId) {
if (!this.filed2IndexValues.containsKey(indexField)) {
return null;
}
return this.filed2IndexValues.get(indexField).get(elementId);
}
- public void addLeftIndex(Id indexField, Set<Object> indexValues,
- Id elementId) {
+ public void addLeftIndex(Id elementId, Id indexField,
+ Set<Object> indexValues) {
LeftIndex leftIndex = new LeftIndex(indexValues, indexField);
if (this.leftIndexMap.containsKey(elementId)) {
this.leftIndexMap.get(elementId).add(leftIndex);
@@ -758,7 +783,7 @@ public class ConditionQuery extends IdQuery {
this.leftIndexMap.remove(elementId);
}
- public boolean validRangeIndex(HugeElement element, Condition cond) {
+ public boolean checkRangeIndex(HugeElement element, Condition cond) {
// Not UserpropRelation
if (!(cond instanceof Condition.UserpropRelation)) {
return true;
@@ -767,35 +792,36 @@ public class ConditionQuery extends IdQuery {
Condition.UserpropRelation propRelation =
(Condition.UserpropRelation) cond;
Id propId = propRelation.key();
- Set<Object> fieldValues = this.removeIndexValues(propId,
- element.id());
+ Set<Object> fieldValues = this.toRemoveIndexValues(propId,
+ element.id());
if (fieldValues == null) {
// Not range index
return true;
}
- HugeProperty<Object> hugeProperty = element.getProperty(propId);
- if (hugeProperty == null) {
- // Property value has been deleted
- this.addLeftIndex(propId, fieldValues, element.id());
+ HugeProperty<Object> property = element.getProperty(propId);
+ if (property == null) {
+ // Property value has been deleted, so it's not matched
+ this.addLeftIndex(element.id(), propId, fieldValues);
return false;
}
/*
- * NOTE: If success remove means has correct index,
- * we should add left index values to left index map
- * waiting to be removed
+ * NOTE: If removing successfully means there is correct index,
+ * else we should add left-index values to left index map to
+ * wait the left-index to be removed.
*/
- boolean hasRightValue = removeValue(fieldValues, hugeProperty.value());
+ boolean hasRightValue = removeFieldValue(fieldValues,
+ property.value());
if (fieldValues.size() > 0) {
- this.addLeftIndex(propId, fieldValues, element.id());
+ this.addLeftIndex(element.id(), propId, fieldValues);
}
/*
* NOTE: When query by more than one range index field,
* if current field is not the selected one, it can only be used to
* determine whether the index values matched, can't determine
- * the element is valid or not
+ * the element is valid or not.
*/
if (this.selectedIndexField != null) {
return !propId.equals(this.selectedIndexField) || hasRightValue;
@@ -804,10 +830,11 @@ public class ConditionQuery extends IdQuery {
return hasRightValue;
}
- private static boolean removeValue(Set<Object> values, Object value){
- for (Object compareValue : values) {
- if (numberEquals(compareValue, value)) {
- values.remove(compareValue);
+ private static boolean removeFieldValue(Set<Object> values,
+ Object value){
+ for (Object elem : values) {
+ if (numberEquals(elem, value)) {
+ values.remove(elem);
return true;
}
}
@@ -847,4 +874,9 @@ public class ConditionQuery extends IdQuery {
return this.indexField;
}
}
+
+ public static interface ResultsFilter {
+
+ public boolean test(HugeElement element);
+ }
}
diff --git a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphIndexTransaction.java b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphIndexTransaction.java
index d497cb9e..3397cc3f 100644
--- a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphIndexTransaction.java
+++ b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphIndexTransaction.java
@@ -828,7 +828,7 @@ public class GraphIndexTransaction extends AbstractTransaction {
private ConditionQuery constructSearchQuery(ConditionQuery query,
MatchedIndex index) {
- ConditionQuery originQuery = query;
+ ConditionQuery newQuery = query;
Set<Id> indexFields = new HashSet<>();
// Convert has(key, text) to has(key, textContainsAny(word1, word2))
for (IndexLabel il : index.indexLabels()) {
@@ -836,39 +836,40 @@ public class GraphIndexTransaction extends AbstractTransaction {
continue;
}
Id indexField = il.indexField();
- String fieldValue = (String) query.userpropValue(indexField);
+ String fieldValue = (String) newQuery.userpropValue(indexField);
Set<String> words = this.segmentWords(fieldValue);
indexFields.add(indexField);
- query = query.copy();
- query.unsetCondition(indexField);
- query.query(Condition.textContainsAny(indexField, words));
+ newQuery = newQuery.copy();
+ newQuery.unsetCondition(indexField);
+ newQuery.query(Condition.textContainsAny(indexField, words));
}
// Register results filter to compare property value and search text
- query.registerResultsFilter(elem -> {
- for (Condition cond : originQuery.conditions()) {
- Object key = cond.isRelation() ? ((Relation) cond).key() : null;
+ newQuery.registerResultsFilter(element -> {
+ assert element != null;
+ for (Condition cond : query.conditions()) {
+ Object key = cond.isRelation() ?
+ ((Relation) cond).key() : null;
if (key instanceof Id && indexFields.contains(key)) {
// This is an index field of search index
Id field = (Id) key;
- assert elem != null;
- HugeProperty<?> property = elem.getProperty(field);
+ HugeProperty<?> property = element.getProperty(field);
String propValue = propertyValueToString(property.value());
- String fieldValue = (String) originQuery.userpropValue(field);
+ String fieldValue = (String) query.userpropValue(field);
if (this.matchSearchIndexWords(propValue, fieldValue)) {
continue;
}
return false;
}
- if (!cond.test(elem)) {
+ if (!cond.test(element)) {
return false;
}
}
return true;
});
- return query;
+ return newQuery;
}
private boolean matchSearchIndexWords(String propValue, String fieldValue) {
@@ -1053,7 +1054,7 @@ public class GraphIndexTransaction extends AbstractTransaction {
private static IndexQueries buildJointIndexesQueries(ConditionQuery query,
MatchedIndex index) {
- IndexQueries queries = new IndexQueries();
+ IndexQueries queries = IndexQueries.of(query);
List<IndexLabel> allILs = new ArrayList<>(index.indexLabels());
// Handle range/search indexes
@@ -1174,7 +1175,7 @@ public class GraphIndexTransaction extends AbstractTransaction {
private static IndexQueries constructQueries(ConditionQuery query,
Set<IndexLabel> ils,
Set<Id> propKeys) {
- IndexQueries queries = new IndexQueries();
+ IndexQueries queries = IndexQueries.of(query);
for (IndexLabel il : ils) {
List<Id> fields = il.indexFields();
@@ -1627,15 +1628,25 @@ public class GraphIndexTransaction extends AbstractTransaction {
extends HashMap<IndexLabel, ConditionQuery> {
private static final long serialVersionUID = 1400326138090922676L;
+ private static final IndexQueries EMPTY = new IndexQueries(null);
+
+ private final ConditionQuery parentQuery;
- public static final IndexQueries EMPTY = new IndexQueries();
+ public IndexQueries(ConditionQuery parentQuery) {
+ this.parentQuery = parentQuery;
+ }
public static IndexQueries of(IndexLabel il, ConditionQuery query) {
- IndexQueries indexQueries = new IndexQueries();
+ IndexQueries indexQueries = new IndexQueries(query);
indexQueries.put(il, query);
return indexQueries;
}
+ public static IndexQueries of(ConditionQuery parentQuery) {
+ IndexQueries indexQueries = new IndexQueries(parentQuery);
+ return indexQueries;
+ }
+
public boolean oomRisk() {
for (Query subQuery : this.values()) {
if (subQuery.bigCapacity() && subQuery.aggregate() != null) {
@@ -1660,26 +1671,36 @@ public class GraphIndexTransaction extends AbstractTransaction {
public Query asJointQuery() {
@SuppressWarnings({ "unchecked", "rawtypes" })
- Collection<Query> queries = (Collection) this.values();;
- return new JointQuery(this.rootQuery().resultType(), queries);
+ Collection<Query> queries = (Collection) this.values();
+ return new JointQuery(this.rootQuery().resultType(),
+ this.parentQuery, queries);
}
private static class JointQuery extends Query {
private final Collection<Query> queries;
+ private final ConditionQuery parentQuery;
- public JointQuery(HugeType type, Collection<Query> queries) {
+ public JointQuery(HugeType type, ConditionQuery parentQuery,
+ Collection<Query> queries) {
super(type, parent(queries));
+ this.parentQuery = parentQuery;
this.queries = queries;
}
@Override
public Query originQuery() {
+ return this.parentQuery;
+ }
+
+ @SuppressWarnings("unused")
+ public Query originJointQuery() {
List<Query> origins = new ArrayList<>();
for (Query q : this.queries) {
origins.add(q.originQuery());
}
- return new JointQuery(this.resultType(), origins);
+ return new JointQuery(this.resultType(),
+ this.parentQuery, origins);
}
@Override
@@ -1712,7 +1733,7 @@ public class GraphIndexTransaction extends AbstractTransaction {
this.query = query;
this.element = element;
this.tx = null;
- this.leftIndexes = query.getElementLeftIndex(element.id());
+ this.leftIndexes = query.getLeftIndexOfElement(element.id());
}
@Override
diff --git a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphTransaction.java b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphTransaction.java
index 0adbaa31..b8694188 100644
--- a/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphTransaction.java
+++ b/hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphTransaction.java
@@ -777,9 +777,15 @@ public class GraphTransaction extends IndexableTransaction {
}
public Iterator<Vertex> queryVertices(Query query) {
- E.checkArgument(this.removedVertices.isEmpty() || query.noLimit(),
- "It's not allowed to query with limit when " +
- "there are uncommitted delete records.");
+ if (this.hasUpdate()) {
+ E.checkArgument(query.noLimitAndOffset(),
+ "It's not allowed to query with offser/limit " +
+ "when there are uncommitted records.");
+ // TODO: also add check: no SCAN, no OLAP
+ E.checkArgument(!query.paging(),
+ "It's not allowed to query by paging when " +
+ "there are uncommitted records.");
+ }
query.resetActualOffset();
@@ -935,9 +941,15 @@ public class GraphTransaction extends IndexableTransaction {
@Watched
public Iterator<Edge> queryEdges(Query query) {
- E.checkArgument(this.removedEdges.isEmpty() || query.noLimit(),
- "It's not allowed to query with limit when " +
- "there are uncommitted delete records.");
+ if (this.hasUpdate()) {
+ E.checkArgument(query.noLimitAndOffset(),
+ "It's not allowed to query with offser/limit " +
+ "when there are uncommitted records.");
+ // TODO: also add check: no SCAN, no OLAP
+ E.checkArgument(!query.paging(),
+ "It's not allowed to query by paging when " +
+ "there are uncommitted records.");
+ }
query.resetActualOffset();
diff --git a/hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/AdamicAdarAPITest.java b/hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/AdamicAdarAPITest.java
index 04a1b67a..4d65c274 100644
--- a/hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/AdamicAdarAPITest.java
+++ b/hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/AdamicAdarAPITest.java
@@ -48,7 +48,6 @@ public class AdamicAdarAPITest extends BaseApiTest {
String markoId = name2Ids.get("marko");
String joshId = name2Ids.get("josh");
- String peterId = name2Ids.get("peter");
Response r = client().get(PATH, ImmutableMap.of("vertex",
id2Json(markoId),
"other",
diff --git a/hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/ResourceAllocationAPITest.java b/hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/ResourceAllocationAPITest.java
index ede6b703..72101e68 100644
--- a/hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/ResourceAllocationAPITest.java
+++ b/hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/ResourceAllocationAPITest.java
@@ -48,7 +48,6 @@ public class ResourceAllocationAPITest extends BaseApiTest {
String markoId = name2Ids.get("marko");
String joshId = name2Ids.get("josh");
- String peterId = name2Ids.get("peter");
Response r = client().get(PATH, ImmutableMap.of("vertex",
id2Json(markoId),
"other",
diff --git a/hugegraph-test/src/main/java/com/baidu/hugegraph/core/BaseCoreTest.java b/hugegraph-test/src/main/java/com/baidu/hugegraph/core/BaseCoreTest.java
index 59556ab2..43118961 100644
--- a/hugegraph-test/src/main/java/com/baidu/hugegraph/core/BaseCoreTest.java
+++ b/hugegraph-test/src/main/java/com/baidu/hugegraph/core/BaseCoreTest.java
@@ -19,6 +19,8 @@
package com.baidu.hugegraph.core;
+import java.util.Random;
+
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.After;
@@ -102,6 +104,17 @@ public class BaseCoreTest {
});
}
+ protected void mayCommitTx() {
+ // Commit tx probabilistically for test
+ if (new Random().nextBoolean()) {
+ graph().tx().commit();
+ }
+ }
+
+ protected void commitTx() {
+ graph().tx().commit();
+ }
+
protected BackendFeatures storeFeatures() {
return graph().backendStoreFeatures();
}
diff --git a/hugegraph-test/src/main/java/com/baidu/hugegraph/core/EdgeCoreTest.java b/hugegraph-test/src/main/java/com/baidu/hugegraph/core/EdgeCoreTest.java
index 51147737..c202f67e 100644
--- a/hugegraph-test/src/main/java/com/baidu/hugegraph/core/EdgeCoreTest.java
+++ b/hugegraph-test/src/main/java/com/baidu/hugegraph/core/EdgeCoreTest.java
@@ -1828,12 +1828,13 @@ public class EdgeCoreTest extends BaseCoreTest {
}
@Test
- public void testQueryAllWithLimitAfterDelete() {
+ public void testQueryAllWithLimitAfterUncommittedDelete() {
HugeGraph graph = graph();
init18Edges();
// Query all with limit after delete
graph.traversal().E().limit(14).drop().iterate();
+
Assert.assertThrows(IllegalArgumentException.class, () -> {
// Query count with uncommitted records
graph.traversal().E().count().next();
@@ -1842,6 +1843,11 @@ public class EdgeCoreTest extends BaseCoreTest {
// Query with limit
graph.traversal().E().limit(3).toList();
});
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ // Query with offset
+ graph.traversal().E().range(1, -1).toList();
+ });
+
graph.tx().commit();
Assert.assertEquals(4L, graph.traversal().E().count().next());
List<Edge> edges = graph.traversal().E().limit(3).toList();
@@ -1854,6 +1860,40 @@ public class EdgeCoreTest extends BaseCoreTest {
Assert.assertEquals(1, edges.size());
}
+ @Test
+ public void testQueryAllWithLimitAfterUncommittedInsert() {
+ HugeGraph graph = graph();
+ init18Edges();
+
+ // Query all with limit after insert
+ Vertex james = graph.addVertex(T.label, "author", "id", 3,
+ "name", "James Gosling", "age", 62,
+ "lived", "Canadian");
+
+ Vertex book = graph.addVertex(T.label, "book", "name", "Test-Book-1");
+
+ james.addEdge("authored", book,
+ "comment", "good book!",
+ "comment", "good book!",
+ "comment", "good book too!");
+
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ // Query count with uncommitted records
+ graph.traversal().E().count().next();
+ });
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ // Query with limit
+ graph.traversal().E().limit(3).toList();
+ });
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ // Query with offset
+ graph.traversal().E().range(1, -1).toList();
+ });
+
+ graph.tx().commit();
+ Assert.assertEquals(19L, graph.traversal().E().count().next());
+ }
+
@Test
public void testQueryAllWithLimitByQueryEdges() {
HugeGraph graph = graph();
diff --git a/hugegraph-test/src/main/java/com/baidu/hugegraph/core/VertexCoreTest.java b/hugegraph-test/src/main/java/com/baidu/hugegraph/core/VertexCoreTest.java
index 674f0e1e..7ab9be2c 100644
--- a/hugegraph-test/src/main/java/com/baidu/hugegraph/core/VertexCoreTest.java
+++ b/hugegraph-test/src/main/java/com/baidu/hugegraph/core/VertexCoreTest.java
@@ -205,7 +205,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Beijing", "age", 20);
graph.addVertex(T.label, "person", "name", "Hebe",
"city", "Taipei", "age", 21);
- graph.tx().commit();
+ this.commitTx();
long count = graph.traversal().V().count().next();
Assert.assertEquals(6, count);
@@ -324,7 +324,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph.addVertex(T.label, "review", "id", 1,
"comment", "looks good!",
"comment", "LGTM!");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("review", "id", 1);
Assert.assertEquals(ImmutableList.of("looks good!", "LGTM!"),
@@ -337,7 +337,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex = graph.addVertex(T.label, "review", "id", 2,
"comment",
ImmutableList.of("looks good 2!", "LGTM!"));
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("review", "id", 2);
Assert.assertEquals(ImmutableList.of("looks good 2!", "LGTM!"),
@@ -350,7 +350,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex = graph.addVertex(T.label, "review", "id", 3,
"comment",
new String[]{"looks good 3!", "LGTM!"});
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("review", "id", 3);
Assert.assertEquals(ImmutableList.of("looks good 3!", "LGTM!"),
@@ -408,7 +408,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "soft", "name", "soft" + i,
"updateTime", i);
}
- graph.tx().commit();
+ this.commitTx();
long count = graph.traversal().V()
.has("soft", "updateTime",
@@ -422,7 +422,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "soft", "name", "soft" + i,
"updateTime", 2 * i);
}
- graph.tx().commit();
+ this.commitTx();
count = graph.traversal().V()
.has("soft", "updateTime",
@@ -446,7 +446,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", i,
"score", i);
}
- graph.tx().commit();
+ this.commitTx();
count = graph.traversal().V()
.hasLabel("developer")
@@ -462,7 +462,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", i * 2,
"score", i * 2);
}
- graph.tx().commit();
+ this.commitTx();
count = graph.traversal().V()
.hasLabel("developer")
@@ -498,7 +498,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", i * 3,
"score", i * 3);
}
- graph.tx().commit();
+ this.commitTx();
if (!removeLeftIndexOnOverwrite) {
Whitebox.setInternalState(params().graphTransaction(),
@@ -535,7 +535,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "soft", "name", "soft" + i,
"country", "china", "updateTime", i);
}
- graph.tx().commit();
+ this.commitTx();
long count = graph.traversal().V()
.hasLabel("soft")
@@ -550,7 +550,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "soft", "name", "soft" + i,
"country", "china", "updateTime", i * 2);
}
- graph.tx().commit();
+ this.commitTx();
count = graph.traversal().V()
.hasLabel("soft")
@@ -569,7 +569,7 @@ public class VertexCoreTest extends BaseCoreTest {
"contribution", "+1",
"contribution", "+2",
"contribution", "+2");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("review", "id", 1);
Assert.assertEquals(ImmutableSet.of("+1", "+2"),
@@ -578,7 +578,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex = graph.addVertex(T.label, "review", "id", 2,
"contribution",
ImmutableSet.of("+1", "+1", "+2"));
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("review", "id", 2);
Assert.assertEquals(ImmutableSet.of("+1", "+2"),
@@ -595,16 +595,17 @@ public class VertexCoreTest extends BaseCoreTest {
schema.vertexLabel("soft").properties("name", "tags", "score",
"country", "category")
- .primaryKeys("name").create();
+ .primaryKeys("name")
+ .create();
- schema.indexLabel("softByTag").onV("soft").secondary()
- .by("tags").create();
+ schema.indexLabel("softByTag").onV("soft").by("tags")
+ .secondary().create();
- schema.indexLabel("softByCategory").onV("soft").search()
- .by("category").create();
+ schema.indexLabel("softByScore").onV("soft").by("score")
+ .secondary().create();
- schema.indexLabel("softByScore").onV("soft").secondary()
- .by("score").create();
+ schema.indexLabel("softByCategory").onV("soft").by("category")
+ .search().create();
HugeGraph graph = graph();
@@ -627,7 +628,8 @@ public class VertexCoreTest extends BaseCoreTest {
ImmutableList.of("hello graph", "graph database"),
"tags", ImmutableList.of("graphdb", "gremlin"));
- graph.tx().commit();
+ // TODO: test mayCommitTx() after support textContains(collection, str)
+ this.commitTx();
List<Vertex> vertices;
vertices = graph.traversal().V()
@@ -643,47 +645,45 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals(2, vertices.size());
Assert.assertThrows(IllegalStateException.class, () -> {
- graph.traversal().V().has("soft", "tags",
- "gremlin").toList();
+ graph.traversal().V().has("soft", "tags", "gremlin").toList();
});
// query by contains
vertices = graph.traversal().V()
- .has("soft", "tags",
- ConditionP.contains("gremlin"))
+ .has("soft", "tags", ConditionP.contains("gremlin"))
.toList();
Assert.assertEquals(2, vertices.size());
// secondary-index with list/set of number properties
vertices = graph.traversal().V()
- .has("soft", "score",
- ConditionP.contains(5))
+ .has("soft", "score", ConditionP.contains(5))
.toList();
Assert.assertEquals(3, vertices.size());
vertices = graph.traversal().V()
- .has("soft", "name",
- "hugegraph").toList();
+ .has("soft", "name", "hugegraph").toList();
Assert.assertEquals(1, vertices.size());
// add a new tag
Vertex vertex = vertices.get(0);
vertex.property("tags", ImmutableSet.of("new_tag"));
- graph.tx().commit();
+
+ this.commitTx();
vertices = graph.traversal().V()
- .has("soft", "tags",
- ConditionP.contains("new_tag")).toList();
+ .has("soft", "tags", ConditionP.contains("new_tag"))
+ .toList();
Assert.assertEquals(1, vertices.size());
// delete tag gremlin
vertex = graph.addVertex(T.label, "soft", "name", "hugegraph",
"country", "china",
"score", ImmutableList.of(5, 4, 3),
- "category",
- ImmutableList.of("hello graph", "graph database"),
- "tags", ImmutableList.of("graphdb", "new_tag"));
- graph.tx().commit();
+ "category", ImmutableList.of("hello graph",
+ "graph database"),
+ "tags", ImmutableList.of("graphdb",
+ "new_tag"));
+ this.mayCommitTx();
vertices = graph.traversal().V()
.has("soft", "tags", ConditionP.contains("gremlin"))
@@ -702,7 +702,7 @@ public class VertexCoreTest extends BaseCoreTest {
// remove
vertex.remove();
- graph.tx().commit();
+ this.mayCommitTx();
vertices = graph.traversal().V()
.has("soft", "tags", ConditionP.contains("new_tag"))
@@ -780,6 +780,8 @@ public class VertexCoreTest extends BaseCoreTest {
// Absent 'age' and 'city'
Vertex vertex = graph().addVertex(T.label, "person", "name", "Baby");
Assert.assertEquals("Baby", vertex.value("name"));
+
+ this.mayCommitTx();
}
@Test
@@ -807,7 +809,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertFalse(vertex.values("cnt").hasNext());
Assert.assertFalse(vertex.values("age").hasNext());
- graph().tx().commit();
+ this.commitTx();
// Exist 'fav' after commit then query
vertex = graph().vertex(vertex.id());
@@ -881,7 +883,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex v1 = graph.addVertex(T.label, "programmer", "name", "marko",
"age", 18, "city", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().toList();
Assert.assertEquals(1, vertices.size());
@@ -891,7 +893,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex v2 = graph.addVertex(T.label, "programmer", "name", "marko",
"age", 18, "city", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertNotEquals(v1.id(), v2.id());
@@ -921,7 +923,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex v1 = graph.addVertex(T.label, "programmer", "name", "marko",
"age", 18, "city", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().toList();
Assert.assertEquals(1, vertices.size());
@@ -931,7 +933,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex v2 = graph.addVertex(T.label, "programmer", "name", "marko",
"age", 18, "city", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertNotEquals(v1.id(), v2.id());
@@ -974,7 +976,7 @@ public class VertexCoreTest extends BaseCoreTest {
.create();
graph.addVertex(T.label, "programmer", "name", "marko",
"age", 18, "city", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
String programmerId = graph.vertexLabel("programmer").id().asString();
String vid = String.format("%s:%s!%s", programmerId, "marko", "1I");
@@ -997,7 +999,7 @@ public class VertexCoreTest extends BaseCoreTest {
.create();
graph.addVertex(T.label, "programmer", T.id, "123456", "name", "marko",
"age", 18, "city", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V("123456").toList();
Assert.assertEquals(1, vertices.size());
@@ -1053,7 +1055,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 18, "city", "Beijing");
graph.addVertex(T.label, "programmer", T.id, 61695499031416832L,
"name", "marko", "age", 19, "city", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V(123456).toList();
Assert.assertEquals(1, vertices.size());
@@ -1116,7 +1118,8 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "programmer",
T.id, "835e1153928149578691cf79258e90ee",
"name", "marko", "age", 19, "city", "Beijing");
- graph.tx().commit();
+
+ this.commitTx();
Assert.assertEquals(2L, graph.traversal().V().count().next());
Object uuid = Text.uuid("835e1153928149578691cf79258e90eb");
@@ -1193,12 +1196,12 @@ public class VertexCoreTest extends BaseCoreTest {
public void testAddVertexWithTtl() {
Vertex vertex = graph().addVertex(T.label, "fan", "name", "Baby",
"age", 3, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().vertices(vertex);
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1215,12 +1218,12 @@ public class VertexCoreTest extends BaseCoreTest {
T.label, "follower", "name",
"Baby", "age", 3, "city", "Beijing",
"birth", graph().now() - 1000L);
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().vertices(vertex);
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(1100L);
@@ -1230,7 +1233,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertices = graph().vertices(vertex);
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(1100L);
@@ -1248,13 +1251,13 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph().addVertex(T.label, "fan", "name", "Baby",
"age", 3, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().traversal().V()
.has("city", "Beijing");
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1283,7 +1286,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 6, "city", "Beijing");
Vertex vertex5 = graph().addVertex(T.label, "fan", "name", "Baby5",
"age", 7, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().traversal().V().has("age", 5);
Assert.assertTrue(vertices.hasNext());
@@ -1304,7 +1307,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertices = graph().traversal().V().has("age", P.lte(4));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(2, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1347,7 +1350,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 7, "city", "Beijing");
Vertex vertex6 = graph().addVertex(T.label, "fan", "name", "Baby6",
"age", 5, "city", "Shanghai");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().traversal().V().has("city",
"Shanghai");
@@ -1378,7 +1381,7 @@ public class VertexCoreTest extends BaseCoreTest {
.has("age", P.lte(4));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(2, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1417,13 +1420,13 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph().addVertex(T.label, "fan", "name", "Baby",
"age", 3, "city", "Beijing Haidian");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().traversal().V().has(
"city", Text.contains("Haidian"));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1443,12 +1446,12 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "fan", "name", "Baby",
"age", 3, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph().addVertex(T.label, "fan", "name", "Baby2",
"age", 3, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
});
try {
@@ -1459,7 +1462,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "fan", "name", "Baby2",
"age", 3, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
}
@Test
@@ -1469,13 +1472,13 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph().addVertex(T.label, "fan", "name", "Baby",
"age", 3, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().traversal().V()
.has("city", "Beijing");
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1486,7 +1489,7 @@ public class VertexCoreTest extends BaseCoreTest {
// Override
vertex = graph().addVertex(T.label, "fan", "name", "Baby",
"age", 3, "city", "Shanghai");
- graph().tx().commit();
+ this.commitTx();
// Due to overridden vertices are expired,
// query will lead to async delete
@@ -1496,7 +1499,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertices = graph().traversal().V().has("city", "Shanghai");
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1528,7 +1531,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 9, "city", "Beijing");
Vertex vertex5 = graph().addVertex(T.label, "fan", "name", "Baby5",
"age", 11, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().traversal().V().has("age", 7);
Assert.assertTrue(vertices.hasNext());
@@ -1549,7 +1552,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertices = graph().traversal().V().has("age", P.lte(5));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(2, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1570,7 +1573,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 10, "city", "Beijing");
Vertex vertex10 = graph().addVertex(T.label, "fan", "name", "Baby10",
"age", 12, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
/*
* Due to overridden vertices are expired,
* query will lead to async delete
@@ -1597,7 +1600,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertices = graph().traversal().V().has("age", P.lte(6));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(2, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1644,7 +1647,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 9, "city", "Beijing");
Vertex vertex6 = graph().addVertex(T.label, "fan", "name", "Baby6",
"age", 5, "city", "Shanghai");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().traversal().V().has("city",
"Shanghai");
@@ -1675,7 +1678,7 @@ public class VertexCoreTest extends BaseCoreTest {
.has("age", P.lte(3));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(2, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1700,7 +1703,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex12 = graph().addVertex(T.label, "fan",
"name", "Baby12", "age", 6,
"city", "Shenzhen");
- graph().tx().commit();
+ this.commitTx();
// Due to overridden vertices are expired, query will lead to async delete
vertices = graph().traversal().V().has("city", "Shanghai");
@@ -1738,7 +1741,7 @@ public class VertexCoreTest extends BaseCoreTest {
.has("age", P.lte(4));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(2, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1785,13 +1788,13 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph().addVertex(T.label, "fan", "name", "Baby1",
"age", 3, "city", "Beijing Haidian");
- graph().tx().commit();
+ this.commitTx();
Iterator<Vertex> vertices = graph().traversal().V().has(
"city", Text.contains("Haidian"));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1801,7 +1804,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex = graph().addVertex(T.label, "fan", "name", "Baby2",
"age", 3, "city", "Shanghai Pudong");
- graph().tx().commit();
+ this.commitTx();
// Due to overridden vertices are expired, query will lead to async delete
vertices = graph().traversal().V().has("city",
@@ -1812,7 +1815,7 @@ public class VertexCoreTest extends BaseCoreTest {
Text.contains("Pudong"));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1830,7 +1833,7 @@ public class VertexCoreTest extends BaseCoreTest {
public void testQueryVertexWithTtlInTx() {
Vertex vertex1 = graph().addVertex(T.label, "fan", "name", "Baby1",
"age", 3, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
// Add vertices in tx
Vertex vertex2 = graph().addVertex(T.label, "fan", "name", "Baby2",
"age", 3, "city", "Beijing");
@@ -1842,7 +1845,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertices = graph().vertices(vertex2);
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(vertex2, vertices.next());
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1865,7 +1868,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "fan", "name", "Baby1",
"age", 3, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
// Add vertices in tx
graph().addVertex(T.label, "fan", "name", "Baby2",
"age", 3, "city", "Beijing");
@@ -1874,7 +1877,7 @@ public class VertexCoreTest extends BaseCoreTest {
.has("city", "Beijing");
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(2, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1902,7 +1905,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 6, "city", "Beijing");
graph().addVertex(T.label, "fan", "name", "Baby5",
"age", 7, "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
// Add vertices in tx
graph().addVertex(T.label, "fan", "name", "Baby6",
@@ -1935,7 +1938,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertices = graph().traversal().V().has("age", P.lte(4));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(4, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -1977,7 +1980,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 7, "city", "Beijing");
graph().addVertex(T.label, "fan", "name", "Baby6",
"age", 5, "city", "Shanghai");
- graph().tx().commit();
+ this.commitTx();
// Add vertices in tx
graph().addVertex(T.label, "fan", "name", "Baby7",
@@ -2022,7 +2025,7 @@ public class VertexCoreTest extends BaseCoreTest {
.has("age", P.lte(4));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(4, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -2062,7 +2065,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "fan", "name", "Baby1",
"age", 3, "city", "Beijing Haidian");
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "fan", "name", "Baby2",
"age", 3, "city", "Beijing Haidian");
@@ -2071,7 +2074,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", Text.contains("Haidian"));
Assert.assertTrue(vertices.hasNext());
Assert.assertEquals(2, IteratorUtils.count(vertices));
- graph().tx().commit();
+ this.commitTx();
try {
Thread.sleep(3100L);
@@ -2097,7 +2100,8 @@ public class VertexCoreTest extends BaseCoreTest {
.writeType(WriteType.OLAP_COMMON)
.ifNotExist().create();
- init10Vertices();
+ this.init10VerticesAndCommit();
+
String author = graph.vertexLabel("author").id().asString();
Id id1 = SplicingIdGenerator.splicing(author,
LongEncoding.encodeNumber(1));
@@ -2127,7 +2131,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.id, id9.asObject(), olapPropName, "i");
graph.addVertex(T.id, id10.asObject(), olapPropName, "j");
- graph.tx().commit();
+ this.commitTx();
Assert.assertEquals(GraphReadMode.OLTP_ONLY, graph.readMode());
Assert.assertThrows(NotAllowException.class, () -> {
@@ -2182,7 +2186,8 @@ public class VertexCoreTest extends BaseCoreTest {
.writeType(WriteType.OLAP_SECONDARY)
.ifNotExist().create();
- init10Vertices();
+ this.init10VerticesAndCommit();
+
String author = graph.vertexLabel("author").id().asString();
Id id1 = SplicingIdGenerator.splicing(author,
LongEncoding.encodeNumber(1));
@@ -2212,7 +2217,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.id, id9.asObject(), olapPropName, "i");
graph.addVertex(T.id, id10.asObject(), olapPropName, "j");
- graph.tx().commit();
+ this.commitTx();
Assert.assertEquals(GraphReadMode.OLTP_ONLY, graph.readMode());
Assert.assertThrows(NotAllowException.class, () -> {
@@ -2268,7 +2273,8 @@ public class VertexCoreTest extends BaseCoreTest {
.writeType(WriteType.OLAP_RANGE)
.ifNotExist().create();
- init10Vertices();
+ this.init10VerticesAndCommit();
+
String author = graph.vertexLabel("author").id().asString();
Id id1 = SplicingIdGenerator.splicing(author,
LongEncoding.encodeNumber(1));
@@ -2298,7 +2304,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.id, id9.asObject(), olapPropName, 0.9D);
graph.addVertex(T.id, id10.asObject(), olapPropName, 1.0D);
- graph.tx().commit();
+ this.commitTx();
Assert.assertEquals(GraphReadMode.OLTP_ONLY, graph.readMode());
Assert.assertThrows(NotAllowException.class, () -> {
@@ -2392,7 +2398,8 @@ public class VertexCoreTest extends BaseCoreTest {
.writeType(WriteType.OLAP_SECONDARY)
.ifNotExist().create();
- init10Vertices();
+ this.init10VerticesAndCommit();
+
String author = graph.vertexLabel("author").id().asString();
Id id1 = SplicingIdGenerator.splicing(author,
LongEncoding.encodeNumber(1));
@@ -2422,7 +2429,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.id, id9.asObject(), "pagerank", 0.9D);
graph.addVertex(T.id, id10.asObject(), "pagerank", 1.0D);
- graph.tx().commit();
+ this.commitTx();
graph.addVertex(T.id, id1.asObject(), "wcc", "a");
graph.addVertex(T.id, id2.asObject(), "wcc", "a");
@@ -2435,7 +2442,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.id, id9.asObject(), "wcc", "f");
graph.addVertex(T.id, id10.asObject(), "wcc", "f");
- graph.tx().commit();
+ this.commitTx();
Assert.assertEquals(GraphReadMode.OLTP_ONLY, graph.readMode());
Assert.assertThrows(NotAllowException.class, () -> {
@@ -2566,7 +2573,8 @@ public class VertexCoreTest extends BaseCoreTest {
.writeType(WriteType.OLAP_SECONDARY)
.ifNotExist().create();
- init10Vertices();
+ this.init10VerticesAndCommit();
+
String author = graph.vertexLabel("author").id().asString();
Id id1 = SplicingIdGenerator.splicing(author,
LongEncoding.encodeNumber(1));
@@ -2576,12 +2584,12 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.id, id1.asObject(), "pagerank", 0.1D);
graph.addVertex(T.id, id2.asObject(), "pagerank", 0.2D);
- graph.tx().commit();
+ this.commitTx();
graph.addVertex(T.id, id1.asObject(), "wcc", "a");
graph.addVertex(T.id, id2.asObject(), "wcc", "b");
- graph.tx().commit();
+ this.commitTx();
Assert.assertEquals(GraphReadMode.OLTP_ONLY, graph.readMode());
Assert.assertThrows(NotAllowException.class, () -> {
@@ -2669,6 +2677,50 @@ public class VertexCoreTest extends BaseCoreTest {
graph.readMode(GraphReadMode.OLTP_ONLY);
}
+ @Test
+ public void testQueryOlapWithUpdates() {
+ Assume.assumeTrue("Not support olap properties",
+ storeFeatures().supportsOlapProperties());
+
+ HugeGraph graph = graph();
+ SchemaManager schema = graph.schema();
+ schema.propertyKey("pagerank")
+ .asDouble().valueSingle()
+ .writeType(WriteType.OLAP_RANGE)
+ .ifNotExist().create();
+
+ this.init10VerticesAndCommit();
+
+ String author = graph.vertexLabel("author").id().asString();
+ Id id1 = SplicingIdGenerator.splicing(author,
+ LongEncoding.encodeNumber(1));
+ Id id2 = SplicingIdGenerator.splicing(author,
+ LongEncoding.encodeNumber(2));
+
+ graph.addVertex(T.id, id1.asObject(), "pagerank", 0.1D);
+ graph.addVertex(T.id, id2.asObject(), "pagerank", 0.2D);
+
+ graph.readMode(GraphReadMode.ALL);
+
+ // FIXME: expect to throw error here
+// Assert.assertThrows(IllegalArgumentException.class, () -> {
+// graph.traversal().V().has("pagerank", 0.1D).toList();
+// }, e -> {
+// Assert.assertContains("not allowed to query by olap " +
+// "when there are uncommitted records",
+// e.toString());
+// });
+
+ this.commitTx();
+
+ List<Vertex> vertices = graph.traversal().V()
+ .has("pagerank", 0.2D)
+ .toList();
+ Assert.assertEquals(1, vertices.size());
+
+ graph.readMode(GraphReadMode.OLTP_ONLY);
+ }
+
@Test
public void testQueryAll() {
HugeGraph graph = graph();
@@ -2710,7 +2762,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryAllWithLimit() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
// Query all with limit
List<Vertex> vertices = graph.traversal().V().limit(6).toList();
@@ -2718,12 +2770,13 @@ public class VertexCoreTest extends BaseCoreTest {
}
@Test
- public void testQueryAllWithLimitAfterDelete() {
+ public void testQueryAllWithLimitAfterUncommittedDelete() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
// Query all with limit after delete
graph.traversal().V().limit(6).drop().iterate();
+
Assert.assertThrows(IllegalArgumentException.class, () -> {
// Query count with uncommitted records
graph.traversal().V().count().next();
@@ -2732,22 +2785,54 @@ public class VertexCoreTest extends BaseCoreTest {
// Query with limit
graph.traversal().V().limit(3).toList();
});
- graph.tx().commit();
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ // Query with offset
+ graph.traversal().V().range(1, -1).toList();
+ });
+
+ this.commitTx();
Assert.assertEquals(4L, graph.traversal().V().count().next());
List<Vertex> vertices = graph.traversal().V().limit(3).toList();
Assert.assertEquals(3, vertices.size());
// Query all with limit after delete twice
graph.traversal().V().limit(3).drop().iterate();
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V().limit(3).toList();
Assert.assertEquals(1, vertices.size());
}
+ @Test
+ public void testQueryAllWithLimitAfterUncommittedInsert() {
+ HugeGraph graph = graph();
+ this.init10VerticesAndCommit();
+
+ // Query all with limit after insert
+ graph.addVertex(T.label, "author", "id", 3,
+ "name", "test", "age", 88,
+ "lived", "California");
+
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ // Query count with uncommitted records
+ graph.traversal().V().count().next();
+ });
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ // Query with limit
+ graph.traversal().V().limit(3).toList();
+ });
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ // Query with offset
+ graph.traversal().V().range(1, -1).toList();
+ });
+
+ this.commitTx();
+ Assert.assertEquals(11L, graph.traversal().V().count().next());
+ }
+
@Test
public void testQueryAllWithLimitByQueryVertices() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
Query query = new Query(HugeType.VERTEX);
query.limit(1);
@@ -2760,7 +2845,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryAllWithLimit0() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
// Query all with limit 0
List<Vertex> vertices = graph.traversal().V().limit(0).toList();
@@ -2781,7 +2866,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryAllWithIllegalLimit() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph.traversal().V().limit(-2).toList();
@@ -2795,7 +2880,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryAllWithOffset() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
List<Vertex> vertices = graph.traversal().V().range(8, 100).toList();
Assert.assertEquals(2, vertices.size());
@@ -2807,7 +2892,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryAllWithOffsetAndLimit() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
List<Vertex> vertices = graph.traversal().V().range(8, 9).toList();
Assert.assertEquals(1, vertices.size());
@@ -2831,7 +2916,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryAllWithOffsetAndLimitWithMultiTimes() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
List<Vertex> vertices = graph.traversal().V()
.range(1, 6)
@@ -2865,7 +2950,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryAllWithIllegalOffsetOrLimit() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph.traversal().V().range(8, 7).toList();
@@ -2888,6 +2973,7 @@ public class VertexCoreTest extends BaseCoreTest {
public void testQueryWithSplicingId() {
HugeGraph graph = graph();
init10Vertices();
+
List<Vertex> vertices = graph.traversal().V().toList();
String bookId = graph.vertexLabel("book").id().asString();
Assert.assertTrue(Utils.containsId(vertices,
@@ -2977,7 +3063,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryByIdWithGraphAPIAndNotCommitedRemoved() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
List<Vertex> vertices = graph.traversal().V()
.hasLabel("author").toList();
@@ -3085,7 +3171,7 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testQueryByLabelWithLimit() {
HugeGraph graph = graph();
- init10Vertices();
+ this.init10VerticesAndCommit();
// Query by vertex label with limit
List<Vertex> vertices = graph.traversal().V().hasLabel("book")
@@ -3094,7 +3180,7 @@ public class VertexCoreTest extends BaseCoreTest {
// Query by vertex label with limit
graph.traversal().V().hasLabel("book").limit(3).drop().iterate();
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V().hasLabel("book")
.limit(3).toList();
@@ -3312,7 +3398,8 @@ public class VertexCoreTest extends BaseCoreTest {
graph.traversal().V().hasLabel("person")
.has("city", "Beijing").limit(2)
.drop().iterate();
- graph.tx().commit();
+ this.commitTx();
+
vertices = graph.traversal().V().hasLabel("person")
.has("city", "Beijing").limit(2).toList();
Assert.assertEquals(1, vertices.size());
@@ -3659,7 +3746,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.traversal().V().hasLabel("person")
.has("age", P.between(3, 21)).limit(3)
.drop().iterate();
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V().hasLabel("person")
.has("age", P.between(3, 21)).limit(3).toList();
@@ -3690,7 +3777,7 @@ public class VertexCoreTest extends BaseCoreTest {
// override vertex without age (in backend) and make left index
graph.addVertex(T.label, "person", "name", "Baby","city", "Hongkong")
.remove(); // avoid merge property mode
- graph.tx().commit();
+ this.mayCommitTx();
// qeury again after commit
vertices = graph.traversal().V().hasLabel("person")
@@ -3749,7 +3836,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "number", "id", 8,
"int", Integer.MIN_VALUE + 1);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("number")
.has("int", 0).toList();
@@ -3831,7 +3918,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "number", "id", 10,
"long", Long.MIN_VALUE + 1);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("number")
.has("long", 0).toList();
@@ -3926,7 +4013,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "number", "id", 12,
"float", -secondSmallest);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("number")
.has("float", 7).toList();
@@ -4039,7 +4126,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "number", "id", 9, "double", min15);
graph().addVertex(T.label, "number", "id", 10, "double", -min15);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("number")
.has("double", 7).toList();
@@ -4126,7 +4213,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "number", "id", 8,
"double", -secondSmallest);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("number")
.has("double", 0.123456789012345678901d)
@@ -4234,7 +4321,8 @@ public class VertexCoreTest extends BaseCoreTest {
graph.traversal().V().hasLabel("person")
.has("birth", P.between(dates[1], dates[4]))
.limit(2).drop().iterate();
- graph.tx().commit();
+ this.commitTx();
+
vertices = graph.traversal().V().hasLabel("person")
.has("birth", P.between(dates[1], dates[4]))
.limit(2).toList();
@@ -4370,7 +4458,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "user", "id", 1, "uuid", uuid1);
graph().addVertex(T.label, "user", "id", 2, "uuid", uuid2);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("user")
.has("uuid", uuid1).toList();
@@ -4399,7 +4487,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "user", "id", 1, "blob", blob1);
graph().addVertex(T.label, "user", "id", 2, "blob", blob2);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("user")
.has("blob", blob1).toList();
@@ -4431,7 +4519,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals(1, vertices.size());
// Committed
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V()
.hasLabel("author")
.has("lived", Text.contains("Bay Area"))
@@ -4464,7 +4552,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "author", "id", 1,
"name", "James Gosling", "age", 62,
"lived", "San Francisco Bay Area");
- graph.tx().commit();
+ this.mayCommitTx();
// By authorByLivedSearch index
List<Vertex> vertices = graph.traversal().V()
@@ -4508,7 +4596,7 @@ public class VertexCoreTest extends BaseCoreTest {
"lived", "Tokyo Bay");
graph.addVertex(T.label, "author", "id", 5, "name", "James", "age", 62,
"lived", "San Francisco Bay Area");
- graph.tx().commit();
+ this.commitTx();
List<Vertex> vertices = graph.traversal().V()
.hasLabel("author")
@@ -4577,7 +4665,7 @@ public class VertexCoreTest extends BaseCoreTest {
"lived", "Tokyo Bay");
graph.addVertex(T.label, "author", "id", 5, "name", "James", "age", 62,
"lived", "San Francisco Bay Area");
- graph.tx().commit();
+ this.commitTx();
List<Vertex> vertices = graph.traversal().V()
.hasLabel("author")
@@ -4603,14 +4691,14 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "author", "id", 1,
"name", "James Gosling", "age", 62,
"lived", "San Francisco Bay Area");
- graph.tx().commit();
+ this.commitTx();
// Override the origin vertex with different property value
// and then lead to index left
graph.addVertex(T.label, "author", "id", 1,
"name", "James Gosling", "age", 62,
"lived", "San Francisco, California, U.S.");
- graph.tx().commit();
+ this.commitTx();
// Set breakpoint to observe the store before and after this statement
List<Vertex> vertices = graph.traversal().V().hasLabel("author")
@@ -4632,7 +4720,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "author", "id", 1,
"name", "James Gosling", "age", 62,
"lived", "San Francisco Bay Area");
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertThrows(NoIndexException.class, () -> {
graph.traversal().V().hasLabel("author")
@@ -4688,7 +4776,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Beijing", "age", 28);
graph.addVertex(T.label, "person", "name", "Zhangyi",
"city", "Hongkong", "age", 29);
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().has("age", 28).toList();
Assert.assertEquals(0, vertices.size());
@@ -4705,7 +4793,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Beijing", "age", 28);
graph.addVertex(T.label, "person", "name", "Zhangyi",
"city", "Hongkong", "age", 29);
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().has("city", "Beijing")
.toList();
@@ -4803,9 +4891,10 @@ public class VertexCoreTest extends BaseCoreTest {
"age", 18, "city", "Beijing");
Vertex v = graph.addVertex(T.label, "person", "name", "james",
"age", 19, "city", "Hongkong");
- graph().tx().commit();
+ this.commitTx();
v.property("age", 20);
+ // Don't commit
List<Vertex> vertices = graph.traversal().V()
.where(__.values("age").is(20))
@@ -4891,7 +4980,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "person", "name", "Tom",
"city", "Hongkong", "age", 3);
- graph().tx().commit();
+ this.commitTx();
List<Vertex> vertices;
vertices = graph().traversal().V().has("age", 3).toList();
@@ -4902,6 +4991,10 @@ public class VertexCoreTest extends BaseCoreTest {
.has("age", 3).toList();
Assert.assertEquals(1, vertices.size());
+ /*
+ * NOTE: may block if not commit records:
+ * Lock [hugegraph_il_delete:3] is locked by other operation
+ */
graph().schema().indexLabel("personByCityAndAge").onV("person")
.by("city", "age").ifNotExist().create();
@@ -4934,6 +5027,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Hongkong", "age", 3);
graph().addVertex(T.label, "cat", "name", "Baby",
"city", "Hongkong", "age", 3);
+ this.mayCommitTx();
List<Vertex> vertices;
vertices = graph().traversal().V().has("age", 3)
@@ -4958,7 +5052,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "dog", "name", "Tom",
"city", "Hongkong", "age", 3);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph().traversal().V().has("age", 3)
.has("city", "Hongkong")
@@ -4990,7 +5084,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "dog", "name", "Tom",
"city", "Hongkong", "age", 3);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph().traversal().V().has("age", P.gt(2))
.has("city", "Hongkong").toList();
@@ -5007,7 +5101,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "dog", "name", "Tom",
"age", 8, "weight", 3);
- graph().tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph().traversal().V().has("age", P.gt(2))
.has("weight", P.lt(10)).toList();
@@ -5032,7 +5126,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "dog", "name", "Coco", "age", 3,
"description", "yellow hair golden tail");
- graph().tx().commit();
+ this.commitTx();
List<Vertex> vertices;
vertices = graph().traversal().V()
@@ -5079,7 +5173,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Shanghai",
"description", "yellow hair golden tail");
- graph().tx().commit();
+ this.commitTx();
List<Vertex> vertices;
vertices = graph().traversal().V()
@@ -5141,7 +5235,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Shanghai Pudong",
"description", "yellow hair golden tail");
- graph().tx().commit();
+ this.commitTx();
List<Vertex> vertices;
vertices = graph().traversal().V()
@@ -5191,6 +5285,70 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals(0, vertices.size());
}
+ @Test
+ public void testQueryByJointIndexesWithSearchAndTwoRangeIndexesAndWithin() {
+ SchemaManager schema = graph().schema();
+
+ schema.propertyKey("type").asInt().ifNotExist().create();
+ schema.propertyKey("kid").asInt().ifNotExist().create();
+ schema.propertyKey("name").asText().ifNotExist().create();
+ schema.propertyKey("confirmType").asInt().ifNotExist().create();
+
+ schema.vertexLabel("test")
+ .properties("confirmType", "name", "kid", "type")
+ .nullableKeys("confirmType", "name", "type")
+ .primaryKeys("kid")
+ .ifNotExist().create();
+
+ schema.indexLabel("test_by_type")
+ .onV("test").by("type")
+ .range()
+ .ifNotExist().create();
+ schema.indexLabel("test_by_confirmType")
+ .onV("test").by("confirmType")
+ .range()
+ .ifNotExist().create();
+ schema.indexLabel("test_by_name")
+ .onV("test").by("name")
+ .search()
+ .ifNotExist().create();
+
+ HugeGraph graph = graph();
+
+ graph.addVertex(T.label, "test", "name", "诚信",
+ "confirmType", 0, "type", 0, "kid", 0);
+ graph.addVertex(T.label, "test", "name", "诚信",
+ "confirmType", 1, "type", 1, "kid", 1);
+ graph.addVertex(T.label, "test", "name", "诚信文明",
+ "confirmType", 2, "type", 1, "kid", 2);
+ graph.addVertex(T.label, "test", "name", "诚信文明",
+ "confirmType", 3, "type", 1, "kid", 3);
+
+ this.mayCommitTx();
+
+ List<Vertex> vertices;
+ vertices = graph().traversal().V()
+ .has("type", 1)
+ .has("confirmType", P.within(0, 1, 2, 3))
+ .has("name", Text.contains("诚信"))
+ .toList();
+ Assert.assertEquals(3, vertices.size());
+
+ vertices = graph().traversal().V()
+ .has("type", 1)
+ .has("confirmType", P.within(0, 1, 2, 3))
+ .has("name", Text.contains("文明"))
+ .toList();
+ Assert.assertEquals(2, vertices.size());
+
+ vertices = graph().traversal().V()
+ .has("type", 0)
+ .has("confirmType", P.within(0, 1, 3))
+ .has("name", Text.contains("诚信"))
+ .toList();
+ Assert.assertEquals(1, vertices.size());
+ }
+
@Test
public void testQueryByShardIndex() {
SchemaManager schema = graph().schema();
@@ -5210,7 +5368,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Beijing", "age", 23);
graph.addVertex(T.label, "person", "name", "p5",
"city", "Beijing", "age", 29);
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph().traversal().V()
.has("city", "Hongkong")
@@ -5693,15 +5851,16 @@ public class VertexCoreTest extends BaseCoreTest {
schema.indexLabel("userByName").onV("user").by("name").unique()
.create();
Vertex v = graph().addVertex(T.label, "user", "name", "Tom");
- graph().tx().commit();
+ this.commitTx();
+
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph().addVertex(T.label, "user", "name", "Tom");
- graph().tx().commit();
+ this.commitTx();
});
v.remove();
graph().addVertex(T.label, "user", "name", "Tom");
- graph().tx().commit();
+ this.commitTx();
}
@Test
@@ -5715,7 +5874,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "user", "name", "Tom");
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph().addVertex(T.label, "user", "name", "Tom");
- graph().tx().commit();
+ this.commitTx();
});
}
@@ -5730,16 +5889,17 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex tom = graph().addVertex(T.label, "user", "name", "Tom");
Vertex jack = graph().addVertex(T.label, "user", "name", "Jack");
Vertex james = graph().addVertex(T.label, "user", "name", "James");
- graph().tx().commit();
+ this.commitTx();
tom.remove();
- graph().tx().commit();
+ this.commitTx();
+
jack.property("name", "Tom");
- graph().tx().commit();
+ this.commitTx();
james.remove();
jack.property("name", "James");
- graph().tx().commit();
+ this.commitTx();
}
@Test
@@ -5754,38 +5914,38 @@ public class VertexCoreTest extends BaseCoreTest {
.unique().create();
graph().addVertex(T.label, "user", "name", "Tom",
"city", "Beijing", "age", 18);
- graph().tx().commit();
+ this.commitTx();
// Nullable properties
graph().addVertex(T.label, "user", "name", "Tom", "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "name", "Tom", "age", 18);
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "city", "Beijing", "age", 18);
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "name", "Tom");
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "age", 18);
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "city", "Beijing");
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user");
- graph().tx().commit();
+ this.commitTx();
// Empty String properties
graph().addVertex(T.label, "user", "name", "", "city", "", "age", 18);
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "name", "", "city", "");
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "name", "", "age", 18);
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "city", "", "age", 18);
- graph().tx().commit();
+ this.commitTx();
graph().addVertex(T.label, "user", "name", "");
- graph().tx().commit();
+ this.commitTx();
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph().addVertex(T.label, "user", "age", 18);
- graph().tx().commit();
+ this.commitTx();
}, e -> {
String message = e.getMessage();
Assert.assertTrue(message.contains("Unique constraint " +
@@ -5793,16 +5953,16 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertTrue(message.contains("conflict is found"));
});
graph().addVertex(T.label, "user", "city", "");
- graph().tx().commit();
+ this.commitTx();
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph().addVertex(T.label, "user");
- graph().tx().commit();
+ this.commitTx();
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph().addVertex(T.label, "user", "city", "\\u0001");
- graph().tx().commit();
+ this.commitTx();
});
}
@@ -5823,7 +5983,7 @@ public class VertexCoreTest extends BaseCoreTest {
.create();
graph.addVertex(T.label, "node", "name", "tom");
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertThrows(NoIndexException.class, () -> {
graph.traversal().V().hasLabel("node").has("name", "tom").next();
@@ -5848,7 +6008,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = vertex("author", "id", 1);
vertex.remove();
- graph.tx().commit();
+ this.mayCommitTx();
vertices = graph.traversal().V().toList();
Assert.assertEquals(9, vertices.size());
@@ -5873,7 +6033,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "author", "id", 2,
"name", "Guido van Rossum", "age", 61,
"lived", "California");
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices = graph.traversal().V().toList();
Assert.assertEquals(2, vertices.size());
@@ -5884,7 +6044,7 @@ public class VertexCoreTest extends BaseCoreTest {
// remove vertex without label index
Vertex vertex = vertex("author2", "id", 1);
graph.removeVertex(vertex.label(), vertex.id());
- graph.tx().commit();
+ this.mayCommitTx();
vertices = graph.traversal().V().toList();
Assert.assertEquals(1, vertices.size());
@@ -5895,7 +6055,7 @@ public class VertexCoreTest extends BaseCoreTest {
// remove vertex with label index
vertex = vertex("author", "id", 2);
graph.removeVertex(vertex.label(), vertex.id());
- graph.tx().commit();
+ this.mayCommitTx();
vertices = graph.traversal().V().toList();
Assert.assertEquals(0, vertices.size());
@@ -5914,7 +6074,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = vertex("author", "id", 1);
vertex.remove();
- graph.tx().commit();
+ this.mayCommitTx();
vertices = graph.traversal().V().toList();
Assert.assertEquals(9, vertices.size());
@@ -5924,7 +6084,7 @@ public class VertexCoreTest extends BaseCoreTest {
// Remove again
vertex.remove();
- graph.tx().commit();
+ this.mayCommitTx();
}
@Test
@@ -5954,7 +6114,7 @@ public class VertexCoreTest extends BaseCoreTest {
for (int i = 0; i < vertices.size(); i++) {
vertices.get(i).remove();
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertEquals(9 - i, graph.traversal().V().toList().size());
}
}
@@ -5964,13 +6124,13 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom");
- graph.tx().commit();
+ this.mayCommitTx();
// Add properties
vertex.property("name", "Tom2");
vertex.property("age", 10);
vertex.property("lived", "USA");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Tom2", vertex.property("name").value());
@@ -5983,13 +6143,13 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Tom", vertex.property("name").value());
vertex.property("name", "Tom2");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Tom2", vertex.property("name").value());
@@ -6000,13 +6160,13 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "person", "name", "Tom",
"city", "Hongkong", "age", 3);
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("person", "name", "Tom");
Assert.assertEquals(3, vertex.property("age").value());
vertex.property("age", 4);
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertEquals(4, vertex.property("age").value());
vertex = vertex("person", "name", "Tom");
@@ -6029,7 +6189,7 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Jim");
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertThrows(IllegalArgumentException.class, () -> {
vertex.property("prop-not-exist", "2017-1-1");
@@ -6041,7 +6201,7 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Jim");
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertEquals(1, vertex.property("id").value());
Assert.assertThrows(IllegalArgumentException.class, () -> {
@@ -6061,7 +6221,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "c\\u0002", "age", 2);
graph.addVertex(T.label, "person", "name", "3",
"city", "d\\u0003", "age", 3);
- graph.tx().commit();
+ this.mayCommitTx();
List<Vertex> vertices;
@@ -6084,7 +6244,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertThrows(Exception.class, () -> {
graph.addVertex(T.label, "person", "name", "0",
"city", "a\\u0000", "age", 0);
- graph.tx().commit();
+ this.commitTx();
}, e -> {
if (e instanceof BackendException) {
Assert.assertContains("0x00", e.getCause().getMessage());
@@ -6095,7 +6255,7 @@ public class VertexCoreTest extends BaseCoreTest {
} else {
graph.addVertex(T.label, "person", "name", "0",
"city", "a\\u0000", "age", 0);
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V().has("city", "a\\u0000").toList();
Assert.assertEquals(1, vertices.size());
@@ -6111,7 +6271,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph.addVertex(T.label, "person", "name", "Baby",
"city", "\\u0000", "age", 3);
- graph.tx().commit();
+ this.commitTx();
}, e -> {
Assert.assertContains("Illegal leading char '\\\\u0' in index",
e.getMessage());
@@ -6120,7 +6280,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph.addVertex(T.label, "person", "name", "Baby",
"city", "\\u0001", "age", 3);
- graph.tx().commit();
+ this.commitTx();
}, e -> {
Assert.assertContains("Illegal leading char '\\\\u1' in index",
e.getMessage());
@@ -6129,7 +6289,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph.addVertex(T.label, "person", "name", "Baby",
"city", "\\u0002", "age", 3);
- graph.tx().commit();
+ this.commitTx();
}, e -> {
Assert.assertContains("Illegal leading char '\\\\u2' in index",
e.getMessage());
@@ -6138,7 +6298,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertThrows(IllegalArgumentException.class, () -> {
graph.addVertex(T.label, "person", "name", "Baby",
"city", "\\u0003", "age", 3);
- graph.tx().commit();
+ this.commitTx();
}, e -> {
Assert.assertContains("Illegal leading char '\\\\u3' in index",
e.getMessage());
@@ -6151,10 +6311,10 @@ public class VertexCoreTest extends BaseCoreTest {
storeFeatures().supportsMergeVertexProperty());
HugeGraph graph = graph();
- // "city" is a nonnullable property
+ // "city" is a non-nullable property
graph.addVertex(T.label, "person", "name", "marko", "city", "Beijing",
"birth", "1992-11-17 12:00:00.000");
- graph.tx().commit();
+ this.commitTx();
Vertex vertex = vertex("person", "name", "marko");
Assert.assertEquals("Beijing", vertex.value("city"));
Assert.assertEquals(Utils.date("1992-11-17 12:00:00.000"),
@@ -6163,7 +6323,7 @@ public class VertexCoreTest extends BaseCoreTest {
// append property 'age'
graph.addVertex(T.label, "person", "name", "marko", "city", "Beijing",
"age", 26);
- graph.tx().commit();
+ this.commitTx();
Assert.assertEquals("Beijing", vertex.value("city"));
vertex = vertex("person", "name", "marko");
Assert.assertEquals(26, (int) vertex.value("age"));
@@ -6172,7 +6332,7 @@ public class VertexCoreTest extends BaseCoreTest {
// update property "birth" and keep the original properties unchanged
graph.addVertex(T.label, "person", "name", "marko", "city", "Beijing",
"birth", "1993-11-17 12:00:00.000");
- graph.tx().commit();
+ this.commitTx();
vertex = vertex("person", "name", "marko");
Assert.assertEquals("Beijing", vertex.value("city"));
Assert.assertEquals(26, (int) vertex.value("age"));
@@ -6185,14 +6345,14 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex v = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "age", 10, "lived", "USA");
- graph.tx().commit();
+ this.mayCommitTx();
// Remove "name" property
Assert.assertTrue(v.property("name").isPresent());
Assert.assertTrue(v.property("lived").isPresent());
Assert.assertThrows(IllegalArgumentException.class, () -> {
v.property("name").remove();
- graph.tx().commit();
+ this.commitTx();
});
Assert.assertTrue(v.property("name").isPresent());
Assert.assertTrue(v.property("lived").isPresent());
@@ -6202,7 +6362,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertTrue(vertex.property("name").isPresent());
Assert.assertTrue(vertex.property("lived").isPresent());
vertex.property("lived").remove();
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertTrue(vertex.property("name").isPresent());
Assert.assertFalse(vertex.property("lived").isPresent());
@@ -6266,7 +6426,7 @@ public class VertexCoreTest extends BaseCoreTest {
initPersonIndex(true);
graph.addVertex(T.label, "person", "name", "Baby", "city", "");
- graph.tx().commit();
+ this.commitTx();
Vertex vertex = graph.traversal().V().has("city", "").next();
Assert.assertEquals("Baby", vertex.value("name"));
@@ -6280,7 +6440,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph.addVertex(T.label, "person", "name", "Baby",
"city", "Hongkong", "age", 3);
- graph.tx().commit();
+ this.commitTx();
List<Vertex> vl = graph.traversal().V().has("age", 3).toList();
Assert.assertEquals(1, vl.size());
@@ -6295,7 +6455,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex.property("age", 5);
vertex.property("city", "Shanghai");
- graph.tx().commit();
+ this.commitTx();
vl = graph.traversal().V().has("age", 3).toList();
Assert.assertEquals(0, vl.size());
@@ -6316,7 +6476,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph.addVertex(T.label, "person", "name", "Baby",
"city", "Hongkong", "age", 3);
- graph.tx().commit();
+ this.commitTx();
List<Vertex> vl = graph.traversal().V().has("city", "Hongkong").toList();
Assert.assertEquals(1, vl.size());
@@ -6325,7 +6485,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals(0, vl.size());
vertex.property("city", "Shanghai");
- graph.tx().commit();
+ this.commitTx();
vl = graph.traversal().V().has("city", "Hongkong").toList();
Assert.assertEquals(0, vl.size());
@@ -6341,7 +6501,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph.addVertex(T.label, "person", "name", "Baby",
"city", "Hongkong", "age", 3);
- graph.tx().commit();
+ this.commitTx();
List<Vertex> vl = graph.traversal().V().has("age", 3).toList();
Assert.assertEquals(1, vl.size());
@@ -6350,7 +6510,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals(0, vl.size());
vertex.property("age", 5);
- graph.tx().commit();
+ this.commitTx();
vl = graph.traversal().V().has("age", 3).toList();
Assert.assertEquals(0, vl.size());
@@ -6366,8 +6526,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "computer", "name", "1st", "band", "10Gbps",
"cpu", "2GHz", "ram", "8GB", "price", 1000);
- graph.tx().commit();
-
+ this.commitTx();
List<Vertex> vl = graph.traversal().V().has("cpu", "2GHz").toList();
Assert.assertEquals(1, vl.size());
@@ -6384,11 +6543,11 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
vertex.property("lived").remove();
vertex.property("lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Shanghai", vertex.property("lived").value());
@@ -6399,7 +6558,7 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
vertex.property("lived").remove();
vertex.property("lived").remove();
@@ -6407,7 +6566,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex.property("lived", "Hangzhou");
vertex.property("lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Shanghai", vertex.property("lived").value());
@@ -6422,7 +6581,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex.property("lived").remove();
vertex.property("lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Shanghai", vertex.property("lived").value());
@@ -6433,7 +6592,7 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
Vertex vertex = vertex("author", "id", 1);
Assert.assertThrows(IllegalArgumentException.class, () -> {
@@ -6457,9 +6616,13 @@ public class VertexCoreTest extends BaseCoreTest {
@Test
public void testUpdateVertexPropertyOfAddingVertex() {
HugeGraph graph = graph();
+ Vertex vertex0 = graph.addVertex(T.label, "author", "id", 1,
+ "name", "Tom", "lived", "Beijing");
+ vertex0.property("lived").remove();
+
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
- graph.tx().commit();
+ this.commitTx();
graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
@@ -6477,7 +6640,7 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
- graph.tx().commit();
+ this.commitTx();
vertex.remove();
@@ -6494,7 +6657,7 @@ public class VertexCoreTest extends BaseCoreTest {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
- graph.tx().commit();
+ this.commitTx();
graph.traversal().V(vertex.id()).drop().iterate();
@@ -6542,7 +6705,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "student", "name", "Tom", "worstScore", 55,
"bestScore", 96, "testNum", 1, "rank", 8, "reword", 8);
- graph.tx().commit();
+ this.commitTx();
Vertex tom = graph.traversal().V().hasLabel("student")
.has("name", "Tom").next();
@@ -6557,7 +6720,7 @@ public class VertexCoreTest extends BaseCoreTest {
tom.property("testNum", 1);
tom.property("rank", 12);
tom.property("reword", 12);
- graph.tx().commit();
+ this.commitTx();
tom = graph.traversal().V().hasLabel("student")
.has("name", "Tom").next();
@@ -6572,7 +6735,7 @@ public class VertexCoreTest extends BaseCoreTest {
tom.property("testNum", 1);
tom.property("rank", 8);
tom.property("reword", 8);
- graph.tx().commit();
+ this.commitTx();
tom = graph.traversal().V().hasLabel("student")
.has("name", "Tom").next();
@@ -6588,7 +6751,7 @@ public class VertexCoreTest extends BaseCoreTest {
tom.property("testNum", 1);
tom.property("rank", 1);
tom.property("reword", 1);
- graph.tx().commit();
+ this.commitTx();
tom = graph.traversal().V().hasLabel("student")
.has("name", "Tom").next();
@@ -6651,7 +6814,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals(ImmutableSet.of(8, 12), result.value("rank"));
Assert.assertEquals(ImmutableList.of(8, 12), result.value("reword"));
- graph.tx().commit();
+ this.commitTx();
result = graph.traversal().V().hasLabel("student")
.has("name", "Tom").next();
@@ -6686,7 +6849,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals(ImmutableList.of(2, 1),
tom.value("reword"));
- graph.tx().commit();
+ this.commitTx();
result = graph.traversal().V().hasLabel("student")
.has("name", "Tom").next();
Assert.assertEquals(65, result.value("worstScore"));
@@ -6765,7 +6928,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "student", "name", "Tom", "worstScore", 55,
"bestScore", 96, "testNum", 1, "no", "001");
- graph.tx().commit();
+ this.commitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("student")
.has("name", "Tom").toList();
@@ -6802,7 +6965,7 @@ public class VertexCoreTest extends BaseCoreTest {
tom.property("bestScore", 98);
tom.property("testNum", 1);
tom.property("no", "002");
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V().hasLabel("student")
.has("name", "Tom").toList();
@@ -6840,7 +7003,7 @@ public class VertexCoreTest extends BaseCoreTest {
tom.property("bestScore", 99);
tom.property("testNum", 1);
tom.property("no", "003");
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V().hasLabel("student")
.has("name", "Tom").toList();
@@ -6878,7 +7041,7 @@ public class VertexCoreTest extends BaseCoreTest {
tom.property("bestScore", 100);
tom.property("testNum", 1);
tom.property("no", "004");
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V().hasLabel("student")
.has("name", "Tom").toList();
@@ -6916,19 +7079,19 @@ public class VertexCoreTest extends BaseCoreTest {
tom.property("bestScore", 99);
tom.property("testNum", 1);
tom.property("no", "005");
- graph.tx().commit();
+ this.commitTx();
tom.property("worstScore", 65);
tom.property("bestScore", 93);
tom.property("testNum", 1);
tom.property("no", "006");
- graph.tx().commit();
+ this.commitTx();
tom.property("worstScore", 58);
tom.property("bestScore", 63);
tom.property("testNum", 1);
tom.property("no", "007");
- graph.tx().commit();
+ this.commitTx();
vertices = graph.traversal().V().hasLabel("student")
.has("name", "Tom").toList();
@@ -7014,7 +7177,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "student", "name", "Tom", "worstScore", 55,
"bestScore", 96, "testNum", 1, "no", "001",
"rank", 1, "reword", 1);
- graph.tx().commit();
+ this.commitTx();
List<Vertex> vertices = graph.traversal().V().hasLabel("student")
.has("name", "Tom").toList();
@@ -7045,7 +7208,7 @@ public class VertexCoreTest extends BaseCoreTest {
reword = random.nextInt();
rewords.add(reword);
tom.property("reword", reword);
- graph.tx().commit();
+ this.commitTx();
tom = graph.traversal().V().hasLabel("student")
.has("name", "Tom").next();
@@ -7068,7 +7231,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
Vertex vertex = vertex("author", "id", 1);
Assert.assertEquals("Shanghai", vertex.property("lived").value());
@@ -7081,7 +7244,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
vertex.remove();
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertNull(vertex("author", "id", 1));
}
@@ -7093,7 +7256,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
vertex.property("lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Shanghai", vertex.property("lived").value());
@@ -7106,7 +7269,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex = graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Beijing");
vertex.property("lived").remove();
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertFalse(vertex.property("lived").isPresent());
@@ -7123,7 +7286,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.traversal().V().hasLabel("author").has("id", 1).next().remove();
graph.addVertex(T.label, "author", "id", 1,
"name", "Tom", "lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
Vertex vertex = vertex("author", "id", 1);
Assert.assertTrue(vertex.property("lived").isPresent());
@@ -7138,7 +7301,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.remove();
vertex.remove();
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertNull(vertex("author", "id", 1));
}
@@ -7151,7 +7314,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.remove();
vertex.property("lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertNull(vertex("author", "id", 1));
}
@@ -7164,7 +7327,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.remove();
vertex.property("lived").remove();
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertNull(vertex("author", "id", 1));
}
@@ -7179,7 +7342,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex.property("lived", "Wuhan");
graph.addVertex(T.label, "author", "id", 1, "name", "Tom",
"lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertTrue(vertex.property("lived").isPresent());
@@ -7194,7 +7357,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("lived", "Wuhan");
vertex.remove();
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertNull(vertex("author", "id", 1));
}
@@ -7206,7 +7369,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("lived", "Wuhan");
vertex.property("lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Shanghai", vertex.property("lived").value());
@@ -7219,7 +7382,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("name", "Tomcat");
vertex.property("lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertEquals("Tomcat", vertex.property("name").value());
@@ -7233,7 +7396,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("lived", "Shanghai");
vertex.property("lived").remove();
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertFalse(vertex.property("lived").isPresent());
@@ -7246,7 +7409,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("name", "Tomcat");
vertex.property("lived").remove();
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertFalse(vertex.property("lived").isPresent());
@@ -7263,7 +7426,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex.property("lived").remove();
graph.addVertex(T.label, "author", "id", 1, "name", "Tom",
"lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertTrue(vertex.property("lived").isPresent());
@@ -7278,7 +7441,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("lived").remove();
vertex.remove();
- graph.tx().commit();
+ this.mayCommitTx();
Assert.assertNull(vertex("author", "id", 1));
}
@@ -7290,7 +7453,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("lived").remove();
vertex.property("lived", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertTrue(vertex.property("lived").isPresent());
@@ -7305,7 +7468,7 @@ public class VertexCoreTest extends BaseCoreTest {
vertex.property("lived").remove();
vertex.property("name", "Tomcat");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertFalse(vertex.property("lived").isPresent());
@@ -7319,7 +7482,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("lived").remove();
vertex.property("lived").remove();
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertFalse(vertex.property("lived").isPresent());
@@ -7332,7 +7495,7 @@ public class VertexCoreTest extends BaseCoreTest {
"name", "Tom", "lived", "Beijing");
vertex.property("age").remove();
vertex.property("lived").remove();
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("author", "id", 1);
Assert.assertFalse(vertex.property("age").isPresent());
@@ -7345,7 +7508,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "person", "name", "marko",
"age", 18, "city", "Beijing");
- graph.tx().commit();
+ this.mayCommitTx();
Vertex vertex = vertex("person", "name", "marko");
Assert.assertTrue(vertex.property("age").isPresent());
Assert.assertEquals(18, vertex.value("age"));
@@ -7353,7 +7516,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals("Beijing", vertex.value("city"));
graph.addVertex(T.label, "person", "name", "marko", "city", "Wuhan");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("person", "name", "marko");
Assert.assertFalse(vertex.property("age").isPresent());
Assert.assertTrue(vertex.property("city").isPresent());
@@ -7361,7 +7524,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "person", "name", "marko",
"age", 19, "city", "Shanghai");
- graph.tx().commit();
+ this.mayCommitTx();
vertex = vertex("person", "name", "marko");
Assert.assertTrue(vertex.property("age").isPresent());
Assert.assertEquals(19, vertex.value("age"));
@@ -7369,7 +7532,6 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertEquals("Shanghai", vertex.value("city"));
}
- @SuppressWarnings("unchecked")
@Test
public void testScanVertex() {
HugeGraph graph = graph();
@@ -7377,13 +7539,14 @@ public class VertexCoreTest extends BaseCoreTest {
Assume.assumeTrue("Not support scan",
storeFeatures().supportsScanToken() ||
storeFeatures().supportsScanKeyRange());
- init10Vertices();
+ this.init10VerticesAndCommit();
List<Vertex> vertices = new LinkedList<>();
long splitSize = 1 * 1024 * 1024;
- Object splits = graph.metadata(HugeType.VERTEX, "splits", splitSize);
- for (Shard split : (List<Shard>) splits) {
+ List<Shard> splits = graph.metadata(HugeType.VERTEX, "splits",
+ splitSize);
+ for (Shard split : splits) {
ConditionQuery q = new ConditionQuery(HugeType.VERTEX);
q.scan(split.start(), split.end());
vertices.addAll(ImmutableList.copyOf(graph.vertices(q)));
@@ -7398,7 +7561,7 @@ public class VertexCoreTest extends BaseCoreTest {
Assume.assumeTrue("Not support scan",
storeFeatures().supportsScanToken() ||
storeFeatures().supportsScanKeyRange());
- init10Vertices();
+ this.init10VerticesAndCommit();
List<Vertex> vertices = new LinkedList<>();
ConditionQuery query = new ConditionQuery(HugeType.VERTEX);
@@ -7895,6 +8058,27 @@ public class VertexCoreTest extends BaseCoreTest {
});
}
+ @Test
+ public void testQueryByPageWithtUncommittedRecords() {
+ Assume.assumeTrue("Not support paging",
+ storeFeatures().supportsQueryByPage());
+
+ HugeGraph graph = graph();
+
+ graph.addVertex(T.label, "author", "id", 1,
+ "name", "James Gosling", "age", 62,
+ "lived", "Canadian");
+ graph.addVertex(T.label, "author", "id", 2,
+ "name", "Guido van Rossum", "age", 61,
+ "lived", "California");
+
+ Assert.assertThrows(IllegalArgumentException.class, () -> {
+ graph.traversal().V()
+ .has("~page", "")
+ .toList();
+ });
+ }
+
@Test
public void testQueryByLabelInPageWithLimitLtePageSize() {
Assume.assumeTrue("Not support paging",
@@ -8542,16 +8726,16 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "programmer", T.id, "123456", "name", "marko",
"age", 18, "city", "Beijing");
- graph.tx().commit();
+ this.commitTx();
graph.addVertex(T.label, "programmer", T.id, "123456", "name", "marko",
"age", 19, "city", "Beijing");
- graph.tx().commit();
+ this.commitTx();
graph.addVertex(T.label, "designer", T.id, "123456", "name", "marko",
"age", 18, "city", "Beijing");
Assert.assertThrows(HugeException.class, () -> {
- graph.tx().commit();
+ this.commitTx();
});
}
@@ -8565,7 +8749,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "user", T.id, 123);
graph.addVertex(T.label, "user", T.id, 456);
graph.addVertex(T.label, "user", T.id, 789);
- graph.tx().commit();
+ this.mayCommitTx();
GraphTraversalSource g = graph.traversal();
List<Vertex> vertices;
@@ -8600,7 +8784,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "user1", T.id, 123);
graph.addVertex(T.label, "user2", T.id, 456);
graph.addVertex(T.label, "user2", T.id, 789);
- graph.tx().commit();
+ this.mayCommitTx();
GraphTraversalSource g = graph.traversal();
List<Vertex> vertices;
@@ -8738,7 +8922,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex3 = graph.addVertex(T.label, "person", "name",
"xyz\\u0003abc", "city", "Hongkong",
"age", 13);
- graph.tx().commit();
+ this.mayCommitTx();
GraphTraversalSource g = graph.traversal();
@@ -8826,7 +9010,7 @@ public class VertexCoreTest extends BaseCoreTest {
Vertex vertex6 = graph.addVertex(T.label, "person", "name", "6",
"city", "\\u0001",
"age", 15);
- graph.tx().commit();
+ this.commitTx();
GraphTraversalSource g = graph.traversal();
@@ -8928,7 +9112,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Beijing", "age", 23);
Vertex vertex5 = graph.addVertex(T.label, "person", "name", "秦始皇帝",
"city", "Beijing", "age", 29);
- graph.tx().commit();
+ this.commitTx();
GraphTraversalSource g = graph.traversal();
@@ -8954,6 +9138,11 @@ public class VertexCoreTest extends BaseCoreTest {
Assert.assertTrue(vertices.contains(vertex4));
}
+ private void init10VerticesAndCommit() {
+ this.init10Vertices();
+ this.commitTx();
+ }
+
private void init10Vertices() {
HugeGraph graph = graph();
@@ -8975,7 +9164,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "book", "name", "java-4");
graph.addVertex(T.label, "book", "name", "java-5");
- graph.tx().commit();
+ this.mayCommitTx();
}
private void init100Books() {
@@ -8985,7 +9174,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph.addVertex(T.label, "book", "name", "java-" + i, "price", i);
}
- graph.tx().commit();
+ this.commitTx();
}
private void init5Persons() {
@@ -9007,7 +9196,7 @@ public class VertexCoreTest extends BaseCoreTest {
"city", "Taipei", "age", 21,
"birth", Utils.date("2016-01-01 00:00:00.000"));
- graph.tx().commit();
+ this.commitTx();
}
private void init100Persons() {
@@ -9021,7 +9210,7 @@ public class VertexCoreTest extends BaseCoreTest {
"age", i % 11);
}
- graph.tx().commit();
+ this.commitTx();
}
private void init5Computers() {
@@ -9045,7 +9234,7 @@ public class VertexCoreTest extends BaseCoreTest {
"band", "asus", "cpu", "3.2GHz", "ram", "16GB",
"price", 6999);
- graph.tx().commit();
+ this.commitTx();
}
private void initPageTestData() {
@@ -9131,7 +9320,7 @@ public class VertexCoreTest extends BaseCoreTest {
graph().addVertex(T.label, "software", T.id, id, "name", "marko",
"lang", "java", "price", price);
}
- graph().tx().commit();
+ this.commitTx();
}
private Vertex vertex(String label, String pkName, Object pkValue) { | ['hugegraph-test/src/main/java/com/baidu/hugegraph/core/BaseCoreTest.java', 'hugegraph-test/src/main/java/com/baidu/hugegraph/core/EdgeCoreTest.java', 'hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/Condition.java', 'hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphIndexTransaction.java', 'hugegraph-core/src/main/java/com/baidu/hugegraph/backend/query/ConditionQuery.java', 'hugegraph-test/src/main/java/com/baidu/hugegraph/core/VertexCoreTest.java', 'hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/AdamicAdarAPITest.java', 'hugegraph-test/src/main/java/com/baidu/hugegraph/api/traversers/ResourceAllocationAPITest.java', 'hugegraph-core/src/main/java/com/baidu/hugegraph/backend/tx/GraphTransaction.java', 'hugegraph-core/src/main/java/com/baidu/hugegraph/backend/page/QueryList.java'] | {'.java': 10} | 10 | 10 | 0 | 0 | 10 | 3,931,898 | 790,512 | 108,914 | 497 | 11,942 | 2,163 | 231 | 5 | 2,242 | 126 | 775 | 51 | 2 | 0 | 2022-03-29T10:40:57 | 2,382 | Java | {'Java': 5925495, 'Shell': 91995, 'Groovy': 5291, 'HTML': 4015, 'Dockerfile': 2072} | Apache License 2.0 |
1,221 | apache/netbeans/6195/6149 | apache | netbeans | https://github.com/apache/netbeans/issues/6149 | https://github.com/apache/netbeans/pull/6195 | https://github.com/apache/netbeans/pull/6195 | 1 | fixes | `Objects.requireNonNull` should disable "Null Pointer Dereference" warnings | ### Apache NetBeans version
Apache NetBeans 18
### What happened
Using `Objects.requireNonNull` should disable "Null Pointer Dereference" warnings. Instead, it doesn't.
### How to reproduce
```java
public static String myToString(Object object) {
Objects.requireNonNull(object);
if (object instanceof Number) {
DecimalFormat df = new DecimalFormat("#.00");
return df.format(((Number) object).doubleValue());
} else {
return object.toString();
}
}
```
### Did this work correctly in an earlier version?
No / Don't know
### Operating System
Windows 10 version 10.0 running on amd64; Cp1252; it_IT (nb)
### JDK
11.0.14.1; OpenJDK 64-Bit Server VM 11.0.14.1+1
### Apache NetBeans packaging
Apache NetBeans binary zip
### Anything else
![null warning](https://github.com/apache/netbeans/assets/18428155/6470fe7e-e4e9-4306-96de-3b02be74788b)
if `Objects.requireNonNull(object);` is replaced by `if (object == null) throw new NullPointerException();` the warning disappears.
### Are you willing to submit a pull request?
No | 7cb0985514507992d998c22ac6b9ab163ca824ff | 0498a037fce87daeecbdcd757db9101552f88e6c | https://github.com/apache/netbeans/compare/7cb0985514507992d998c22ac6b9ab163ca824ff...0498a037fce87daeecbdcd757db9101552f88e6c | diff --git a/java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java b/java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java
index d671eec7e4..4e59f3257c 100644
--- a/java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java
+++ b/java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java
@@ -823,17 +823,23 @@ public class HintTest {
}
/**Assert that the hint(s) produced warnings do not include the given warnings. The provided strings
- * should match {@code toString()} results of {@link ErrorDescription}s produced
+ * should match {@code getDescription()} results of {@link ErrorDescription}s produced
* by the hint(s).
*
- * @param warnings expected {@code toString()} results of {@link ErrorDescription}s produced
+ * @param warnings expected {@code getDescription()} results of {@link ErrorDescription}s produced
* by the hint
* @return itself
- * @throws AssertionError if the given warnings do not match the actual warnings
+ * @throws AssertionError if the given warnings contain the actual warnings
*/
public HintOutput assertNotContainsWarnings(String... warnings) {
Set<String> goldenSet = new HashSet<String>(Arrays.asList(warnings));
List<String> errorsNames = new LinkedList<String>();
+
+ for (String warning : goldenSet) {
+ if (warning.split(":").length >= 5) {
+ assertFalse("this method expects hint descriptions, not toString()! errors found: "+errors, true);
+ }
+ }
boolean fail = false;
for (ErrorDescription d : errors) {
diff --git a/java/java.hints/src/org/netbeans/modules/java/hints/bugs/NPECheck.java b/java/java.hints/src/org/netbeans/modules/java/hints/bugs/NPECheck.java
index e2e3392d3c..32ef1bd43d 100644
--- a/java/java.hints/src/org/netbeans/modules/java/hints/bugs/NPECheck.java
+++ b/java/java.hints/src/org/netbeans/modules/java/hints/bugs/NPECheck.java
@@ -1068,12 +1068,16 @@ public class NPECheck {
State targetState = null;
switch (e.getSimpleName().toString()) {
- case "assertNotNull": targetState = State.NOT_NULL; break;
+ case "assertNotNull":
+ case "requireNonNull":
+ case "requireNonNullElse":
+ case "requireNonNullElseGet": targetState = State.NOT_NULL; break;
case "assertNull": targetState = State.NULL; break;
}
switch (ownerFQN) {
- case "org.testng.Assert": argument = node.getArguments().get(0); break;
+ case "org.testng.Assert":
+ case "java.util.Objects": argument = node.getArguments().get(0); break;
case "junit.framework.Assert":
case "org.junit.Assert":
case "org.junit.jupiter.api.Assertions": argument = node.getArguments().get(node.getArguments().size() - 1); break;
diff --git a/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/bugs/NPECheckTest.java b/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/bugs/NPECheckTest.java
index e62a098374..20f6663f79 100644
--- a/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/bugs/NPECheckTest.java
+++ b/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/bugs/NPECheckTest.java
@@ -1798,6 +1798,38 @@ public class NPECheckTest extends NbTestCase {
"9:7-9:15:verifier:Possibly Dereferencing null");
}
+ public void testObjectsRequireNonNull() throws Exception {
+ HintTest.create()
+ .input("package test;\\n"
+ + "import java.util.Objects;\\n"
+ + "public class Test {\\n"
+ + " public String test(Object obj) {\\n"
+ + " Objects.requireNonNull(obj);\\n"
+ + " if (obj instanceof Number)\\n"
+ + " return \\"\\";\\n"
+ + " return obj.toString();\\n"
+ + " }\\n"
+ + "}")
+ .run(NPECheck.class)
+ .assertNotContainsWarnings("Possibly Dereferencing null");
+ }
+
+ public void testObjectsRequireNonNullElse() throws Exception {
+ HintTest.create()
+ .input("package test;\\n"
+ + "import java.util.Objects;\\n"
+ + "public class Test {\\n"
+ + " public String test(Object obj) {\\n"
+ + " Objects.requireNonNullElse(obj, \\"\\");\\n"
+ + " if (obj instanceof Number)\\n"
+ + " return \\"\\";\\n"
+ + " return obj.toString();\\n"
+ + " }\\n"
+ + "}")
+ .run(NPECheck.class)
+ .assertNotContainsWarnings("Possibly Dereferencing null");
+ }
+
private void performAnalysisTest(String fileName, String code, String... golden) throws Exception {
HintTest.create()
.input(fileName, code)
diff --git a/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertToSwitchPatternInstanceOfTest.java b/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertToSwitchPatternInstanceOfTest.java
index e89761e214..094a091672 100644
--- a/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertToSwitchPatternInstanceOfTest.java
+++ b/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertToSwitchPatternInstanceOfTest.java
@@ -105,7 +105,7 @@ public class ConvertToSwitchPatternInstanceOfTest extends NbTestCase {
.sourceLevel("17")
.options("--enable-preview")
.run(ConvertToSwitchPatternInstanceOf.class)
- .assertNotContainsWarnings("3:8-3:10:verifier:" + Bundle.ERR_ConvertToSwitchPatternInstanceOf());
+ .assertNotContainsWarnings(Bundle.ERR_ConvertToSwitchPatternInstanceOf());
}
@Test
@@ -184,7 +184,7 @@ public class ConvertToSwitchPatternInstanceOfTest extends NbTestCase {
.sourceLevel(SourceVersion.latest().name())
.options("--enable-preview")
.run(ConvertToSwitchPatternInstanceOf.class)
- .assertNotContainsWarnings("4:8-4:10:verifier:" + Bundle.ERR_ConvertToSwitchPatternInstanceOf());
+ .assertNotContainsWarnings(Bundle.ERR_ConvertToSwitchPatternInstanceOf());
}
@Test
@@ -278,7 +278,7 @@ public class ConvertToSwitchPatternInstanceOfTest extends NbTestCase {
.sourceLevel(SourceVersion.latest().name())
.options("--enable-preview")
.run(ConvertToSwitchPatternInstanceOf.class)
- .assertNotContainsWarnings("4:8-4:24:verifier:" + Bundle.ERR_ConvertToSwitchPatternInstanceOf());
+ .assertNotContainsWarnings(Bundle.ERR_ConvertToSwitchPatternInstanceOf());
}
@Test
diff --git a/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/mapreduce/ForLoopToFunctionalHintTest.java b/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/mapreduce/ForLoopToFunctionalHintTest.java
index 093c3764ec..0752a57c3a 100644
--- a/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/mapreduce/ForLoopToFunctionalHintTest.java
+++ b/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/mapreduce/ForLoopToFunctionalHintTest.java
@@ -1406,7 +1406,7 @@ public class ForLoopToFunctionalHintTest extends NbTestCase {
+ "}")
.sourceLevel("1.8")
.run(ForLoopToFunctionalHint.class)
- .assertNotContainsWarnings("23:8-23:11:hint:" + Bundle.ERR_ForLoopToFunctionalHint());
+ .assertNotContainsWarnings(Bundle.ERR_ForLoopToFunctionalHint());
}
public void testNoHintDueToNEF() throws Exception {
@@ -1789,7 +1789,7 @@ public class ForLoopToFunctionalHintTest extends NbTestCase {
+ "}")
.sourceLevel("1.8")
.run(ForLoopToFunctionalHint.class)
- .assertNotContainsWarnings("23:8-23:11:hint:Can use functional operation");
+ .assertNotContainsWarnings("Can use functional operation");
}
@@ -1832,7 +1832,7 @@ public class ForLoopToFunctionalHintTest extends NbTestCase {
+ "}")
.sourceLevel("1.8")
.run(ForLoopToFunctionalHint.class)
- .assertNotContainsWarnings("23:8-23:11:hint:Can use functional operation");
+ .assertNotContainsWarnings("Can use functional operation");
}
@@ -1873,7 +1873,7 @@ public class ForLoopToFunctionalHintTest extends NbTestCase {
+ "}")
.sourceLevel("1.8")
.run(ForLoopToFunctionalHint.class)
- .assertNotContainsWarnings("23:8-23:11:hint:Can use functional operation");
+ .assertNotContainsWarnings("Can use functional operation");
}
| ['java/java.hints/src/org/netbeans/modules/java/hints/bugs/NPECheck.java', 'java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java', 'java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/mapreduce/ForLoopToFunctionalHintTest.java', 'java/java.hints/test/unit/src/org/netbeans/modules/java/hints/bugs/NPECheckTest.java', 'java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertToSwitchPatternInstanceOfTest.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 242,190,921 | 49,224,303 | 6,196,307 | 28,088 | 535 | 96 | 8 | 1 | 1,086 | 126 | 269 | 47 | 1 | 1 | 2023-07-13T23:15:49 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,229 | apache/netbeans/5668/4227 | apache | netbeans | https://github.com/apache/netbeans/issues/4227 | https://github.com/apache/netbeans/pull/5668 | https://github.com/apache/netbeans/pull/5668 | 1 | fixes | Module graph fails to display | ### Apache NetBeans version
Apache NetBeans 13
### What happened
Applies in both Apache Netbeans 14 and 13.
While module-info.java is loaded into editor window, click Graph view button (of Source, History, Graph). No graph display and an Unexpected Exception notification is generated.
Priority: Silent; Category: Error.
Cannot invoke "org.netbeans.modules.java.graph.GraphNode.getImpl()" because the return value of "org.netbeans.modules.java.graph.DependencyGraphScene.getRootGraphNode()" is null.
Full text is:
```
java.lang.NullPointerException: Cannot invoke "org.netbeans.modules.java.graph.GraphNode.getImpl()" because the return value of "org.netbeans.modules.java.graph.DependencyGraphScene.getRootGraphNode()" is null
at org.netbeans.modules.java.graph.DependencyGraphScene.highlightDepth(DependencyGraphScene.java:690)
at org.netbeans.modules.java.graph.DependencyGraphScene.highlightDepthIntern(DependencyGraphScene.java:706)
at org.netbeans.modules.java.graph.DependencyGraphScene.access$900(DependencyGraphScene.java:75)
at org.netbeans.modules.java.graph.DependencyGraphScene$AllActionsProvider.select(DependencyGraphScene.java:672)
at org.netbeans.modules.visual.action.SelectAction.mousePressed(SelectAction.java:69)
at org.netbeans.api.visual.action.WidgetAction$Chain.mousePressed(WidgetAction.java:749)
at org.netbeans.api.visual.widget.SceneComponent$Operator$2.operate(SceneComponent.java:529)
at org.netbeans.api.visual.widget.SceneComponent.processLocationOperator(SceneComponent.java:306)
at org.netbeans.api.visual.widget.SceneComponent.processLocationOperator(SceneComponent.java:261)
at org.netbeans.api.visual.widget.SceneComponent.mousePressed(SceneComponent.java:133)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6623)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
at java.desktop/java.awt.Component.processEvent(Component.java:6391)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4572)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:136)
[catch] at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
```
### How to reproduce
Load a project, open module-info.java in the editor, click Graph button.
### Did this work correctly in an earlier version?
No
### Operating System
macos Monterey 12.4 (on Apple M1 Max)
### JDK
zulu17.34.19-ca-fx-jdk17.0.3-macosx_aarch64 (java --version: openjdk 17.0.3 2022-04-19 LTS OpenJDK Runtime Environment Zulu17.34+19-CA (build 17.0.3+7-LTS) OpenJDK 64-Bit Server VM Zulu17.34+19-CA (build 17.0.3+7-LTS, mixed mode, sharing)
### Apache NetBeans packaging
Apache NetBeans provided installer
### Anything else
As far as I can tell (I'm a very new user), this happens every time in both v13 and v14.
### Are you willing to submit a pull request?
No
### Code of Conduct
Yes | 347d63a7b2acd3254b8bb9f6d512c89f4b84a48e | ba654d0f34b6b6b046350ef07423c0ceaae5abd1 | https://github.com/apache/netbeans/compare/347d63a7b2acd3254b8bb9f6d512c89f4b84a48e...ba654d0f34b6b6b046350ef07423c0ceaae5abd1 | diff --git a/java/java.graph/src/org/netbeans/modules/java/graph/SearchVisitor.java b/java/java.graph/src/org/netbeans/modules/java/graph/SearchVisitor.java
index 87cf0cdd76..c61f662229 100644
--- a/java/java.graph/src/org/netbeans/modules/java/graph/SearchVisitor.java
+++ b/java/java.graph/src/org/netbeans/modules/java/graph/SearchVisitor.java
@@ -44,7 +44,7 @@ class SearchVisitor implements GraphNodeVisitor {
if (root == null) {
root = node;
}
- if (scene.isIncluded(node)) {
+ if (!path.contains(node) && scene.isIncluded(node)) {
GraphNode grNode = scene.getGraphNodeRepresentant(node);
if (grNode == null) {
return false;
@@ -59,7 +59,7 @@ class SearchVisitor implements GraphNodeVisitor {
}
@Override public boolean endVisit(GraphNodeImplementation node) {
- if (scene.isIncluded(node)) {
+ if (path.peek() == node) {
path.pop();
}
return true;
diff --git a/java/java.module.graph/src/org/netbeans/modules/java/module/graph/DependencyCalculator.java b/java/java.module.graph/src/org/netbeans/modules/java/module/graph/DependencyCalculator.java
index e13cc4e9d2..b82c3b8c34 100644
--- a/java/java.module.graph/src/org/netbeans/modules/java/module/graph/DependencyCalculator.java
+++ b/java/java.module.graph/src/org/netbeans/modules/java/module/graph/DependencyCalculator.java
@@ -18,7 +18,7 @@
*/
package org.netbeans.modules.java.module.graph;
-import com.sun.source.tree.Tree;
+import com.sun.source.tree.ModuleTree;
import com.sun.source.util.TreePath;
import java.io.IOException;
import java.util.ArrayList;
@@ -31,13 +31,10 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.lang.model.element.ModuleElement;
-import javax.tools.JavaFileObject;
import org.netbeans.api.annotations.common.NonNull;
-import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.source.ClasspathInfo;
import org.netbeans.api.java.source.JavaSource;
import org.openide.filesystems.FileObject;
-import org.openide.filesystems.URLMapper;
import org.openide.util.Exceptions;
import org.openide.util.Parameters;
@@ -81,9 +78,9 @@ final class DependencyCalculator {
try {
js.runUserActionTask((cc)-> {
cc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
- final List<? extends Tree> decls = cc.getCompilationUnit().getTypeDecls();
- final ModuleElement me = !decls.isEmpty() && decls.get(0).getKind() == Tree.Kind.MODULE ?
- (ModuleElement) cc.getTrees().getElement(TreePath.getPath(cc.getCompilationUnit(), decls.get(0))) :
+ final ModuleTree moduleTree = cc.getCompilationUnit().getModule();
+ final ModuleElement me = moduleTree != null ?
+ (ModuleElement) cc.getTrees().getElement(TreePath.getPath(cc.getCompilationUnit(), moduleTree)) :
null;
if (me != null) {
final Map<String, ModuleNode> mods = new LinkedHashMap<>(); | ['java/java.graph/src/org/netbeans/modules/java/graph/SearchVisitor.java', 'java/java.module.graph/src/org/netbeans/modules/java/module/graph/DependencyCalculator.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 239,296,252 | 48,639,962 | 6,119,176 | 27,676 | 1,022 | 203 | 15 | 2 | 5,076 | 264 | 1,080 | 90 | 0 | 1 | 2023-03-16T10:58:20 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,218 | apache/netbeans/6228/6222 | apache | netbeans | https://github.com/apache/netbeans/issues/6222 | https://github.com/apache/netbeans/pull/6228 | https://github.com/apache/netbeans/pull/6228 | 1 | fixes | ArtifactResolutionExceptions when working with certain maven projects | ### Apache NetBeans version
Apache NetBeans 19 rc 1
### What happened
Tried to open the parent project of https://github.com/apache/maven-indexer/ and got several exceptions. The exceptions already start before the project is open, as soon it is selected in the project open dialog (NB is loading the model to try to find sub projects).
Once the project is open the exceptions will keep showing up while working with the pom etc.
```
[org.netbeans.modules.project.ui.ProjectChooserAccessory$ModelUpdater] INFO org.eclipse.aether.internal.impl.DefaultArtifactResolver - Artifact org.apache:apache:pom:29 is present in the local repository, but cached from a remote repository ID that is unavailable in current build context, verifying that is downloadable from [apache.snapshots (https://repository.apache.org/snapshots, default, snapshots)]
SEVERE [org.openide.util.Exceptions]
org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact org.apache:apache:pom:29
at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:450)
Caused: org.eclipse.aether.resolution.ArtifactResolutionException: The following artifacts could not be resolved: org.apache:apache:pom:29 (present, but unavailable): Could not find artifact org.apache:apache:pom:29
at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:459)
at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:259)
at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:242)
at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveArtifact(DefaultRepositorySystem.java:277)
at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:197)
Caused: org.apache.maven.artifact.resolver.ArtifactNotFoundException: The following artifacts could not be resolved: org.apache:apache:pom:29 (present, but unavailable): Could not find artifact org.apache:apache:pom:29
org.apache:apache:pom:29
from the specified remote repositories:
apache.snapshots (https://repository.apache.org/snapshots, releases=false, snapshots=true)
at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:200)
at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolveAlways(DefaultArtifactResolver.java:152)
at org.netbeans.modules.maven.embedder.MavenEmbedder.resolve(MavenEmbedder.java:380)
[catch] at org.netbeans.modules.maven.embedder.NBRepositoryModelResolver.resolveModel(NBRepositoryModelResolver.java:74)
at org.netbeans.modules.maven.embedder.NBRepositoryModelResolver.resolveModel(NBRepositoryModelResolver.java:88)
at org.apache.maven.model.building.DefaultModelBuilder.readParentExternally(DefaultModelBuilder.java:1009)
at org.apache.maven.model.building.DefaultModelBuilder.readParent(DefaultModelBuilder.java:801)
at org.apache.maven.model.building.DefaultModelBuilder.build(DefaultModelBuilder.java:327)
at org.apache.maven.model.building.DefaultModelBuilder.build(DefaultModelBuilder.java:243)
at org.netbeans.modules.maven.embedder.impl.NBModelBuilder.build(NBModelBuilder.java:53)
at org.netbeans.modules.maven.embedder.MavenEmbedder.executeModelBuilder(MavenEmbedder.java:445)
at org.netbeans.modules.maven.NbMavenProjectImpl.getRawModel(NbMavenProjectImpl.java:216)
at org.netbeans.modules.maven.api.NbMavenProject.getRawModel(NbMavenProject.java:392)
at org.netbeans.modules.maven.MavenProjectPropsImpl.lambda$get$0(MavenProjectPropsImpl.java:93)
at org.netbeans.modules.openide.util.DefaultMutexImplementation.readAccess(DefaultMutexImplementation.java:188)
at org.openide.util.Mutex.readAccess(Mutex.java:199)
at org.netbeans.modules.maven.MavenProjectPropsImpl.get(MavenProjectPropsImpl.java:78)
at org.netbeans.modules.maven.MavenProjectPropsImpl.get(MavenProjectPropsImpl.java:74)
at org.netbeans.modules.maven.MavenProjectPropsImpl$PackagingProviderImpl.packaging(MavenProjectPropsImpl.java:306)
at org.netbeans.modules.maven.api.NbMavenProject.getPackagingType(NbMavenProject.java:378)
at org.netbeans.modules.maven.NbMavenProjectImpl$PackagingTypeDependentLookup.check(NbMavenProjectImpl.java:1050)
at org.netbeans.modules.maven.NbMavenProjectImpl$PackagingTypeDependentLookup.<init>(NbMavenProjectImpl.java:1008)
at org.netbeans.modules.maven.NbMavenProjectImpl.<init>(NbMavenProjectImpl.java:274)
at org.netbeans.modules.maven.NbMavenProjectFactory.loadProject(NbMavenProjectFactory.java:98)
at org.netbeans.modules.projectapi.nb.NbProjectManager.createProject(NbProjectManager.java:376)
at org.netbeans.modules.projectapi.nb.NbProjectManager.access$300(NbProjectManager.java:69)
at org.netbeans.modules.projectapi.nb.NbProjectManager$2.run(NbProjectManager.java:289)
at org.netbeans.modules.projectapi.nb.NbProjectManager$2.run(NbProjectManager.java:218)
at org.netbeans.modules.openide.util.DefaultMutexImplementation.readAccess(DefaultMutexImplementation.java:188)
at org.openide.util.Mutex.readAccess(Mutex.java:232)
at org.netbeans.modules.projectapi.nb.NbProjectManager.findProject(NbProjectManager.java:218)
at org.netbeans.api.project.ProjectManager.findProject(ProjectManager.java:142)
at org.netbeans.modules.project.ui.OpenProjectList.fileToProject(OpenProjectList.java:1257)
at org.netbeans.modules.project.ui.ProjectChooserAccessory.getProject(ProjectChooserAccessory.java:363)
at org.netbeans.modules.project.ui.ProjectChooserAccessory.access$000(ProjectChooserAccessory.java:67)
at org.netbeans.modules.project.ui.ProjectChooserAccessory$1.run(ProjectChooserAccessory.java:236)
at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1419)
at org.netbeans.modules.openide.util.GlobalLookup.execute(GlobalLookup.java:45)
at org.openide.util.lookup.Lookups.executeWith(Lookups.java:287)
at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2034)
```
### How to reproduce
open the above mentioned project
### Did this work correctly in an earlier version?
18
### Operating System
linux
### JDK
20
### Apache NetBeans packaging
Apache NetBeans binary zip
### Anything else
_No response_
### Are you willing to submit a pull request?
Maybe | 8df65b70ed0d17f0e641b961b0ede8ef89ba640d | f954a246d84d0846cedeaa308868031a577e1e46 | https://github.com/apache/netbeans/compare/8df65b70ed0d17f0e641b961b0ede8ef89ba640d...f954a246d84d0846cedeaa308868031a577e1e46 | diff --git a/java/maven.embedder/src/org/netbeans/modules/maven/embedder/MavenEmbedder.java b/java/maven.embedder/src/org/netbeans/modules/maven/embedder/MavenEmbedder.java
index 7608be2203..4bf4c38954 100644
--- a/java/maven.embedder/src/org/netbeans/modules/maven/embedder/MavenEmbedder.java
+++ b/java/maven.embedder/src/org/netbeans/modules/maven/embedder/MavenEmbedder.java
@@ -45,7 +45,6 @@ import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
-import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.cli.configuration.SettingsXmlConfigurationProcessor;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.DefaultMavenExecutionResult;
@@ -94,7 +93,6 @@ import org.openide.util.Exceptions;
import org.openide.util.BaseUtilities;
import org.eclipse.aether.repository.Authentication;
import org.eclipse.aether.DefaultRepositorySystemSession;
-import org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManagerFactory;
import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.NoLocalRepositoryManagerException;
@@ -372,13 +370,17 @@ public final class MavenEmbedder {
*/
public void resolve(Artifact sources, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository) throws ArtifactResolutionException, ArtifactNotFoundException {
setUpLegacySupport();
-
- // must call internal Resolver API directly, as the RepositorySystem does not report an exception,
- // even in ArtifactResolutionResult: resolve(ArtifactResolutionRequest request) catches the exception and
- // swallows ArtifactNotFoundException.
- // The existing calling code that handles these exception cannot work, in fact, when using resolve(ArtifactResolutionRequest request) API.
- lookupComponent(ArtifactResolver.class).resolveAlways(sources, remoteRepositories, localRepository);
+ ArtifactResolutionRequest req = new ArtifactResolutionRequest();
+ req.setLocalRepository(localRepository);
+ req.setRemoteRepositories(remoteRepositories);
+ req.setArtifact(sources);
+ req.setOffline(isOffline());
+ ArtifactResolutionResult result = repositorySystem.resolve(req);
normalizePath(sources);
+ // XXX check result for exceptions and throw them now?
+ for (Exception ex : result.getExceptions()) {
+ LOG.log(Level.FINE, null, ex);
+ }
}
//TODO possibly rename.. build sounds like something else..
@@ -509,7 +511,7 @@ public final class MavenEmbedder {
return req;
}
-
+
/**
* Needed to avoid an NPE in {@link org.eclipse.org.eclipse.aether.DefaultArtifactResolver#resolveArtifacts} under some conditions.
* (Also {@link org.eclipse.org.eclipse.aether.DefaultMetadataResolver#resolve}; wherever a {@link org.eclipse.aether.RepositorySystemSession} is used.)
@@ -522,7 +524,7 @@ public final class MavenEmbedder {
}
DefaultRepositorySystemSession session = new DefaultRepositorySystemSession();
session.setOffline(isOffline());
- EnhancedLocalRepositoryManagerFactory f = lookupComponent(EnhancedLocalRepositoryManagerFactory.class);
+ SimpleLocalRepositoryManagerFactory f = new SimpleLocalRepositoryManagerFactory();
try {
session.setLocalRepositoryManager(f.newInstance(session, new LocalRepository(getLocalRepository().getBasedir())));
} catch (NoLocalRepositoryManagerException ex) {
diff --git a/java/maven/test/unit/src/org/netbeans/modules/maven/classpath/AbstractProjectClassPathImplTest.java b/java/maven/test/unit/src/org/netbeans/modules/maven/classpath/AbstractProjectClassPathImplTest.java
index c1f5edfd78..78a54701ca 100644
--- a/java/maven/test/unit/src/org/netbeans/modules/maven/classpath/AbstractProjectClassPathImplTest.java
+++ b/java/maven/test/unit/src/org/netbeans/modules/maven/classpath/AbstractProjectClassPathImplTest.java
@@ -23,7 +23,6 @@ import java.io.File;
import java.util.Collections;
import java.util.logging.Level;
import org.apache.maven.artifact.Artifact;
-import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.codehaus.plexus.util.FileUtils;
import org.netbeans.junit.NbTestCase;
import org.netbeans.modules.maven.embedder.EmbedderFactory;
@@ -61,11 +60,7 @@ public class AbstractProjectClassPathImplTest extends NbTestCase {
File downloaded = new File(repo, "nbtest/grp/art/1.10-SNAPSHOT/art-1.10-20210520.222429-1.jar");
Artifact a = EmbedderFactory.getProjectEmbedder().createArtifact("nbtest.grp", "art", "1.10-20210520.222429-1", "jar");
assertNull(AbstractProjectClassPathImpl.getFile(a));
- try {
- EmbedderFactory.getProjectEmbedder().resolve(a, Collections.emptyList(), EmbedderFactory.getProjectEmbedder().getLocalRepository());
- } catch (ArtifactNotFoundException ex) {
- // the downloaded artifact was not found, expected as only -SNAPSHOT is installed.
- }
+ EmbedderFactory.getProjectEmbedder().resolve(a, Collections.emptyList(), EmbedderFactory.getProjectEmbedder().getLocalRepository());
assertEquals(installed, a.getFile());
assertEquals(installed, AbstractProjectClassPathImpl.getFile(a));
FileUtils.mkdir(downloaded.getParent()); | ['java/maven/test/unit/src/org/netbeans/modules/maven/classpath/AbstractProjectClassPathImplTest.java', 'java/maven.embedder/src/org/netbeans/modules/maven/embedder/MavenEmbedder.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 242,284,917 | 49,242,196 | 6,198,704 | 28,101 | 1,402 | 246 | 22 | 1 | 6,399 | 304 | 1,345 | 97 | 3 | 1 | 2023-07-19T13:59:29 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,219 | apache/netbeans/6220/6214 | apache | netbeans | https://github.com/apache/netbeans/issues/6214 | https://github.com/apache/netbeans/pull/6220 | https://github.com/apache/netbeans/pull/6220 | 1 | fixes | Options to Import does not work correctly | ### Apache NetBeans version
Apache NetBeans latest daily build
### What happened
When you select a file to import options it does not import options like :
- Java Platforms
- Libraries
- Font & Colors
It does import the Look and Feel option. The PR that introduce this bug was [PR-6094](https://github.com/apache/netbeans/pull/6094)
### How to reproduce
1. Start a clean instance of NetBeans
2. Activate Java SE & Java Web and EE plugins
3. Add new Java Platforms
4. Add a new library in Libraries
5. Change Font & Colors Profile from FlatLaf to any other
6. Change Font & Colors font and size to any other
7. Change Look and Feel from FlatLaf to any other
8. Export your options to a new file.
9. Start a clean instance of NetBeans
10. Activate Java SE & Java Web and EE plugins
11. Import your options file
Only the Look and Feel should have changed, no other option should have been imported.
### Did this work correctly in an earlier version?
Apache NetBeans 17
### Operating System
Linux Pop OS 22.04
### JDK
oracle-17
### Apache NetBeans packaging
Own source build
### Anything else
Reverting the file `org.netbeans.modules.options.export.OptionsExportModel.java` fix this. Will try to fix this tomorrow.
### Are you willing to submit a pull request?
Yes | 8df65b70ed0d17f0e641b961b0ede8ef89ba640d | 97438e5b355ba6113cce48c49a1efbea3f94975d | https://github.com/apache/netbeans/compare/8df65b70ed0d17f0e641b961b0ede8ef89ba640d...97438e5b355ba6113cce48c49a1efbea3f94975d | diff --git a/platform/options.api/src/org/netbeans/modules/options/export/OptionsExportModel.java b/platform/options.api/src/org/netbeans/modules/options/export/OptionsExportModel.java
index 7a48551aa5..f440ed0577 100644
--- a/platform/options.api/src/org/netbeans/modules/options/export/OptionsExportModel.java
+++ b/platform/options.api/src/org/netbeans/modules/options/export/OptionsExportModel.java
@@ -746,23 +746,24 @@ public final class OptionsExportModel {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = entries.nextElement();
- if (!zipEntry.isDirectory() && !checkIntegrity(zipEntry)) {
+ if (!zipEntry.isDirectory() && checkIntegrity(zipEntry)) {
copyFile(zipEntry.getName());
}
}
}
}
+ // true if ok
private boolean checkIntegrity(ZipEntry entry) throws IOException {
if (entry.getName().endsWith(".properties")) {
try (ZipFile zip = new ZipFile(source);
BufferedReader reader = new BufferedReader(new InputStreamReader(zip.getInputStream(entry), StandardCharsets.UTF_8))) {
// invalid code point check JDK-8075156
- boolean corrupted = reader.lines().anyMatch(l -> l.indexOf('\\u0000') != -1);
- if (corrupted) {
+ boolean ok = reader.lines().noneMatch(l -> l.indexOf('\\u0000') != -1);
+ if (!ok) {
LOGGER.log(Level.WARNING, "ignoring corrupted properties file at {0}", entry.getName());
}
- return corrupted;
+ return ok;
}
}
return true; | ['platform/options.api/src/org/netbeans/modules/options/export/OptionsExportModel.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 242,284,917 | 49,242,196 | 6,198,704 | 28,101 | 478 | 102 | 9 | 1 | 1,304 | 216 | 310 | 56 | 1 | 0 | 2023-07-18T15:21:18 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,222 | apache/netbeans/6184/6180 | apache | netbeans | https://github.com/apache/netbeans/issues/6180 | https://github.com/apache/netbeans/pull/6184 | https://github.com/apache/netbeans/pull/6184 | 1 | fixes | NumberFormatException with auto-complete when editing pom.xml | ### Apache NetBeans version
Apache NetBeans 18
### What happened
Edited pom.xml of an old project with the aim to find newest version of a dependency.
Changed from originally 3.3 to 3.6.1, then undo to 3.3, then added this comment, then removed version string and invoked auto-complete.
See code snippet:
```xml
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<!-- Changed from originally 3.3 to 3.6.1, then undo to 3.3, then added this comment, then removed version string and invoked auto-complete -->
<version>3.6.1</version>
</dependency>
</dependencies>
```
Getting an exception as follows:
```
java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at org.netbeans.modules.maven.hints.pom.UpdateDependencyHint.noTimestamp(UpdateDependencyHint.java:178)
at org.netbeans.modules.maven.hints.pom.UpdateDependencyHint.addHintsTo(UpdateDependencyHint.java:128)
at org.netbeans.modules.maven.hints.pom.UpdateDependencyHint.getErrorsForDocument(UpdateDependencyHint.java:85)
at org.netbeans.modules.maven.hints.pom.PomModelUtils.findHints(PomModelUtils.java:166)
at org.netbeans.modules.maven.hints.pom.MavenFileHintsTask.run(MavenFileHintsTask.java:55)
at org.netbeans.modules.maven.hints.pom.MavenFileHintsTask.run(MavenFileHintsTask.java:45)
at org.netbeans.modules.parsing.impl.TaskProcessor.callParserResultTask(TaskProcessor.java:561)
[catch] at org.netbeans.modules.parsing.impl.TaskProcessor$RequestPerformer.run(TaskProcessor.java:786)
at org.openide.util.lookup.Lookups.executeWith(Lookups.java:288)
at org.netbeans.modules.parsing.impl.TaskProcessor$RequestPerformer.execute(TaskProcessor.java:702)
at org.netbeans.modules.parsing.impl.TaskProcessor$CompilationJob.run(TaskProcessor.java:663)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1419)
at org.netbeans.modules.openide.util.GlobalLookup.execute(GlobalLookup.java:45)
at org.openide.util.lookup.Lookups.executeWith(Lookups.java:287)
at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2034)
```
### How to reproduce
See above.
### Did this work correctly in an earlier version?
No / Don't know
### Operating System
Windows 7
### JDK
Java: 14; Java HotSpot(TM) 64-Bit Server VM 14+36-1461
### Apache NetBeans packaging
Apache NetBeans provided installer
### Anything else
I have seen this the first time. But that does not seem to matter much. What seems to matter is that the number of errors appearing in the notifications is getting smaller with every release, and now I pay more attention to what is left. It does not seem to have an impact, but fixing it would mean that more important issues could get focused on better.
[SampleProject.zip](https://github.com/apache/netbeans/files/12024803/SampleProject.zip)
[messages.log](https://github.com/apache/netbeans/files/12024812/messages.log)
### Are you willing to submit a pull request?
No | 02a5586907ea6b6500ca8fb7a95fd28a760f7259 | d9335fa23e88afd38e0c701cd8d8992d1e21f737 | https://github.com/apache/netbeans/compare/02a5586907ea6b6500ca8fb7a95fd28a760f7259...d9335fa23e88afd38e0c701cd8d8992d1e21f737 | diff --git a/java/maven.hints/src/org/netbeans/modules/maven/hints/pom/UpdateDependencyHint.java b/java/maven.hints/src/org/netbeans/modules/maven/hints/pom/UpdateDependencyHint.java
index bd7c4998f9..b42343f1e5 100644
--- a/java/maven.hints/src/org/netbeans/modules/maven/hints/pom/UpdateDependencyHint.java
+++ b/java/maven.hints/src/org/netbeans/modules/maven/hints/pom/UpdateDependencyHint.java
@@ -175,7 +175,7 @@ public class UpdateDependencyHint implements POMErrorFixProvider {
return i == 0 || Integer.parseInt(v.substring(0, i)) < 10_000;
}
}
- return Integer.parseInt(v) < 10_000;
+ return v.isEmpty() || Integer.parseInt(v) < 10_000;
}
// example: in '3.14' -> out '3.' | ['java/maven.hints/src/org/netbeans/modules/maven/hints/pom/UpdateDependencyHint.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 242,190,007 | 49,224,109 | 6,196,286 | 28,088 | 106 | 28 | 2 | 1 | 3,470 | 259 | 773 | 83 | 2 | 2 | 2023-07-12T12:47:04 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,227 | apache/netbeans/5739/5738 | apache | netbeans | https://github.com/apache/netbeans/issues/5738 | https://github.com/apache/netbeans/pull/5739 | https://github.com/apache/netbeans/pull/5739 | 1 | fixes | Disassembled `*.class` opened instead of `*.java` when folder with name of class exists in sources JAR | ### Apache NetBeans version
Apache NetBeans 17
### What happened
When you have a Maven sources JAR present in the local repository, confirmed by `SourceForBinaryQuery` via `apisupport.projectinspector`¹, then visiting a type or member in the classpath should open the editor on a read-only source file. In NB 16 this used to work consistently. In 17 it sometimes works, but sometimes you get the disassembled bytecode instead. I am still working out the precise conditions for the bug, since it happens on some types in a single JAR file and not others.
----
¹Sadly abandoned in `contrib` Hg rather than donated, AFAICT, but I still have a personal copy.
### How to reproduce
```bash
git clone https://github.com/jenkinsci/log-cli-plugin
cd log-cli-plugin
mvn -Pquick-build package dependency:sources
```
Now open this project in NB and wait for classpath scanning to complete. At https://github.com/jenkinsci/log-cli-plugin/blob/3d86457a9f2b19567d90542074224416a9ca474c/src/main/java/org/jenkinsci/plugins/log_cli/TailLogCommand.java#L55 place the caret on the call to `get` and press Ctrl-B to visit the definition.
Expected: you should see https://github.com/jenkinsci/jenkins/blob/jenkins-2.361.4/core/src/main/java/jenkins/model/Jenkins.java#L810
Actual: you will see disassembled bytecode
```java
@NonNull
public static Jenkins get() throws IllegalStateException {
// <editor-fold defaultstate="collapsed" desc="Compiled Code">
/* 0: invokestatic #8 // Method getInstanceOrNull:()Ljenkins/model/Jenkins;
* 3: astore_0
* 4: aload_0
* 5: ifnonnull 18
* 8: new #9 // class java/lang/IllegalStateException
* 11: dup
* 12: ldc #10 // String Jenkins.instance is missing. Read the documentation of Jenkins.getInstanceOrNull to see what you are doing wrong.
* 14: invokespecial #11 // Method java/lang/IllegalStateException."<init>":(Ljava/lang/String;)V
* 17: athrow
* 18: aload_0
* 19: areturn
* */
// </editor-fold>
}
```
Note that if on the same line of source you instead click on the next method call, `checkPermission`, you are correctly taken to https://github.com/jenkinsci/jenkins/blob/jenkins-2.361.4/core/src/main/java/hudson/security/AccessControlled.java#L48 from `~/.m2/repository/org/jenkins-ci/main/jenkins-core/2.361.4/jenkins-core-2.361.4-sources.jar`.
### Did this work correctly in an earlier version?
Apache NetBeans 16
### Operating System
Xubuntu 22.04.2
### JDK
11.0.18; OpenJDK 64-Bit Server VM 11.0.18+10-post-Ubuntu-0ubuntu122.04; Ubuntu
### Apache NetBeans packaging
Apache NetBeans Snap Package
### Anything else
Using `git bisect` I was able to identify #5152 (@jtulach) as the cause of the regression. This does _not_ appear to be a duplicate of #5266, which apparently involved a visible exception (no error is printed in this case) and which was allegedly fixed in NB 17 in #5279 (@matthiasblaesing).
I hope to find time to study the bug and offer a PR, since this affects everyday usage of the IDE for me and is the one noticeable regression in NB 17.
### Are you willing to submit a pull request?
Yes | c7847c670343d78335d0cfafd3dc223713091d10 | 5d45c28aac066f568bcbb1dc5e0e800c47f9e601 | https://github.com/apache/netbeans/compare/c7847c670343d78335d0cfafd3dc223713091d10...5d45c28aac066f568bcbb1dc5e0e800c47f9e601 | diff --git a/java/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java b/java/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java
index e58a6a257c..dfb02790c6 100644
--- a/java/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java
+++ b/java/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java
@@ -628,7 +628,9 @@ public class SourceUtils {
private static FileObject findMatchingChild(String sourceFileName, Collection<FileObject> folders, boolean caseSensitive) {
final Match matchSet = caseSensitive ? new CaseSensitiveMatch(sourceFileName) : new CaseInsensitiveMatch(sourceFileName);
for (FileObject folder : folders) {
- for (FileObject child : folder.getChildren()) {
+ FileObject[] children = folder.getChildren();
+ Arrays.sort(children, Comparator.comparing(FileObject::getNameExt)); // for determinism
+ for (FileObject child : children) {
if (matchSet.apply(child)) {
return child;
}
@@ -684,6 +686,9 @@ public class SourceUtils {
}
final boolean apply(final FileObject fo) {
+ if (fo.isFolder()) {
+ return false;
+ }
if (fo.getNameExt().equals(name)) {
return true;
}
@@ -1127,9 +1132,8 @@ public class SourceUtils {
}
/**
- * Returns candidate filenames given a classname. The return value is either
- * a String (top-level class, no $) or List<String> as the JLS permits $ in
- * class names.
+ * Returns candidate filenames given a classname.
+ * @return a single name (top-level class, no $) or multiple as the JLS permits $ in class names.
*/
private static List<String> getSourceFileNames(String classFileName) {
int index = classFileName.lastIndexOf('$');
diff --git a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/SourceUtilsTest.java b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/SourceUtilsTest.java
index 0a12ba30d8..90da3063a1 100644
--- a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/SourceUtilsTest.java
+++ b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/SourceUtilsTest.java
@@ -321,6 +321,7 @@ public class SourceUtilsTest extends ClassIndexTestCase {
FileObject srcInDefPkg = src.createData("Foo","java");
assertNotNull(srcInDefPkg);
FileObject sourceFile = src.createFolder("org").createFolder("me").createData("Test", "java");
+ src.getFileObject("org/me").createFolder("Test"); // https://github.com/apache/netbeans/issues/5738
assertNotNull(sourceFile);
ClasspathInfo cpInfo = ClasspathInfo.create(ClassPathSupport.createClassPath(new FileObject[0]), ClassPathSupport.createClassPath(new FileObject[0]),
ClassPathSupport.createClassPath(new FileObject[]{src}));
@@ -337,16 +338,16 @@ public class SourceUtilsTest extends ClassIndexTestCase {
ElementHandle<? extends Element> handle = ElementHandle.createTypeElementHandle(ElementKind.CLASS, "org.me.Test");
assertNotNull (handle);
FileObject result = SourceUtils.getFile(handle, cpInfo);
- assertNotNull(result);
+ assertEquals(sourceFile, result);
handle = ElementHandle.createTypeElementHandle(ElementKind.CLASS, "org.me.Test$Inner");
result = SourceUtils.getFile(handle,cpInfo);
- assertNotNull(result);
+ assertEquals(sourceFile, result);
handle = ElementHandle.createPackageElementHandle("org.me");
result = SourceUtils.getFile(handle,cpInfo);
- assertNotNull(result);
+ assertEquals(sourceFile.getParent(), result);
handle = ElementHandle.createTypeElementHandle(ElementKind.CLASS, "Foo");
result = SourceUtils.getFile(handle,cpInfo);
- assertNotNull(result);
+ assertEquals(srcInDefPkg, result);
}
public void testGetMainClasses() throws Exception { | ['java/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java', 'java/java.source.base/test/unit/src/org/netbeans/api/java/source/SourceUtilsTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 240,463,782 | 48,885,393 | 6,151,579 | 27,796 | 694 | 145 | 12 | 1 | 3,358 | 403 | 837 | 73 | 4 | 2 | 2023-03-29T15:31:41 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,228 | apache/netbeans/5669/5403 | apache | netbeans | https://github.com/apache/netbeans/issues/5403 | https://github.com/apache/netbeans/pull/5669 | https://github.com/apache/netbeans/pull/5669 | 1 | fixes | JavaDoc popup renders incorrectly | ### Apache NetBeans version
Apache NetBeans 16
### What happened
The JavaDoc popup does not render the text in some tags. Specifically text in fixed-width code style appears to be missing. For example references to system properties in the JavaDoc for ClassLoader.getSystemClassLoader().
### How to reproduce
In a Java editor type "ClassLoader." hit the autocompete shortcut and select the getSystemClassLoader() method such that the JavaDocs appear. Notice that there are missing parts compared to viewing the same documentation in a web browser. Such as:
If the system property "java.system.class.loader" is defined when...
appearing instead as:
If the system property "" is defined when...
### Did this work correctly in an earlier version?
No / Don't know
### Operating System
macOS 13.2
### JDK
JDK 17.0.6
### Apache NetBeans packaging
Apache NetBeans binary zip
### Anything else
_No response_
### Are you willing to submit a pull request?
Yes
### Code of Conduct
Yes | 347d63a7b2acd3254b8bb9f6d512c89f4b84a48e | 8d935fd1e74736de883e0796d4bdccfbd53d6f7c | https://github.com/apache/netbeans/compare/347d63a7b2acd3254b8bb9f6d512c89f4b84a48e...8d935fd1e74736de883e0796d4bdccfbd53d6f7c | diff --git a/java/java.sourceui/src/org/netbeans/api/java/source/ui/ElementJavadoc.java b/java/java.sourceui/src/org/netbeans/api/java/source/ui/ElementJavadoc.java
index ed8edb9fa3..6d1df08284 100644
--- a/java/java.sourceui/src/org/netbeans/api/java/source/ui/ElementJavadoc.java
+++ b/java/java.sourceui/src/org/netbeans/api/java/source/ui/ElementJavadoc.java
@@ -39,6 +39,7 @@ import com.sun.source.doctree.SinceTree;
import com.sun.source.doctree.SnippetTree;
import com.sun.source.doctree.StartElementTree;
import com.sun.source.doctree.SummaryTree;
+import com.sun.source.doctree.SystemPropertyTree;
import com.sun.source.doctree.TextTree;
import com.sun.source.doctree.ThrowsTree;
import com.sun.source.doctree.UnknownBlockTagTree;
@@ -1332,6 +1333,19 @@ public class ElementJavadoc {
List<? extends DocTree> summary = summaryTag.getSummary();
sb.append(inlineTags(summary, docPath, doc, trees, null));
break;
+ case SYSTEM_PROPERTY:
+ SystemPropertyTree systemPropTag = (SystemPropertyTree) tag;
+ sb.append("<code>"); //NOI18N
+ sb.append(systemPropTag.getPropertyName());
+ sb.append("</code>"); //NOI18N
+ break;
+ default:
+ sb.append("<code>"); //NOI18N
+ try {
+ sb.append(XMLUtil.toElementContent(tag.toString()));
+ } catch (IOException ioe) {}
+ sb.append("</code>"); //NOI18N
+ break;
}
}
return sb; | ['java/java.sourceui/src/org/netbeans/api/java/source/ui/ElementJavadoc.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 239,296,252 | 48,639,962 | 6,119,176 | 27,676 | 679 | 124 | 14 | 1 | 1,011 | 153 | 223 | 45 | 0 | 0 | 2023-03-16T15:26:08 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,220 | apache/netbeans/6217/6199 | apache | netbeans | https://github.com/apache/netbeans/issues/6199 | https://github.com/apache/netbeans/pull/6217 | https://github.com/apache/netbeans/pull/6217 | 1 | fixes | Rerun failed tests button is not getting enabled | ### Apache NetBeans version
Apache NetBeans 18
### What happened
I have noticed that when running unit tests, the button for reruning failed tests in Test Results never gets enabled.
### How to reproduce
* Create Java with Maven project
* Add some unit tests that fail
* Run tests and check the button - should be enabled but it's not.
### Did this work correctly in an earlier version?
No / Don't know
### Operating System
Manjaro Linux
### JDK
OpenJDK 11
### Apache NetBeans packaging
Apache NetBeans binary zip
### Anything else
I checked the source code and the problem seems to be in the condition
`rerunFailedButton.setEnabled(displayHandler.sessionFinished &&
rerunHandler.enabled(RerunType.CUSTOM) &&
!treePanel.getFailedTests().isEmpty());`
in netbeans/ide/gsf.testrunner.ui/src/org/netbeans/modules/gsf/testrunner/ui/StatisticsPanel.java
RerunType.CUSTOM doesn't seem to be used anywhere thus the condition is always false. Using `RerunType.ALL` fixes the issue, but I am not sure if it has any side-effects, I haven't found any yet.
### Are you willing to submit a pull request?
Yes | 8df65b70ed0d17f0e641b961b0ede8ef89ba640d | 459c2d151118d48bdc92a90155da5a5d8920db79 | https://github.com/apache/netbeans/compare/8df65b70ed0d17f0e641b961b0ede8ef89ba640d...459c2d151118d48bdc92a90155da5a5d8920db79 | diff --git a/java/maven.junit/src/org/netbeans/modules/maven/junit/JUnitOutputListenerProvider.java b/java/maven.junit/src/org/netbeans/modules/maven/junit/JUnitOutputListenerProvider.java
index 4cda2cca62..2c04b7406d 100644
--- a/java/maven.junit/src/org/netbeans/modules/maven/junit/JUnitOutputListenerProvider.java
+++ b/java/maven.junit/src/org/netbeans/modules/maven/junit/JUnitOutputListenerProvider.java
@@ -470,7 +470,9 @@ public class JUnitOutputListenerProvider implements OutputProcessor {
return usingSurefire28(config.getMavenProject());
} else if (usingJUnit4(config.getMavenProject())) { //#214334
return usingSurefire2121(config.getMavenProject());
- }
+ } else if (getJUnitVersion(config.getMavenProject()).equals("JUNIT5")){
+ return usingSurefire2220(config.getMavenProject());
+ }
}
}
return false;
@@ -505,7 +507,12 @@ public class JUnitOutputListenerProvider implements OutputProcessor {
private boolean usingSurefire28(MavenProject prj) {
String v = PluginPropertyUtils.getPluginVersion(prj, Constants.GROUP_APACHE_PLUGINS, Constants.PLUGIN_SUREFIRE);
return v != null && new ComparableVersion(v).compareTo(new ComparableVersion("2.8")) >= 0;
- }
+ }
+
+ private boolean usingSurefire2220(MavenProject prj) {
+ String v = PluginPropertyUtils.getPluginVersion(prj, Constants.GROUP_APACHE_PLUGINS, Constants.PLUGIN_SUREFIRE);
+ return v != null && new ComparableVersion(v).compareTo(new ComparableVersion("2.22.0")) >= 0;
+ }
private boolean usingTestNG(MavenProject prj) {
for (Artifact a : prj.getArtifacts()) {
@@ -528,6 +535,12 @@ public class JUnitOutputListenerProvider implements OutputProcessor {
return "JUNIT3"; //NOI18N
}
}
+ if ("org.junit.jupiter".equals(a.getGroupId()) && "junit-jupiter-api".equals(a.getArtifactId())) {
+ String version = a.getVersion();
+ if (version != null && new ComparableVersion(version).compareTo(new ComparableVersion("5.0")) >= 0) {
+ return "JUNIT5"; //NOI18N
+ }
+ }
}
return juVersion;
} | ['java/maven.junit/src/org/netbeans/modules/maven/junit/JUnitOutputListenerProvider.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 242,284,917 | 49,242,196 | 6,198,704 | 28,101 | 893 | 190 | 17 | 1 | 1,195 | 158 | 264 | 43 | 0 | 0 | 2023-07-18T10:35:53 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,226 | apache/netbeans/5899/5896 | apache | netbeans | https://github.com/apache/netbeans/issues/5896 | https://github.com/apache/netbeans/pull/5899 | https://github.com/apache/netbeans/pull/5899 | 1 | fixes | groovy.lang.MissingPropertyException from Micronaut-Core | ### Apache NetBeans version
Apache NetBeans 18 release candidate
### What happened
Clone micronaut-core from GH, this gets you to default branch 4.0.x
Install VSNetBeans 18.0.0 RC2 https://nightlies.apache.org/netbeans/candidate/vsix/ use GraalVM 22.3.0 JDK17.
In VSNetBeans enable JavaLSP and Groovy support, both are Enabled.
Open cloned micronaut-core.
later you will see following exception thrown several times and shown also in VSCode dialog during project background scanning.
```Failed to retrieve project information for: /Users/mbalin/micronaut/micronaut-core/aop
Reason: groovy.lang.MissingPropertyException: Could not get unknown property 'sourceCompatibility' for task ':aop:compileKotlin' of type org.jetbrains.kotlin.gradle.tasks.KotlinCompile.
groovy.lang.MissingPropertyException: Could not get unknown property 'sourceCompatibility' for task ':aop:compileKotlin' of type org.jetbrains.kotlin.gradle.tasks.KotlinCompile.
at org.gradle.internal.metaobject.AbstractDynamicObject.getMissingProperty(AbstractDynamicObject.java:85)
at org.gradle.internal.metaobject.AbstractDynamicObject.getProperty(AbstractDynamicObject.java:62)
at org.gradle.api.internal.AbstractTask.property(AbstractTask.java:571)
at org.gradle.api.DefaultTask.property(DefaultTask.java:169)
at org.netbeans.modules.gradle.tooling.NbProjectInfoBuilder.detectSources(NbProjectInfoBuilder.java:1088)
at```
see attachement for the full stack trace.
This DOES NOT happen when Groovy is Disabled.
### How to reproduce
See steps above.
[groovy.lang.MissingProperyExc.txt](https://github.com/apache/netbeans/files/11347233/groovy.lang.MissingProperyExc.txt)
### Did this work correctly in an earlier version?
No / Don't know
### Operating System
macOS venture
### JDK
GraalVM 22.3.0 JDK17
### Apache NetBeans packaging
Apache VSNetBeans for VSCode
### Anything else
_No response_
### Are you willing to submit a pull request?
No | f2c685a525d5301d00dd3c0ac2799cd63aed5d90 | e188e685e02b8a6f51703d95ba80958522bca19b | https://github.com/apache/netbeans/compare/f2c685a525d5301d00dd3c0ac2799cd63aed5d90...e188e685e02b8a6f51703d95ba80958522bca19b | diff --git a/extide/gradle/netbeans-gradle-tooling/src/main/java/org/netbeans/modules/gradle/tooling/NbProjectInfoBuilder.java b/extide/gradle/netbeans-gradle-tooling/src/main/java/org/netbeans/modules/gradle/tooling/NbProjectInfoBuilder.java
index 126ed14e36..ae4ac827e7 100644
--- a/extide/gradle/netbeans-gradle-tooling/src/main/java/org/netbeans/modules/gradle/tooling/NbProjectInfoBuilder.java
+++ b/extide/gradle/netbeans-gradle-tooling/src/main/java/org/netbeans/modules/gradle/tooling/NbProjectInfoBuilder.java
@@ -1083,13 +1083,36 @@ class NbProjectInfoBuilder {
String langId = lang.toLowerCase();
Task compileTask = project.getTasks().findByName(sourceSet.getCompileTaskName(langId));
if (compileTask != null) {
- model.getInfo().put(
+ Object o = null;
+
+ // try to get from Kotlin options; breaking change in kotlinCompile 1.7+ does not derive from
+ // SourceTask and does not have source/targetCompatibility. It reportedly ignores those options
+ // even before 1.7
+ if ("KOTLIN".equals(lang)) {
+ o = getProperty(compileTask, "kotlinOptions", "languageVersion");
+ }
+ if (o == null && compileTask.hasProperty("sourceCompatibility")) {
+ o = getProperty(compileTask, "sourceCompatibility");
+ }
+ if (o != null) {
+ model.getInfo().put(
propBase + lang + "_source_compatibility",
- compileTask.property("sourceCompatibility"));
- model.getInfo().put(
- propBase + lang + "_target_compatibility",
- compileTask.property("targetCompatibility"));
-
+ o.toString()
+ );
+ }
+ o = null;
+ if ("KOTLIN".equals(lang)) {
+ o = getProperty(compileTask, "kotlinOptions", "jvmTarget");
+ }
+ if (o == null && compileTask.hasProperty("targetCompatibility")) {
+ o = getProperty(compileTask, "targetCompatibility");
+ }
+ if (o != null) {
+ model.getInfo().put(
+ propBase + lang + "_target_compatibility",
+ o.toString()
+ );
+ }
List<String> compilerArgs;
compilerArgs = (List<String>) getProperty(compileTask, "options", "allCompilerArgs"); | ['extide/gradle/netbeans-gradle-tooling/src/main/java/org/netbeans/modules/gradle/tooling/NbProjectInfoBuilder.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 240,630,072 | 48,920,707 | 6,155,834 | 27,830 | 2,050 | 280 | 35 | 1 | 1,948 | 178 | 448 | 53 | 2 | 1 | 2023-04-28T18:10:59 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,225 | apache/netbeans/5912/4587 | apache | netbeans | https://github.com/apache/netbeans/issues/4587 | https://github.com/apache/netbeans/pull/5912 | https://github.com/apache/netbeans/pull/5912 | 1 | fixes | Unit test on single file is converted to integration test | ### Apache NetBeans version
Apache NetBeans 14
### What happened
I noticed that my Netesta plugin does not work anymore with Netbeans 14.
Each time it tries to apply `ActionProvider.COMMAND_TEST_SINGLE`, the action is replaced by the new `COMMAND_INTEGRATION_TEST_SINGLE`.
### How to reproduce
I use Netesta plugin to automatically trigger unit tests on a single file
### Did this work correctly in an earlier version?
Apache NetBeans 13
### Operating System
Ubuntu
### JDK
1.8, 11, 17 & 18
### Apache NetBeans packaging
Apache NetBeans binary zip
### Anything else
I have done some debugging, so I can tell where the problem occurs.
In the class `DefaultReplaceTokenProvider`, in the method `isIntegrationTestTarget`, the variable `targetFiles` can be also empty (and not only `null`)
In this case, the `allMatch` method of the stream return `true` whereas there are no files.
### Are you willing to submit a pull request?
No
### Code of Conduct
Yes | 2470c07ccc00d29fcf6c33d6d6f6ec47b96a9056 | 7b755b85e34810f4d763ee4f522678f4c5c7dd93 | https://github.com/apache/netbeans/compare/2470c07ccc00d29fcf6c33d6d6f6ec47b96a9056...7b755b85e34810f4d763ee4f522678f4c5c7dd93 | diff --git a/java/maven/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProvider.java b/java/maven/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProvider.java
index b6212bf21c..186a3bf618 100644
--- a/java/maven/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProvider.java
+++ b/java/maven/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProvider.java
@@ -30,6 +30,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.java.queries.UnitTestForSourceQuery;
@@ -359,13 +360,9 @@ public class DefaultReplaceTokenProvider implements ReplaceTokenProvider, Action
}
private boolean isIntegrationTestTarget(Lookup lookup) {
- final SingleMethod targetMethod = lookup.lookup(SingleMethod.class); //JavaDataObject
- if (targetMethod != null) {
- return isIntegrationTestFile(targetMethod.getFile());
- }
- final Collection<? extends FileObject> targetFiles = lookup.lookupAll(FileObject.class);
- if (targetFiles != null) {
- return targetFiles.stream().allMatch(file -> isIntegrationTestFile(file));
+ FileObject[] targetFiles = extractFileObjectsfromLookup(lookup);
+ if (targetFiles.length > 0) {
+ return Stream.of(targetFiles).allMatch(file -> isIntegrationTestFile(file));
}
return false;
}
diff --git a/java/maven/test/unit/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProviderTest.java b/java/maven/test/unit/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProviderTest.java
index 394a23f22d..f023b38b5f 100644
--- a/java/maven/test/unit/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProviderTest.java
+++ b/java/maven/test/unit/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProviderTest.java
@@ -28,6 +28,7 @@ import org.netbeans.spi.project.ActionProvider;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.filesystems.test.TestFileUtils;
+import org.openide.loaders.DataObject;
import org.openide.util.Lookup;
import org.openide.util.lookup.Lookups;
@@ -73,6 +74,31 @@ public class DefaultReplaceTokenProviderTest extends NbTestCase {
assertEquals(null, ActionProviderImpl.replacements(p, ActionProvider.COMMAND_RUN, Lookup.EMPTY).get(DefaultReplaceTokenProvider.CLASSNAME_EXT));
}
+
+ public void testTestNotIT_GH4587() throws Exception {
+ TestFileUtils.writeFile(d, "pom.xml", "<project><modelVersion>4.0.0</modelVersion>"
+ + "<groupId>g</groupId><artifactId>a</artifactId><version>0</version></project>");
+ TestFileUtils.writeFile(d, "src/test/java/p1/FirstTest.java", "package p1; class FirstTest {}");
+ TestFileUtils.writeFile(d, "src/test/java/p1/FirstIT.java", "package p1; class FirstIT {}");
+ Project p = ProjectManager.getDefault().findProject(d);
+ DefaultReplaceTokenProvider instance = new DefaultReplaceTokenProvider(p);
+ FileObject file = d.getFileObject("src/test/java/p1/FirstTest.java");
+ String converted = instance.convert(ActionProvider.COMMAND_TEST_SINGLE, Lookups.singleton(file));
+ assertNull(converted);
+ converted = instance.convert(ActionProvider.COMMAND_DEBUG_TEST_SINGLE, Lookups.singleton(file));
+ assertNull(converted);
+ DataObject dob = DataObject.find(file);
+ converted = instance.convert(ActionProvider.COMMAND_TEST_SINGLE, Lookups.singleton(dob));
+ assertNull(converted);
+ converted = instance.convert(ActionProvider.COMMAND_DEBUG_TEST_SINGLE, Lookups.singleton(dob));
+ assertNull(converted);
+ file = d.getFileObject("src/test/java/p1/FirstIT.java");
+ converted = instance.convert(ActionProvider.COMMAND_TEST_SINGLE, Lookups.singleton(file));
+ assertEquals(ActionProviderImpl.COMMAND_INTEGRATION_TEST_SINGLE, converted);
+ dob = DataObject.find(file);
+ converted = instance.convert(ActionProvider.COMMAND_TEST_SINGLE, Lookups.singleton(dob));
+ assertEquals(ActionProviderImpl.COMMAND_INTEGRATION_TEST_SINGLE, converted);
+ }
public void testNgSingle() throws Exception {
TestFileUtils.writeFile(d, "pom.xml", "<project><modelVersion>4.0.0</modelVersion>" | ['java/maven/test/unit/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProviderTest.java', 'java/maven/src/org/netbeans/modules/maven/execute/DefaultReplaceTokenProvider.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 240,631,404 | 48,920,908 | 6,155,857 | 27,830 | 668 | 133 | 11 | 1 | 1,015 | 152 | 232 | 44 | 0 | 0 | 2023-05-03T09:38:29 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,224 | apache/netbeans/6140/5407 | apache | netbeans | https://github.com/apache/netbeans/issues/5407 | https://github.com/apache/netbeans/pull/6140 | https://github.com/apache/netbeans/pull/6140 | 1 | fix | Netbeans dont Support WildFly 27 | ### Apache NetBeans version
Apache NetBeans 16
### What happened
Try to add WildFly 27 on Netbeans 16 and you get no imports of jakartaee.* to your project
### How to reproduce
Try to add WildFly 27 on Netbeans 16 and you get no imports of jakartaee.* to your project
### Did this work correctly in an earlier version?
No / Don't know
### Operating System
Windows
### JDK
JDK17
### Apache NetBeans packaging
Apache NetBeans provided installer
### Anything else
_No response_
### Are you willing to submit a pull request?
No
### Code of Conduct
Yes | aee53d5558a2a1996f65f5daf60821e1b265544e | d18ab87ca6106bfe2d41ca71e6f22161e5668eb2 | https://github.com/apache/netbeans/compare/aee53d5558a2a1996f65f5daf60821e1b265544e...d18ab87ca6106bfe2d41ca71e6f22161e5668eb2 | diff --git a/enterprise/javaee.wildfly/src/org/netbeans/modules/javaee/wildfly/util/WildFlyProperties.java b/enterprise/javaee.wildfly/src/org/netbeans/modules/javaee/wildfly/util/WildFlyProperties.java
index 19bc47292e..711855ee35 100644
--- a/enterprise/javaee.wildfly/src/org/netbeans/modules/javaee/wildfly/util/WildFlyProperties.java
+++ b/enterprise/javaee.wildfly/src/org/netbeans/modules/javaee/wildfly/util/WildFlyProperties.java
@@ -232,12 +232,16 @@ public class WildFlyProperties {
}
public List<URL> getClasses() {
- List<URL> list = selectJars(FileUtil.toFileObject(new File(getModulePath("javax"))));
+ List<URL> classes = new ArrayList<>();
+
+ classes.addAll(selectJars(FileUtil.toFileObject(new File(getModulePath("jakarta")))));
+ classes.addAll(selectJars(FileUtil.toFileObject(new File(getModulePath("javax")))));
+
File glassfish = new File(getModulePath("org/glassfish/javax"));
if(glassfish.exists()) {
- list.addAll(selectJars(FileUtil.toFileObject(glassfish)));
+ classes.addAll(selectJars(FileUtil.toFileObject(glassfish)));
}
- return list;
+ return classes;
}
public List<URL> getSources() { | ['enterprise/javaee.wildfly/src/org/netbeans/modules/javaee/wildfly/util/WildFlyProperties.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 242,159,265 | 49,216,761 | 6,195,465 | 28,086 | 530 | 115 | 10 | 1 | 566 | 98 | 139 | 39 | 0 | 0 | 2023-06-28T20:46:25 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
1,223 | apache/netbeans/6142/6134 | apache | netbeans | https://github.com/apache/netbeans/issues/6134 | https://github.com/apache/netbeans/pull/6142 | https://github.com/apache/netbeans/pull/6142 | 2 | fixes | forms designer re-ordering components dragging gone weird | ### Apache NetBeans version
Apache NetBeans 18
### What happened
Dragging not smooth
### How to reproduce
(*) Open Netbeans form designer on a complex form
(*) open the Object navigator
(*) try and drag an item up or down
(*) Notice that the insertion point is not following the drag point properly, but bouncing around
### Did this work correctly in an earlier version?
Apache NetBeans 17
### Operating System
Windows 10 version 10.0 running on amd64; Cp1252; en_US (nb)
### JDK
17.0.5; OpenJDK 64-Bit Server VM 17.0.5+8
### Apache NetBeans packaging
Apache NetBeans provided installer
### Anything else
_No response_
### Are you willing to submit a pull request?
No | aee53d5558a2a1996f65f5daf60821e1b265544e | c5225744500101c5ec62c72d68bc8e48c035a8dd | https://github.com/apache/netbeans/compare/aee53d5558a2a1996f65f5daf60821e1b265544e...c5225744500101c5ec62c72d68bc8e48c035a8dd | diff --git a/ide/spi.palette/src/org/netbeans/modules/palette/ui/DnDSupport.java b/ide/spi.palette/src/org/netbeans/modules/palette/ui/DnDSupport.java
index 808e428799..fcfc718b11 100644
--- a/ide/spi.palette/src/org/netbeans/modules/palette/ui/DnDSupport.java
+++ b/ide/spi.palette/src/org/netbeans/modules/palette/ui/DnDSupport.java
@@ -280,8 +280,8 @@ public class DnDSupport implements DragGestureListener, DropTargetListener {
p1.y += target.getHeight();
p2.y += target.getHeight();
}
- p1 = SwingUtilities.convertPoint( target, p1, palette.getRootPane() );
- p2 = SwingUtilities.convertPoint( target, p2, palette.getRootPane() );
+ p1 = SwingUtilities.convertPoint( target, p1, dropPane );
+ p2 = SwingUtilities.convertPoint( target, p2, dropPane );
Line2D line = new Line2D.Double( p1.x, p1.y, p2.x, p2.y );
dropPane.setDropLine( line );
} else {
@@ -411,8 +411,8 @@ public class DnDSupport implements DragGestureListener, DropTargetListener {
p2.y += rect.height;
}
}
- p1 = SwingUtilities.convertPoint( list, p1, palette.getRootPane() );
- p2 = SwingUtilities.convertPoint( list, p2, palette.getRootPane() );
+ p1 = SwingUtilities.convertPoint( list, p1, dropPane );
+ p2 = SwingUtilities.convertPoint( list, p2, dropPane );
Line2D line = new Line2D.Double( p1.x, p1.y, p2.x, p2.y );
dropPane.setDropLine( line );
targetItem = (Item)list.getModel().getElementAt( dropIndex );
diff --git a/platform/openide.explorer/src/org/openide/explorer/view/OutlineViewDropSupport.java b/platform/openide.explorer/src/org/openide/explorer/view/OutlineViewDropSupport.java
index 0d0732d544..a0867ffb45 100644
--- a/platform/openide.explorer/src/org/openide/explorer/view/OutlineViewDropSupport.java
+++ b/platform/openide.explorer/src/org/openide/explorer/view/OutlineViewDropSupport.java
@@ -34,7 +34,6 @@ import java.awt.dnd.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
-import java.awt.geom.Line2D.Double;
import java.util.Arrays;
import java.util.Comparator;
@@ -290,14 +289,14 @@ final class OutlineViewDropSupport implements DropTargetListener, Runnable {
} else {
// line and selection of parent if any
if (pointAt == DragDropUtilities.NODE_UP) {
- Line2D line = new Double( 0, nodeArea.y, table.getWidth(), nodeArea.y );
+ Line2D line = new Line2D.Double( 0, nodeArea.y, table.getWidth(), nodeArea.y );
convertBoundsAndSetDropLine(line);
// enlagre node area with area for line
Rectangle lineArea = new Rectangle( 0, nodeArea.y - 5, table.getWidth(), 10 );
nodeArea = (Rectangle) nodeArea.createUnion(lineArea);
} else {
- Line2D line = new Double( 0, nodeArea.y + nodeArea.height, table.getWidth(), nodeArea.y + nodeArea.height );
+ Line2D line = new Line2D.Double( 0, nodeArea.y + nodeArea.height, table.getWidth(), nodeArea.y + nodeArea.height );
convertBoundsAndSetDropLine(line);
// enlagre node area with area for line
@@ -340,16 +339,16 @@ final class OutlineViewDropSupport implements DropTargetListener, Runnable {
view.repaint(r.x - 5, r.y - 5, r.width + 10, r.height + 10);
}
- /** Converts line's bounds by the bounds of the root pane. Drop glass pane
- * is over this root pane. After covert a given line is set to drop glass pane.
+ /** Converts line's bounds by the bounds of the drop glass pane.
+ * After covert a given line is set to drop glass pane.
* @param line line for show in drop glass pane */
private void convertBoundsAndSetDropLine(final Line2D line) {
int x1 = (int) line.getX1();
int x2 = (int) line.getX2();
int y1 = (int) line.getY1();
int y2 = (int) line.getY2();
- Point p1 = SwingUtilities.convertPoint(table, x1, y1, table.getRootPane());
- Point p2 = SwingUtilities.convertPoint(table, x2, y2, table.getRootPane());
+ Point p1 = SwingUtilities.convertPoint(table, x1, y1, dropPane);
+ Point p2 = SwingUtilities.convertPoint(table, x2, y2, dropPane);
line.setLine(p1, p2);
dropPane.setDropLine(line);
}
diff --git a/platform/openide.explorer/src/org/openide/explorer/view/TreeViewDropSupport.java b/platform/openide.explorer/src/org/openide/explorer/view/TreeViewDropSupport.java
index d4a0e30bce..0462e61c66 100644
--- a/platform/openide.explorer/src/org/openide/explorer/view/TreeViewDropSupport.java
+++ b/platform/openide.explorer/src/org/openide/explorer/view/TreeViewDropSupport.java
@@ -33,7 +33,6 @@ import java.awt.dnd.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
-import java.awt.geom.Line2D.Double;
import java.util.ArrayList;
import java.util.Arrays;
@@ -285,7 +284,7 @@ final class TreeViewDropSupport implements DropTargetListener, Runnable {
} else {
// line and selection of parent if any
if (pointAt == DragDropUtilities.NODE_UP) {
- Line2D line = new Double(
+ Line2D line = new Line2D.Double(
nodeArea.x - SHIFT_LEFT, nodeArea.y + SHIFT_DOWN, endPointX, nodeArea.y + SHIFT_DOWN
);
convertBoundsAndSetDropLine(line);
@@ -296,7 +295,7 @@ final class TreeViewDropSupport implements DropTargetListener, Runnable {
);
nodeArea = (Rectangle) nodeArea.createUnion(lineArea);
} else {
- Line2D line = new Double(
+ Line2D line = new Line2D.Double(
nodeArea.x - SHIFT_LEFT, nodeArea.y + nodeArea.height + SHIFT_DOWN, endPointX,
nodeArea.y + nodeArea.height + SHIFT_DOWN
);
@@ -359,19 +358,21 @@ final class TreeViewDropSupport implements DropTargetListener, Runnable {
tree.repaint(r.x - 5, r.y - 5, r.width + 10, r.height + 10);
}
- /** Converts line's bounds by the bounds of the root pane. Drop glass pane
- * is over this root pane. After covert a given line is set to drop glass pane.
+ /** Converts line's bounds by the bounds of the drop glass pane.
+ * After covert a given line is set to drop glass pane.
* @param line line for show in drop glass pane */
private void convertBoundsAndSetDropLine(final Line2D line) {
+ if (dropPane == null)
+ return;
+
int x1 = (int) line.getX1();
int x2 = (int) line.getX2();
int y1 = (int) line.getY1();
int y2 = (int) line.getY2();
- Point p1 = SwingUtilities.convertPoint(tree, x1, y1, tree.getRootPane());
- Point p2 = SwingUtilities.convertPoint(tree, x2, y2, tree.getRootPane());
+ Point p1 = SwingUtilities.convertPoint(tree, x1, y1, dropPane);
+ Point p2 = SwingUtilities.convertPoint(tree, x2, y2, dropPane);
line.setLine(p1, p2);
- if( null != dropPane )
- dropPane.setDropLine(line);
+ dropPane.setDropLine(line);
}
/** Removes timer and all listeners. */ | ['platform/openide.explorer/src/org/openide/explorer/view/OutlineViewDropSupport.java', 'ide/spi.palette/src/org/netbeans/modules/palette/ui/DnDSupport.java', 'platform/openide.explorer/src/org/openide/explorer/view/TreeViewDropSupport.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 242,159,265 | 49,216,761 | 6,195,465 | 28,086 | 2,685 | 651 | 40 | 3 | 694 | 112 | 169 | 41 | 0 | 0 | 2023-07-01T10:05:44 | 2,343 | Java | {'Java': 316389044, 'Standard ML': 34542672, 'HTML': 11688407, 'PHP': 4301877, 'XSLT': 1555745, 'JavaScript': 1469543, 'C': 507526, 'CSS': 420676, 'Shell': 394265, 'Lex': 260140, 'TypeScript': 199687, 'Roff': 150799, 'FreeMarker': 131129, 'ANTLR': 121011, 'Groovy': 100233, 'GAP': 76572, 'Makefile': 51863, 'Smarty': 41098, 'Latte': 35596, 'Twig': 33425, 'C++': 32245, 'Batchfile': 31017, 'Pug': 28575, 'AspectJ': 12305, 'Perl': 10188, 'SCSS': 6321, 'Swift': 5322, 'R': 4196, 'Less': 3685, 'Haskell': 3625, 'Rust': 3514, 'Python': 3334, 'Ruby': 3304, 'RenderScript': 2162, 'Grammatical Framework': 1954, 'Hack': 1870, 'HCL': 1225, 'Dockerfile': 1079, 'Slash': 885, 'Go': 498, 'NASL': 144} | Apache License 2.0 |
9,970 | datalinkdc/dinky/413/393 | datalinkdc | dinky | https://github.com/DataLinkDC/dinky/issues/393 | https://github.com/DataLinkDC/dinky/pull/413 | https://github.com/DataLinkDC/dinky/pull/413 | 1 | fix | [Bug] [core] program in loop when offline task failed | ### Search before asking
- [X] I had searched in the [issues](https://github.com/DataLinkDC/dlink/issues?q=is%3Aissue) and found no similar issues.
### What happened
program in loop
### What you expected to happen
offline task succeed
### How to reproduce
submit task to online,
offline task when the jobinstant is high Backpressure
happen the issue
### Anything else
_No response_
### Version
0.6.1-SNAPSHOT
### Are you willing to submit PR?
- [X] Yes I am willing to submit a PR!
### Code of Conduct
- [X] I agree to follow this project's [Code of Conduct](https://www.apache.org/foundation/policies/conduct)
| 0781bc44aefc2ef75e924025b82fc4decdb49480 | 570eeb1cd50e8800f9ba749ba26115a15c279da3 | https://github.com/datalinkdc/dinky/compare/0781bc44aefc2ef75e924025b82fc4decdb49480...570eeb1cd50e8800f9ba749ba26115a15c279da3 | diff --git a/dlink-admin/src/main/java/com/dlink/service/impl/TaskServiceImpl.java b/dlink-admin/src/main/java/com/dlink/service/impl/TaskServiceImpl.java
index f49fe6e9..28754de4 100644
--- a/dlink-admin/src/main/java/com/dlink/service/impl/TaskServiceImpl.java
+++ b/dlink-admin/src/main/java/com/dlink/service/impl/TaskServiceImpl.java
@@ -463,7 +463,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
return jobManager.cancel(jobId);
}
SavePointResult savePointResult = jobManager.savepoint(jobId, savePointType, null);
- if (Asserts.isNotNull(savePointResult)) {
+ if (Asserts.isNotNull(savePointResult.getJobInfos())) {
for (JobInfo item : savePointResult.getJobInfos()) {
if (Asserts.isEqualsIgnoreCase(jobId, item.getJobId()) && Asserts.isNotNull(jobConfig.getTaskId())) {
Savepoints savepoints = new Savepoints();
diff --git a/dlink-core/src/main/java/com/dlink/api/FlinkAPI.java b/dlink-core/src/main/java/com/dlink/api/FlinkAPI.java
index f841a0c6..605b62a0 100644
--- a/dlink-core/src/main/java/com/dlink/api/FlinkAPI.java
+++ b/dlink-core/src/main/java/com/dlink/api/FlinkAPI.java
@@ -97,7 +97,10 @@ public class FlinkAPI {
Map<String, Object> paramMap = new HashMap<>();
switch (type) {
case CANCEL:
+ paramMap.put("cancel-job", true);
+ paramType = FlinkRestAPIConstant.SAVEPOINTS;
jobInfo.setStatus(JobInfo.JobStatus.CANCEL);
+ break;
case STOP:
paramMap.put("drain", false);
paramType = FlinkRestAPIConstant.STOP;
@@ -127,7 +130,7 @@ public class FlinkAPI {
continue;
}
if (node.get("operation").has("failure-cause")) {
- String failureCause = node.get("operation").get("failure-cause").asText();
+ String failureCause = node.get("operation").get("failure-cause").toString();
if (Asserts.isNotNullString(failureCause)) {
result.fail(failureCause);
break; | ['dlink-core/src/main/java/com/dlink/api/FlinkAPI.java', 'dlink-admin/src/main/java/com/dlink/service/impl/TaskServiceImpl.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,656,066 | 335,573 | 49,031 | 534 | 445 | 89 | 7 | 2 | 629 | 91 | 158 | 35 | 2 | 0 | 2022-04-16T07:39:19 | 2,268 | Java | {'Java': 4553099, 'TypeScript': 2955424, 'PLpgSQL': 171812, 'Less': 119119, 'HTML': 105126, 'JavaScript': 53548, 'EJS': 6000, 'Shell': 4826, 'Python': 3022, 'Batchfile': 1208, 'Dockerfile': 528, 'CSS': 304} | Apache License 2.0 |
9,969 | datalinkdc/dinky/511/509 | datalinkdc | dinky | https://github.com/DataLinkDC/dinky/issues/509 | https://github.com/DataLinkDC/dinky/pull/511 | https://github.com/DataLinkDC/dinky/pull/511 | 1 | fix | [Bug] [dlink-metabase] MySqlTypeConvert precision and scale is null | ### Search before asking
- [X] I had searched in the [issues](https://github.com/DataLinkDC/dlink/issues?q=is%3Aissue) and found no similar issues.
### What happened
decimal precision and scale is null
### What you expected to happen
decimal precision and scale is not null and has the correct value
### How to reproduce
submit cdcsouce mysql task
### Anything else
_No response_
### Version
dev
### Are you willing to submit PR?
- [X] Yes I am willing to submit a PR!
### Code of Conduct
- [X] I agree to follow this project's [Code of Conduct](https://www.apache.org/foundation/policies/conduct)
| 74ec170a21a045e9da2e42c6c9dc0ac60217c0ff | 9fbf7ac669fbab31a74ac0559c30bf4f4316ee95 | https://github.com/datalinkdc/dinky/compare/74ec170a21a045e9da2e42c6c9dc0ac60217c0ff...9fbf7ac669fbab31a74ac0559c30bf4f4316ee95 | diff --git a/dlink-metadata/dlink-metadata-mysql/src/main/java/com/dlink/metadata/convert/MySqlTypeConvert.java b/dlink-metadata/dlink-metadata-mysql/src/main/java/com/dlink/metadata/convert/MySqlTypeConvert.java
index 758e52ae..ae740879 100644
--- a/dlink-metadata/dlink-metadata-mysql/src/main/java/com/dlink/metadata/convert/MySqlTypeConvert.java
+++ b/dlink-metadata/dlink-metadata-mysql/src/main/java/com/dlink/metadata/convert/MySqlTypeConvert.java
@@ -13,40 +13,42 @@ import com.dlink.model.ColumnType;
public class MySqlTypeConvert implements ITypeConvert {
@Override
public ColumnType convert(Column column) {
+ ColumnType columnType = ColumnType.STRING;
if (Asserts.isNull(column)) {
- return ColumnType.STRING;
+ return columnType;
}
String t = column.getType().toLowerCase();
if (t.contains("tinyint")) {
- return ColumnType.BYTE;
+ columnType = ColumnType.BYTE;
} else if (t.contains("smallint") || t.contains("tinyint unsigned")) {
- return ColumnType.SHORT;
+ columnType = ColumnType.SHORT;
} else if (t.contains("bigint unsigned") || t.contains("numeric") || t.contains("decimal")) {
- return ColumnType.DECIMAL;
+ columnType = ColumnType.DECIMAL;
} else if (t.contains("bigint") || t.contains("int unsigned")) {
- return ColumnType.LONG;
+ columnType = ColumnType.LONG;
} else if (t.contains("float")) {
- return ColumnType.FLOAT;
+ columnType = ColumnType.FLOAT;
} else if (t.contains("double")) {
- return ColumnType.DOUBLE;
+ columnType = ColumnType.DOUBLE;
} else if (t.contains("boolean") || t.contains("tinyint(1)")) {
- return ColumnType.BOOLEAN;
+ columnType = ColumnType.BOOLEAN;
} else if (t.contains("datetime")) {
- return ColumnType.TIMESTAMP;
+ columnType = ColumnType.TIMESTAMP;
} else if (t.contains("date")) {
- return ColumnType.DATE;
+ columnType = ColumnType.DATE;
} else if (t.contains("timestamp")) {
- return ColumnType.TIMESTAMP;
+ columnType = ColumnType.TIMESTAMP;
} else if (t.contains("time")) {
- return ColumnType.TIME;
+ columnType = ColumnType.TIME;
} else if (t.contains("char") || t.contains("text")) {
- return ColumnType.STRING;
+ columnType = ColumnType.STRING;
} else if (t.contains("binary") || t.contains("blob")) {
- return ColumnType.BYTES;
+ columnType = ColumnType.BYTES;
} else if (t.contains("int") || t.contains("mediumint") || t.contains("smallint unsigned")) {
- return ColumnType.INTEGER;
+ columnType = ColumnType.INTEGER;
}
- return ColumnType.STRING;
+ columnType.setPrecisionAndScale(column.getPrecision(), column.getScale());
+ return columnType;
}
@Override | ['dlink-metadata/dlink-metadata-mysql/src/main/java/com/dlink/metadata/convert/MySqlTypeConvert.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,814,677 | 366,756 | 53,288 | 561 | 1,441 | 265 | 34 | 1 | 614 | 92 | 149 | 33 | 2 | 0 | 2022-05-17T13:42:26 | 2,268 | Java | {'Java': 4553099, 'TypeScript': 2955424, 'PLpgSQL': 171812, 'Less': 119119, 'HTML': 105126, 'JavaScript': 53548, 'EJS': 6000, 'Shell': 4826, 'Python': 3022, 'Batchfile': 1208, 'Dockerfile': 528, 'CSS': 304} | Apache License 2.0 |
784 | moquette-io/moquette/561/553 | moquette-io | moquette | https://github.com/moquette-io/moquette/issues/553 | https://github.com/moquette-io/moquette/pull/561 | https://github.com/moquette-io/moquette/pull/561 | 2 | fixes | NullPointerException caused by async connect/disconnect processing | ### Expected behavior
Session is not removed by handleConnectionLost if new session is already reopened
### Actual behavior
1. handleConnectionLost starts
2. processConnect starts and reopen session
3. handleConnectionLost continues and removes session
4. PostOffice.flushInFlight fails to use session
### Steps to reproduce
1. Run broker
2. Use clean session=true in mqtt-client
3. Start and stop mqtt-client several times. Try to do pause between stop and start as short as possible.
P.S. It seems like one more mqtt-client connected permanently gives better chance to reproduce.
### Minimal yet complete reproducer code (or URL to code) or complete log file
I added extra logging to catch the problem
```
14:59:39.254 [nioEventLoopGroup-3-6] io.moquette.broker.SessionRegistry - retrieve session OK by handleConnectionLost
14:59:39.254 [nioEventLoopGroup-3-7] io.moquette.broker.MQTTConnection - processConnect started
14:59:39.254 [nioEventLoopGroup-3-7] io.moquette.broker.SessionRegistry - NEW SESSION
14:59:39.255 [nioEventLoopGroup-3-7] io.moquette.broker.SessionRegistry - REOPEN SESSION
14:59:39.255 [nioEventLoopGroup-3-6] io.moquette.broker.SessionRegistry - remove session by handleConnectionLost
14:59:39.255 [nioEventLoopGroup-3-7] io.moquette.broker.MQTTConnection - processConnect ACK started
14:59:39.257 [nioEventLoopGroup-3-7] io.moquette.broker.MQTTConnection - processConnect ACK end with true
14:59:39.257 [nioEventLoopGroup-3-7] io.moquette.broker.SessionRegistry - retrieve session NULL by flushInFlight
14:59:39.257 [nioEventLoopGroup-3-7] io.moquette.broker.NewNettyMQTTHandler - Unexpected exception while processing MQTT message. Closing Netty channel. CId=
java.lang.NullPointerException: Attempt to invoke virtual method 'void io.moquette.broker.Session.flushAllQueuedMessages()' on a null object reference
at io.moquette.broker.PostOffice.flushInFlight(PostOffice.java:319)
at io.moquette.broker.MQTTConnection.readCompleted(MQTTConnection.java:536)
at io.moquette.broker.NewNettyMQTTHandler.channelReadComplete(NewNettyMQTTHandler.java:76)
```
### Moquette MQTT version
0.12.1, master 4665c5e
### JVM version (e.g. `java -version`)
1.8 | 08cc8ce1b885990b86411a96d2b62f71b6b5b429 | ed68d38c7ac5aae60a6d36dbe8a24ed120dd183e | https://github.com/moquette-io/moquette/compare/08cc8ce1b885990b86411a96d2b62f71b6b5b429...ed68d38c7ac5aae60a6d36dbe8a24ed120dd183e | diff --git a/broker/src/main/java/io/moquette/broker/SessionRegistry.java b/broker/src/main/java/io/moquette/broker/SessionRegistry.java
index a65cdc96..d86cedb7 100644
--- a/broker/src/main/java/io/moquette/broker/SessionRegistry.java
+++ b/broker/src/main/java/io/moquette/broker/SessionRegistry.java
@@ -90,9 +90,10 @@ public class SessionRegistry {
SessionCreationResult createOrReopenSession(MqttConnectMessage msg, String clientId, String username) {
SessionCreationResult postConnectAction;
- if (!pool.containsKey(clientId)) {
+ final Session newSession = createNewSession(msg, clientId);
+ final Session oldSession = pool.get(clientId);
+ if (oldSession == null) {
// case 1
- final Session newSession = createNewSession(msg, clientId);
postConnectAction = new SessionCreationResult(newSession, CreationModeEnum.CREATED_CLEAN_NEW, false);
// publish the session
@@ -102,19 +103,17 @@ public class SessionRegistry {
if (success) {
LOG.trace("case 1, not existing session with CId {}", clientId);
} else {
- postConnectAction = reopenExistingSession(msg, clientId, newSession, username);
+ postConnectAction = reopenExistingSession(msg, clientId, previous, newSession, username);
}
} else {
- final Session newSession = createNewSession(msg, clientId);
- postConnectAction = reopenExistingSession(msg, clientId, newSession, username);
+ postConnectAction = reopenExistingSession(msg, clientId, oldSession, newSession, username);
}
return postConnectAction;
}
private SessionCreationResult reopenExistingSession(MqttConnectMessage msg, String clientId,
- Session newSession, String username) {
+ Session oldSession, Session newSession, String username) {
final boolean newIsClean = msg.variableHeader().isCleanSession();
- final Session oldSession = pool.get(clientId);
final SessionCreationResult creationResult;
if (oldSession.disconnected()) {
if (newIsClean) {
@@ -150,16 +149,17 @@ public class SessionRegistry {
creationResult = new SessionCreationResult(newSession, CreationModeEnum.DROP_EXISTING, true);
}
- final boolean published;
if (creationResult.mode == CreationModeEnum.DROP_EXISTING) {
LOG.debug("Drop session of already connected client with same id");
- published = pool.replace(clientId, oldSession, newSession);
+ if (!pool.replace(clientId, oldSession, newSession)) {
+ //the other client was disconnecting and removed it's own session
+ pool.put(clientId, newSession);
+ }
} else {
LOG.debug("Replace session of client with same id");
- published = pool.replace(clientId, oldSession, oldSession);
- }
- if (!published) {
- throw new SessionCorruptedException("old session was already removed");
+ if (!pool.replace(clientId, oldSession, oldSession)) {
+ throw new SessionCorruptedException("old session was already removed");
+ }
}
// case not covered new session is clean true/false and old session not in CONNECTED/DISCONNECTED | ['broker/src/main/java/io/moquette/broker/SessionRegistry.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 302,569 | 60,850 | 8,294 | 87 | 1,709 | 301 | 26 | 1 | 2,236 | 216 | 585 | 41 | 0 | 1 | 2020-12-26T17:12:29 | 2,163 | Java | {'Java': 868753, 'Groovy': 98266, 'HTML': 37346, 'Shell': 4112, 'Batchfile': 3910, 'Ruby': 212} | Apache License 2.0 |
1 | connectbot/connectbot/662/594 | connectbot | connectbot | https://github.com/connectbot/connectbot/issues/594 | https://github.com/connectbot/connectbot/pull/662 | https://github.com/connectbot/connectbot/pull/662 | 1 | fixes | timers on the hosts list | The timers displayed on the hosts list screen only seem to update after a failed login attempt. So a newly created host displays as Never Connected and continues to do so (somewhat inaccurately) no matter how may times it has actually connected. Ironically, it only ever stops displaying Never Connected on the occasion that it fails to connect.
It looks like the timer is zeroed on pressing the button to connect to a host. Then it's like there is some back to front logic, such that it resets the timer to its previous value if a connection is successful, instead of unsuccessful. So a check to prevent the timer simply showing time-since-last-button-press has (inadvertently) resulted in it showing time-since-last-failed-connection. | b7ae4cb5311eab7f452e111ce6dc4b4e3d2c9659 | b38a16738e3e6ced65c47c9f13bae41c1413b06d | https://github.com/connectbot/connectbot/compare/b7ae4cb5311eab7f452e111ce6dc4b4e3d2c9659...b38a16738e3e6ced65c47c9f13bae41c1413b06d | diff --git a/app/src/main/java/org/connectbot/util/HostDatabase.java b/app/src/main/java/org/connectbot/util/HostDatabase.java
index 1e71b57c..2250b8e2 100644
--- a/app/src/main/java/org/connectbot/util/HostDatabase.java
+++ b/app/src/main/java/org/connectbot/util/HostDatabase.java
@@ -406,6 +406,7 @@ public class HostDatabase extends RobustSQLiteOpenHelper implements HostStorage,
@Override
public void touchHost(HostBean host) {
long now = System.currentTimeMillis() / 1000;
+ host.setLastConnect(now);
ContentValues values = new ContentValues();
values.put(FIELD_HOST_LASTCONNECT, now); | ['app/src/main/java/org/connectbot/util/HostDatabase.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 781,061 | 215,828 | 25,138 | 78 | 28 | 7 | 1 | 1 | 744 | 119 | 155 | 3 | 0 | 0 | 2018-11-08T17:03:21 | 2,131 | Java | {'Java': 836170, 'C++': 5503, 'Dockerfile': 1773, 'Shell': 1577, 'CMake': 223} | Apache License 2.0 |
0 | connectbot/connectbot/276/36 | connectbot | connectbot | https://github.com/connectbot/connectbot/issues/36 | https://github.com/connectbot/connectbot/pull/276 | https://github.com/connectbot/connectbot/pull/276#issuecomment-145992999 | 1 | solve | No ipv6 support | Inserting a sequence of ipv6 address such as 2620:0:1cfe:face:b00c::3 will result in connectbot warning about malformed hostname. Putting the ipv6 address in brackets has no effect. Connectbot still treats ipv6 in brackets as invalid hostname format.
| fde40fdcb62c764df90e889ae95e28b86ac5f746 | cb578fe3aed5625fd4d1d31318a9af4ac1c76aff | https://github.com/connectbot/connectbot/compare/fde40fdcb62c764df90e889ae95e28b86ac5f746...cb578fe3aed5625fd4d1d31318a9af4ac1c76aff | diff --git a/app/src/main/java/org/connectbot/transport/SSH.java b/app/src/main/java/org/connectbot/transport/SSH.java
index 0867256b..89e2d8d1 100644
--- a/app/src/main/java/org/connectbot/transport/SSH.java
+++ b/app/src/main/java/org/connectbot/transport/SSH.java
@@ -101,7 +101,7 @@ public class SSH extends AbsTransport implements ConnectionMonitor, InteractiveC
static final Pattern hostmask;
static {
- hostmask = Pattern.compile("^(.+)@([0-9a-z.-]+)(:(\\\\d+))?$", Pattern.CASE_INSENSITIVE);
+ hostmask = Pattern.compile("^(.+)@(([0-9a-z.-]+)|(\\\\[[a-f:0-9]+\\\\]))(:(\\\\d+))?$", Pattern.CASE_INSENSITIVE);
}
private boolean compression = false;
@@ -770,9 +770,9 @@ public class SSH extends AbsTransport implements ConnectionMonitor, InteractiveC
.append("://")
.append(Uri.encode(matcher.group(1)))
.append('@')
- .append(matcher.group(2));
+ .append(Uri.encode(matcher.group(2)));
- String portString = matcher.group(4);
+ String portString = matcher.group(6);
int port = DEFAULT_PORT;
if (portString != null) {
try { | ['app/src/main/java/org/connectbot/transport/SSH.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 728,060 | 202,770 | 23,315 | 68 | 358 | 120 | 6 | 1 | 251 | 36 | 60 | 2 | 0 | 0 | 2015-10-06T18:27:50 | 2,131 | Java | {'Java': 836170, 'C++': 5503, 'Dockerfile': 1773, 'Shell': 1577, 'CMake': 223} | Apache License 2.0 |
2 | connectbot/connectbot/497/493 | connectbot | connectbot | https://github.com/connectbot/connectbot/issues/493 | https://github.com/connectbot/connectbot/pull/497 | https://github.com/connectbot/connectbot/pull/497 | 1 | fixes | StringIndexOutOfBoundsException when generating public keys under Traditional Chinese locale | Steps to reprduce:
1. Use Traditional Chinese locale. On my phone it's displayed as 中文(繁體)
2. "Manage Pubkeys" (管理公鑰) => "+"
3. Type a random name and hit "Generate" (產生)
Then the generation dialog crashes: (I add two ```Log.e()``` to see what's wrong)
```
02-28 02:29:35.812 27000 27000 DEBUG E 觸摸此方框來收集隨機數:0%完成
02-28 02:29:35.813 27000 27000 DEBUG E -1
02-28 02:29:35.818 27000 27000 AndroidRuntime D Shutting down VM
02-28 02:29:35.819 27000 27000 AndroidRuntime E FATAL EXCEPTION: main
02-28 02:29:35.819 27000 27000 AndroidRuntime E Process: org.connectbot.debug, PID: 27000
02-28 02:29:35.819 27000 27000 AndroidRuntime E java.lang.StringIndexOutOfBoundsException: length=16; regionStart=0; regionLength=-1
02-28 02:29:35.819 27000 27000 AndroidRuntime E at java.lang.String.startEndAndLength(String.java:298)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at java.lang.String.substring(String.java:1087)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at org.connectbot.util.EntropyView.onDraw(EntropyView.java:101)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.draw(View.java:16200)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.updateDisplayListIfDirty(View.java:15197)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.draw(View.java:15970)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.updateDisplayListIfDirty(View.java:15192)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.draw(View.java:15970)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.updateDisplayListIfDirty(View.java:15192)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.draw(View.java:15970)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.updateDisplayListIfDirty(View.java:15192)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.draw(View.java:15970)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.draw(View.java:16203)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at com.android.internal.policy.PhoneWindow$DecorView.draw(PhoneWindow.java:2690)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.View.updateDisplayListIfDirty(View.java:15197)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:281)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:287)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:322)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewRootImpl.draw(ViewRootImpl.java:2620)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2439)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2072)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1112)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6035)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.Choreographer.doCallbacks(Choreographer.java:670)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.Choreographer.doFrame(Choreographer.java:606)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.os.Handler.handleCallback(Handler.java:739)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.os.Handler.dispatchMessage(Handler.java:95)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.os.Looper.loop(Looper.java:148)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at android.app.ActivityThread.main(ActivityThread.java:5451)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at java.lang.reflect.Method.invoke(Native Method)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
02-28 02:29:35.819 27000 27000 AndroidRuntime E at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
```
Everything works fine with English locale.
Tested with the latest git master (0a380c1795e088b2915446d2d270eb64b0902aff) | fe3112fce1159409e2e8a3c2ca62adc8452f6ee9 | d96836d28589cc6f1afb036d8179937e46cfdc09 | https://github.com/connectbot/connectbot/compare/fe3112fce1159409e2e8a3c2ca62adc8452f6ee9...d96836d28589cc6f1afb036d8179937e46cfdc09 | diff --git a/app/src/main/java/org/connectbot/util/EntropyView.java b/app/src/main/java/org/connectbot/util/EntropyView.java
index e25cb0d3..c7411b02 100644
--- a/app/src/main/java/org/connectbot/util/EntropyView.java
+++ b/app/src/main/java/org/connectbot/util/EntropyView.java
@@ -94,6 +94,8 @@ public class EntropyView extends View {
mPaint.measureText(prompt) > (getWidth() * 0.8)) {
if (splitText == 0)
splitText = prompt.indexOf(' ', prompt.length() / 2);
+ if (splitText < 0)
+ splitText = prompt.length() / 2;
c.drawText(prompt.substring(0, splitText),
getWidth() / 2.0f, | ['app/src/main/java/org/connectbot/util/EntropyView.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 770,327 | 213,191 | 24,728 | 74 | 60 | 21 | 2 | 1 | 6,158 | 447 | 1,994 | 61 | 0 | 2 | 2017-03-02T08:31:33 | 2,131 | Java | {'Java': 836170, 'C++': 5503, 'Dockerfile': 1773, 'Shell': 1577, 'CMake': 223} | Apache License 2.0 |
3 | connectbot/connectbot/478/377 | connectbot | connectbot | https://github.com/connectbot/connectbot/issues/377 | https://github.com/connectbot/connectbot/pull/478 | https://github.com/connectbot/connectbot/pull/478 | 1 | fix | Swipe to send page up/down does not work | Even though I have checked "Page up/down gesture" in the settings, swiping on the left side of the screen does not send page up/down keys. It only scrolls the terminal, like the rest of the screen.
This is with the current newest master (c9682d3). The error was introduced by #277, as stated by @rhansby in #270.
| d54a6407ab705c5944e4f8dca849893fd4b7e7e9 | 2aa96df232686235477276949e467d943def7afb | https://github.com/connectbot/connectbot/compare/d54a6407ab705c5944e4f8dca849893fd4b7e7e9...2aa96df232686235477276949e467d943def7afb | diff --git a/app/src/main/java/org/connectbot/TerminalView.java b/app/src/main/java/org/connectbot/TerminalView.java
index 11e71ac3..bdeba26a 100644
--- a/app/src/main/java/org/connectbot/TerminalView.java
+++ b/app/src/main/java/org/connectbot/TerminalView.java
@@ -200,14 +200,12 @@ public class TerminalView extends FrameLayout implements FontSizeChangedListener
private TerminalBridge bridge = TerminalView.this.bridge;
private float totalY = 0;
+ /**
+ * This should only handle scrolling when terminalTextViewOverlay is {@code null}, but
+ * we need to handle the page up/down gesture if it's enabled.
+ */
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
- // The terminalTextViewOverlay handles scrolling. Only handle scrolling if it
- // is not available (i.e. on pre-Honeycomb devices).
- if (terminalTextViewOverlay != null) {
- return false;
- }
-
// activate consider if within x tolerance
int touchSlop =
ViewConfiguration.get(TerminalView.this.context).getScaledTouchSlop();
@@ -221,7 +219,7 @@ public class TerminalView extends FrameLayout implements FontSizeChangedListener
// enabled.
boolean pgUpDnGestureEnabled =
prefs.getBoolean(PreferenceConstants.PG_UPDN_GESTURE, false);
- if (e2.getX() <= getWidth() / 3 && pgUpDnGestureEnabled) {
+ if (pgUpDnGestureEnabled && e2.getX() <= getWidth() / 3) {
// otherwise consume as pgup/pgdown for every 5 lines
if (moved > 5) {
((vt320) bridge.buffer).keyPressed(vt320.KEY_PAGE_DOWN, ' ', 0);
@@ -232,14 +230,16 @@ public class TerminalView extends FrameLayout implements FontSizeChangedListener
bridge.tryKeyVibrate();
totalY = 0;
}
- } else if (moved != 0) {
+ return true;
+ } else if (terminalTextViewOverlay == null && moved != 0) {
int base = bridge.buffer.getWindowBase();
bridge.buffer.setWindowBase(base + moved);
totalY = 0;
+ return false;
}
}
- return true;
+ return false;
}
@Override
@@ -266,8 +266,8 @@ public class TerminalView extends FrameLayout implements FontSizeChangedListener
@Override
public boolean onTouchEvent(MotionEvent event) {
- if (gestureDetector != null) {
- gestureDetector.onTouchEvent(event);
+ if (gestureDetector != null && gestureDetector.onTouchEvent(event)) {
+ return true;
}
// Old version of copying, only for pre-Honeycomb.
@@ -341,9 +341,7 @@ public class TerminalView extends FrameLayout implements FontSizeChangedListener
return true;
}
- super.onTouchEvent(event);
-
- return true;
+ return super.onTouchEvent(event);
}
/**
diff --git a/app/src/main/java/org/connectbot/service/TerminalBridge.java b/app/src/main/java/org/connectbot/service/TerminalBridge.java
index d15585ce..798db16b 100644
--- a/app/src/main/java/org/connectbot/service/TerminalBridge.java
+++ b/app/src/main/java/org/connectbot/service/TerminalBridge.java
@@ -986,15 +986,8 @@ public class TerminalBridge implements VDUDisplay {
color = manager.colordb.getColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME);
}
- private static Pattern urlPattern = null;
-
- /**
- * @return
- */
- public List<String> scanForURLs() {
- List<String> urls = new LinkedList<String>();
-
- if (urlPattern == null) {
+ private static class PatternHolder {
+ static {
// based on http://www.ietf.org/rfc/rfc2396.txt
String scheme = "[A-Za-z][-+.0-9A-Za-z]*";
String unreserved = "[-._~0-9A-Za-z]";
@@ -1024,13 +1017,21 @@ public class TerminalBridge implements VDUDisplay {
String uriRegex = scheme + ":" + hierPart + "(?:" + query + ")?(?:#" + fragment + ")?";
urlPattern = Pattern.compile(uriRegex);
}
+ private static final Pattern urlPattern;
+ }
+
+ /**
+ * @return
+ */
+ public List<String> scanForURLs() {
+ List<String> urls = new LinkedList<String>();
char[] visibleBuffer = new char[buffer.height * buffer.width];
for (int l = 0; l < buffer.height; l++)
System.arraycopy(buffer.charArray[buffer.windowBase + l], 0,
visibleBuffer, l * buffer.width, buffer.width);
- Matcher urlMatcher = urlPattern.matcher(new String(visibleBuffer));
+ Matcher urlMatcher = PatternHolder.urlPattern.matcher(new String(visibleBuffer));
while (urlMatcher.find())
urls.add(urlMatcher.group());
diff --git a/app/src/main/java/org/connectbot/util/TerminalTextViewOverlay.java b/app/src/main/java/org/connectbot/util/TerminalTextViewOverlay.java
index a3e5388c..c219ce11 100644
--- a/app/src/main/java/org/connectbot/util/TerminalTextViewOverlay.java
+++ b/app/src/main/java/org/connectbot/util/TerminalTextViewOverlay.java
@@ -75,16 +75,23 @@ public class TerminalTextViewOverlay extends TextView {
oldBufferHeight = numRows;
StringBuilder buffer = new StringBuilder();
+ int previousTotalLength = 0;
for (int r = 0; r < numRows && vb.charArray[r] != null; r++) {
for (int c = 0; c < numCols; c++) {
buffer.append(vb.charArray[r][c]);
}
- while (buffer.length() > 0 &&
+
+ // Truncate all the new whitespace without removing the old data.
+ while (buffer.length() > previousTotalLength &&
Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
buffer.setLength(buffer.length() - 1);
}
+
+ // Make sure each line ends with a carriage return and then remember the buffer
+ // at that length.
buffer.append('\\n');
+ previousTotalLength = buffer.length();
}
oldScrollY = vb.getWindowBase() * getLineHeight();
@@ -184,12 +191,12 @@ public class TerminalTextViewOverlay extends TextView {
}
terminalView.viewPager.setPagingEnabled(true);
} else {
- terminalView.onTouchEvent(event);
+ if (terminalView.onTouchEvent(event)) {
+ return true;
+ }
}
- super.onTouchEvent(event);
-
- return true;
+ return super.onTouchEvent(event);
}
@Override | ['app/src/main/java/org/connectbot/util/TerminalTextViewOverlay.java', 'app/src/main/java/org/connectbot/TerminalView.java', 'app/src/main/java/org/connectbot/service/TerminalBridge.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 766,136 | 212,300 | 24,584 | 72 | 2,031 | 480 | 64 | 3 | 314 | 56 | 78 | 4 | 0 | 0 | 2017-02-19T00:40:59 | 2,131 | Java | {'Java': 836170, 'C++': 5503, 'Dockerfile': 1773, 'Shell': 1577, 'CMake': 223} | Apache License 2.0 |
4 | connectbot/connectbot/328/228 | connectbot | connectbot | https://github.com/connectbot/connectbot/issues/228 | https://github.com/connectbot/connectbot/pull/328 | https://github.com/connectbot/connectbot/pull/328 | 1 | resolved | Connection closed detection | This may be related to issue #227
1 - Start ConnectBot
2 - Open a connection
3 - Power off device
4 - Power on device
5 - Type "exit" to close the connection
6 - Console say "Connection closed" but no button yes/no to close the activity (need to menu -> Disconnect)
| d41c2661b4451782854a9fac894e7f2406c21a01 | 9a8b735260b33d22361029cfa9205d47a5f2e5c3 | https://github.com/connectbot/connectbot/compare/d41c2661b4451782854a9fac894e7f2406c21a01...9a8b735260b33d22361029cfa9205d47a5f2e5c3 | diff --git a/app/src/main/java/org/connectbot/ConsoleActivity.java b/app/src/main/java/org/connectbot/ConsoleActivity.java
index 0bb7858f..9cdb4a50 100644
--- a/app/src/main/java/org/connectbot/ConsoleActivity.java
+++ b/app/src/main/java/org/connectbot/ConsoleActivity.java
@@ -172,6 +172,10 @@ public class ConsoleActivity extends AppCompatActivity implements BridgeDisconne
adapter.notifyDataSetChanged();
final int requestedIndex = bound.getBridges().indexOf(requestedBridge);
+ if (requestedBridge != null)
+ requestedBridge.promptHelper.setHandler(promptHandler);
+
+
if (requestedIndex != -1) {
pager.post(new Runnable() {
@Override | ['app/src/main/java/org/connectbot/ConsoleActivity.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 755,848 | 209,432 | 24,262 | 70 | 97 | 19 | 4 | 1 | 267 | 53 | 68 | 9 | 0 | 0 | 2015-10-23T14:39:09 | 2,131 | Java | {'Java': 836170, 'C++': 5503, 'Dockerfile': 1773, 'Shell': 1577, 'CMake': 223} | Apache License 2.0 |
5 | connectbot/connectbot/291/285 | connectbot | connectbot | https://github.com/connectbot/connectbot/issues/285 | https://github.com/connectbot/connectbot/pull/291 | https://github.com/connectbot/connectbot/pull/291 | 2 | fixes | Unable to show the ActionBar (when set to auto hide) | Since the very nice #277 when actionbar (Toolbar) is set to auto hide in settings, touching the screen does not show the action bar.
| 584cc8c9478b2fd14463f23a3b841c4991822617 | f3d05a6d7333db6a9b3dda993e8e05c69c695da1 | https://github.com/connectbot/connectbot/compare/584cc8c9478b2fd14463f23a3b841c4991822617...f3d05a6d7333db6a9b3dda993e8e05c69c695da1 | diff --git a/app/src/main/java/org/connectbot/ConsoleActivity.java b/app/src/main/java/org/connectbot/ConsoleActivity.java
index 440661a1..7c9ee056 100644
--- a/app/src/main/java/org/connectbot/ConsoleActivity.java
+++ b/app/src/main/java/org/connectbot/ConsoleActivity.java
@@ -661,7 +661,7 @@ public class ConsoleActivity extends AppCompatActivity implements BridgeDisconne
@Override
public void onClick(View v) {
if (keyboardGroup.getVisibility() == View.GONE) {
- showEmulatedKeys(false);
+ showEmulatedKeys(true);
}
}
}); | ['app/src/main/java/org/connectbot/ConsoleActivity.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 745,935 | 207,008 | 23,892 | 69 | 60 | 14 | 2 | 1 | 133 | 24 | 30 | 2 | 0 | 0 | 2015-10-13T18:57:02 | 2,131 | Java | {'Java': 836170, 'C++': 5503, 'Dockerfile': 1773, 'Shell': 1577, 'CMake': 223} | Apache License 2.0 |
1,450 | minestom/minestom/232/135 | minestom | minestom | https://github.com/Minestom/Minestom/issues/135 | https://github.com/Minestom/Minestom/pull/232 | https://github.com/Minestom/Minestom/pull/232 | 1 | fix | FireworkEffect is not right | ### What is the current behavior?
FireworkEffect have primaryColor and fadeColor as ChatColor.
```
if (compound.containsKey("Colors")) {
int[] color = compound.getIntArray("Colors");
primaryColor = ChatColor.fromRGB((byte) color[0], (byte) color[1], (byte) color[2]);
}
if (compound.containsKey("FadeColors")) {
int[] fadeColor = compound.getIntArray("FadeColors");
secondaryColor = ChatColor.fromRGB((byte) fadeColor[0], (byte) fadeColor[1], (byte) fadeColor[2]);
}
```
### What is the expected behavior?
They should be array of chat color not a single color
### What steps will reproduce the problem?
Because of this you can't get firework with FireworkEffect.
### What operating system and java version is being used?
Win10, Java1.15 amazon corretto
### If there is an exception, use pastebin/hastebin (NB: no expiry date!) to send the stacktrace
### Additional information / Possible thoughts on why this bug is happening
| 25176e9b9d6ea988a479e56f34f383fae5f97c22 | 96155e826e987764f75521a9aaa53e47db61e017 | https://github.com/minestom/minestom/compare/25176e9b9d6ea988a479e56f34f383fae5f97c22...96155e826e987764f75521a9aaa53e47db61e017 | diff --git a/src/main/java/net/minestom/server/item/firework/FireworkEffect.java b/src/main/java/net/minestom/server/item/firework/FireworkEffect.java
index c9aad763c..dcb8008b4 100644
--- a/src/main/java/net/minestom/server/item/firework/FireworkEffect.java
+++ b/src/main/java/net/minestom/server/item/firework/FireworkEffect.java
@@ -2,44 +2,32 @@ package net.minestom.server.item.firework;
import net.minestom.server.chat.ChatColor;
import net.minestom.server.color.Color;
+import net.minestom.server.exception.ExceptionManager;
+import org.apache.commons.lang3.Validate;
import org.jetbrains.annotations.NotNull;
-import org.jglrxavpok.hephaistos.nbt.NBTCompound;
+import org.jglrxavpok.hephaistos.nbt.*;
-import java.util.Objects;
+import java.util.*;
public class FireworkEffect {
private final boolean flicker;
private final boolean trail;
private final FireworkEffectType type;
- private final Color color;
- private final Color fadeColor;
+ private final List<Color> color;
+ private final List<Color> fadeColor;
+ //FIXME: fix javadoc
/**
* Initializes a new firework effect.
*
* @param flicker {@code true} if this explosion has the Twinkle effect (glowstone dust), otherwise {@code false}.
* @param trail {@code true} if this explosion hsa the Trail effect (diamond), otherwise {@code false}.
* @param type The shape of this firework's explosion.
- * @param color The primary color of this firework effect.
- * @param fadeColor The secondary color of this firework effect.
- * @deprecated Use {@link #FireworkEffect(boolean, boolean, FireworkEffectType, Color, Color)}
+ * @param color The primary colors of this firework effect.
+ * @param fadeColor The secondary colors of this firework effect.
*/
- @Deprecated
- public FireworkEffect(boolean flicker, boolean trail, FireworkEffectType type, ChatColor color, ChatColor fadeColor) {
- this(flicker, trail, type, color.asColor(), fadeColor.asColor());
- }
-
- /**
- * Initializes a new firework effect.
- *
- * @param flicker {@code true} if this explosion has the Twinkle effect (glowstone dust), otherwise {@code false}.
- * @param trail {@code true} if this explosion hsa the Trail effect (diamond), otherwise {@code false}.
- * @param type The shape of this firework's explosion.
- * @param color The primary color of this firework effect.
- * @param fadeColor The secondary color of this firework effect.
- */
- public FireworkEffect(boolean flicker, boolean trail, FireworkEffectType type, Color color, Color fadeColor) {
+ public FireworkEffect(boolean flicker, boolean trail, FireworkEffectType type, List<Color> color, List<Color> fadeColor) {
this.flicker = flicker;
this.trail = trail;
this.type = type;
@@ -55,18 +43,21 @@ public class FireworkEffect {
*/
public static FireworkEffect fromCompound(@NotNull NBTCompound compound) {
- Color primaryColor = null;
- Color secondaryColor = null;
+ List<Color> primaryColor = new ArrayList<>();
+ List<Color> secondaryColor = new ArrayList<>();
if (compound.containsKey("Colors")) {
int[] color = compound.getIntArray("Colors");
- primaryColor = new Color(color[0], color[1], color[2]);
+ for (int i = 0; i < color.length; i++) {
+ primaryColor.add(new Color(color[i]));
+ }
}
if (compound.containsKey("FadeColors")) {
int[] fadeColor = compound.getIntArray("FadeColors");
- secondaryColor = new Color(fadeColor[0], fadeColor[1], fadeColor[2]);
-
+ for (int i = 0; i < fadeColor.length; i++) {
+ secondaryColor.add(new Color(fadeColor[i]));
+ }
}
boolean flicker = compound.containsKey("Flicker") && compound.getByte("Flicker") == 1;
@@ -118,11 +109,11 @@ public class FireworkEffect {
* @return An array of integer values corresponding to the primary colors of this firework's explosion.
*/
public int[] getColors() {
- return new int[]{
- this.color.getRed(),
- this.color.getGreen(),
- this.color.getBlue()
- };
+ int[] primary = new int[color.size()];
+ for (int i = 0; i < color.size(); i++) {
+ primary[i] = color.get(i).asRGB();
+ }
+ return primary;
}
/**
@@ -133,11 +124,11 @@ public class FireworkEffect {
* @return An array of integer values corresponding to the fading colors of this firework's explosion.
*/
public int[] getFadeColors() {
- return new int[]{
- this.fadeColor.getRed(),
- this.fadeColor.getGreen(),
- this.fadeColor.getBlue()
- };
+ int[] secondary = new int[fadeColor.size()];
+ for (int i = 0; i < fadeColor.size(); i++) {
+ secondary[i] = fadeColor.get(i).asRGB();
+ }
+ return secondary;
}
/** | ['src/main/java/net/minestom/server/item/firework/FireworkEffect.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 5,917,809 | 1,439,402 | 118,866 | 1,425 | 3,070 | 694 | 65 | 1 | 1,041 | 122 | 233 | 31 | 0 | 1 | 2021-04-08T15:18:01 | 1,923 | Java | {'Java': 3534778, 'Kotlin': 7298} | Apache License 2.0 |
527 | spring-cloud/spring-cloud-config/719/718 | spring-cloud | spring-cloud-config | https://github.com/spring-cloud/spring-cloud-config/issues/718 | https://github.com/spring-cloud/spring-cloud-config/pull/719 | https://github.com/spring-cloud/spring-cloud-config/pull/719 | 1 | fixes | config.client.version no longer in Dalston | I was using Camden.SR7 on my Spring Cloud Config Server and there's a config.client.version and it changes everytime the properties get refreshed.
{"name":"application.properties","profiles":["master"],"label":"master",**"version":"9ad0fd174feb0cdbc5ab73753e64be061af2ba3b"**,"state":null,"propertySources":[]}
But on Dalston, the version is null, is this a feature or a bug? | a33487312a144acd5c37c5f8424559b4edceab5e | bb4168380435f6102c922ead68d5203fca40a077 | https://github.com/spring-cloud/spring-cloud-config/compare/a33487312a144acd5c37c5f8424559b4edceab5e...bb4168380435f6102c922ead68d5203fca40a077 | diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java
index 77d2f44f..f58509f2 100644
--- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java
+++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java
@@ -41,8 +41,15 @@ public class CompositeEnvironmentRepository implements EnvironmentRepository {
@Override
public Environment findOne(String application, String profile, String label) {
Environment env = new Environment(application, new String[]{profile}, label, null, null);
- for(EnvironmentRepository repo : environmentRepositories) {
- env.addAll(repo.findOne(application, profile, label).getPropertySources());
+ if(environmentRepositories.size() == 1) {
+ Environment envRepo = environmentRepositories.get(0).findOne(application, profile, label);
+ env.addAll(envRepo.getPropertySources());
+ env.setVersion(envRepo.getVersion());
+ env.setState(envRepo.getState());
+ } else {
+ for (EnvironmentRepository repo : environmentRepositories) {
+ env.addAll(repo.findOne(application, profile, label).getPropertySources());
+ }
}
return env;
}
diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java
index b1cc7904..138f9f56 100644
--- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java
+++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java
@@ -110,4 +110,38 @@ public class CompositeEnvironmentRepositoryTests {
assertEquals(sLoc4, locationStrings[3]);
assertEquals(sLoc1, locationStrings[4]);
}
+
+ @Test
+ public void testVersion() {
+ PropertySource p1 = mock(PropertySource.class);
+ doReturn("p1").when(p1).getName();
+ PropertySource p2 = mock(PropertySource.class);
+ doReturn("p2").when(p2).getName();
+ String sLoc1 = "loc1";
+ String sLoc2 = "loc2";
+ Environment e1 = new Environment("app", "dev");
+ e1.add(p1);
+ e1.setVersion("1");
+ e1.setState("state");
+ Environment e2 = new Environment("app", "dev");
+ e2.add(p2);
+ e2.setVersion("2");
+ e2.setState("state2");
+ SearchPathLocator.Locations loc1 = new SearchPathLocator.Locations("app", "dev", "label", "version", new String[]{sLoc1});
+ SearchPathLocator.Locations loc2 = new SearchPathLocator.Locations("app", "dev", "label", "version", new String[]{sLoc1, sLoc2});
+ List<EnvironmentRepository> repos = new ArrayList<EnvironmentRepository>();
+ repos.add(new TestOrderedEnvironmentRepository(3, e1, loc1));
+ List<EnvironmentRepository> repos2 = new ArrayList<EnvironmentRepository>();
+ repos2.add(new TestOrderedEnvironmentRepository(3, e1, loc1));
+ repos2.add(new TestOrderedEnvironmentRepository(3, e2, loc2));
+ SearchPathCompositeEnvironmentRepository compositeRepo = new SearchPathCompositeEnvironmentRepository(repos);
+ SearchPathCompositeEnvironmentRepository multiCompositeRepo = new SearchPathCompositeEnvironmentRepository(repos2);
+ Environment env = compositeRepo.findOne("app", "dev", "label");
+ assertEquals("1", env.getVersion());
+ assertEquals("state", env.getState());
+ Environment multiEnv = multiCompositeRepo.findOne("app", "dev", "label");
+ assertEquals(null, multiEnv.getVersion());
+ assertEquals(null, multiEnv.getState());
+
+ }
} | ['spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java', 'spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 259,042 | 54,659 | 8,225 | 77 | 572 | 110 | 11 | 1 | 381 | 37 | 99 | 5 | 0 | 0 | 2017-06-14T18:48:25 | 1,895 | Java | {'Java': 1817085, 'Shell': 65648, 'Ruby': 488, 'Groovy': 140} | Apache License 2.0 |