id
int64
0
10.2k
text_id
stringlengths
17
67
repo_owner
stringclasses
232 values
repo_name
stringclasses
295 values
issue_url
stringlengths
39
89
pull_url
stringlengths
37
87
comment_url
stringlengths
37
94
links_count
int64
1
2
link_keyword
stringclasses
12 values
issue_title
stringlengths
7
197
issue_body
stringlengths
45
21.3k
base_sha
stringlengths
40
40
head_sha
stringlengths
40
40
diff_url
stringlengths
120
170
diff
stringlengths
478
132k
changed_files
stringlengths
47
2.6k
changed_files_exts
stringclasses
22 values
changed_files_count
int64
1
22
java_changed_files_count
int64
1
22
kt_changed_files_count
int64
0
0
py_changed_files_count
int64
0
0
code_changed_files_count
int64
1
22
repo_symbols_count
int64
32.6k
242M
repo_tokens_count
int64
6.59k
49.2M
repo_lines_count
int64
992
6.2M
repo_files_without_tests_count
int64
12
28.1k
changed_symbols_count
int64
0
36.1k
changed_tokens_count
int64
0
6.5k
changed_lines_count
int64
0
561
changed_files_without_tests_count
int64
1
17
issue_symbols_count
int64
45
21.3k
issue_words_count
int64
2
1.39k
issue_tokens_count
int64
13
4.47k
issue_lines_count
int64
1
325
issue_links_count
int64
0
19
issue_code_blocks_count
int64
0
31
pull_create_at
timestamp[s]
repo_stars
int64
10
44.3k
repo_language
stringclasses
8 values
repo_languages
stringclasses
296 values
repo_license
stringclasses
2 values
379
adobe-consulting-services/acs-aem-commons/379/378
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/378
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/379
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/379
2
fix
Component,Page Error Handler - Not rendering html snippets in edit, preview mode when component throws error
Component error handler is not working as expected in AEM 6.0+service pack 1 and in some scenerios mentioned below impacting error handler as well. We are using latest released ACS commons package at https://github.com/Adobe-Consulting-Services/acs-aem-commons/releases/tag/acs-aem-commons-1.9.2 Publisher Instance: Seems to render the html snippet and works fine. Author instance (both classic and touch ui) If there is a scripting or any exception thrown by the component. Check for the scenerios - Not rending the respective html snippets configured in the edit, preview mode if the page has component throwing exception. - Working for publish view using http://localhost:4502/content/geometrixx/en.html?wcmmode=disabled - Rending the respective html snippets configured in the edit, preview mode of the component error handler configuration if the page accessed doesn't not exits (404) and ACS commons error page handler is configured. - Above is working for publish view using http://localhost:4502/content/geometrixx/en.html?wcmmode=disabled - In touch UI, if we access 404 page, it takes to http://localhost:4502/sites.html/content rather than custom 404 page i.e. http://localhost:4502/editor.html/content/geometrixx/en.html -> in edit or preview mode takes to http://localhost:4502/sites.html/content
47d896f64a9ccb9a18c9c294bb909541ab22146d
7a079170b9698a3691c1945ac51c870ce6b2c724
https://github.com/adobe-consulting-services/acs-aem-commons/compare/47d896f64a9ccb9a18c9c294bb909541ab22146d...7a079170b9698a3691c1945ac51c870ce6b2c724
diff --git a/bundle/src/main/java/com/adobe/acs/commons/wcm/impl/ComponentErrorHandlerImpl.java b/bundle/src/main/java/com/adobe/acs/commons/wcm/impl/ComponentErrorHandlerImpl.java index 4bd9c43fa..192b07ede 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/wcm/impl/ComponentErrorHandlerImpl.java +++ b/bundle/src/main/java/com/adobe/acs/commons/wcm/impl/ComponentErrorHandlerImpl.java @@ -50,6 +50,7 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; +import java.util.Arrays; import java.util.Map; @Component( @@ -75,12 +76,15 @@ import java.util.Map; public class ComponentErrorHandlerImpl implements ComponentErrorHandler, Filter { private static final Logger log = LoggerFactory.getLogger(ComponentErrorHandlerImpl.class.getName()); - // Magic number pushes filter lower in the chain so it executes after the - // OOTB WCM Debug Filter - static final int FILTER_ORDER = 1001; + // Magic number pushes filter lower in the chain so it executes after the OOTB WCM Debug Filter + // In AEM6 this must execute after WCM Developer Mode Filter which requires overriding the service.ranking via a + // sling:OsgiConfig node + static final int FILTER_ORDER = 1000000; static final String BLANK_HTML = "/dev/null"; - static final String REQ_ATTR_PREVIOUSLY_PROCESSED = ComponentErrorHandlerImpl.class.getName() + "_previouslyProcessed"; + + static final String REQ_ATTR_PREVIOUSLY_PROCESSED = + ComponentErrorHandlerImpl.class.getName() + "_previouslyProcessed"; @Reference private ResourceResolverFactory resourceResolverFactory; @@ -316,7 +320,7 @@ public class ComponentErrorHandlerImpl implements ComponentErrorHandler, Filter } private boolean isFirstInChain(final SlingHttpServletRequest request) { - if(request.getAttribute(REQ_ATTR_PREVIOUSLY_PROCESSED) != null) { + if (request.getAttribute(REQ_ATTR_PREVIOUSLY_PROCESSED) != null) { return false; } else { request.setAttribute(REQ_ATTR_PREVIOUSLY_PROCESSED, true); @@ -376,10 +380,7 @@ public class ComponentErrorHandlerImpl implements ComponentErrorHandler, Filter suppressedResourceTypes = PropertiesUtil.toStringArray(config.get(PROP_SUPPRESSED_RESOURCE_TYPES), DEFAULT_SUPPRESSED_RESOURCE_TYPES); - log.info("Suppressed Resource Types:"); - for (final String tmp : suppressedResourceTypes) { - log.info(" > {}", tmp); - } + log.info("Suppressed Resource Types: {}", Arrays.toString(suppressedResourceTypes)); } @Override
['bundle/src/main/java/com/adobe/acs/commons/wcm/impl/ComponentErrorHandlerImpl.java']
{'.java': 1}
1
1
0
0
1
1,011,244
205,832
28,477
225
1,139
249
19
1
1,319
167
304
13
6
0
1970-01-01T00:23:36
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0
380
adobe-consulting-services/acs-aem-commons/376/375
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/375
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/376
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/376
1
fixes
Dispatcher Flush Rules Multi-Path Flush uses comma as delimiter
1.9.0 introduced a new feature that allows chaining of flush paths using commas. This makes it hard to parse Flush Rules from the provided sling:OsgiConfigs.. `prop.rules.hierarchical="[regex=/abs-path&/foo&/bar,regex2=abs-path2]"` Change to use `&` as the path delimiter `prop.rules.hierarchical="[regex=/abs-path&/foo&/bar,regex2=abs-path2]"`
8c0b40de91a22f955fc62b6d2e5cd2f6f275743c
3178346120fe113fce426d0f1d29bad4bf05f429
https://github.com/adobe-consulting-services/acs-aem-commons/compare/8c0b40de91a22f955fc62b6d2e5cd2f6f275743c...3178346120fe113fce426d0f1d29bad4bf05f429
diff --git a/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java b/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java index 7d6b0b2d8..36a140d5f 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java +++ b/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java @@ -265,7 +265,7 @@ public class DispatcherFlushRulesImpl implements Preprocessor { for (final Map.Entry<String, String> entry : configuredRules.entrySet()) { final Pattern pattern = Pattern.compile(entry.getKey()); - rules.put(pattern, entry.getValue().split(",")); + rules.put(pattern, entry.getValue().split("&")); } return rules; diff --git a/bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java b/bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java index 87543457a..ebf085a99 100644 --- a/bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java +++ b/bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java @@ -116,7 +116,7 @@ public class DispatcherFlushRulesImplTest { validFlushRules.put("/a/.*", "/b"); validFlushRules.put("/b/.*", "/c"); validFlushRules.put("/c/d/.*", "/e/f"); - validFlushRules.put("/c/a/.*", "/e/f,/g/h"); + validFlushRules.put("/c/a/.*", "/e/f&/g/h"); final Map<Pattern, String[]> expected = new LinkedHashMap<Pattern, String[]>(); expected.put(Pattern.compile("/a/.*"), new String[] { "/b" }); @@ -431,5 +431,4 @@ public class DispatcherFlushRulesImplTest { verifyNoMoreInteractions(dispatcherFlusher); } - }
['bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java', 'bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java']
{'.java': 2}
2
2
0
0
2
1,011,244
205,832
28,477
225
123
22
2
1
348
35
96
8
0
0
1970-01-01T00:23:36
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0
381
adobe-consulting-services/acs-aem-commons/340/339
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/339
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/340
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/340
1
fixes
AEM Environment Indicator displays twice on /cf#
AEM Env indicator renders twice for /cf loaded pages since both the /cf and the page are candidates for indicator injection. This does not look bad when it is just a bar since they overlap one another and you cant tell, but the custom tab example displays 2 tabs. Tenatively going to reject add any requests refers whose path is /cf
a5c9bb132074de299b1f65cb9798c15d99906d64
bb80c275198e840001d4b8ecdbc53acea79a36b3
https://github.com/adobe-consulting-services/acs-aem-commons/compare/a5c9bb132074de299b1f65cb9798c15d99906d64...bb80c275198e840001d4b8ecdbc53acea79a36b3
diff --git a/bundle/src/main/java/com/adobe/acs/commons/wcm/impl/AemEnvironmentIndicatorFilter.java b/bundle/src/main/java/com/adobe/acs/commons/wcm/impl/AemEnvironmentIndicatorFilter.java index 01daa3ab6..7abd9166a 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/wcm/impl/AemEnvironmentIndicatorFilter.java +++ b/bundle/src/main/java/com/adobe/acs/commons/wcm/impl/AemEnvironmentIndicatorFilter.java @@ -192,8 +192,10 @@ public class AemEnvironmentIndicatorFilter implements Filter { } else if (StringUtils.endsWith(request.getHeader("Referer"), "/editor.html" + request.getRequestURI())) { // Do not apply to pages loaded in the TouchUI editor.html return false; + } else if (StringUtils.endsWith(request.getHeader("Referer"), "/cf")) { + // Do not apply to pages loaded in the Classic Content Finder + return false; } - return true; }
['bundle/src/main/java/com/adobe/acs/commons/wcm/impl/AemEnvironmentIndicatorFilter.java']
{'.java': 1}
1
1
0
0
1
825,286
168,637
23,081
178
184
35
4
1
335
61
71
4
0
0
1970-01-01T00:23:34
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0
382
adobe-consulting-services/acs-aem-commons/222/221
adobe-consulting-services
acs-aem-commons
https://github.com/Adobe-Consulting-Services/acs-aem-commons/issues/221
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/222
https://github.com/Adobe-Consulting-Services/acs-aem-commons/pull/222
1
fixes
bug/Dispatcher Flush Rules - Regex replace not implemented for ResourceOnly flushing
/content/geometrixx/([^/]+)/([^/]+)=/content/$1/geometrixx/$2 Does not work for ResourceOnly flushing (was not implemented)
4b89cd27f6c366ca346bfa2275230b8b956af141
fd7d31f99f8b96825c5faeccb5cee5e567db318c
https://github.com/adobe-consulting-services/acs-aem-commons/compare/4b89cd27f6c366ca346bfa2275230b8b956af141...fd7d31f99f8b96825c5faeccb5cee5e567db318c
diff --git a/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java b/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java index dd6bb44fa..b8e0efd8c 100644 --- a/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java +++ b/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java @@ -74,8 +74,10 @@ public class DispatcherFlushRulesImpl implements Preprocessor { private static final String OPTION_DELETE = "DELETE"; - private static final DispatcherFlushFilter HIERARCHICAL_FILTER = new DispatcherFlushRulesFilter(FlushType.Hierarchical); - private static final DispatcherFlushFilter RESOURCE_ONLY_FILTER = new DispatcherFlushRulesFilter(FlushType.ResourceOnly); + private static final DispatcherFlushFilter HIERARCHICAL_FILTER = + new DispatcherFlushRulesFilter(FlushType.Hierarchical); + private static final DispatcherFlushFilter RESOURCE_ONLY_FILTER = + new DispatcherFlushRulesFilter(FlushType.ResourceOnly); /* Replication Action Type Property */ @@ -154,7 +156,8 @@ public class DispatcherFlushRulesImpl implements Preprocessor { final Matcher m = pattern.matcher(path); if (m.matches()) { - final String flushPath = m.replaceAll(entry.getValue()); + final String flushPath = m.replaceAll(entry.getValue()); + log.debug("Requesting hierarchical flush of associated path: {} ~> {}", path, flushPath); dispatcherFlusher.flush(resourceResolver, flushActionType, false, @@ -169,10 +172,12 @@ public class DispatcherFlushRulesImpl implements Preprocessor { final Matcher m = pattern.matcher(path); if (m.matches()) { + final String flushPath = m.replaceAll(entry.getValue()); + log.debug("Requesting ResourceOnly flush of associated path: {} ~> {}", path, entry.getValue()); dispatcherFlusher.flush(resourceResolver, flushActionType, false, RESOURCE_ONLY_FILTER, - entry.getValue()); + flushPath); } } diff --git a/bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java b/bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java index f1a0a06ec..4e6ec06b5 100644 --- a/bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java +++ b/bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java @@ -391,4 +391,33 @@ public class DispatcherFlushRulesImplTest { verifyNoMoreInteractions(dispatcherFlusher); } + + @Test + public void testPreprocess_success_resourceonly_translation2() throws Exception { + resourceOnlyFlushRules.put(Pattern.compile("/content/acs-aem-commons/(.*)/(.*)"), "/content/target/$1/acs-aem-commons/$2"); + + final ReplicationAction replicationAction = mock(ReplicationAction.class); + when(replicationAction.getPath()).thenReturn("/content/acs-aem-commons/en/page"); + when(replicationAction.getType()).thenReturn(ReplicationActionType.ACTIVATE); + + final ReplicationOptions replicationOptions = new ReplicationOptions(); + replicationOptions.setSynchronous(false); + + final ArgumentCaptor<DispatcherFlushFilter> agentFilterCaptor = ArgumentCaptor.forClass(DispatcherFlushFilter + .class); + + dispatcherFlushRules.preprocess(replicationAction, replicationOptions); + + verify(dispatcherFlusher, times(1)).flush(any(ResourceResolver.class), eq(ReplicationActionType.ACTIVATE), + eq(false), + agentFilterCaptor.capture(), + eq("/content/target/en/acs-aem-commons/page")); + + assertEquals(DispatcherFlushFilter.FlushType.ResourceOnly, agentFilterCaptor.getValue().getFlushType()); + // Private impl class; no access to test for instanceof + assertEquals("DispatcherFlushRulesFilter", agentFilterCaptor.getValue().getClass().getSimpleName()); + + verifyNoMoreInteractions(dispatcherFlusher); + } + }
['bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImpl.java', 'bundle/src/test/java/com/adobe/acs/commons/replication/dispatcher/impl/DispatcherFlushRulesImplTest.java']
{'.java': 2}
2
2
0
0
2
593,637
122,352
16,928
137
855
137
13
1
125
10
36
4
0
0
1970-01-01T00:23:20
438
Java
{'Java': 6698660, 'JavaScript': 326616, 'HTML': 122754, 'Less': 30283, 'CSS': 19369, 'Groovy': 3717, 'Shell': 960, 'Rich Text Format': 363}
Apache License 2.0
561
openhft/chronicle-wire/650/649
openhft
chronicle-wire
https://github.com/OpenHFT/Chronicle-Wire/issues/649
https://github.com/OpenHFT/Chronicle-Wire/pull/650
https://github.com/OpenHFT/Chronicle-Wire/pull/650
1
fixes
There's no way to encode a "zero" value in the SymbolsLongConverters
We take numeric zero to mean empty string which means strings that consist entirely of the "zero" character can't be round-tripped. e.g. the following both fail `assertEquals(Base85LongConverter.INSTANCE.asText(Base85LongConverter.INSTANCE.parse("0")), "0");` `assertEquals(Base85LongConverter.INSTANCE.asText(Base85LongConverter.INSTANCE.parse("00000")), "00000");` a similar problem exists for values with leading "zero" values e.g. `assertEquals(Base85LongConverter.INSTANCE.asText(Base85LongConverter.INSTANCE.parse("00012")), "00012");` Not sure if this is a bug, or just a limitation to be aware of when using them to encode strings. Perhaps it's something we need to be explicit about in our docs?
38c8a6abd9b09fd2d3ad77329224648bb4542e7c
7218ab25eb32deb95655770a75cc1ed42690f6a6
https://github.com/openhft/chronicle-wire/compare/38c8a6abd9b09fd2d3ad77329224648bb4542e7c...7218ab25eb32deb95655770a75cc1ed42690f6a6
diff --git a/src/main/java/net/openhft/chronicle/wire/converter/SymbolsLongConverter.java b/src/main/java/net/openhft/chronicle/wire/converter/SymbolsLongConverter.java index 747abebb..e0750a12 100644 --- a/src/main/java/net/openhft/chronicle/wire/converter/SymbolsLongConverter.java +++ b/src/main/java/net/openhft/chronicle/wire/converter/SymbolsLongConverter.java @@ -63,6 +63,11 @@ public class SymbolsLongConverter implements LongConverter { @Override public void append(StringBuilder text, long value) { + if (value == 0) { + text.append(decode[0]); + return; + } + final int start = text.length(); if (value < 0) { int v = (int) Long.remainderUnsigned(value, factor); diff --git a/src/test/java/net/openhft/chronicle/wire/Base85LongConverterTest.java b/src/test/java/net/openhft/chronicle/wire/Base85LongConverterTest.java index aaf0fbd2..1c0cd5f3 100644 --- a/src/test/java/net/openhft/chronicle/wire/Base85LongConverterTest.java +++ b/src/test/java/net/openhft/chronicle/wire/Base85LongConverterTest.java @@ -34,7 +34,7 @@ public class Base85LongConverterTest extends WireTestCommon { public void parse() { LongConverter c = Base85LongConverter.INSTANCE; // System.out.println(c.asString(-1L)); - for (String s : ",a,ab,abc,abcd,ab.de,123=56,1234567,12345678,zzzzzzzzz,+ko2&)z.0".split(",")) { + for (String s : "a,ab,abc,abcd,ab.de,123=56,1234567,12345678,zzzzzzzzz,+ko2&)z.0".split(",")) { long v = c.parse(s); StringBuilder sb = new StringBuilder(); c.append(sb, v); @@ -91,6 +91,20 @@ public class Base85LongConverterTest extends WireTestCommon { allSafeChars(wire); } + @Test + public void willParseEmptyStringAsZero() { + assertEquals(0, Base85LongConverter.INSTANCE.converter.parse("")); + } + + @Test + public void testEncodeAndDecodeZero() { + assertEquals(0, Base85LongConverter.INSTANCE.converter.parse("0")); + assertEquals("0", Base85LongConverter.INSTANCE.converter.asText(0).toString()); + StringBuilder b = new StringBuilder(); + Base85LongConverter.INSTANCE.append(b, 0); + assertEquals("0", b.toString()); + } + private void allSafeChars(Wire wire) { final Base85LongConverter converter = Base85LongConverter.INSTANCE; for (long i = 0; i <= 85 * 85; i++) {
['src/main/java/net/openhft/chronicle/wire/converter/SymbolsLongConverter.java', 'src/test/java/net/openhft/chronicle/wire/Base85LongConverterTest.java']
{'.java': 2}
2
2
0
0
2
1,678,235
352,010
49,668
278
97
22
5
1
718
76
159
11
0
0
1970-01-01T00:28:00
423
Java
{'Java': 3464093, 'Shell': 771}
Apache License 2.0
927
scalar-labs/scalardb/71/66
scalar-labs
scalardb
https://github.com/scalar-labs/scalardb/issues/66
https://github.com/scalar-labs/scalardb/pull/71
https://github.com/scalar-labs/scalardb/pull/71
1
fix
Non-serializable execution (lost update) when a recode is deleted
### Environment - Version 2.0.0 - with SERIALIZABLE ### How to reproduce ``` CREATE TRANSACTION TABLE foo.foo ( id TEXT PARTITIONKEY, value TEXT ); ``` - Initial state: id | value | tx_version (tx metadata) -- | ------ | --- foo | 2 | 1 - Steps - T1: start - T1: Read a record that has id = foo and put the value into A. If the record does not exist, put 0. - (id, value, tx_version) = ("foo", 2, 1) - T2: start - T2: Delete a record that has id = foo - T2: commit - T3: start - T3: Read a record that has id = foo and put the value into B. If the record does not exist, put 0. - T3: Add 1 to B and put - (id, value, tx_version) = ("foo", 1, 1) - T3: commit - T1: Add 1 to A and put - (id, value, tx_version) = ("foo", 3, 2) - T1: commit - Actual states : id | value | tx_version -- | ------ | ------ foo | 3 | 2 The above state can NOT be produced by T1, T2 and T3 in some serial order, which means the execution is not serializable. - T1->T3->T2 and T3->T1->T2 no record - T2->T1->T3 and T2->T3->T1 id | value | tx_version -- | ------ | ------ foo | 2 | 2 - T1->T2->T3 and T3->T2->T1 id | value | tx_version -- | ------ | ------ foo | 1 | 1
65df3f9531d3afb7a42a79dc96610f174429ea74
fd2b484c03910e462c41676760dc3a85eb8f5a1c
https://github.com/scalar-labs/scalardb/compare/65df3f9531d3afb7a42a79dc96610f174429ea74...fd2b484c03910e462c41676760dc3a85eb8f5a1c
diff --git a/src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitIntegrationTest.java b/src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitIntegrationTest.java index 40a9f278..c6dac7ff 100644 --- a/src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitIntegrationTest.java +++ b/src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitIntegrationTest.java @@ -21,6 +21,7 @@ import com.scalar.db.api.Scan; import com.scalar.db.api.Selection; import com.scalar.db.api.TransactionState; import com.scalar.db.exception.storage.ExecutionException; +import com.scalar.db.exception.storage.NoMutationException; import com.scalar.db.exception.transaction.CommitConflictException; import com.scalar.db.exception.transaction.CommitException; import com.scalar.db.exception.transaction.CoordinatorException; @@ -1371,6 +1372,93 @@ public class ConsensusCommitIntegrationTest { assertThat(thrown2).isInstanceOf(CommitException.class); } + public void putAndCommit_DeleteGivenInBetweenTransactions_ShouldProduceSerializableResults() + throws CrudException, CommitException, UnknownTransactionStatusException { + // Arrange + DistributedTransaction transaction = manager.start(); + transaction.put(preparePut(0, 0, NAMESPACE, TABLE_1).withValue(new IntValue(BALANCE, 2))); + transaction.commit(); + + // Act + DistributedTransaction transaction1 = manager.start(); + Optional<Result> result1 = transaction1.get(prepareGet(0, 0, NAMESPACE, TABLE_1)); + int balance1 = 0; + if (result1.isPresent()) { + balance1 = ((IntValue) result1.get().getValue(BALANCE).get()).get(); + } + transaction1.put( + preparePut(0, 0, NAMESPACE, TABLE_1).withValue(new IntValue(BALANCE, balance1 + 1))); + + DistributedTransaction transaction2 = manager.start(); + transaction2.get(prepareGet(0, 0, NAMESPACE, TABLE_1)); + transaction2.delete(prepareDelete(0, 0, NAMESPACE, TABLE_1)); + transaction2.commit(); + + // the same transaction processing as transaction1 + DistributedTransaction transaction3 = manager.start(); + Optional<Result> result3 = transaction3.get(prepareGet(0, 0, NAMESPACE, TABLE_1)); + int balance3 = 0; + if (result3.isPresent()) { + balance3 = ((IntValue) result3.get().getValue(BALANCE).get()).get(); + } + transaction3.put( + preparePut(0, 0, NAMESPACE, TABLE_1).withValue(new IntValue(BALANCE, balance3 + 1))); + transaction3.commit(); + + Throwable thrown = catchThrowable(() -> transaction1.commit()); + + // Assert + assertThat(thrown) + .isInstanceOf(CommitConflictException.class) + .hasCauseInstanceOf(NoMutationException.class); + transaction = manager.start(); + Optional<Result> result = transaction.get(prepareGet(0, 0, NAMESPACE, TABLE_1)); + assertThat(((IntValue) result.get().getValue(BALANCE).get()).get()).isEqualTo(1); + } + + public void deleteAndCommit_DeleteGivenInBetweenTransactions_ShouldProduceSerializableResults() + throws CrudException, CommitException, UnknownTransactionStatusException { + // Arrange + DistributedTransaction transaction = manager.start(); + transaction.put(preparePut(0, 0, NAMESPACE, TABLE_1).withValue(new IntValue(BALANCE, 2))); + transaction.commit(); + + // Act + DistributedTransaction transaction1 = manager.start(); + Optional<Result> result1 = transaction1.get(prepareGet(0, 0, NAMESPACE, TABLE_1)); + int balance1 = 0; + if (result1.isPresent()) { + balance1 = ((IntValue) result1.get().getValue(BALANCE).get()).get(); + } + transaction1.delete(prepareDelete(0, 0, NAMESPACE, TABLE_1)); + + DistributedTransaction transaction2 = manager.start(); + transaction2.get(prepareGet(0, 0, NAMESPACE, TABLE_1)); + transaction2.delete(prepareDelete(0, 0, NAMESPACE, TABLE_1)); + transaction2.commit(); + + // the same transaction processing as transaction1 + DistributedTransaction transaction3 = manager.start(); + Optional<Result> result3 = transaction3.get(prepareGet(0, 0, NAMESPACE, TABLE_1)); + int balance3 = 0; + if (result3.isPresent()) { + balance3 = ((IntValue) result3.get().getValue(BALANCE).get()).get(); + } + transaction3.put( + preparePut(0, 0, NAMESPACE, TABLE_1).withValue(new IntValue(BALANCE, balance3 + 1))); + transaction3.commit(); + + Throwable thrown = catchThrowable(() -> transaction1.commit()); + + // Assert + assertThat(thrown) + .isInstanceOf(CommitConflictException.class) + .hasCauseInstanceOf(NoMutationException.class); + transaction = manager.start(); + Optional<Result> result = transaction.get(prepareGet(0, 0, NAMESPACE, TABLE_1)); + assertThat(((IntValue) result.get().getValue(BALANCE).get()).get()).isEqualTo(1); + } + private ConsensusCommit prepareTransfer(int fromId, int toId, int amount) throws CrudException { ConsensusCommit transaction = manager.start(); List<Get> gets = prepareGets(NAMESPACE, TABLE_1); diff --git a/src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitWithCassandraIntegrationTest.java b/src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitWithCassandraIntegrationTest.java index db18b2d3..59c2ce77 100644 --- a/src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitWithCassandraIntegrationTest.java +++ b/src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitWithCassandraIntegrationTest.java @@ -359,6 +359,18 @@ public class ConsensusCommitWithCassandraIntegrationTest { test.commit_WriteSkewWithScanOnNonExistingRecordsWithSerializable_ShouldThrowCommitException(); } + @Test + public void putAndCommit_DeleteGivenInBetweenTransactions_ShouldProduceSerializableResults() + throws Exception { + test.putAndCommit_DeleteGivenInBetweenTransactions_ShouldProduceSerializableResults(); + } + + @Test + public void deleteAndCommit_DeleteGivenInBetweenTransactions_ShouldProduceSerializableResults() + throws Exception { + test.deleteAndCommit_DeleteGivenInBetweenTransactions_ShouldProduceSerializableResults(); + } + @BeforeClass public static void setUpBeforeClass() throws IOException, InterruptedException { executeStatement(createNamespaceStatement(ConsensusCommitIntegrationTest.NAMESPACE)); diff --git a/src/main/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposer.java b/src/main/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposer.java index 247880de..979b66d6 100644 --- a/src/main/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposer.java +++ b/src/main/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposer.java @@ -1,7 +1,10 @@ package com.scalar.db.transaction.consensuscommit; import static com.scalar.db.api.ConditionalExpression.Operator; -import static com.scalar.db.transaction.consensuscommit.Attribute.*; +import static com.scalar.db.transaction.consensuscommit.Attribute.ID; +import static com.scalar.db.transaction.consensuscommit.Attribute.VERSION; +import static com.scalar.db.transaction.consensuscommit.Attribute.toIdValue; +import static com.scalar.db.transaction.consensuscommit.Attribute.toVersionValue; import com.google.common.annotations.VisibleForTesting; import com.scalar.db.api.ConditionalExpression; @@ -64,7 +67,9 @@ public class PrepareMutationComposer extends AbstractMutationComposer { // check if the record is not interrupted by other conflicting transactions put.withCondition( - new PutIf(new ConditionalExpression(VERSION, toVersionValue(version), Operator.EQ))); + new PutIf( + new ConditionalExpression(VERSION, toVersionValue(version), Operator.EQ), + new ConditionalExpression(ID, toIdValue(result.getId()), Operator.EQ))); } else { // initial record values.add(Attribute.toVersionValue(1)); @@ -98,7 +103,9 @@ public class PrepareMutationComposer extends AbstractMutationComposer { // check if the record is not interrupted by other conflicting transactions put.withCondition( - new PutIf(new ConditionalExpression(VERSION, toVersionValue(version), Operator.EQ))); + new PutIf( + new ConditionalExpression(VERSION, toVersionValue(version), Operator.EQ), + new ConditionalExpression(ID, toIdValue(result.getId()), Operator.EQ))); put.withValues(values); mutations.add(put); diff --git a/src/test/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposerTest.java b/src/test/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposerTest.java index 0096a06b..0e2f59d5 100644 --- a/src/test/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposerTest.java +++ b/src/test/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposerTest.java @@ -1,7 +1,10 @@ package com.scalar.db.transaction.consensuscommit; import static com.scalar.db.api.ConditionalExpression.Operator; -import static com.scalar.db.transaction.consensuscommit.Attribute.*; +import static com.scalar.db.transaction.consensuscommit.Attribute.ID; +import static com.scalar.db.transaction.consensuscommit.Attribute.VERSION; +import static com.scalar.db.transaction.consensuscommit.Attribute.toIdValue; +import static com.scalar.db.transaction.consensuscommit.Attribute.toVersionValue; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -120,7 +123,9 @@ public class PrepareMutationComposerTest { Put actual = (Put) mutations.get(0); put.withConsistency(Consistency.LINEARIZABLE); put.withCondition( - new PutIf(new ConditionalExpression(VERSION, toVersionValue(2), Operator.EQ))); + new PutIf( + new ConditionalExpression(VERSION, toVersionValue(2), Operator.EQ), + new ConditionalExpression(ID, toIdValue(ANY_ID_2), Operator.EQ))); put.withValue(Attribute.toPreparedAtValue(ANY_TIME_5)); put.withValue(Attribute.toIdValue(ANY_ID_3)); put.withValue(Attribute.toStateValue(TransactionState.PREPARED)); @@ -170,7 +175,9 @@ public class PrepareMutationComposerTest { .forTable(delete.forTable().get()); expected.withConsistency(Consistency.LINEARIZABLE); expected.withCondition( - new PutIf(new ConditionalExpression(VERSION, toVersionValue(2), Operator.EQ))); + new PutIf( + new ConditionalExpression(VERSION, toVersionValue(2), Operator.EQ), + new ConditionalExpression(ID, toIdValue(ANY_ID_2), Operator.EQ))); expected.withValue(Attribute.toPreparedAtValue(ANY_TIME_5)); expected.withValue(Attribute.toIdValue(ANY_ID_3)); expected.withValue(Attribute.toStateValue(TransactionState.DELETED));
['src/main/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposer.java', 'src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitWithCassandraIntegrationTest.java', 'src/integration-test/java/com/scalar/db/transaction/consensuscommit/ConsensusCommitIntegrationTest.java', 'src/test/java/com/scalar/db/transaction/consensuscommit/PrepareMutationComposerTest.java']
{'.java': 4}
4
4
0
0
4
217,416
47,418
7,661
97
961
175
13
1
1,277
249
450
57
0
1
1970-01-01T00:26:27
410
Java
{'Java': 5071062, 'TLA': 16905, 'Shell': 4976, 'JavaScript': 3576, 'Ruby': 2936, 'Dockerfile': 1459}
Apache License 2.0
577
gwtmaterialdesign/gwt-material/242/233
gwtmaterialdesign
gwt-material
https://github.com/GwtMaterialDesign/gwt-material/issues/233
https://github.com/GwtMaterialDesign/gwt-material/pull/242
https://github.com/GwtMaterialDesign/gwt-material/pull/242#issuecomment-196896448
1
close
HasFlexBox: Error setting the display attribute on UiBinder
The HasFlexBox interface defines two methods with the same name: ``` java void setDisplay(Style.Display display); void setDisplay(Display display); ``` And that causes a problem when you define a `display` attribute on UiBinder on any MaterialWidget: ``` xml <m:MaterialPanel display="NONE" /> ``` The error is: ``` [ERROR] Ambiguous setter requested: MaterialPanel.display ```
512fdf1886300daa5abb37fda5472e91d0dca234
f8712e893c1cb825cc86ec6139f508826dfdd7e7
https://github.com/gwtmaterialdesign/gwt-material/compare/512fdf1886300daa5abb37fda5472e91d0dca234...f8712e893c1cb825cc86ec6139f508826dfdd7e7
diff --git a/gwt-material/src/main/java/gwt/material/design/client/base/AbstractTextWidget.java b/gwt-material/src/main/java/gwt/material/design/client/base/AbstractTextWidget.java index 5e5b8440..b14ad95a 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/base/AbstractTextWidget.java +++ b/gwt-material/src/main/java/gwt/material/design/client/base/AbstractTextWidget.java @@ -20,6 +20,10 @@ package gwt.material.design.client.base; * #L% */ +import gwt.material.design.client.base.mixin.FontSizeMixin; +import gwt.material.design.client.base.mixin.IdMixin; +import gwt.material.design.client.constants.Display; + import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.editor.client.IsEditor; @@ -27,8 +31,6 @@ import com.google.gwt.editor.client.LeafValueEditor; import com.google.gwt.editor.ui.client.adapters.HasTextEditor; import com.google.gwt.user.client.ui.HasHTML; import com.google.gwt.user.client.ui.Widget; -import gwt.material.design.client.base.mixin.FontSizeMixin; -import gwt.material.design.client.base.mixin.IdMixin; /** * @author Ben Dol @@ -171,8 +173,8 @@ public abstract class AbstractTextWidget extends Widget implements HasId, HasHTM } @Override - public void setDisplay(Style.Display display) { - getElement().getStyle().setDisplay(display); + public void setDisplay(Display display) { + getElement().getStyle().setProperty("display", display.getCssName()); } @Override diff --git a/gwt-material/src/main/java/gwt/material/design/client/base/HasFlexbox.java b/gwt-material/src/main/java/gwt/material/design/client/base/HasFlexbox.java index 0fd4f856..f4b32503 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/base/HasFlexbox.java +++ b/gwt-material/src/main/java/gwt/material/design/client/base/HasFlexbox.java @@ -32,7 +32,7 @@ import gwt.material.design.client.constants.*; * @see MaterialWidget */ public interface HasFlexbox { - void setDisplay(Style.Display display); + void setGwtDisplay(Style.Display display); void setDisplay(Display display); diff --git a/gwt-material/src/main/java/gwt/material/design/client/base/HasInlineStyle.java b/gwt-material/src/main/java/gwt/material/design/client/base/HasInlineStyle.java index 6af390c5..ae1be415 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/base/HasInlineStyle.java +++ b/gwt-material/src/main/java/gwt/material/design/client/base/HasInlineStyle.java @@ -21,7 +21,7 @@ package gwt.material.design.client.base; */ -import com.google.gwt.dom.client.Style; +import gwt.material.design.client.constants.Display; /** * @author Ben Dol @@ -47,5 +47,5 @@ public interface HasInlineStyle extends HasColors, HasOpacity, HasFontSize { void setPaddingBottom(double padding); - void setDisplay(Style.Display display); + void setDisplay(Display display); } \\ No newline at end of file diff --git a/gwt-material/src/main/java/gwt/material/design/client/base/MaterialWidget.java b/gwt-material/src/main/java/gwt/material/design/client/base/MaterialWidget.java index 4904d77c..83804ff9 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/base/MaterialWidget.java +++ b/gwt-material/src/main/java/gwt/material/design/client/base/MaterialWidget.java @@ -20,12 +20,39 @@ package gwt.material.design.client.base; * #L% */ +import gwt.material.design.client.base.helper.StyleHelper; +import gwt.material.design.client.base.mixin.ColorsMixin; +import gwt.material.design.client.base.mixin.CssNameMixin; +import gwt.material.design.client.base.mixin.EnabledMixin; +import gwt.material.design.client.base.mixin.FlexboxMixin; +import gwt.material.design.client.base.mixin.FocusableMixin; +import gwt.material.design.client.base.mixin.FontSizeMixin; +import gwt.material.design.client.base.mixin.GridMixin; +import gwt.material.design.client.base.mixin.IdMixin; +import gwt.material.design.client.base.mixin.ScrollspyMixin; +import gwt.material.design.client.base.mixin.SeparatorMixin; +import gwt.material.design.client.base.mixin.ShadowMixin; +import gwt.material.design.client.base.mixin.ToggleStyleMixin; +import gwt.material.design.client.base.mixin.TooltipMixin; +import gwt.material.design.client.base.mixin.WavesMixin; +import gwt.material.design.client.constants.CenterOn; +import gwt.material.design.client.constants.Display; +import gwt.material.design.client.constants.Flex; +import gwt.material.design.client.constants.FlexAlignContent; +import gwt.material.design.client.constants.FlexAlignItems; +import gwt.material.design.client.constants.FlexAlignSelf; +import gwt.material.design.client.constants.FlexDirection; +import gwt.material.design.client.constants.FlexJustifyContent; +import gwt.material.design.client.constants.FlexWrap; +import gwt.material.design.client.constants.HideOn; +import gwt.material.design.client.constants.Position; +import gwt.material.design.client.constants.ShowOn; +import gwt.material.design.client.constants.TextAlign; +import gwt.material.design.client.constants.WavesType; + import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.*; -import gwt.material.design.client.base.helper.StyleHelper; -import gwt.material.design.client.base.mixin.*; -import gwt.material.design.client.constants.*; import java.util.Iterator; public class MaterialWidget extends ComplexPanel implements HasId, HasEnabled, HasTextAlign, HasColors, HasGrid, @@ -322,8 +349,8 @@ public class MaterialWidget extends ComplexPanel implements HasId, HasEnabled, H } @Override - public void setDisplay(Style.Display display) { - getFlexboxMixin().setDisplay(display); + public void setGwtDisplay(Style.Display display) { + getFlexboxMixin().setGwtDisplay(display); } @Override diff --git a/gwt-material/src/main/java/gwt/material/design/client/base/mixin/FlexboxMixin.java b/gwt-material/src/main/java/gwt/material/design/client/base/mixin/FlexboxMixin.java index 024daef0..fa0f60d2 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/base/mixin/FlexboxMixin.java +++ b/gwt-material/src/main/java/gwt/material/design/client/base/mixin/FlexboxMixin.java @@ -46,10 +46,12 @@ public class FlexboxMixin<T extends Widget & HasFlexbox> extends AbstractMixin<T private Display displayValueBeforeHidden; - public void setDisplay(Style.Display display) { + @Override + public void setGwtDisplay(Style.Display display) { setDisplay(Display.parse(display)); } + @Override public void setDisplay(Display display) { if (display == null) { displayValueBeforeHidden = null; @@ -76,6 +78,7 @@ public class FlexboxMixin<T extends Widget & HasFlexbox> extends AbstractMixin<T } } + @Override public void setVisible(boolean visible) { uiObject.setVisible(visible); @@ -86,6 +89,7 @@ public class FlexboxMixin<T extends Widget & HasFlexbox> extends AbstractMixin<T } } + @Override public void setFlexDirection(FlexDirection flexDirection) { boolean isCurrentlyVisible = uiObject.isVisible(); @@ -101,6 +105,7 @@ public class FlexboxMixin<T extends Widget & HasFlexbox> extends AbstractMixin<T } } + @Override public void setFlex(Flex flex) { if (flex == null) { setFlexGrow(null); @@ -114,38 +119,47 @@ public class FlexboxMixin<T extends Widget & HasFlexbox> extends AbstractMixin<T setFlexBasis(flex.getBasis()); } + @Override public void setFlexGrow(Integer flexGrow) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), new String[]{"MsFlexGrow", "WebkitFlexGrow", "MozFlexGrow", "flexGrow"}, flexGrow != null ? flexGrow.toString() : null); } + @Override public void setFlexShrink(Integer flexShrink) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), new String[]{"MsFlexShrink", "WebkitFlexShrink", "MozFlexShrink", "flexShrink"}, flexShrink != null ? flexShrink.toString() : null); } + @Override public void setFlexBasis(String flexBasis) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), new String[]{"MsFlexBasis", "WebkitFlexBasis", "MozFlexBasis", "flexBasis"}, flexBasis); } + @Override public void setFlexOrder(Integer flexOrder) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), new String[]{"MsFlexOrder", "WebkitOrder", "MozFlexOrder", "order"}, flexOrder != null ? flexOrder.toString() : null); } + @Override public void setFlexWrap(FlexWrap flexWrap) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), new String[]{"MsFlexWrap", "WebkitFlexWrap", "MozFlexWrap", "flexWrap"}, flexWrap != null ? flexWrap.getValue() : null); } + @Override public void setFlexAlignContent(FlexAlignContent flexAlignContent) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), "MsFlexLinePack", new String[]{"WebkitAlignContent", "MozFlexAlignContent", "alignContent"}, flexAlignContent); } + @Override public void setFlexAlignSelf(FlexAlignSelf flexAlignSelf) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), "MsFlexItemAlign", new String[]{"WebkitAlignSelf", "MozFlexItemAlign", "alignSelf"}, flexAlignSelf); } + @Override public void setFlexAlignItems(FlexAlignItems flexAlignItems) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), "MsFlexAlign", new String[]{"WebkitAlignItems", "MozFlexAlign", "alignItems"}, flexAlignItems); } + @Override public void setFlexJustifyContent(FlexJustifyContent flexJustifyContent) { BrowserPrefixHelper.updateStyleProperties(uiObject.getElement(), "MsFlexPack", new String[]{"WebkitJustifyContent", "MozJustifyContent", "justifyContent"}, flexJustifyContent); } diff --git a/gwt-material/src/main/java/gwt/material/design/client/base/mixin/ProgressMixin.java b/gwt-material/src/main/java/gwt/material/design/client/base/mixin/ProgressMixin.java index 7c7c39c0..8776a719 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/base/mixin/ProgressMixin.java +++ b/gwt-material/src/main/java/gwt/material/design/client/base/mixin/ProgressMixin.java @@ -20,15 +20,16 @@ package gwt.material.design.client.base.mixin; * #L% */ -import com.google.gwt.dom.client.Style; -import com.google.gwt.user.client.ui.UIObject; import gwt.material.design.client.base.HasProgress; +import gwt.material.design.client.constants.Display; import gwt.material.design.client.constants.ProgressType; import gwt.material.design.client.ui.MaterialCollapsibleBody; import gwt.material.design.client.ui.MaterialCollapsibleItem; import gwt.material.design.client.ui.MaterialNavBar; import gwt.material.design.client.ui.MaterialProgress; +import com.google.gwt.user.client.ui.UIObject; + /** * @author kevzlou7979 */ @@ -73,10 +74,10 @@ public class ProgressMixin<T extends UIObject & HasProgress> return; }else { if (isShow) { - body.setDisplay(Style.Display.NONE); + body.setDisplay(Display.NONE); item.add(progress); } else { - body.setDisplay(Style.Display.BLOCK); + body.setDisplay(Display.BLOCK); progress.removeFromParent(); } } diff --git a/gwt-material/src/main/java/gwt/material/design/client/constants/Display.java b/gwt-material/src/main/java/gwt/material/design/client/constants/Display.java index 7d4ed035..1483165e 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/constants/Display.java +++ b/gwt-material/src/main/java/gwt/material/design/client/constants/Display.java @@ -21,12 +21,13 @@ package gwt.material.design.client.constants; */ import com.google.gwt.dom.client.Style; +import com.google.gwt.dom.client.Style.HasCssName; /** * @author chriswjones */ -public enum Display { - FLEX(null), +public enum Display implements HasCssName { + FLEX("flex"), NONE(Style.Display.NONE), BLOCK(Style.Display.BLOCK), INLINE(Style.Display.INLINE), @@ -45,26 +46,35 @@ public enum Display { TABLE_ROW(Style.Display.TABLE_ROW), INITIAL(Style.Display.INITIAL); - private final Style.Display gwtDisplay; + private final String cssName; - Display(Style.Display gwtDisplay) { - this.gwtDisplay = gwtDisplay; + Display(HasCssName gwtDisplay) { + this.cssName = gwtDisplay.getCssName(); + } + + Display(String cssName) { + this.cssName = cssName; } public Style.Display getGwtDisplay() { - return gwtDisplay; + return Style.Display.valueOf(this.name()); } - - public static Display parse(Style.Display gwtDisplay) { - if (gwtDisplay == null) { - return null; - } - + + public static Display parse(String display) { for (Display d : Display.values()) { - if (d.getGwtDisplay() != null && d.getGwtDisplay().equals(gwtDisplay)) { + if (d.getCssName().equals(display)){ return d; } } return null; } + + public static Display parse(HasCssName display) { + return parse(display.getCssName()); + } + + @Override + public String getCssName() { + return cssName; + } } diff --git a/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialCollapsibleItem.java b/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialCollapsibleItem.java index fda9e7fa..f8c0c18e 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialCollapsibleItem.java +++ b/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialCollapsibleItem.java @@ -1,17 +1,18 @@ package gwt.material.design.client.ui; -import com.google.gwt.dom.client.Document; -import com.google.gwt.dom.client.Element; -import com.google.gwt.dom.client.Style.Display; -import com.google.gwt.user.client.ui.HasWidgets; -import com.google.gwt.user.client.ui.Widget; import gwt.material.design.client.base.AbstractButton; import gwt.material.design.client.base.HasProgress; import gwt.material.design.client.base.mixin.ProgressMixin; +import gwt.material.design.client.constants.Display; import gwt.material.design.client.constants.ProgressType; import gwt.material.design.client.constants.WavesType; import gwt.material.design.client.ui.MaterialCollapsible.HasCollapsibleParent; +import com.google.gwt.dom.client.Document; +import com.google.gwt.dom.client.Element; +import com.google.gwt.user.client.ui.HasWidgets; +import com.google.gwt.user.client.ui.Widget; + /* * #%L * GwtMaterial diff --git a/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialSplashScreen.java b/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialSplashScreen.java index 5a8b0b6d..cd9b9f21 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialSplashScreen.java +++ b/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialSplashScreen.java @@ -19,13 +19,14 @@ */ package gwt.material.design.client.ui; +import gwt.material.design.client.base.MaterialWidget; +import gwt.material.design.client.constants.Display; +import gwt.material.design.client.ui.html.Div; + import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Style; -import com.google.gwt.dom.client.Style.Display; import com.google.gwt.user.client.ui.HasVisibility; import com.google.gwt.user.client.ui.Widget; -import gwt.material.design.client.base.MaterialWidget; -import gwt.material.design.client.ui.html.Div; //@formatter:off /** @@ -83,11 +84,11 @@ public class MaterialSplashScreen extends MaterialWidget implements HasVisibilit } public void show(){ - getElement().getStyle().setDisplay(Display.BLOCK); + getElement().getStyle().setDisplay(Display.BLOCK.getGwtDisplay()); } public void hide(){ - getElement().getStyle().setDisplay(Display.NONE); + getElement().getStyle().setDisplay(Display.NONE.getGwtDisplay()); } }
['gwt-material/src/main/java/gwt/material/design/client/base/mixin/ProgressMixin.java', 'gwt-material/src/main/java/gwt/material/design/client/base/AbstractTextWidget.java', 'gwt-material/src/main/java/gwt/material/design/client/base/HasInlineStyle.java', 'gwt-material/src/main/java/gwt/material/design/client/constants/Display.java', 'gwt-material/src/main/java/gwt/material/design/client/base/HasFlexbox.java', 'gwt-material/src/main/java/gwt/material/design/client/ui/MaterialSplashScreen.java', 'gwt-material/src/main/java/gwt/material/design/client/base/MaterialWidget.java', 'gwt-material/src/main/java/gwt/material/design/client/ui/MaterialCollapsibleItem.java', 'gwt-material/src/main/java/gwt/material/design/client/base/mixin/FlexboxMixin.java']
{'.java': 9}
9
9
0
0
9
656,897
147,374
22,371
260
5,701
1,133
136
9
384
51
87
20
0
3
1970-01-01T00:24:12
404
Java
{'Java': 1902077, 'JavaScript': 396598, 'CSS': 97198, 'Batchfile': 674, 'Shell': 384}
Apache License 2.0
49
citrusframework/citrus/598/588
citrusframework
citrus
https://github.com/citrusframework/citrus/issues/588
https://github.com/citrusframework/citrus/pull/598
https://github.com/citrusframework/citrus/pull/598
2
fixes
BooleanExpressionParser parses expression groups containing boolean strings inconsistently
**Citrus Version** 2.7.8 **Expected behavior** As a user I would expect Citrus to consistently parse valid boolean expression like `(i = 5) and (${conditional} = true)` in e.g. iteration containers. **Actual behavior** Expression groups containing strings, like `(${conditional} = true)`, are handled inconsistently by `BooleanExpressionParser`. Due to its implementation, these groups require additional spaces between expression and parentheses, otherwise parsing will fail. `com.consol.citrus.exceptions.CitrusRuntimeException: Unknown operator 'false)'` Source: [stackoverflow](https://stackoverflow.com/questions/53928625/cannot-use-test-on-variable-to-exit-in-citrus-repeat-until-statement) **Test case sample** > Please, share the test case (as small as possible) which shows the issue ``` public class ExpressionParserTest extends TestNGCitrusTestRunner { /** * Test fails b/c '(${conditional} = true)' is not parsed correctly * @param runner Citrus TestRunner */ @Test @Parameters("runner") @CitrusTest public void failingTest(@Optional @CitrusResource TestRunner runner) { runner.createVariable("conditional", String.valueOf(true)); runner.repeat().until("(i = 5) and (${conditional} = true)").index("i").actions( runner.sleep(1000), new AbstractTestAction() { @Override public void doExecute(TestContext testContext) { System.out.println(testContext.getVariable("i")); } } ); } /** * Test succeeds due to spaces in expression * @param runner Citrus TestRunner */ @Test @Parameters("runner") @CitrusTest public void successfulTest(@Optional @CitrusResource TestRunner runner) { runner.createVariable("conditional", String.valueOf(true)); runner.repeat().until("(j = 5) and ( ${conditional} = true )").index("j").actions( runner.sleep(1000), new AbstractTestAction() { @Override public void doExecute(TestContext testContext) { System.out.println(testContext.getVariable("j")); } } ); } } ```
dded6e61012d64a98d70e3a4be95c84eb0c52904
98575325fe8037e995c91b2d9cc8667938a0a67b
https://github.com/citrusframework/citrus/compare/dded6e61012d64a98d70e3a4be95c84eb0c52904...98575325fe8037e995c91b2d9cc8667938a0a67b
diff --git a/modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java b/modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java index 0b89a1796..8ea578945 100644 --- a/modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java +++ b/modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2010 the original author or authors. + * Copyright 2006-2019 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. @@ -19,164 +19,319 @@ package com.consol.citrus.util; import com.consol.citrus.exceptions.CitrusRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.util.CollectionUtils; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.List; +import java.util.NoSuchElementException; + +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; /** * Parses boolean expression strings and evaluates to boolean result. - * - * @author Christoph Deppisch */ -@SuppressWarnings("unchecked") public final class BooleanExpressionParser { - - /** List of known operators */ - private static final List<String> OPERATORS = new ArrayList<String>( - CollectionUtils.arrayToList(new String[]{"(", "=", "and", "or", "lt", "lt=", "gt", "gt=", ")"})); - /** List of known boolean values */ - private static final List<String> BOOLEAN_VALUES = new ArrayList<String>( - CollectionUtils.arrayToList(new String[]{"true", "false"})); - + /** + * List of known non-boolean operators + */ + private static final List<String> OPERATORS = new ArrayList<>(Arrays.asList("lt", "lt=", "gt", "gt=")); + + /** + * List of known boolean operators + */ + private static final List<String> BOOLEAN_OPERATORS = new ArrayList<>(Arrays.asList("=", "and", "or")); + + /** + * List of known boolean values + */ + private static final List<String> BOOLEAN_VALUES = new ArrayList<>( + Arrays.asList(TRUE.toString(), FALSE.toString())); + + /** + * SeparatorToken is an explicit type to identify different kinds of separators. + */ + private enum SeparatorToken { + SPACE(' '), + OPEN_PARENTHESIS('('), + CLOSE_PARENTHESIS(')'); + + private final Character value; + + SeparatorToken(final Character value) { + this.value = value; + } + + @Override + public String toString(){ + return value.toString(); + } + } + /** * Logger */ - private static Logger log = LoggerFactory.getLogger(BooleanExpressionParser.class); + private static final Logger log = LoggerFactory.getLogger(BooleanExpressionParser.class); /** * Prevent instantiation. */ private BooleanExpressionParser() { } - + /** * Perform evaluation of boolean expression string. - * @param expression - * @throws CitrusRuntimeException - * @return + * + * @param expression The expression to evaluate + * @return boolean result + * @throws CitrusRuntimeException When unable to parse expression */ - public static boolean evaluate(String expression) { - Stack<String> operators = new Stack<String>(); - Stack<String> values = new Stack<String>(); - boolean result = true; + public static boolean evaluate(final String expression) { + final Deque<String> operators = new ArrayDeque<>(); + final Deque<String> values = new ArrayDeque<>(); + final boolean result; - char actChar; + char currentCharacter; + int currentCharacterIndex = 0; try { - for (int i = 0; i < expression.length(); i++) { - actChar = expression.charAt(i); - - if (actChar == '(') { - operators.push("("); - } else if (actChar == ' ') { - continue; //ignore - } else if (actChar == ')') { - String operator = operators.pop(); - while (!(operator).equals("(")) { - values.push(getBooleanResultAsString(operator, values.pop(), values.pop())); - operator = operators.pop(); - } - } else if (!Character.isDigit(actChar)) { - StringBuffer operatorBuffer = new StringBuffer(); - - int m = i; - do { - operatorBuffer.append(actChar); - m++; - - if (m < expression.length()) { - actChar = expression.charAt(m); - } - } while (m < expression.length() && !Character.isDigit(actChar) && !(actChar == ' ') && !(actChar == '(')); - - i = m - 1; - - if (BOOLEAN_VALUES.contains(operatorBuffer.toString())) { - values.push(Boolean.valueOf(operatorBuffer.toString()) ? "1" : "0"); + while (currentCharacterIndex < expression.length()) { + currentCharacter = expression.charAt(currentCharacterIndex); + + if (SeparatorToken.OPEN_PARENTHESIS.value == currentCharacter) { + operators.push(SeparatorToken.OPEN_PARENTHESIS.toString()); + currentCharacterIndex += moveCursor(SeparatorToken.OPEN_PARENTHESIS.toString()); + } else if (SeparatorToken.SPACE.value == currentCharacter) { + currentCharacterIndex += moveCursor(SeparatorToken.SPACE.toString()); + } else if (SeparatorToken.CLOSE_PARENTHESIS.value == currentCharacter) { + evaluateSubexpression(operators, values); + currentCharacterIndex += moveCursor(SeparatorToken.CLOSE_PARENTHESIS.toString()); + } else if (!Character.isDigit(currentCharacter)) { + final String parsedNonDigit = parseNonDigits(expression, currentCharacterIndex); + if (isBoolean(parsedNonDigit)) { + values.push(replaceBooleanStringByIntegerRepresentation(parsedNonDigit)); } else { - operators.push(validateOperator(operatorBuffer.toString())); + operators.push(validateOperator(parsedNonDigit)); } - } else if (Character.isDigit(actChar)) { - StringBuffer digitBuffer = new StringBuffer(); - - int m = i; - do { - digitBuffer.append(actChar); - m++; - - if (m < expression.length()) { - actChar = expression.charAt(m); - } - } while (m < expression.length() && Character.isDigit(actChar)); - - i = m - 1; - - values.push(digitBuffer.toString()); + currentCharacterIndex += moveCursor(parsedNonDigit); + } else if (Character.isDigit(currentCharacter)) { + final String parsedDigits = parseDigits(expression, currentCharacterIndex); + values.push(parsedDigits); + currentCharacterIndex += moveCursor(parsedDigits); } } - - while (!operators.isEmpty()) { - values.push(getBooleanResultAsString(operators.pop(), values.pop(), values.pop())); - } - - String value = values.pop(); - if (value.equals("0")) { - value = "false"; - } else if (value.equals("1")) { - value = "true"; - } + result = Boolean.valueOf(evaluateExpressionStack(operators, values)); - result = Boolean.valueOf(value).booleanValue(); - if (log.isDebugEnabled()) { - log.debug("Boolean expression " + expression + " evaluates to " + result); + log.debug("Boolean expression {} evaluates to {}", expression, result); } - } catch(EmptyStackException e) { + } catch (final NoSuchElementException e) { throw new CitrusRuntimeException("Unable to parse boolean expression '" + expression + "'. Maybe expression is incomplete!", e); } return result; } - + + /** + * This method takes stacks of operators and values and evaluates possible expressions + * This is done by popping one operator and two values, applying the operator to the values and pushing the result back onto the value stack + * + * @param operators Operators to apply + * @param values Values + * @return The final result popped of the values stack + */ + private static String evaluateExpressionStack(final Deque<String> operators, final Deque<String> values) { + while (!operators.isEmpty()) { + values.push(getBooleanResultAsString(operators.pop(), values.pop(), values.pop())); + } + return replaceIntegerStringByBooleanRepresentation(values.pop()); + } + + /** + * Evaluates a sub expression within a pair of parentheses and pushes its result onto the stack of values + * + * @param operators Stack of operators + * @param values Stack of values + */ + private static void evaluateSubexpression(final Deque<String> operators, final Deque<String> values) { + String operator = operators.pop(); + while (!(operator).equals(SeparatorToken.OPEN_PARENTHESIS.toString())) { + values.push(getBooleanResultAsString(operator, + values.pop(), + values.pop())); + operator = operators.pop(); + } + } + + /** + * This method reads digit characters from a given string, starting at a given index. + * It will read till the end of the string or up until it encounters a non-digit character + * + * @param expression The string to parse + * @param startIndex The start index from where to parse + * @return The parsed substring + */ + private static String parseDigits(final String expression, final int startIndex) { + final StringBuilder digitBuffer = new StringBuilder(); + + char currentCharacter = expression.charAt(startIndex); + int subExpressionIndex = startIndex; + + do { + digitBuffer.append(currentCharacter); + ++subExpressionIndex; + + if (subExpressionIndex < expression.length()) { + currentCharacter = expression.charAt(subExpressionIndex); + } + } while (subExpressionIndex < expression.length() && Character.isDigit(currentCharacter)); + + return digitBuffer.toString(); + } + + /** + * This method reads non-digit characters from a given string, starting at a given index. + * It will read till the end of the string or up until it encounters + * <p> + * - a digit + * - a separator token + * + * @param expression The string to parse + * @param startIndex The start index from where to parse + * @return The parsed substring + */ + private static String parseNonDigits(final String expression, final int startIndex) { + final StringBuilder operatorBuffer = new StringBuilder(); + + char currentCharacter = expression.charAt(startIndex); + int subExpressionIndex = startIndex; + do { + operatorBuffer.append(currentCharacter); + subExpressionIndex++; + + if (subExpressionIndex < expression.length()) { + currentCharacter = expression.charAt(subExpressionIndex); + } + } while (subExpressionIndex < expression.length() && !Character.isDigit(currentCharacter) && !isSeparatorToken(currentCharacter)); + + return operatorBuffer.toString(); + } + + /** + * Checks whether a string can be interpreted as a boolean value. + * + * @param possibleBoolean The possible boolean value as string + * @return Either true or false + */ + private static Boolean isBoolean(final String possibleBoolean) { + return BOOLEAN_VALUES.contains(possibleBoolean); + } + + /** + * Checks whether a String is a Boolean value and replaces it with its Integer representation + * "true" -> "1" + * "false" -> "0" + * + * @param possibleBooleanString "true" or "false" + * @return "1" or "0" + */ + private static String replaceBooleanStringByIntegerRepresentation(final String possibleBooleanString) { + if (possibleBooleanString.equals(TRUE.toString())) { + return "1"; + } else if (possibleBooleanString.equals(FALSE.toString())) { + return "0"; + } + return possibleBooleanString; + } + + /** + * Counterpart of {@link #replaceBooleanStringByIntegerRepresentation} + * Checks whether a String is the Integer representation of a Boolean value and replaces it with its Boolean representation + * "1" -> "true" + * "0" -> "false" + * otherwise -> value + * + * @param value "1", "0" or other string + * @return "true", "false" or the input value + */ + private static String replaceIntegerStringByBooleanRepresentation(final String value) { + if (value.equals("0")) { + return FALSE.toString(); + } else if (value.equals("1")) { + return TRUE.toString(); + } + return value; + } + + /** + * Checks whether a given character is a known separator token or no + * + * @param possibleSeparatorChar The character to check + * @return True in case its a separator, false otherwise + */ + private static boolean isSeparatorToken(final char possibleSeparatorChar) { + for (final SeparatorToken token : SeparatorToken.values()) { + if (token.value == possibleSeparatorChar) { + return true; + } + } + return false; + } + /** * Check if operator is known to this class. + * * @param operator to validate * @return the operator itself. - * @throws CitrusRuntimeException + * @throws CitrusRuntimeException When encountering an unknown operator */ - private static String validateOperator(String operator) { - if (!OPERATORS.contains(operator)) { + private static String validateOperator(final String operator) { + if (!OPERATORS.contains(operator) && !BOOLEAN_OPERATORS.contains(operator)) { throw new CitrusRuntimeException("Unknown operator '" + operator + "'"); } return operator; } + /** + * Returns the amount of characters to move the cursor after parsing a token + * + * @param lastToken Last parsed token + * @return Amount of characters to move forward + */ + private static int moveCursor(final String lastToken) { + return lastToken.length(); + } + /** * Evaluates a boolean expression to a String representation (true/false). - * @param operator - * @param value1 - * @param value2 + * + * @param operator The operator to apply on operands + * @param rightOperand The right hand side of the expression + * @param leftOperand The left hand side of the expression * @return true/false as String */ - private static String getBooleanResultAsString(String operator, String value1, String value2) { - if (operator.equals("lt")) { - return Boolean.valueOf(Integer.valueOf(value2).intValue() < Integer.valueOf(value1).intValue()).toString(); - } else if (operator.equals("lt=")) { - return Boolean.valueOf(Integer.valueOf(value2).intValue() <= Integer.valueOf(value1).intValue()).toString(); - } else if (operator.equals("gt")) { - return Boolean.valueOf(Integer.valueOf(value2).intValue() > Integer.valueOf(value1).intValue()).toString(); - } else if (operator.equals("gt=")) { - return Boolean.valueOf(Integer.valueOf(value2).intValue() >= Integer.valueOf(value1).intValue()).toString(); - } else if (operator.equals("=")) { - return Boolean.valueOf(Integer.valueOf(value2).intValue() == Integer.valueOf(value1).intValue()).toString(); - } else if (operator.equals("and")) { - return Boolean.valueOf(Boolean.valueOf(value2).booleanValue() && Boolean.valueOf(value1).booleanValue()).toString(); - } else if (operator.equals("or")) { - return Boolean.valueOf(Boolean.valueOf(value2).booleanValue() || Boolean.valueOf(value1).booleanValue()).toString(); - } else { - throw new CitrusRuntimeException("Unknown operator '" + operator + "'"); + private static String getBooleanResultAsString(final String operator, final String rightOperand, final String leftOperand) { + switch (operator) { + case "lt": + return Boolean.toString(Integer.valueOf(leftOperand) < Integer.valueOf(rightOperand)); + case "lt=": + return Boolean.toString(Integer.valueOf(leftOperand) <= Integer.valueOf(rightOperand)); + case "gt": + return Boolean.toString(Integer.valueOf(leftOperand) > Integer.valueOf(rightOperand)); + case "gt=": + return Boolean.toString(Integer.valueOf(leftOperand) >= Integer.valueOf(rightOperand)); + case "=": + return Boolean.toString(Integer.parseInt(leftOperand) == Integer.parseInt(rightOperand)); + case "and": + return Boolean.toString(Boolean.valueOf(leftOperand) && Boolean.valueOf(rightOperand)); + case "or": + return Boolean.toString(Boolean.valueOf(leftOperand) || Boolean.valueOf(rightOperand)); + default: + throw new CitrusRuntimeException("Unknown operator '" + operator + "'"); } } } diff --git a/modules/citrus-core/src/test/java/com/consol/citrus/util/BooleanExpressionParserTest.java b/modules/citrus-core/src/test/java/com/consol/citrus/util/BooleanExpressionParserTest.java index 40aff4ac5..28d319b31 100644 --- a/modules/citrus-core/src/test/java/com/consol/citrus/util/BooleanExpressionParserTest.java +++ b/modules/citrus-core/src/test/java/com/consol/citrus/util/BooleanExpressionParserTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2010 the original author or authors. + * Copyright 2006-2019 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. @@ -48,6 +48,10 @@ public class BooleanExpressionParserTest { Assert.assertFalse(BooleanExpressionParser.evaluate("(1 lt 1) and (2 gt 2)")); Assert.assertFalse(BooleanExpressionParser.evaluate("(1 gt 2) or (2 = 3)")); Assert.assertFalse(BooleanExpressionParser.evaluate("((1 = 5) and (2 = 6)) or (2 lt 1)")); + } + + @Test + public void testExpressionParserWithStringValues() { Assert.assertTrue(BooleanExpressionParser.evaluate("true")); Assert.assertTrue(BooleanExpressionParser.evaluate("true = true")); Assert.assertTrue(BooleanExpressionParser.evaluate("false = false")); @@ -56,13 +60,21 @@ public class BooleanExpressionParserTest { Assert.assertFalse(BooleanExpressionParser.evaluate("false = true")); Assert.assertTrue(BooleanExpressionParser.evaluate("( false = false ) and ( true = true )")); Assert.assertFalse(BooleanExpressionParser.evaluate("( false = false ) and ( true = false )")); + Assert.assertTrue(BooleanExpressionParser.evaluate("(false = false) and (true = true)")); + Assert.assertFalse(BooleanExpressionParser.evaluate("(false = false) and (true = false)")); + Assert.assertTrue(BooleanExpressionParser.evaluate("( false = false) and (true = true )")); + Assert.assertFalse(BooleanExpressionParser.evaluate("(false = false ) and ( true = false)")); + Assert.assertTrue(BooleanExpressionParser.evaluate("( true = false ) or ( false = false )")); + Assert.assertTrue(BooleanExpressionParser.evaluate("(false = false) or (true = true)")); + Assert.assertTrue(BooleanExpressionParser.evaluate("(false = false) or (true = false)")); + Assert.assertTrue(BooleanExpressionParser.evaluate("(false = false ) or ( true = false)")); } @Test public void testExpressionParserWithUnknownOperator() { try { BooleanExpressionParser.evaluate("wahr"); - } catch(CitrusRuntimeException e) { + } catch(final CitrusRuntimeException e) { Assert.assertEquals(e.getLocalizedMessage(), "Unknown operator 'wahr'"); return; } @@ -74,7 +86,7 @@ public class BooleanExpressionParserTest { public void testExpressionParserWithBrokenExpression() { try { BooleanExpressionParser.evaluate("1 = "); - } catch(CitrusRuntimeException e) { + } catch(final CitrusRuntimeException e) { Assert.assertEquals(e.getLocalizedMessage(), "Unable to parse boolean expression '1 = '. Maybe expression is incomplete!"); return; }
['modules/citrus-core/src/test/java/com/consol/citrus/util/BooleanExpressionParserTest.java', 'modules/citrus-core/src/main/java/com/consol/citrus/util/BooleanExpressionParser.java']
{'.java': 2}
2
2
0
0
2
5,473,150
1,096,313
161,581
1,557
16,633
3,069
375
1
2,359
197
480
60
1
1
1970-01-01T00:25:47
399
Java
{'Java': 12001798, 'Groovy': 120014, 'XSLT': 39429, 'Shell': 34409, 'HTML': 12074, 'Makefile': 1941, 'Gherkin': 798, 'Dockerfile': 107}
Apache License 2.0
489
gluufederation/oxauth/741/739
gluufederation
oxauth
https://github.com/GluuFederation/oxAuth/issues/739
https://github.com/GluuFederation/oxAuth/pull/741
https://github.com/GluuFederation/oxAuth/pull/741
1
fix
Fix the list of scopes in the authorization page
A dynamically registered client only gets the `openid` scope. Yet oxAuth is prompting for release of scopes like `profile` and `email` based on client request. Although data is not being leaked, it oxAuth is presenting the wrong authorization message to the user. We should also add a _**negative test**_ to reflect the above case.
be362879d6b8009d918d87a4b6ba98ced398aee7
72eb2370d62ee84c49e3b55ca3bf37bc57e3176c
https://github.com/gluufederation/oxauth/compare/be362879d6b8009d918d87a4b6ba98ced398aee7...72eb2370d62ee84c49e3b55ca3bf37bc57e3176c
diff --git a/Server/src/main/java/org/xdi/oxauth/model/authorize/ScopeChecker.java b/Server/src/main/java/org/xdi/oxauth/model/authorize/ScopeChecker.java index 8e847f619..b504f159b 100644 --- a/Server/src/main/java/org/xdi/oxauth/model/authorize/ScopeChecker.java +++ b/Server/src/main/java/org/xdi/oxauth/model/authorize/ScopeChecker.java @@ -6,24 +6,24 @@ package org.xdi.oxauth.model.authorize; -import java.util.HashSet; -import java.util.Set; - -import javax.ejb.Stateless; -import javax.inject.Inject; -import javax.inject.Named; - import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.xdi.oxauth.model.registration.Client; import org.xdi.oxauth.service.ScopeService; +import javax.ejb.Stateless; +import javax.inject.Inject; +import javax.inject.Named; +import java.util.HashSet; +import java.util.Set; + /** * Validates the scopes received for the authorize web service. * * @author Yuriy Zabrovarnyy * @author Yuriy Movchan - * @version June 3, 2015 + * @author Javier Rojas Blum + * @version January 30, 2018 */ @Stateless @Named("scopeChecker") @@ -39,6 +39,10 @@ public class ScopeChecker { log.debug("Checking scopes policy for: " + scope); Set<String> grantedScopes = new HashSet<String>(); + if (scope == null || client == null) { + return grantedScopes; + } + final String[] scopesRequested = scope.split(" "); final String[] scopesAllowed = client.getScopes();
['Server/src/main/java/org/xdi/oxauth/model/authorize/ScopeChecker.java']
{'.java': 1}
1
1
0
0
1
2,301,717
466,478
64,918
482
459
103
20
1
340
54
72
5
0
0
1970-01-01T00:25:17
397
Java
{'Java': 8006952, 'JavaScript': 1475711, 'Python': 1042483, 'HTML': 696561, 'CSS': 91820, 'Mustache': 2244, 'Shell': 302, 'Batchfile': 78}
MIT License
484
gluufederation/oxauth/1821/1820
gluufederation
oxauth
https://github.com/GluuFederation/oxAuth/issues/1820
https://github.com/GluuFederation/oxAuth/pull/1821
https://github.com/GluuFederation/oxAuth/pull/1821
1
fix
bug(oxauth): apply `clientWhiteList` when session is valid (`allowPostLogoutRedirectWithoutValidation=true` )
## Describe the issue When session is valid and `allowPostLogoutRedirectWithoutValidation=true` call to `/end_session` does not run check against `clientWhiteList` for `post_logout_redirect_uri`.
cf82315ba562d575786ecb3856a31e80182fbd8f
1eb990a5e5b4dbc26c9bbe4955c497178cfe5772
https://github.com/gluufederation/oxauth/compare/cf82315ba562d575786ecb3856a31e80182fbd8f...1eb990a5e5b4dbc26c9bbe4955c497178cfe5772
diff --git a/Server/src/main/java/org/gluu/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java b/Server/src/main/java/org/gluu/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java index 237d64cd2..94bcffa60 100644 --- a/Server/src/main/java/org/gluu/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java +++ b/Server/src/main/java/org/gluu/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java @@ -8,7 +8,6 @@ package org.gluu.oxauth.session.ws.rs; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.gluu.model.security.Identity; import org.gluu.oxauth.audit.ApplicationAuditLogger; @@ -57,6 +56,8 @@ import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +import static org.apache.commons.lang.BooleanUtils.isTrue; + /** * @author Javier Rojas Blum * @author Yuriy Movchan @@ -262,7 +263,13 @@ public class EndSessionRestWebServiceImpl implements EndSessionRestWebService { final Boolean allowPostLogoutRedirectWithoutValidation = appConfiguration.getAllowPostLogoutRedirectWithoutValidation(); return allowPostLogoutRedirectWithoutValidation != null && allowPostLogoutRedirectWithoutValidation && - new URLPatternList(appConfiguration.getClientWhiteList()).isUrlListed(postLogoutRedirectUri); + isUrlWhiteListed(postLogoutRedirectUri); + } + + public boolean isUrlWhiteListed(String url) { + final boolean result = new URLPatternList(appConfiguration.getClientWhiteList()).isUrlListed(url); + log.trace("White listed result: {}, url: {}", result, url); + return result; } private SessionId validateSidRequestParameter(String sid, String postLogoutRedirectUri) { @@ -280,7 +287,7 @@ public class EndSessionRestWebServiceImpl implements EndSessionRestWebService { } public Jwt validateIdTokenHint(String idTokenHint, SessionId sidSession, String postLogoutRedirectUri) { - final boolean isIdTokenHintRequired = BooleanUtils.isTrue(appConfiguration.getForceIdTokenHintPrecense()); + final boolean isIdTokenHintRequired = isTrue(appConfiguration.getForceIdTokenHintPrecense()); if (isIdTokenHintRequired && StringUtils.isBlank(idTokenHint)) { // must be present for logout tests #1279 final String reason = "id_token_hint is not set"; @@ -336,7 +343,7 @@ public class EndSessionRestWebServiceImpl implements EndSessionRestWebService { throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, "id_token signature verification failed.")); } - if (BooleanUtils.isTrue(appConfiguration.getAllowEndSessionWithUnmatchedSid())) { + if (isTrue(appConfiguration.getAllowEndSessionWithUnmatchedSid())) { return; } final String sidClaim = jwt.getClaims().getClaimAsString("sid"); @@ -375,8 +382,8 @@ public class EndSessionRestWebServiceImpl implements EndSessionRestWebService { if (StringUtils.isBlank(postLogoutRedirectUri)) { return ""; } - if (appConfiguration.getAllowPostLogoutRedirectWithoutValidation()) { - log.trace("Skipped post_logout_redirect_uri validation (because allowPostLogoutRedirectWithoutValidation=true)"); + if (isTrue(appConfiguration.getAllowPostLogoutRedirectWithoutValidation()) && isUrlWhiteListed(postLogoutRedirectUri)) { + log.trace("Skipped post_logout_redirect_uri validation (because allowPostLogoutRedirectWithoutValidation=true and white listed)"); return postLogoutRedirectUri; }
['Server/src/main/java/org/gluu/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java']
{'.java': 1}
1
1
0
0
1
2,975,427
607,811
84,409
638
1,421
268
19
1
203
21
44
5
0
0
1970-01-01T00:28:01
397
Java
{'Java': 8006952, 'JavaScript': 1475711, 'Python': 1042483, 'HTML': 696561, 'CSS': 91820, 'Mustache': 2244, 'Shell': 302, 'Batchfile': 78}
MIT License
485
gluufederation/oxauth/1726/1725
gluufederation
oxauth
https://github.com/GluuFederation/oxAuth/issues/1725
https://github.com/GluuFederation/oxAuth/pull/1726
https://github.com/GluuFederation/oxAuth/pull/1726
1
fix
test(oxauth): SpontaneousScopeHttpTest fails during build
## Describe the issue ``` at org.testng.Assert.fail(Assert.java:96) at org.testng.Assert.failNotEquals(Assert.java:776) at org.testng.Assert.assertTrue(Assert.java:44) at org.testng.Assert.assertTrue(Assert.java:54) at org.gluu.oxauth.ws.rs.SpontaneousScopeHttpTest.spontaneousScope(SpontaneousScopeHttpTest.java:54) ``` ## Steps To Reproduce Run build with tests ## Expected behavior Test must pass. ## Actual behavior Fails.
980e29440ffdc0f6722516852337380470923fa1
efd7e1ef0ad4f1dd4a37c3e35515d53bfd8e9eb7
https://github.com/gluufederation/oxauth/compare/980e29440ffdc0f6722516852337380470923fa1...efd7e1ef0ad4f1dd4a37c3e35515d53bfd8e9eb7
diff --git a/Model/src/main/java/org/gluu/oxauth/model/configuration/AppConfiguration.java b/Model/src/main/java/org/gluu/oxauth/model/configuration/AppConfiguration.java index 76fd97c4e..82498084b 100644 --- a/Model/src/main/java/org/gluu/oxauth/model/configuration/AppConfiguration.java +++ b/Model/src/main/java/org/gluu/oxauth/model/configuration/AppConfiguration.java @@ -70,7 +70,7 @@ public class AppConfiguration implements Configuration { private int statTimerIntervalInSeconds; private int statWebServiceIntervalLimitInSeconds; - private Boolean allowSpontaneousScopes; + private Boolean allowSpontaneousScopes = true; private int spontaneousScopeLifetime; private String openidSubAttribute; private Set<Set<ResponseType>> responseTypesSupported; @@ -1215,7 +1215,7 @@ public class AppConfiguration implements Configuration { } public Boolean getAllowSpontaneousScopes() { - if (allowSpontaneousScopes == null) allowSpontaneousScopes = false; + if (allowSpontaneousScopes == null) allowSpontaneousScopes = true; return allowSpontaneousScopes; }
['Model/src/main/java/org/gluu/oxauth/model/configuration/AppConfiguration.java']
{'.java': 1}
1
1
0
0
1
2,947,727
602,325
83,713
635
249
64
4
1
451
34
116
20
0
1
1970-01-01T00:27:43
397
Java
{'Java': 8006952, 'JavaScript': 1475711, 'Python': 1042483, 'HTML': 696561, 'CSS': 91820, 'Mustache': 2244, 'Shell': 302, 'Batchfile': 78}
MIT License
486
gluufederation/oxauth/1724/1723
gluufederation
oxauth
https://github.com/GluuFederation/oxAuth/issues/1723
https://github.com/GluuFederation/oxAuth/pull/1724
https://github.com/GluuFederation/oxAuth/pull/1724
1
fix
bug(oxauth): fix NPE in JwtAuthorizationRequest
## Describe the issue ``` java.lang.NullPointerException: null at org.gluu.oxauth.model.authorize.JwtAuthorizationRequest.createJwtRequest(JwtAuthorizationRequest.java:466) ~[classes/:?] at org.gluu.oxauth.bcauthorize.ws.rs.BackchannelAuthorizeRestWebServiceImpl.requestBackchannelAuthorizationPost(BackchannelAuthorizeRestWebServiceImpl.java:167) ~[classes/:?] at org.gluu.oxauth.bcauthorize.ws.rs.BackchannelAuthorizeRestWebServiceImpl$Proxy$_$$_WeldClientProxy.requestBackchannelAuthorizationPost(Unknown Source) ~[classes/:?] at jdk.internal.reflect.GeneratedMethodAccessor660.invoke(Unknown Source) ~[?:?] at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?] ``` ## Expected behavior There must not be NPE. ## Actual behavior NPE if redirect response is null.
3fe6db5e932216dc53ae5c1ec66bf466cb706219
8d9d6c4d6afba46f880bfda54f8e7b50f97b95bd
https://github.com/gluufederation/oxauth/compare/3fe6db5e932216dc53ae5c1ec66bf466cb706219...8d9d6c4d6afba46f880bfda54f8e7b50f97b95bd
diff --git a/Server/src/main/java/org/gluu/oxauth/model/authorize/JwtAuthorizationRequest.java b/Server/src/main/java/org/gluu/oxauth/model/authorize/JwtAuthorizationRequest.java index 72773d939..2e1dfb565 100644 --- a/Server/src/main/java/org/gluu/oxauth/model/authorize/JwtAuthorizationRequest.java +++ b/Server/src/main/java/org/gluu/oxauth/model/authorize/JwtAuthorizationRequest.java @@ -463,7 +463,7 @@ public class JwtAuthorizationRequest { } public static JwtAuthorizationRequest createJwtRequest(String request, String requestUri, Client client, RedirectUriResponse redirectUriResponse, AbstractCryptoProvider cryptoProvider, AppConfiguration appConfiguration) { - validateRequestUri(requestUri, client, appConfiguration, redirectUriResponse.getState()); + validateRequestUri(requestUri, client, appConfiguration, redirectUriResponse != null ? redirectUriResponse.getState() : null); final String requestFromClient = queryRequest(requestUri, redirectUriResponse, appConfiguration); if (StringUtils.isNotBlank(requestFromClient)) { request = requestFromClient;
['Server/src/main/java/org/gluu/oxauth/model/authorize/JwtAuthorizationRequest.java']
{'.java': 1}
1
1
0
0
1
2,947,690
602,316
83,713
635
234
43
2
1
874
42
207
16
0
1
1970-01-01T00:27:43
397
Java
{'Java': 8006952, 'JavaScript': 1475711, 'Python': 1042483, 'HTML': 696561, 'CSS': 91820, 'Mustache': 2244, 'Shell': 302, 'Batchfile': 78}
MIT License
490
gluufederation/oxauth/740/739
gluufederation
oxauth
https://github.com/GluuFederation/oxAuth/issues/739
https://github.com/GluuFederation/oxAuth/pull/740
https://github.com/GluuFederation/oxAuth/pull/740
1
fix
Fix the list of scopes in the authorization page
A dynamically registered client only gets the `openid` scope. Yet oxAuth is prompting for release of scopes like `profile` and `email` based on client request. Although data is not being leaked, it oxAuth is presenting the wrong authorization message to the user. We should also add a _**negative test**_ to reflect the above case.
227f79d8aba8e5a7c15151eb4083243e583aa308
113f114a86a1549c031066620d51d161c607bfcc
https://github.com/gluufederation/oxauth/compare/227f79d8aba8e5a7c15151eb4083243e583aa308...113f114a86a1549c031066620d51d161c607bfcc
diff --git a/Client/src/test/java/org/xdi/oxauth/ws/rs/AuthorizationCodeFlowHttpTest.java b/Client/src/test/java/org/xdi/oxauth/ws/rs/AuthorizationCodeFlowHttpTest.java index 1142aa1b4..48ed59c99 100644 --- a/Client/src/test/java/org/xdi/oxauth/ws/rs/AuthorizationCodeFlowHttpTest.java +++ b/Client/src/test/java/org/xdi/oxauth/ws/rs/AuthorizationCodeFlowHttpTest.java @@ -34,7 +34,7 @@ import static org.xdi.oxauth.model.register.RegisterRequestParam.*; * Test cases for the authorization code flow (HTTP) * * @author Javier Rojas Blum - * @version November 29, 2017 + * @version January 30, 2018 */ public class AuthorizationCodeFlowHttpTest extends BaseTest { @@ -153,6 +153,132 @@ public class AuthorizationCodeFlowHttpTest extends BaseTest { assertNull(userInfoResponse.getClaim("work_phone")); } + /** + * Test for the complete Authorization Code Flow. + * Register just the openid scope. + * Request authorization with scopes openid, profile, address, email, phone, user_name. + * Expected result is just prompt the user to authorize openid scope. + */ + @Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"}) + @Test + public void authorizationCodeFlowNegativeTest( + final String userId, final String userSecret, final String redirectUris, final String redirectUri, + final String sectorIdentifierUri) throws Exception { + showTitle("authorizationCodeFlow"); + + List<ResponseType> responseTypes = Arrays.asList( + ResponseType.CODE, + ResponseType.ID_TOKEN); + List<String> registerScopes = Arrays.asList("openid"); + + // 1. Register client + RegisterResponse registerResponse = registerClient(redirectUris, responseTypes, registerScopes, sectorIdentifierUri); + + assertTrue(registerResponse.getClaims().containsKey(SCOPE.toString())); + assertNotNull(registerResponse.getClaims().get(SCOPE.toString())); + assertEquals(registerResponse.getClaims().get(SCOPE.toString()), "openid"); + + String clientId = registerResponse.getClientId(); + String clientSecret = registerResponse.getClientSecret(); + + // 2. Request authorization and receive the authorization code. + String nonce = UUID.randomUUID().toString(); + List<String> scopes = Arrays.asList("openid", "profile", "address", "email", "phone", "user_name"); + AuthorizationResponse authorizationResponse = requestAuthorization(userId, userSecret, redirectUri, responseTypes, scopes, clientId, nonce); + + assertEquals(authorizationResponse.getScope(), "openid"); + + String scope = authorizationResponse.getScope(); + String authorizationCode = authorizationResponse.getCode(); + String idToken = authorizationResponse.getIdToken(); + + // 3. Request access token using the authorization code. + TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE); + tokenRequest.setCode(authorizationCode); + tokenRequest.setRedirectUri(redirectUri); + tokenRequest.setAuthUsername(clientId); + tokenRequest.setAuthPassword(clientSecret); + tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC); + + TokenClient tokenClient1 = new TokenClient(tokenEndpoint); + tokenClient1.setRequest(tokenRequest); + TokenResponse tokenResponse1 = tokenClient1.exec(); + + showClient(tokenClient1); + assertEquals(tokenResponse1.getStatus(), 200, "Unexpected response code: " + tokenResponse1.getStatus()); + assertNotNull(tokenResponse1.getEntity(), "The entity is null"); + assertNotNull(tokenResponse1.getAccessToken(), "The access token is null"); + assertNotNull(tokenResponse1.getExpiresIn(), "The expires in value is null"); + assertNotNull(tokenResponse1.getTokenType(), "The token type is null"); + assertNotNull(tokenResponse1.getRefreshToken(), "The refresh token is null"); + + String refreshToken = tokenResponse1.getRefreshToken(); + + // 4. Validate id_token + Jwt jwt = Jwt.parse(idToken); + assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE)); + assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM)); + assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER)); + assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE)); + assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME)); + assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT)); + assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER)); + assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH)); + assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME)); + assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.OX_OPENID_CONNECT_VERSION)); + + RSAPublicKey publicKey = JwkClient.getRSAPublicKey( + jwksUri, + jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID)); + RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey); + + assertTrue(rsaSigner.validate(jwt)); + + // 5. Request new access token using the refresh token. + TokenClient tokenClient2 = new TokenClient(tokenEndpoint); + TokenResponse tokenResponse2 = tokenClient2.execRefreshToken(scope, refreshToken, clientId, clientSecret); + + showClient(tokenClient2); + assertEquals(tokenResponse2.getStatus(), 200, "Unexpected response code: " + tokenResponse2.getStatus()); + assertNotNull(tokenResponse2.getEntity(), "The entity is null"); + assertNotNull(tokenResponse2.getAccessToken(), "The access token is null"); + assertNotNull(tokenResponse2.getTokenType(), "The token type is null"); + assertNotNull(tokenResponse2.getRefreshToken(), "The refresh token is null"); + assertNotNull(tokenResponse2.getScope(), "The scope is null"); + assertEquals(tokenResponse2.getScope(), "openid"); + + String accessToken = tokenResponse2.getAccessToken(); + + // 6. Request user info + UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint); + UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken); + + showClient(userInfoClient); + assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus()); + assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER)); + assertNull(userInfoResponse.getClaim(JwtClaimName.NAME)); + assertNull(userInfoResponse.getClaim(JwtClaimName.BIRTHDATE)); + assertNull(userInfoResponse.getClaim(JwtClaimName.FAMILY_NAME)); + assertNull(userInfoResponse.getClaim(JwtClaimName.GENDER)); + assertNull(userInfoResponse.getClaim(JwtClaimName.GIVEN_NAME)); + assertNull(userInfoResponse.getClaim(JwtClaimName.MIDDLE_NAME)); + assertNull(userInfoResponse.getClaim(JwtClaimName.NICKNAME)); + assertNull(userInfoResponse.getClaim(JwtClaimName.PICTURE)); + assertNull(userInfoResponse.getClaim(JwtClaimName.PREFERRED_USERNAME)); + assertNull(userInfoResponse.getClaim(JwtClaimName.PROFILE)); + assertNull(userInfoResponse.getClaim(JwtClaimName.WEBSITE)); + assertNull(userInfoResponse.getClaim(JwtClaimName.EMAIL)); + assertNull(userInfoResponse.getClaim(JwtClaimName.EMAIL_VERIFIED)); + assertNull(userInfoResponse.getClaim(JwtClaimName.PHONE_NUMBER)); + assertNull(userInfoResponse.getClaim(JwtClaimName.PHONE_NUMBER_VERIFIED)); + assertNull(userInfoResponse.getClaim(JwtClaimName.ADDRESS)); + assertNull(userInfoResponse.getClaim(JwtClaimName.LOCALE)); + assertNull(userInfoResponse.getClaim(JwtClaimName.ZONEINFO)); + assertNull(userInfoResponse.getClaim(JwtClaimName.USER_NAME)); + assertNull(userInfoResponse.getClaim("org_name")); + assertNull(userInfoResponse.getClaim("work_phone")); + } + @Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"}) @Test public void authorizationCodeWithNotAllowedScopeFlow( diff --git a/Server/src/main/java/org/xdi/oxauth/authorize/ws/rs/AuthorizeAction.java b/Server/src/main/java/org/xdi/oxauth/authorize/ws/rs/AuthorizeAction.java index 38b3d92d8..7e3ed7c95 100644 --- a/Server/src/main/java/org/xdi/oxauth/authorize/ws/rs/AuthorizeAction.java +++ b/Server/src/main/java/org/xdi/oxauth/authorize/ws/rs/AuthorizeAction.java @@ -18,6 +18,7 @@ import org.xdi.oxauth.model.auth.AuthenticationMode; import org.xdi.oxauth.model.authorize.AuthorizeErrorResponseType; import org.xdi.oxauth.model.authorize.AuthorizeParamsValidator; import org.xdi.oxauth.model.authorize.AuthorizeRequestParam; +import org.xdi.oxauth.model.authorize.ScopeChecker; import org.xdi.oxauth.model.common.Prompt; import org.xdi.oxauth.model.common.SessionId; import org.xdi.oxauth.model.common.SessionIdState; @@ -51,7 +52,7 @@ import java.util.*; /** * @author Javier Rojas Blum * @author Yuriy Movchan - * @version January 17, 2018 + * @version January 30, 2018 */ @RequestScoped @Named @@ -117,6 +118,9 @@ public class AuthorizeAction { @Inject private RequestParameterService requestParameterService; + @Inject + private ScopeChecker scopeChecker; + // OAuth 2.0 request parameters private String scope; private String responseType; @@ -144,6 +148,8 @@ public class AuthorizeAction { // custom oxAuth parameters private String sessionId; + private String allowedScope; + public void checkUiLocales() { List<String> uiLocalesList = null; if (StringUtils.isNotBlank(uiLocales)) { @@ -187,6 +193,10 @@ public class AuthorizeAction { return; } + // Fix the list of scopes in the authorization page. oxAuth #739 + Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope); + allowedScope = org.xdi.oxauth.model.util.StringUtils.implode(grantedScopes, " "); + SessionId session = getSession(); List<Prompt> prompts = Prompt.fromString(prompt, " "); @@ -343,7 +353,7 @@ public class AuthorizeAction { } public List<org.xdi.oxauth.model.common.Scope> getScopes() { - return authorizeService.getScopes(scope); + return authorizeService.getScopes(allowedScope); } /**
['Client/src/test/java/org/xdi/oxauth/ws/rs/AuthorizationCodeFlowHttpTest.java', 'Server/src/main/java/org/xdi/oxauth/authorize/ws/rs/AuthorizeAction.java']
{'.java': 2}
2
2
0
0
2
2,301,325
466,389
64,908
482
563
130
14
1
340
54
72
5
0
0
1970-01-01T00:25:17
397
Java
{'Java': 8006952, 'JavaScript': 1475711, 'Python': 1042483, 'HTML': 696561, 'CSS': 91820, 'Mustache': 2244, 'Shell': 302, 'Batchfile': 78}
MIT License
1,037
artipie/artipie/396/395
artipie
artipie
https://github.com/artipie/artipie/issues/395
https://github.com/artipie/artipie/pull/396
https://github.com/artipie/artipie/pull/396
1
fixes
GitHub API quota is drained too fast when authenticating via personal tokens
When using personal GitHub access tokens, the quota is drained very fast, it seems caching is not working.
60a5e03ce6ad47988068b33cbd91eccd745db43f
800f6d290fa4fe37582b8d7e9d8a0c9d134a7f18
https://github.com/artipie/artipie/compare/60a5e03ce6ad47988068b33cbd91eccd745db43f...800f6d290fa4fe37582b8d7e9d8a0c9d134a7f18
diff --git a/src/main/java/com/artipie/YamlSettings.java b/src/main/java/com/artipie/YamlSettings.java index e3cbaeb09..fb1b249af 100644 --- a/src/main/java/com/artipie/YamlSettings.java +++ b/src/main/java/com/artipie/YamlSettings.java @@ -29,6 +29,7 @@ import com.artipie.asto.Remaining; import com.artipie.asto.Storage; import com.artipie.auth.AuthFromEnv; import com.artipie.auth.AuthFromYaml; +import com.artipie.auth.CachedAuth; import com.artipie.auth.ChainedAuth; import com.artipie.auth.GithubAuth; import com.artipie.http.auth.Authentication; @@ -120,7 +121,7 @@ public final class YamlSettings implements Settings { return auth; } ).thenApply( - auth -> new ChainedAuth(new GithubAuth(), auth) + auth -> new ChainedAuth(new CachedAuth(new GithubAuth()), auth) ); } else if (YamlSettings.hasTypeFile(cred)) { res = CompletableFuture.failedFuture( diff --git a/src/main/java/com/artipie/auth/AuthFromEnv.java b/src/main/java/com/artipie/auth/AuthFromEnv.java index c6a8c8c0c..26f42418f 100644 --- a/src/main/java/com/artipie/auth/AuthFromEnv.java +++ b/src/main/java/com/artipie/auth/AuthFromEnv.java @@ -77,4 +77,9 @@ public final class AuthFromEnv implements Authentication { } return result; } + + @Override + public String toString() { + return String.format("%s()", this.getClass().getSimpleName()); + } } diff --git a/src/main/java/com/artipie/auth/AuthFromYaml.java b/src/main/java/com/artipie/auth/AuthFromYaml.java index b5a68c23b..c4f265709 100644 --- a/src/main/java/com/artipie/auth/AuthFromYaml.java +++ b/src/main/java/com/artipie/auth/AuthFromYaml.java @@ -87,6 +87,11 @@ public final class AuthFromYaml implements Authentication { return res; } + @Override + public String toString() { + return String.format("%s()", this.getClass().getSimpleName()); + } + /** * Checks stored password against the given one with type. * @param stored Password from settings diff --git a/src/main/java/com/artipie/auth/CachedAuth.java b/src/main/java/com/artipie/auth/CachedAuth.java index 5397bd5af..159baee15 100644 --- a/src/main/java/com/artipie/auth/CachedAuth.java +++ b/src/main/java/com/artipie/auth/CachedAuth.java @@ -81,4 +81,12 @@ public final class CachedAuth implements Authentication { public Optional<String> user(final String username, final String password) { return this.cache.computeIfAbsent(username, key -> this.origin.user(key, password)); } + + @Override + public String toString() { + return String.format( + "%s(origin=%s, size=%d)", + this.getClass().getSimpleName(), this.origin, this.cache.size() + ); + } } diff --git a/src/main/java/com/artipie/auth/ChainedAuth.java b/src/main/java/com/artipie/auth/ChainedAuth.java index 4ca9a9838..40c3733a5 100644 --- a/src/main/java/com/artipie/auth/ChainedAuth.java +++ b/src/main/java/com/artipie/auth/ChainedAuth.java @@ -28,6 +28,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; /** * Chained authentication provider, composed by multiple @@ -79,4 +80,13 @@ public final class ChainedAuth implements Authentication { } return result; } + + @Override + public String toString() { + return String.format( + "%s([%s])", + this.getClass().getSimpleName(), + this.list.stream().map(Object::toString).collect(Collectors.joining(",")) + ); + } } diff --git a/src/main/java/com/artipie/auth/GithubAuth.java b/src/main/java/com/artipie/auth/GithubAuth.java index 1bd721f81..c6868aace 100644 --- a/src/main/java/com/artipie/auth/GithubAuth.java +++ b/src/main/java/com/artipie/auth/GithubAuth.java @@ -92,4 +92,9 @@ public final class GithubAuth implements Authentication { } return result; } + + @Override + public String toString() { + return String.format("%s()", this.getClass().getSimpleName()); + } } diff --git a/src/main/java/com/artipie/auth/LoggingAuth.java b/src/main/java/com/artipie/auth/LoggingAuth.java index 6454fef29..a253ec359 100644 --- a/src/main/java/com/artipie/auth/LoggingAuth.java +++ b/src/main/java/com/artipie/auth/LoggingAuth.java @@ -67,9 +67,17 @@ public final class LoggingAuth implements Authentication { public Optional<String> user(final String username, final String password) { final Optional<String> res = this.origin.user(username, password); if (res.isEmpty()) { - Logger.log(this.level, this.origin, "Failed to authenticate '%s' user", username); + Logger.log( + this.level, this.origin, + "Failed to authenticate '%s' user via %s", + username, this.origin + ); } else { - Logger.log(this.level, this.origin, "Successfully authenticated '%s' user", username); + Logger.log( + this.level, this.origin, + "Successfully authenticated '%s' user via %s", + username, this.origin + ); } return res; }
['src/main/java/com/artipie/auth/GithubAuth.java', 'src/main/java/com/artipie/auth/LoggingAuth.java', 'src/main/java/com/artipie/auth/AuthFromEnv.java', 'src/main/java/com/artipie/auth/ChainedAuth.java', 'src/main/java/com/artipie/auth/AuthFromYaml.java', 'src/main/java/com/artipie/auth/CachedAuth.java', 'src/main/java/com/artipie/YamlSettings.java']
{'.java': 7}
7
7
0
0
7
225,214
46,189
6,269
66
1,633
315
48
7
106
18
21
1
0
0
1970-01-01T00:26:35
394
Java
{'Java': 819427, 'HTML': 3447, 'Python': 1338, 'Elixir': 1094, 'Dockerfile': 901, 'JavaScript': 827, 'CSS': 202}
MIT License
1,169
hibernate/hibernate-reactive/978/976
hibernate
hibernate-reactive
https://github.com/hibernate/hibernate-reactive/issues/976
https://github.com/hibernate/hibernate-reactive/pull/978
https://github.com/hibernate/hibernate-reactive/pull/978
1
fixes
ReactiveSessionImpl#reactiveClose()
The implementation of `reactiveClose()` is first closing the connection, and then invoking close() on super. I believe it needs to happen in the opposite order, for two reasons: 1. we need to flag the Session as closed ASAP to produce an error on illegal use 2. the super.close() method might need the connection to finalize pending operations
c5f48c06ad07e45dd2784ee258bad953d471b17c
f2310c0583d52d125674b224c059a8f1abc89441
https://github.com/hibernate/hibernate-reactive/compare/c5f48c06ad07e45dd2784ee258bad953d471b17c...f2310c0583d52d125674b224c059a8f1abc89441
diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java index a3e18857..0d4dca69 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java @@ -1485,10 +1485,10 @@ public void close() throws HibernateException { @Override public CompletionStage<Void> reactiveClose() { - CompletionStage<Void> closeStage = reactiveConnection != null + super.close(); + return reactiveConnection != null ? reactiveConnection.close() : voidFuture(); - return closeStage.thenAccept( v -> super.close() ); } @Override @SuppressWarnings("unchecked")
['hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java']
{'.java': 1}
1
1
0
0
1
1,425,192
311,880
41,706
249
174
38
4
1
350
57
71
6
0
0
1970-01-01T00:27:12
390
Java
{'Java': 3376271, 'Shell': 1406}
Apache License 2.0
1,170
hibernate/hibernate-reactive/360/359
hibernate
hibernate-reactive
https://github.com/hibernate/hibernate-reactive/issues/359
https://github.com/hibernate/hibernate-reactive/pull/360
https://github.com/hibernate/hibernate-reactive/pull/360
2
fixes
session.remove && session.getReference
Hello, as i understand, following jpa, there is only one way to remove detached entity: ``` factory.withTransaction((session, transaction) -> session.merge(sampleEntity).invokeUni(session::remove) ).await().indefinitely(); ``` Everything is fine, but if it's about performance, merge operation takes large amount of time and can cause real performance troubles. For instance, according to my inaccurate time measurements, removing 5000 entities takes ~4s, in hibernate-orm it takes 50ms. I've just read about a new method called ```session.getReference``` which returns the persistent instance of given entity. Is it possible to allow its use for ```session.remove```?
d265e520441230171f021bc0cc2f27bd9a2fa248
c5c39f5c0f521536b2afa71f0678d0b111e884b9
https://github.com/hibernate/hibernate-reactive/compare/d265e520441230171f021bc0cc2f27bd9a2fa248...c5c39f5c0f521536b2afa71f0678d0b111e884b9
diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveDeleteEventListener.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveDeleteEventListener.java index ced3306e..ae6b299d 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveDeleteEventListener.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveDeleteEventListener.java @@ -105,18 +105,26 @@ public CompletionStage<Void> reactiveOnDelete(DeleteEvent event) throws Hibernat */ public CompletionStage<Void> reactiveOnDelete(DeleteEvent event, IdentitySet transientEntities) throws HibernateException { - final EventSource source = event.getSession(); + EventSource source = event.getSession(); boolean detached = event.getEntityName() != null ? !source.contains( event.getEntityName(), event.getObject() ) : !source.contains( event.getObject() ); if ( detached ) { - // Hibernate Reactive doesn't support detached instances in refresh() - throw new IllegalArgumentException("unmanaged instance passed to refresh()"); + // Hibernate Reactive doesn't support detached instances in remove() + throw new IllegalArgumentException("unmanaged instance passed to remove()"); } - final PersistenceContext persistenceContext = source.getPersistenceContextInternal(); - Object entity = persistenceContext.unproxyAndReassociate( event.getObject() ); + //Object entity = persistenceContext.unproxyAndReassociate( event.getObject() ); + + return ( (ReactiveSession) source ).reactiveFetch( event.getObject(), true ) + .thenCompose( entity -> reactiveOnDelete( event, transientEntities, entity ) ); + } + + private CompletionStage<Void> reactiveOnDelete(DeleteEvent event, IdentitySet transientEntities, Object entity) { + + EventSource source = event.getSession(); + PersistenceContext persistenceContext = source.getPersistenceContextInternal(); EntityEntry entityEntry = persistenceContext.getEntry( entity ); @@ -129,11 +137,17 @@ public CompletionStage<Void> reactiveOnDelete(DeleteEvent event, IdentitySet tra .thenCompose( trans -> { if ( trans ) { // EARLY EXIT!!! - return deleteTransientEntity( source, entity, event.isCascadeDeleteEnabled(), persister, transientEntities ); + return deleteTransientEntity( + source, + entity, + event.isCascadeDeleteEnabled(), + persister, + transientEntities + ); } - performDetachedEntityDeletionCheck( event ); + performDetachedEntityDeletionCheck(event); - final Serializable id = persister.getIdentifier( entity, source ); + final Serializable id = persister.getIdentifier( entity, source); if ( id == null ) { throw new TransientObjectException( @@ -145,7 +159,7 @@ public CompletionStage<Void> reactiveOnDelete(DeleteEvent event, IdentitySet tra persistenceContext.checkUniqueness( key, entity ); - new OnUpdateVisitor( source, id, entity ).process( entity, persister ); + new OnUpdateVisitor(source, id, entity ).process( entity, persister ); final Object version = persister.getVersion( entity ); @@ -160,7 +174,7 @@ public CompletionStage<Void> reactiveOnDelete(DeleteEvent event, IdentitySet tra persister, false ); - persister.afterReassociate( entity, source ); + persister.afterReassociate( entity, source); callbackRegistry.preRemove( entity ); @@ -175,7 +189,7 @@ public CompletionStage<Void> reactiveOnDelete(DeleteEvent event, IdentitySet tra ) .thenAccept( v -> { if ( source.getFactory().getSessionFactoryOptions().isIdentifierRollbackEnabled() ) { - persister.resetIdentifier( entity, id, version, source ); + persister.resetIdentifier( entity, id, version, source); } } ); } ); @@ -204,7 +218,7 @@ public CompletionStage<Void> reactiveOnDelete(DeleteEvent event, IdentitySet tra ) .thenAccept( v -> { if ( source.getFactory().getSessionFactoryOptions().isIdentifierRollbackEnabled() ) { - persister.resetIdentifier( entity, id, version, source ); + persister.resetIdentifier( entity, id, version, source); } } ); } diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveLockEventListener.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveLockEventListener.java index b6afb5cb..46a3cef5 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveLockEventListener.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveLockEventListener.java @@ -61,7 +61,8 @@ public CompletionStage<Void> reactiveOnLock(LockEvent event) throws HibernateExc log.explicitSkipLockedLockCombo(); } - SessionImplementor source = event.getSession(); + EventSource source = event.getSession(); + boolean detached = event.getEntityName() != null ? !source.contains( event.getEntityName(), event.getObject() ) : !source.contains( event.getObject() ); @@ -70,17 +71,26 @@ public CompletionStage<Void> reactiveOnLock(LockEvent event) throws HibernateExc throw new IllegalArgumentException("unmanaged instance passed to refresh()"); } - final PersistenceContext persistenceContext = source.getPersistenceContextInternal(); - Object entity = persistenceContext.unproxyAndReassociate( event.getObject() ); + +// Object entity = persistenceContext.unproxyAndReassociate( event.getObject() ); //TODO: if object was an uninitialized proxy, this is inefficient, // resulting in two SQL selects + return ( (ReactiveSession) source ).reactiveFetch( event.getObject(), true ) + .thenCompose( entity -> reactiveOnLock( event, entity ) ); + } + + private CompletionStage<Void> reactiveOnLock(LockEvent event, Object entity) { + + SessionImplementor source = event.getSession(); + PersistenceContext persistenceContext = source.getPersistenceContextInternal(); + EntityEntry entry = persistenceContext.getEntry(entity); CompletionStage<EntityEntry> stage; if (entry==null) { - final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity ); - final Serializable id = persister.getIdentifier( entity, source ); - stage = ForeignKeys.isNotTransient( event.getEntityName(), entity, Boolean.FALSE, source ) + final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity); + final Serializable id = persister.getIdentifier(entity, source); + stage = ForeignKeys.isNotTransient( event.getEntityName(), entity, Boolean.FALSE, source) .thenApply( trans -> { if (!trans) { @@ -100,7 +110,7 @@ public CompletionStage<Void> reactiveOnLock(LockEvent event) throws HibernateExc stage = CompletionStages.completedFuture(entry); } - return stage.thenCompose( e -> upgradeLock( entity, e, event.getLockOptions(), event.getSession() ) ); + return stage.thenCompose( e -> upgradeLock(entity, e, event.getLockOptions(), event.getSession() ) ); } private void cascadeOnLock(LockEvent event, EntityPersister persister, Object entity) { diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveRefreshEventListener.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveRefreshEventListener.java index c3fb8402..239a05ab 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveRefreshEventListener.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveRefreshEventListener.java @@ -26,6 +26,7 @@ import org.hibernate.reactive.engine.impl.CascadingActions; import org.hibernate.reactive.event.ReactiveRefreshEventListener; import org.hibernate.reactive.persister.entity.impl.ReactiveAbstractEntityPersister; +import org.hibernate.reactive.session.ReactiveSession; import org.hibernate.reactive.util.impl.CompletionStages; import org.hibernate.type.CollectionType; import org.hibernate.type.CompositeType; @@ -64,7 +65,8 @@ public void onRefresh(RefreshEvent event, Map refreshedAlready) throws Hibernate */ public CompletionStage<Void> reactiveOnRefresh(RefreshEvent event, IdentitySet refreshedAlready) { - final EventSource source = event.getSession(); + EventSource source = event.getSession(); + boolean detached = event.getEntityName() != null ? !source.contains( event.getEntityName(), event.getObject() ) : !source.contains( event.getObject() ); @@ -73,38 +75,42 @@ public CompletionStage<Void> reactiveOnRefresh(RefreshEvent event, IdentitySet r throw new IllegalArgumentException("unmanaged instance passed to refresh()"); } - final PersistenceContext persistenceContext = source.getPersistenceContextInternal(); - if ( persistenceContext.reassociateIfUninitializedProxy( event.getObject() ) ) { - if ( detached ) { - source.setReadOnly( event.getObject(), source.isDefaultReadOnly() ); - } - return CompletionStages.voidFuture(); - } +// if ( persistenceContext.reassociateIfUninitializedProxy( event.getObject() ) ) { +// if (detached) { +// source.setReadOnly( event.getObject(), source.isDefaultReadOnly() ); +// } +// return CompletionStages.voidFuture(); +// } +// +// final Object entity = persistenceContext.unproxyAndReassociate( event.getObject() ); + + return ( (ReactiveSession) source ).reactiveFetch( event.getObject(), true ) + .thenCompose( entity -> reactiveOnRefresh( event, refreshedAlready, entity ) ); + } - final Object object = persistenceContext.unproxyAndReassociate( event.getObject() ); + private CompletionStage<Void> reactiveOnRefresh(RefreshEvent event, IdentitySet refreshedAlready, Object entity) { + EventSource source = event.getSession(); + PersistenceContext persistenceContext = source.getPersistenceContextInternal(); - if ( refreshedAlready.contains( object ) ) { + if ( refreshedAlready.contains( entity ) ) { LOG.trace( "Already refreshed" ); return CompletionStages.voidFuture(); } - final EntityEntry e = persistenceContext.getEntry( object ); + final EntityEntry e = persistenceContext.getEntry( entity ); final EntityPersister persister; final Serializable id; if ( e == null ) { persister = source.getEntityPersister( event.getEntityName(), - object + entity ); //refresh() does not pass an entityName - id = persister.getIdentifier( object, event.getSession() ); + id = persister.getIdentifier( entity, event.getSession() ); if ( LOG.isTraceEnabled() ) { LOG.tracev( - "Refreshing transient {0}", MessageHelper.infoString( - persister, - id, - source.getFactory() - ) + "Refreshing transient {0}", + MessageHelper.infoString( persister, id, source.getFactory() ) ); } final EntityKey key = source.generateEntityKey( id, persister ); @@ -137,16 +143,16 @@ public CompletionStage<Void> reactiveOnRefresh(RefreshEvent event, IdentitySet r } // cascade the refresh prior to refreshing this entity - refreshedAlready.add( object ); + refreshedAlready.add( entity ); - return cascadeRefresh( source, persister, object, refreshedAlready ) + return cascadeRefresh(source, persister, entity, refreshedAlready) .thenCompose(v -> { if ( e != null ) { final EntityKey key = source.generateEntityKey( id, persister ); persistenceContext.removeEntity( key ); if ( persister.hasCollections() ) { - new EvictVisitor( source, object ).process( object, persister ); + new EvictVisitor(source, entity ).process( entity, persister ); } } @@ -156,7 +162,7 @@ public CompletionStage<Void> reactiveOnRefresh(RefreshEvent event, IdentitySet r // we need to grab the version value from the entity, otherwise // we have issues with generated-version entities that may have // multiple actions queued during the same flush - previousVersion = persister.getVersion( object ); + previousVersion = persister.getVersion( entity ); } final EntityDataAccess cache = persister.getCacheAccessStrategy(); final Object ck = cache.generateCacheKey( @@ -165,12 +171,12 @@ public CompletionStage<Void> reactiveOnRefresh(RefreshEvent event, IdentitySet r source.getFactory(), source.getTenantIdentifier() ); - final SoftLock lock = cache.lockItem( source, ck, previousVersion ); - cache.remove( source, ck ); + final SoftLock lock = cache.lockItem(source, ck, previousVersion ); + cache.remove(source, ck ); source.getActionQueue().registerProcess( (success, session) -> cache.unlockItem( session, ck, lock ) ); } - evictCachedCollections( persister, id, source ); + evictCachedCollections( persister, id, source); String previousFetchProfile = source.getLoadQueryInfluencers().getInternalFetchProfile(); source.getLoadQueryInfluencers().setInternalFetchProfile( "refresh" ); @@ -217,7 +223,7 @@ public CompletionStage<Void> reactiveOnRefresh(RefreshEvent event, IdentitySet r postRefreshLockMode = null; } - return ( (ReactiveAbstractEntityPersister) persister ).reactiveLoad( id, object, lockOptionsToUse, source ) + return ( (ReactiveAbstractEntityPersister) persister ).reactiveLoad( id, entity, lockOptionsToUse, source) .thenAccept(result -> { if ( result!=null ) { diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java index 83376a12..33525e5e 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java @@ -100,6 +100,8 @@ import java.util.function.Function; import java.util.function.Supplier; +import static org.hibernate.reactive.util.impl.CompletionStages.completedFuture; + /** * An {@link ReactiveSession} implemented by extension of * the {@link SessionImpl} in Hibernate core. Extension was @@ -148,33 +150,43 @@ public Object immediateLoad(String entityName, Serializable id) throws Hibernate + " - use Session.fetch() (entity '" + entityName + "' with id '" + id + "' was not loaded)"); } - @Override + @Override @SuppressWarnings("unchecked") public <T> CompletionStage<T> reactiveFetch(T association, boolean unproxy) { checkOpen(); if ( association instanceof HibernateProxy ) { LazyInitializer initializer = ((HibernateProxy) association).getHibernateLazyInitializer(); - //TODO: is this correct? - // SessionImpl doesn't use IdentifierLoadAccessImpl for initializing proxies - String entityName = initializer.getEntityName(); - Serializable identifier = initializer.getIdentifier(); - return new ReactiveIdentifierLoadAccessImpl<T>( entityName ) - .fetch( identifier ) - .thenApply( SessionUtil.checkEntityFound( this, entityName, identifier ) ) - .thenApply( entity -> { - initializer.setSession( this ); - initializer.setImplementation( entity ); - return unproxy ? entity : association; - } ); + if ( !initializer.isUninitialized() ) { + return completedFuture( unproxy ? (T) initializer.getImplementation() : association ); + } + else { + //TODO: is this correct? + // SessionImpl doesn't use IdentifierLoadAccessImpl for initializing proxies + String entityName = initializer.getEntityName(); + Serializable identifier = initializer.getIdentifier(); + return new ReactiveIdentifierLoadAccessImpl<T>( entityName ) + .fetch( identifier ) + .thenApply( SessionUtil.checkEntityFound( this, entityName, identifier ) ) + .thenApply( entity -> { + initializer.setSession( this ); + initializer.setImplementation( entity ); + return unproxy ? entity : association; + } ); + } } else if ( association instanceof PersistentCollection ) { PersistentCollection persistentCollection = (PersistentCollection) association; - return reactiveInitializeCollection( persistentCollection, false ) - // don't reassociate the collection instance, because - // its owner isn't associated with this session - .thenApply( pc -> association ); + if ( persistentCollection.wasInitialized() ) { + return completedFuture( association ); + } + else { + return reactiveInitializeCollection( persistentCollection, false ) + // don't reassociate the collection instance, because + // its owner isn't associated with this session + .thenApply( pc -> association ); + } } else { - return CompletionStages.completedFuture( association ); + return completedFuture( association ); } } diff --git a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/ReferenceTest.java b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/ReferenceTest.java index 63c4e84e..d54fa94f 100644 --- a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/ReferenceTest.java +++ b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/ReferenceTest.java @@ -7,6 +7,7 @@ import io.vertx.ext.unit.TestContext; import org.hibernate.Hibernate; +import org.hibernate.LockMode; import org.hibernate.cfg.Configuration; import org.hibernate.reactive.stage.Stage; import org.junit.Test; @@ -108,12 +109,90 @@ public void testDetachedProxyReference(TestContext context) { ); } + @Test + public void testRemoveDetachedProxy(TestContext context) { + final Book goodOmens = new Book("Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch"); + + test( + context, + completedFuture( openSession() ) + .thenCompose( s -> s.persist(goodOmens).thenCompose( v -> s.flush() ) ) + .thenApply( v -> openSession() ) + .thenCompose( sess -> { + Book reference = sess.getReference(goodOmens); + context.assertFalse( Hibernate.isInitialized(reference) ); + sess.close(); + return completedFuture( openSession() ) + .thenCompose( s -> s.remove( s.getReference(reference) ) + .thenCompose( v -> s.flush() ) ); + } ) + .thenApply( v -> openSession() ) + .thenCompose( sess -> sess.find( Book.class, goodOmens.getId() ) ) + .thenAccept( book -> context.assertNull(book) ) + ); + } + + @Test + public void testLockDetachedProxy(TestContext context) { + final Book goodOmens = new Book("Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch"); + + test( + context, + completedFuture( openSession() ) + .thenCompose( s -> s.persist(goodOmens).thenCompose( v -> s.flush() ) ) + .thenApply( v -> openSession() ) + .thenCompose( sess -> { + Book reference = sess.getReference(goodOmens); + context.assertFalse( Hibernate.isInitialized(reference) ); + sess.close(); + return completedFuture( openSession() ) + .thenCompose( s -> s.lock( s.getReference(reference), LockMode.PESSIMISTIC_FORCE_INCREMENT ) + .thenCompose( v -> s.flush() ) ); + } ) + .thenApply( v -> openSession() ) + .thenCompose( sess -> sess.find( Book.class, goodOmens.getId() ) ) + .thenAccept( book -> { + context.assertNotNull(book); + context.assertEquals( 2, book.version ); + } ) + ); + } + + @Test + public void testRefreshDetachedProxy(TestContext context) { + final Book goodOmens = new Book("Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch"); + + test( + context, + completedFuture( openSession() ) + .thenCompose( s -> s.persist(goodOmens).thenCompose( v -> s.flush() ) ) + .thenApply( v -> openSession() ) + .thenCompose( sess -> { + Book reference = sess.getReference(goodOmens); + context.assertFalse( Hibernate.isInitialized(reference) ); + sess.close(); + return completedFuture( openSession() ) + .thenCompose( s -> s.refresh( s.getReference(reference) ) + .thenAccept( v -> context.assertTrue( Hibernate.isInitialized( s.getReference(reference) ) ) ) + .thenCompose( v -> s.flush() ) ); + } ) + .thenApply( v -> openSession() ) + .thenCompose( sess -> sess.find( Book.class, goodOmens.getId() ) ) + .thenAccept( book -> { + context.assertNotNull(book); + context.assertEquals( 1, book.version ); + } ) + ); + } + @Entity(name = "Tome") @Table(name = "Book") public static class Book { @Id @GeneratedValue private Integer id; + @Version + private Integer version = 1; private String title; @OneToMany(fetch = FetchType.LAZY, mappedBy="book")
['hibernate-reactive-core/src/test/java/org/hibernate/reactive/ReferenceTest.java', 'hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveLockEventListener.java', 'hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java', 'hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveDeleteEventListener.java', 'hibernate-reactive-core/src/main/java/org/hibernate/reactive/event/impl/DefaultReactiveRefreshEventListener.java']
{'.java': 5}
5
5
0
0
5
1,004,652
219,732
29,894
196
8,668
1,797
168
4
685
87
146
11
0
3
1970-01-01T00:26:39
390
Java
{'Java': 3376271, 'Shell': 1406}
Apache License 2.0
789
spongepowered/sponge/3765/3727
spongepowered
sponge
https://github.com/SpongePowered/Sponge/issues/3727
https://github.com/SpongePowered/Sponge/pull/3765
https://github.com/SpongePowered/Sponge/pull/3765
1
fixes
Cancelling a `InteractBlockEvent.Secondary` doesn't refresh count in inventory
### Affected Product(s) SpongeForge, SpongeVanilla ### Version 1.16.5-36.2.5-8.1.0-RC1164 ### Operating System Windows ### Java Version OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_282-b08) ### Plugins/Mods ```shell None other than this plugin ``` ### Describe the bug ``` @Listener public void test(InteractBlockEvent.Secondary event, @First ServerPlayer p) { event.setCancelled(true); } ``` When a user tries to place some a block such as dirt with this listener active, the dirt will be prevented from placing, but the quantity of the item stack will drop by 1 as-if the place went through. The count can be updated by moving the stack from one slot or another, or simply collecting another block of dirt. ### Link to logs _No response_
6e443ec04ded4385d12c2e609360e81a770fbfcb
d40af3cf30ee0b36a3b598cd9b785876da16f21d
https://github.com/spongepowered/sponge/compare/6e443ec04ded4385d12c2e609360e81a770fbfcb...d40af3cf30ee0b36a3b598cd9b785876da16f21d
diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java index fe8b20b4f..b94a1d308 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java @@ -53,6 +53,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.common.bridge.server.level.ServerPlayerGameModeBridge; import org.spongepowered.common.bridge.world.inventory.container.ContainerBridge; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.inventory.InventoryEventFactory; @@ -100,11 +101,12 @@ public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worl final Vector3d hitVec = Vector3d.from(blockRaytraceResultIn.getBlockPos().getX(), blockRaytraceResultIn.getBlockPos().getY(), blockRaytraceResultIn.getBlockPos().getZ()); final org.spongepowered.api.util.Direction direction = DirectionFacingProvider.INSTANCE.getKey(blockRaytraceResultIn.getDirection()).get(); final InteractBlockEvent.Secondary event = SpongeCommonEventFactory.callInteractBlockEventSecondary(playerIn, stackIn, hitVec, snapshot, direction, handIn); + final Tristate useItem = event.useItemResult(); + final Tristate useBlock = event.useBlockResult(); + ((ServerPlayerGameModeBridge) this).bridge$setInteractBlockRightClickCancelled(event.isCancelled()); if (event.isCancelled()) { return InteractionResult.FAIL; } - final Tristate useItem = event.useItemResult(); - final Tristate useBlock = event.useBlockResult(); // Sponge end if (this.gameModeForPlayer == GameType.SPECTATOR) { final MenuProvider inamedcontainerprovider = blockstate.getMenuProvider(worldIn, blockpos); @@ -152,6 +154,7 @@ public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worl if (!stackIn.isEmpty() && !playerIn.getCooldowns().isOnCooldown(stackIn.getItem())) { // Sponge start if (useItem == Tristate.FALSE) { + ((ServerPlayerGameModeBridge) this).bridge$setInteractBlockRightClickCancelled(true); return InteractionResult.PASS; } // Sponge end @@ -177,6 +180,12 @@ public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worl return result; } else { + // Sponge start + if(useBlock == Tristate.FALSE && !flag1) { + ((ServerPlayerGameModeBridge) this).bridge$setInteractBlockRightClickCancelled(true); + } + // Sponge end + return InteractionResult.PASS; } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/network/ServerGamePacketListenerImplMixin_Tracker.java b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/network/ServerGamePacketListenerImplMixin_Tracker.java index 25bc612a1..c2863fb86 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/tracker/server/network/ServerGamePacketListenerImplMixin_Tracker.java +++ b/src/mixins/java/org/spongepowered/common/mixin/tracker/server/network/ServerGamePacketListenerImplMixin_Tracker.java @@ -39,11 +39,9 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.bridge.world.entity.PlatformEntityBridge; import org.spongepowered.common.bridge.server.level.ServerPlayerGameModeBridge; import org.spongepowered.common.bridge.world.level.LevelBridge; -import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.phase.packet.PacketContext; import org.spongepowered.common.event.tracking.phase.packet.PacketPhaseUtil; @@ -80,21 +78,17 @@ public abstract class ServerGamePacketListenerImplMixin_Tracker { if (PhaseTracker.getInstance().getPhaseContext().isEmpty()) { return actionResult; } - final PacketContext<?> context = ((PacketContext<?>) PhaseTracker.getInstance().getPhaseContext()); - // If a plugin or mod has changed the item, avoid restoring - if (!context.getInteractItemChanged()) { - final ItemStack itemStack = ItemStackUtil.toNative(context.getItemUsed()); + final PacketContext<?> context = ((PacketContext<?>) PhaseTracker.getInstance().getPhaseContext()); + final ItemStack itemStack = ItemStackUtil.toNative(context.getItemUsed()); - // Only do a restore if something actually changed. The client does an identity check ('==') - // to determine if it should continue using an itemstack. If we always resend the itemstack, we end up - // cancelling item usage (e.g. eating food) that occurs while targeting a block - final boolean isInteractionCancelled = ((ServerPlayerGameModeBridge) this.player.gameMode).bridge$isInteractBlockRightClickCancelled(); - if (!ItemStack.matches(itemStack, this.player.getItemInHand(hand)) && isInteractionCancelled) { - PacketPhaseUtil.handlePlayerSlotRestore(this.player, itemStack, hand); - } + // Only do a restore if the items should stay the same. The client does an identity check ('==') + // to determine if it should continue using an itemstack. + final boolean isInteractionCancelled = ((ServerPlayerGameModeBridge) this.player.gameMode).bridge$isInteractBlockRightClickCancelled(); + if (ItemStack.matches(itemStack, this.player.getItemInHand(hand)) && isInteractionCancelled) { + PacketPhaseUtil.handlePlayerSlotRestore(this.player, itemStack, hand); } - context.interactItemChanged(false); + ((ServerPlayerGameModeBridge) this.player.gameMode).bridge$setInteractBlockRightClickCancelled(false); return actionResult; }
['src/mixins/java/org/spongepowered/common/mixin/tracker/server/level/ServerPlayerGameModeMixin_Tracker.java', 'src/mixins/java/org/spongepowered/common/mixin/tracker/server/network/ServerGamePacketListenerImplMixin_Tracker.java']
{'.java': 2}
2
2
0
0
2
11,615,757
2,352,623
265,025
2,928
2,630
515
35
2
776
112
203
37
0
2
1970-01-01T00:27:44
358
Java
{'Java': 12523507, 'Kotlin': 74371, 'Shell': 70}
MIT License
792
spongepowered/sponge/2462/3035
spongepowered
sponge
https://github.com/SpongePowered/Sponge/issues/3035
https://github.com/SpongePowered/Sponge/pull/2462
https://github.com/SpongePowered/Sponge/pull/2462
1
fixes
ChangeBlockEvent cause does not contain who activated TNT
**I am currently running** - SpongeVanilla version: spongevanilla-1.12.2-7.2.3-RC373 **Issue Description** This is my test code: https://gist.github.com/XakepSDK/a0f874facd1349e27a2484968a1897a9 This is results i obtain doing different things with TNT in-game: I placed 1 TNT, 1 redstone dust and 1 pressure plate, then stand on the plate to activate TNT. I got this output: https://gist.github.com/XakepSDK/96beb111deac789d4f7861fa2e18c0cc I activated TNT using flint and steel https://gist.github.com/XakepSDK/0f769a93a4bafd05f59f33303b29d85a Is it intended that when TNT explodes, cause does not contain player who activated that TNT? I thought it would contain TNT explosion as root cause and a Player who activated it.
78b0883e022aae3c3f22c1c6da36f83d26f39f81
85f1a678271c803448517d4b31a1348e72df0d76
https://github.com/spongepowered/sponge/compare/78b0883e022aae3c3f22c1c6da36f83d26f39f81...85f1a678271c803448517d4b31a1348e72df0d76
diff --git a/src/main/java/org/spongepowered/common/mixin/core/world/chunk/ChunkMixin.java b/src/main/java/org/spongepowered/common/mixin/core/world/chunk/ChunkMixin.java index 140ad1f37..62099c0b3 100644 --- a/src/main/java/org/spongepowered/common/mixin/core/world/chunk/ChunkMixin.java +++ b/src/main/java/org/spongepowered/common/mixin/core/world/chunk/ChunkMixin.java @@ -545,8 +545,10 @@ public IBlockState setBlockState(final BlockPos pos, final IBlockState state) { // Sponge End TileEntity tileentity = this.getTileEntity(pos, net.minecraft.world.chunk.Chunk.EnumCreateEntityType.CHECK); - if (tileentity == null) { - // Sponge Start - use SpongeImplHooks for forge compatibility + // Sponge Start - Additional check for the tile entity being queued for removal. + // if (tileentity == null) { // Sponge + if (tileentity == null || (transaction != null && transaction.queuedRemoval != null)) { + // Use SpongeImplHooks for forge compatibility // tileentity = ((ITileEntityProvider)block).createNewTileEntity(this.worldObj, block.getMetaFromState(state)); // Sponge tileentity = SpongeImplHooks.createTileEntity(newBlock, this.world, newState);
['src/main/java/org/spongepowered/common/mixin/core/world/chunk/ChunkMixin.java']
{'.java': 1}
1
1
0
0
1
13,466,940
2,769,055
308,726
3,294
428
83
6
1
742
91
218
16
3
0
1970-01-01T00:26:18
358
Java
{'Java': 12523507, 'Kotlin': 74371, 'Shell': 70}
MIT License
790
spongepowered/sponge/3764/3691
spongepowered
sponge
https://github.com/SpongePowered/Sponge/issues/3691
https://github.com/SpongePowered/Sponge/pull/3764
https://github.com/SpongePowered/Sponge/pull/3764
1
fixes
setBiome uses incorrect math
### Affected Product(s) SpongeForge, SpongeVanilla ### Version spongevanilla-1.16.5-8.1.0-RC1134 ### Operating System Linux ### Java Version 17.0.3 ### Plugins/Mods ```shell WorldEdit ``` ### Describe the bug setBiome uses incorrect math, specifically in `VolumeStreamUtils#setBiomeOnNativeChunk` it takes block positions but does not shift them `>> 2` to convert them to "quad" positions, as e.g. `BiomeManager#getNoiseBiomeAtPosition` does. ### Link to logs _No response_
6e443ec04ded4385d12c2e609360e81a770fbfcb
a944e33aa9d02d242e3b9a5867e9416dbc8b4696
https://github.com/spongepowered/sponge/compare/6e443ec04ded4385d12c2e609360e81a770fbfcb...a944e33aa9d02d242e3b9a5867e9416dbc8b4696
diff --git a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java index abf748d92..1f49ee52e 100644 --- a/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java +++ b/src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java @@ -160,17 +160,17 @@ public static Function<ChunkAccess, Stream<Map.Entry<BlockPos, BlockState>>> get return VolumeStreamUtils.getElementByPosition(VolumeStreamUtils.chunkSectionBlockStateGetter(), min, max); } - public static boolean setBiomeOnNativeChunk(final int x, final int y, final int z, final - org.spongepowered.api.world.biome.Biome biome, final Supplier<@Nullable ChunkBiomeContainerAccessor> accessor, + public static boolean setBiomeOnNativeChunk(final int x, final int y, final int z, + final org.spongepowered.api.world.biome.Biome biome, final Supplier<@Nullable ChunkBiomeContainerAccessor> accessor, final Runnable finalizer - ) { + ) { @Nullable final ChunkBiomeContainerAccessor chunkBiomeContainerAccessor = accessor.get(); if (chunkBiomeContainerAccessor == null) { return false; } - final int maskedX = x & ChunkBiomeContainer.HORIZONTAL_MASK; - final int maskedY = Mth.clamp(y, 0, ChunkBiomeContainer.VERTICAL_MASK); - final int maskedZ = z & ChunkBiomeContainer.HORIZONTAL_MASK; + final int maskedX = (x >> 2) & ChunkBiomeContainer.HORIZONTAL_MASK; + final int maskedY = Mth.clamp((y >> 2), 0, ChunkBiomeContainer.VERTICAL_MASK); + final int maskedZ = (z >> 2) & ChunkBiomeContainer.HORIZONTAL_MASK; final int WIDTH_BITS = ChunkBiomeContainerAccessor.accessor$WIDTH_BITS(); final int posKey = maskedY << WIDTH_BITS + WIDTH_BITS | maskedZ << WIDTH_BITS | maskedX; final Biome[] biomes = chunkBiomeContainerAccessor.accessor$biomes(); diff --git a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java index 4a834f244..e7d0f19b6 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java +++ b/src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java @@ -453,7 +453,7 @@ public VolumeStream<W, Entity> entityStream(final Vector3i min, final Vector3i m @SuppressWarnings("rawtypes") @Override public boolean setBiome(final int x, final int y, final int z, final Biome biome) { - if (!((Level) (Object) this).hasChunk(x << 4, z << 4)) { + if (!((Level) (Object) this).hasChunk(x >> 4, z >> 4)) { return false; } final LevelChunk levelChunk = this.shadow$getChunkAt(new BlockPos(x, y, z));
['src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/level/LevelMixin_API.java', 'src/main/java/org/spongepowered/common/world/volume/VolumeStreamUtils.java']
{'.java': 2}
2
2
0
0
2
11,615,757
2,352,623
265,025
2,928
1,043
269
14
2
487
59
141
30
0
1
1970-01-01T00:27:44
358
Java
{'Java': 12523507, 'Kotlin': 74371, 'Shell': 70}
MIT License
791
spongepowered/sponge/3634/3631
spongepowered
sponge
https://github.com/SpongePowered/Sponge/issues/3631
https://github.com/SpongePowered/Sponge/pull/3634
https://github.com/SpongePowered/Sponge/pull/3634
1
fixes
Mekanism Crash On Launch
### Affected Product(s) SpongeForge ### Version spongeforge-1.16.5-36.2.5-8.0.0-RC1073-universal.jar ### Operating System Windows ### Java Version Adopt OpenJDK Hotspot 1.8.0_322 ### Plugins/Mods ```shell SpongeForge Mekanism-1.16.5-10.1.1.456.jar (Latest) ``` ### Describe the bug When both Mekanism and SpongeForge are installed, Minecraft crashes on launch [latest.log](https://github.com/mekanism/Mekanism/files/8066821/latest.log) [debug.log](https://github.com/mekanism/Mekanism/files/8066822/debug.log) [crash-2022-02-15_18.35.43-fml.txt](https://github.com/mekanism/Mekanism/files/8066824/crash-2022-02-15_18.35.43-fml.txt) ### Link to logs _No response_
0ea18fb9665e3a89df7a1bb50bbea40bb56afdbf
5f7b4c58adf9103e17ae9b70a1774adeee9988b0
https://github.com/spongepowered/sponge/compare/0ea18fb9665e3a89df7a1bb50bbea40bb56afdbf...5f7b4c58adf9103e17ae9b70a1774adeee9988b0
diff --git a/forge/src/mixins/java/org/spongepowered/forge/mixin/core/world/entity/item/ItemEntityMixin_Forge.java b/forge/src/mixins/java/org/spongepowered/forge/mixin/core/world/entity/item/ItemEntityMixin_Forge.java index fb2b502d4..1ad9b4ed9 100644 --- a/forge/src/mixins/java/org/spongepowered/forge/mixin/core/world/entity/item/ItemEntityMixin_Forge.java +++ b/forge/src/mixins/java/org/spongepowered/forge/mixin/core/world/entity/item/ItemEntityMixin_Forge.java @@ -42,8 +42,11 @@ public abstract class ItemEntityMixin_Forge { // @formatter:on @Inject(method = "<init>(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/level/Level;)V", at = @At("RETURN")) - private void forge$setLifespanFromConfig(EntityType<? extends ItemEntity> type, Level level, CallbackInfo ci) { - if (!level.isClientSide) { + private void forge$setLifespanFromConfig(final EntityType<? extends ItemEntity> type, final Level level, + final CallbackInfo ci + ) { + // Check the level is not null to avoid an NPE + if (level != null && !level.isClientSide) { this.lifespan = SpongeGameConfigs.getForWorld(level).get().entity.item.despawnRate; } }
['forge/src/mixins/java/org/spongepowered/forge/mixin/core/world/entity/item/ItemEntityMixin_Forge.java']
{'.java': 1}
1
1
0
0
1
11,680,426
2,367,031
266,946
2,940
411
98
7
1
682
49
231
35
3
1
1970-01-01T00:27:25
358
Java
{'Java': 12523507, 'Kotlin': 74371, 'Shell': 70}
MIT License
3,326
ls1intum/artemis/7058/7056
ls1intum
artemis
https://github.com/ls1intum/Artemis/issues/7056
https://github.com/ls1intum/Artemis/pull/7058
https://github.com/ls1intum/Artemis/pull/7058
1
closes
`Programming exercises`: Missing build plan when importing programming exercises
### Describe the bug After importing a programming exercise, the build plan is missing. No inputs can be made, and the wheel in the top bar keeps on spinning. The re-create build plan option also doesn't work. ### To Reproduce 1. Import a programming exercise from instance (meaning from another course, for example) 2. Click on 'Edit Build Plan' 3. The editor is empty and no inputs can be made ### Expected behavior I expect the import to also include the build plan. ### Screenshots ![bpe](https://github.com/ls1intum/Artemis/assets/53149143/d08e9873-6148-4636-89fd-3f087c5973cd) ### Which version of Artemis are you seeing the problem on? 6.3.8 ### What browsers are you seeing the problem on? Chrome ### Additional context _No response_ ### Relevant log output _No response_
e0bd92657cffcb1a92bcbfe52cf5a02522bbb1f4
f57220274d7b74f7ff3cc9bec52c3af82a449cda
https://github.com/ls1intum/artemis/compare/e0bd92657cffcb1a92bcbfe52cf5a02522bbb1f4...f57220274d7b74f7ff3cc9bec52c3af82a449cda
diff --git a/src/main/java/de/tum/in/www1/artemis/repository/BuildPlanRepository.java b/src/main/java/de/tum/in/www1/artemis/repository/BuildPlanRepository.java index 9d6113fb08..ad98dcf17f 100644 --- a/src/main/java/de/tum/in/www1/artemis/repository/BuildPlanRepository.java +++ b/src/main/java/de/tum/in/www1/artemis/repository/BuildPlanRepository.java @@ -44,4 +44,9 @@ public interface BuildPlanRepository extends JpaRepository<BuildPlan, Long> { buildPlanWrapper.addProgrammingExercise(exercise); return save(buildPlanWrapper); } + + default void copyBetweenExercises(ProgrammingExercise sourceExercise, ProgrammingExercise targetExercise) { + BuildPlan buildPlan = findByProgrammingExercises_IdWithProgrammingExercisesElseThrow(sourceExercise.getId()); + setBuildPlanForExercise(buildPlan.getBuildPlan(), targetExercise); + } } diff --git a/src/main/java/de/tum/in/www1/artemis/service/ParticipationService.java b/src/main/java/de/tum/in/www1/artemis/service/ParticipationService.java index 90cb01efe3..4e60f3f109 100644 --- a/src/main/java/de/tum/in/www1/artemis/service/ParticipationService.java +++ b/src/main/java/de/tum/in/www1/artemis/service/ParticipationService.java @@ -449,14 +449,14 @@ public class ParticipationService { private ProgrammingExerciseStudentParticipation copyBuildPlan(ProgrammingExerciseStudentParticipation participation) { // only execute this step if it has not yet been completed yet or if the build plan id is missing for some reason if (!participation.getInitializationState().hasCompletedState(InitializationState.BUILD_PLAN_COPIED) || participation.getBuildPlanId() == null) { - final var projectKey = participation.getProgrammingExercise().getProjectKey(); + final var exercise = participation.getProgrammingExercise(); final var planName = BuildPlanType.TEMPLATE.getName(); final var username = participation.getParticipantIdentifier(); final var buildProjectName = participation.getExercise().getCourseViaExerciseGroupOrCourseMember().getShortName().toUpperCase() + " " + participation.getExercise().getTitle(); final var targetPlanName = participation.addPracticePrefixIfTestRun(username.toUpperCase()); // the next action includes recovery, which means if the build plan has already been copied, we simply retrieve the build plan id and do not copy it again - final var buildPlanId = continuousIntegrationService.orElseThrow().copyBuildPlan(projectKey, planName, projectKey, buildProjectName, targetPlanName, true); + final var buildPlanId = continuousIntegrationService.orElseThrow().copyBuildPlan(exercise, planName, exercise, buildProjectName, targetPlanName, true); participation.setBuildPlanId(buildPlanId); participation.setInitializationState(InitializationState.BUILD_PLAN_COPIED); return programmingExerciseStudentParticipationRepository.saveAndFlush(participation); diff --git a/src/main/java/de/tum/in/www1/artemis/service/connectors/bamboo/BambooService.java b/src/main/java/de/tum/in/www1/artemis/service/connectors/bamboo/BambooService.java index f5c5628d28..24386d0334 100644 --- a/src/main/java/de/tum/in/www1/artemis/service/connectors/bamboo/BambooService.java +++ b/src/main/java/de/tum/in/www1/artemis/service/connectors/bamboo/BambooService.java @@ -352,8 +352,11 @@ public class BambooService extends AbstractContinuousIntegrationService { } @Override - public String copyBuildPlan(String sourceProjectKey, String sourcePlanName, String targetProjectKey, String targetProjectName, String targetPlanName, + public String copyBuildPlan(ProgrammingExercise sourceExercise, String sourcePlanName, ProgrammingExercise targetExercise, String targetProjectName, String targetPlanName, boolean targetProjectExists) { + String sourceProjectKey = sourceExercise.getProjectKey(); + String targetProjectKey = targetExercise.getProjectKey(); + final var cleanPlanName = getCleanPlanName(targetPlanName); final var sourcePlanKey = sourceProjectKey + "-" + sourcePlanName; final var targetPlanKey = targetProjectKey + "-" + cleanPlanName; diff --git a/src/main/java/de/tum/in/www1/artemis/service/connectors/ci/ContinuousIntegrationService.java b/src/main/java/de/tum/in/www1/artemis/service/connectors/ci/ContinuousIntegrationService.java index d87948fb51..21d0b82ed6 100644 --- a/src/main/java/de/tum/in/www1/artemis/service/connectors/ci/ContinuousIntegrationService.java +++ b/src/main/java/de/tum/in/www1/artemis/service/connectors/ci/ContinuousIntegrationService.java @@ -53,15 +53,16 @@ public interface ContinuousIntegrationService { /** * Clones an existing build plan. Illegal characters in the plan key, or name will be replaced. * - * @param sourceProjectKey The key of the source project, normally the key of the exercise -> courseShortName + exerciseShortName. + * @param sourceExercise The exercise from which the build plan should be copied * @param sourcePlanName The name of the source plan - * @param targetProjectKey The key of the project the plan should get copied to + * @param targetExercise The exercise to which the build plan is copied to * @param targetProjectName The wanted name of the new project * @param targetPlanName The wanted name of the new plan after copying it * @param targetProjectExists whether the target project already exists or not * @return The key of the new build plan */ - String copyBuildPlan(String sourceProjectKey, String sourcePlanName, String targetProjectKey, String targetProjectName, String targetPlanName, boolean targetProjectExists); + String copyBuildPlan(ProgrammingExercise sourceExercise, String sourcePlanName, ProgrammingExercise targetExercise, String targetProjectName, String targetPlanName, + boolean targetProjectExists); /** * Configure the build plan with the given participation on the CI system. Common configurations: - update the repository in the build plan - set appropriate user permissions - diff --git a/src/main/java/de/tum/in/www1/artemis/service/connectors/gitlabci/GitLabCIService.java b/src/main/java/de/tum/in/www1/artemis/service/connectors/gitlabci/GitLabCIService.java index 13170b8628..536f49092b 100644 --- a/src/main/java/de/tum/in/www1/artemis/service/connectors/gitlabci/GitLabCIService.java +++ b/src/main/java/de/tum/in/www1/artemis/service/connectors/gitlabci/GitLabCIService.java @@ -193,14 +193,14 @@ public class GitLabCIService extends AbstractContinuousIntegrationService { } @Override - public String copyBuildPlan(String sourceProjectKey, String sourcePlanName, String targetProjectKey, String targetProjectName, String targetPlanName, + public String copyBuildPlan(ProgrammingExercise sourceExercise, String sourcePlanName, ProgrammingExercise targetExercise, String targetProjectName, String targetPlanName, boolean targetProjectExists) { // In GitLab CI we don't have to copy the build plan. // Instead, we configure a CI config path leading to the API when enabling the CI. // When sending the build results back, the build plan key is used to identify the participation. // Therefore, we return the key here even though GitLab CI does not need it. - return targetProjectKey + "-" + targetPlanName.toUpperCase().replaceAll("[^A-Z0-9]", ""); + return targetExercise.getProjectKey() + "-" + targetPlanName.toUpperCase().replaceAll("[^A-Z0-9]", ""); } @Override diff --git a/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/JenkinsService.java b/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/JenkinsService.java index 7a23093332..243e19c584 100644 --- a/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/JenkinsService.java +++ b/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/JenkinsService.java @@ -98,9 +98,9 @@ public class JenkinsService extends AbstractContinuousIntegrationService { } @Override - public String copyBuildPlan(String sourceProjectKey, String sourcePlanName, String targetProjectKey, String targetProjectName, String targetPlanName, + public String copyBuildPlan(ProgrammingExercise sourceExercise, String sourcePlanName, ProgrammingExercise targetExercise, String targetProjectName, String targetPlanName, boolean targetProjectExists) { - return jenkinsBuildPlanService.copyBuildPlan(sourceProjectKey, sourcePlanName, targetProjectKey, targetPlanName); + return jenkinsBuildPlanService.copyBuildPlan(sourceExercise, sourcePlanName, targetExercise, targetPlanName); } @Override diff --git a/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/build_plan/JenkinsBuildPlanService.java b/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/build_plan/JenkinsBuildPlanService.java index 0a94f3a2ab..f756160991 100644 --- a/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/build_plan/JenkinsBuildPlanService.java +++ b/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/build_plan/JenkinsBuildPlanService.java @@ -37,6 +37,7 @@ import de.tum.in.www1.artemis.domain.enumeration.ProjectType; import de.tum.in.www1.artemis.domain.enumeration.RepositoryType; import de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseParticipation; import de.tum.in.www1.artemis.exception.JenkinsException; +import de.tum.in.www1.artemis.repository.BuildPlanRepository; import de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository; import de.tum.in.www1.artemis.repository.UserRepository; import de.tum.in.www1.artemis.service.connectors.ci.ContinuousIntegrationService; @@ -78,9 +79,12 @@ public class JenkinsBuildPlanService { private final ProgrammingExerciseRepository programmingExerciseRepository; + private final BuildPlanRepository buildPlanRepository; + public JenkinsBuildPlanService(@Qualifier("jenkinsRestTemplate") RestTemplate restTemplate, JenkinsServer jenkinsServer, JenkinsBuildPlanCreator jenkinsBuildPlanCreator, JenkinsJobService jenkinsJobService, JenkinsJobPermissionsService jenkinsJobPermissionsService, JenkinsInternalUrlService jenkinsInternalUrlService, - UserRepository userRepository, ProgrammingExerciseRepository programmingExerciseRepository, JenkinsPipelineScriptCreator jenkinsPipelineScriptCreator) { + UserRepository userRepository, ProgrammingExerciseRepository programmingExerciseRepository, JenkinsPipelineScriptCreator jenkinsPipelineScriptCreator, + BuildPlanRepository buildPlanRepository) { this.restTemplate = restTemplate; this.jenkinsServer = jenkinsServer; this.jenkinsBuildPlanCreator = jenkinsBuildPlanCreator; @@ -90,6 +94,7 @@ public class JenkinsBuildPlanService { this.programmingExerciseRepository = programmingExerciseRepository; this.jenkinsInternalUrlService = jenkinsInternalUrlService; this.jenkinsPipelineScriptCreator = jenkinsPipelineScriptCreator; + this.buildPlanRepository = buildPlanRepository; } /** @@ -233,13 +238,20 @@ public class JenkinsBuildPlanService { /** * Copies a build plan to another and replaces the old reference to the master and main branch with a reference to the default branch * - * @param sourceProjectKey the source project key - * @param sourcePlanName the source plan name - * @param targetProjectKey the target project key - * @param targetPlanName the target plan name + * @param sourceExercise the source exercise + * @param sourcePlanName the source plan name + * @param targetExercise the target exercise + * @param targetPlanName the target plan name * @return the key of the created build plan */ - public String copyBuildPlan(String sourceProjectKey, String sourcePlanName, String targetProjectKey, String targetPlanName) { + public String copyBuildPlan(ProgrammingExercise sourceExercise, String sourcePlanName, ProgrammingExercise targetExercise, String targetPlanName) { + buildPlanRepository.copyBetweenExercises(sourceExercise, targetExercise); + targetExercise.generateAndSetBuildPlanAccessSecret(); + targetExercise = programmingExerciseRepository.save(targetExercise); + + String sourceProjectKey = sourceExercise.getProjectKey(); + String targetProjectKey = targetExercise.getProjectKey(); + final var cleanTargetName = getCleanPlanName(targetPlanName); final var sourcePlanKey = sourceProjectKey + "-" + sourcePlanName; final var targetPlanKey = targetProjectKey + "-" + cleanTargetName; @@ -362,7 +374,7 @@ public class JenkinsBuildPlanService { /** * Assigns access permissions to instructors and TAs for the specified build plan. * This is done by getting all users that belong to the instructor and TA groups of - * the exercise' course and adding permissions to the Jenkins job. + * the exercises' course and adding permissions to the Jenkins job. * * @param programmingExercise the programming exercise * @param planName the name of the build plan diff --git a/src/main/java/de/tum/in/www1/artemis/service/connectors/localci/LocalCIService.java b/src/main/java/de/tum/in/www1/artemis/service/connectors/localci/LocalCIService.java index ed969ec8f0..23579184d3 100644 --- a/src/main/java/de/tum/in/www1/artemis/service/connectors/localci/LocalCIService.java +++ b/src/main/java/de/tum/in/www1/artemis/service/connectors/localci/LocalCIService.java @@ -110,11 +110,11 @@ public class LocalCIService extends AbstractContinuousIntegrationService { } @Override - public String copyBuildPlan(String sourceProjectKey, String sourcePlanName, String targetProjectKey, String targetProjectName, String targetPlanName, + public String copyBuildPlan(ProgrammingExercise sourceExercise, String sourcePlanName, ProgrammingExercise targetExercise, String targetProjectName, String targetPlanName, boolean targetProjectExists) { // No build plans exist for local CI. Only return a plan name. final String cleanPlanName = getCleanPlanName(targetPlanName); - return targetProjectKey + "-" + cleanPlanName; + return targetExercise.getProjectKey() + "-" + cleanPlanName; } @Override diff --git a/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseImportService.java b/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseImportService.java index 317e591956..c9c0eafc4d 100644 --- a/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseImportService.java +++ b/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseImportService.java @@ -200,8 +200,8 @@ public class ProgrammingExerciseImportService { final var targetKey = newExercise.getProjectKey(); final var targetName = newExercise.getCourseViaExerciseGroupOrCourseMember().getShortName().toUpperCase() + " " + newExercise.getTitle(); continuousIntegrationService.orElseThrow().createProjectForExercise(newExercise); - continuousIntegrationService.get().copyBuildPlan(templateKey, templatePlanName, targetKey, targetName, templatePlanName, false); - continuousIntegrationService.get().copyBuildPlan(templateKey, solutionPlanName, targetKey, targetName, solutionPlanName, true); + continuousIntegrationService.get().copyBuildPlan(templateExercise, templatePlanName, newExercise, targetName, templatePlanName, false); + continuousIntegrationService.get().copyBuildPlan(templateExercise, solutionPlanName, newExercise, targetName, solutionPlanName, true); continuousIntegrationService.get().givePlanPermissions(newExercise, templatePlanName); continuousIntegrationService.get().givePlanPermissions(newExercise, solutionPlanName); programmingExerciseService.giveCIProjectPermissions(newExercise); diff --git a/src/test/java/de/tum/in/www1/artemis/service/GitlabCIServiceTest.java b/src/test/java/de/tum/in/www1/artemis/service/GitlabCIServiceTest.java index e9360f48a2..228ae25390 100644 --- a/src/test/java/de/tum/in/www1/artemis/service/GitlabCIServiceTest.java +++ b/src/test/java/de/tum/in/www1/artemis/service/GitlabCIServiceTest.java @@ -22,6 +22,7 @@ import org.springframework.security.test.context.support.WithMockUser; import de.tum.in.www1.artemis.AbstractSpringIntegrationGitlabCIGitlabSamlTest; import de.tum.in.www1.artemis.domain.BuildLogEntry; +import de.tum.in.www1.artemis.domain.Course; import de.tum.in.www1.artemis.domain.ProgrammingExercise; import de.tum.in.www1.artemis.domain.enumeration.ProgrammingLanguage; import de.tum.in.www1.artemis.domain.enumeration.ProjectType; @@ -241,15 +242,20 @@ class GitlabCIServiceTest extends AbstractSpringIntegrationGitlabCIGitlabSamlTes @Test @WithMockUser(username = TEST_PREFIX + "instructor1", roles = "INSTRUCTOR") void testCopyBuildPlan() { - final String targetProjectKey = "TARGETPROJECTKEY"; + final Course course = new Course(); + final ProgrammingExercise targetExercise = new ProgrammingExercise(); + course.addExercises(targetExercise); + targetExercise.generateAndSetProjectKey(); + + final String targetProjectKey = targetExercise.getProjectKey(); final String targetPlanName1 = "TARGETPLANNAME1"; final String targetPlanName2 = "target-plan-name-#2"; - final String expectedBuildPlanKey1 = "TARGETPROJECTKEY-TARGETPLANNAME1"; - final String expectedBuildPlanKey2 = "TARGETPROJECTKEY-TARGETPLANNAME2"; + final String expectedBuildPlanKey1 = targetProjectKey + "-TARGETPLANNAME1"; + final String expectedBuildPlanKey2 = targetProjectKey + "-TARGETPLANNAME2"; - assertThat(continuousIntegrationService.copyBuildPlan(null, null, targetProjectKey, null, targetPlanName1, false)).isEqualTo(expectedBuildPlanKey1); - assertThat(continuousIntegrationService.copyBuildPlan(null, null, targetProjectKey, null, targetPlanName2, false)).isEqualTo(expectedBuildPlanKey2); + assertThat(continuousIntegrationService.copyBuildPlan(null, null, targetExercise, null, targetPlanName1, false)).isEqualTo(expectedBuildPlanKey1); + assertThat(continuousIntegrationService.copyBuildPlan(null, null, targetExercise, null, targetPlanName2, false)).isEqualTo(expectedBuildPlanKey2); } @Test diff --git a/src/test/java/de/tum/in/www1/artemis/service/JenkinsServiceTest.java b/src/test/java/de/tum/in/www1/artemis/service/JenkinsServiceTest.java index 7501e70093..ba35d12081 100644 --- a/src/test/java/de/tum/in/www1/artemis/service/JenkinsServiceTest.java +++ b/src/test/java/de/tum/in/www1/artemis/service/JenkinsServiceTest.java @@ -25,11 +25,15 @@ import org.springframework.util.StreamUtils; import com.offbytwo.jenkins.model.JobWithDetails; import de.tum.in.www1.artemis.AbstractSpringIntegrationJenkinsGitlabTest; +import de.tum.in.www1.artemis.course.CourseUtilService; +import de.tum.in.www1.artemis.domain.BuildPlan; +import de.tum.in.www1.artemis.domain.ProgrammingExercise; import de.tum.in.www1.artemis.domain.enumeration.ProgrammingLanguage; import de.tum.in.www1.artemis.exception.JenkinsException; import de.tum.in.www1.artemis.exercise.programmingexercise.ContinuousIntegrationTestService; import de.tum.in.www1.artemis.exercise.programmingexercise.ProgrammingExerciseUtilService; import de.tum.in.www1.artemis.participation.ParticipationUtilService; +import de.tum.in.www1.artemis.repository.BuildPlanRepository; import de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository; import de.tum.in.www1.artemis.service.programming.ProgrammingExerciseImportService; @@ -52,6 +56,12 @@ class JenkinsServiceTest extends AbstractSpringIntegrationJenkinsGitlabTest { @Autowired private ParticipationUtilService participationUtilService; + @Autowired + private CourseUtilService courseUtilService; + + @Autowired + private BuildPlanRepository buildPlanRepository; + /** * This method initializes the test case by setting up a local repo */ @@ -256,4 +266,29 @@ class JenkinsServiceTest extends AbstractSpringIntegrationJenkinsGitlabTest { List.of()); }).withMessageStartingWith("Error trying to configure build plan in Jenkins"); } + + @Test + @WithMockUser(roles = "INSTRUCTOR", username = TEST_PREFIX + "instructor1") + void testCopyBuildPlan() throws IOException { + var course = courseUtilService.addEmptyCourse(); + + ProgrammingExercise sourceExercise = new ProgrammingExercise(); + course.addExercises(sourceExercise); + sourceExercise.generateAndSetProjectKey(); + sourceExercise = programmingExerciseRepository.save(sourceExercise); + String buildPlanContent = "this is just to test if the build plan is copied correctly"; + buildPlanRepository.setBuildPlanForExercise(buildPlanContent, sourceExercise); + + ProgrammingExercise targetExercise = new ProgrammingExercise(); + course.addExercises(targetExercise); + targetExercise.generateAndSetProjectKey(); + targetExercise = programmingExerciseRepository.save(targetExercise); + + jenkinsRequestMockProvider.mockCopyBuildPlan(sourceExercise.getProjectKey(), targetExercise.getProjectKey()); + + continuousIntegrationService.copyBuildPlan(sourceExercise, "", targetExercise, "", "", true); + BuildPlan sourceBuildPlan = buildPlanRepository.findByProgrammingExercises_IdWithProgrammingExercisesElseThrow(sourceExercise.getId()); + BuildPlan targetBuildPlan = buildPlanRepository.findByProgrammingExercises_IdWithProgrammingExercisesElseThrow(targetExercise.getId()); + assertThat(sourceBuildPlan).isEqualTo(targetBuildPlan); + } }
['src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseImportService.java', 'src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/JenkinsService.java', 'src/main/java/de/tum/in/www1/artemis/service/connectors/gitlabci/GitLabCIService.java', 'src/main/java/de/tum/in/www1/artemis/service/connectors/ci/ContinuousIntegrationService.java', 'src/test/java/de/tum/in/www1/artemis/service/GitlabCIServiceTest.java', 'src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/build_plan/JenkinsBuildPlanService.java', 'src/main/java/de/tum/in/www1/artemis/service/ParticipationService.java', 'src/test/java/de/tum/in/www1/artemis/service/JenkinsServiceTest.java', 'src/main/java/de/tum/in/www1/artemis/service/connectors/localci/LocalCIService.java', 'src/main/java/de/tum/in/www1/artemis/service/connectors/bamboo/BambooService.java', 'src/main/java/de/tum/in/www1/artemis/repository/BuildPlanRepository.java']
{'.java': 11}
11
11
0
0
11
7,326,194
1,453,958
160,946
1,268
5,987
1,144
63
9
831
119
201
36
1
0
1970-01-01T00:28:11
354
Java
{'Java': 13557695, 'TypeScript': 11937642, 'HTML': 2646433, 'SCSS': 351993, 'Scala': 203267, 'JavaScript': 145109, 'Shell': 96776, 'Python': 65037, 'Swift': 47826, 'PHP': 30694, 'OCaml': 30536, 'Groovy': 23787, 'CSS': 14104, 'Assembly': 12789, 'Kotlin': 8996, 'Dockerfile': 6710, 'Haskell': 4691, 'C': 4480, 'VHDL': 4142}
MIT License
3,327
ls1intum/artemis/6842/6691
ls1intum
artemis
https://github.com/ls1intum/Artemis/issues/6691
https://github.com/ls1intum/Artemis/pull/6842
https://github.com/ls1intum/Artemis/pull/6842
1
fix
Outdated activation links shouldn't cause a full stracktrace in server logs
### Describe the bug Clicking outdated activation links lead to an internal server error with full stacktrace in the server logs and make me, as a server admin, think that something really bad has happened (i.e., sth that needs further investigation). ### To Reproduce 1. Go to `/account/activate?key=foo`. 2. Check the server logs and see an *Internal Server Error* in from `o.z.problem.spring.common.AdviceTraits`. ### Expected behavior There should be only an `INFO` log line mentioning that the activation key XYZ was not found or is otherwise invalid. ### Screenshots _No response_ ### Which version of Artemis are you seeing the problem on? 6.2.1 ### What browsers are you seeing the problem on? Firefox ### Additional context _No response_ ### Relevant log output ```shell 2023-06-08 12:14:16.223 ERROR 264042 --- [.1-8080-exec-68] o.z.problem.spring.common.AdviceTraits : Internal Server Error de.tum.in.www1.artemis.web.rest.errors.InternalServerErrorException: No user was found for this activation key at de.tum.in.www1.artemis.web.rest.AccountResource.activateAccount(AccountResource.java:116) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1072) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:965) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) at javax.servlet.http.HttpServlet.service(HttpServlet.java:497) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:584) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:209) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:111) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) at de.tum.in.www1.artemis.config.ApiVersionFilter.doFilter(ApiVersionFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) at io.sentry.spring.SentryUserFilter.doFilterInternal(SentryUserFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:337) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at de.tum.in.www1.artemis.security.jwt.JWTFilter.doFilter(JWTFilter.java:36) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at de.tum.in.www1.artemis.security.lti.Lti13LaunchFilter.doFilterInternal(Lti13LaunchFilter.java:51) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at uk.ac.ox.ctl.lti13.security.oauth2.client.lti.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:147) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346) at org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ... ```
83ae671d4b0123c59fa86f658c50d800091ef78e
8993f16e21a55773c0c30f5c0016da5b92822781
https://github.com/ls1intum/artemis/compare/83ae671d4b0123c59fa86f658c50d800091ef78e...8993f16e21a55773c0c30f5c0016da5b92822781
diff --git a/src/main/java/de/tum/in/www1/artemis/web/rest/open/PublicAccountResource.java b/src/main/java/de/tum/in/www1/artemis/web/rest/open/PublicAccountResource.java index 75fa9cd1af..0db3d9347f 100644 --- a/src/main/java/de/tum/in/www1/artemis/web/rest/open/PublicAccountResource.java +++ b/src/main/java/de/tum/in/www1/artemis/web/rest/open/PublicAccountResource.java @@ -34,7 +34,6 @@ import de.tum.in.www1.artemis.web.rest.errors.AccessForbiddenException; import de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException; import de.tum.in.www1.artemis.web.rest.errors.EmailAlreadyUsedException; import de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException; -import de.tum.in.www1.artemis.web.rest.errors.InternalServerErrorException; import de.tum.in.www1.artemis.web.rest.errors.LoginAlreadyUsedException; import de.tum.in.www1.artemis.web.rest.errors.PasswordViolatesRequirementsException; import de.tum.in.www1.artemis.web.rest.vm.KeyAndPasswordVM; @@ -104,7 +103,8 @@ public class PublicAccountResource { * {@code GET /activate} : activate the registered user. * * @param key the activation key. - * @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be activated. + * @throws AccessForbiddenException {@code 403 (Forbidden)} if the user registration is disabled + * @throws EntityNotFoundException {@code 404 (Not Found)} if the user provided an invalid activation key */ @GetMapping("activate") @EnforceNothing @@ -114,7 +114,7 @@ public class PublicAccountResource { } Optional<User> user = userService.activateRegistration(key); if (user.isEmpty()) { - throw new InternalServerErrorException("No user was found for this activation key"); + throw new EntityNotFoundException("Activation key", key); } } diff --git a/src/test/java/de/tum/in/www1/artemis/user/AccountResourceIntegrationTest.java b/src/test/java/de/tum/in/www1/artemis/user/AccountResourceIntegrationTest.java index 3196f743ef..3ab808db34 100644 --- a/src/test/java/de/tum/in/www1/artemis/user/AccountResourceIntegrationTest.java +++ b/src/test/java/de/tum/in/www1/artemis/user/AccountResourceIntegrationTest.java @@ -224,7 +224,7 @@ class AccountResourceIntegrationTest extends AbstractSpringIntegrationBambooBitb void activateAccountNoUser() throws Exception { LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("key", ""); - request.get("/api/public/activate", HttpStatus.INTERNAL_SERVER_ERROR, String.class, params); + request.get("/api/public/activate", HttpStatus.NOT_FOUND, String.class, params); } @Test diff --git a/src/test/java/de/tum/in/www1/artemis/user/AccountResourceWithGitLabIntegrationTest.java b/src/test/java/de/tum/in/www1/artemis/user/AccountResourceWithGitLabIntegrationTest.java index d6408dd9f0..638b475273 100644 --- a/src/test/java/de/tum/in/www1/artemis/user/AccountResourceWithGitLabIntegrationTest.java +++ b/src/test/java/de/tum/in/www1/artemis/user/AccountResourceWithGitLabIntegrationTest.java @@ -247,7 +247,7 @@ class AccountResourceWithGitLabIntegrationTest extends AbstractSpringIntegration // Activate the user gitlabRequestMockProvider.mockActivateUser(user.getLogin(), true); String activationKey = registeredUser.get().getActivationKey(); - request.get("/api/public/activate?key=" + activationKey, HttpStatus.INTERNAL_SERVER_ERROR, Void.class); + request.get("/api/public/activate?key=" + activationKey, HttpStatus.NOT_FOUND, Void.class); verify(gitlabRequestMockProvider.getMockedUserApi()).unblockUser(anyLong()); assertThat(registeredUser.get().getActivationKey()).isNotNull();
['src/test/java/de/tum/in/www1/artemis/user/AccountResourceWithGitLabIntegrationTest.java', 'src/main/java/de/tum/in/www1/artemis/web/rest/open/PublicAccountResource.java', 'src/test/java/de/tum/in/www1/artemis/user/AccountResourceIntegrationTest.java']
{'.java': 3}
3
3
0
0
3
7,297,855
1,448,505
160,660
1,267
562
110
6
1
9,550
295
1,848
112
0
1
1970-01-01T00:28:08
354
Java
{'Java': 13557695, 'TypeScript': 11937642, 'HTML': 2646433, 'SCSS': 351993, 'Scala': 203267, 'JavaScript': 145109, 'Shell': 96776, 'Python': 65037, 'Swift': 47826, 'PHP': 30694, 'OCaml': 30536, 'Groovy': 23787, 'CSS': 14104, 'Assembly': 12789, 'Kotlin': 8996, 'Dockerfile': 6710, 'Haskell': 4691, 'C': 4480, 'VHDL': 4142}
MIT License
137
dita-ot/dita-ot/3925/3917
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3917
https://github.com/dita-ot/dita-ot/pull/3925
https://github.com/dita-ot/dita-ot/pull/3925
2
fixes
if parallel=true, some files are not rendered
## Expected Behavior all files are rendered ## Actual Behavior some files are skipped with error "folder could not be created". seemingly randomly in documents, but consistently between builds ## Steps to Reproduce render a document with a lot of topics in the same subfolder (?) ## Copy of the error message, log file or stack trace [xslt] Failed to transform document: Failed to transform document: Failed to create directory ## Environment * DITA-OT version: 3.7.1, 3.6.1 * Operating system and version: Linux, Windows * How did you run DITA-OT? `dita` command * Transformation type: HTML5
d7e92f038accc942c386ee1935aaffdb619f9514
8798c69e8876d309cec447a916321cd15112d3ec
https://github.com/dita-ot/dita-ot/compare/d7e92f038accc942c386ee1935aaffdb619f9514...8798c69e8876d309cec447a916321cd15112d3ec
diff --git a/src/main/java/org/dita/dost/ant/DITAOTCopy.java b/src/main/java/org/dita/dost/ant/DITAOTCopy.java index 391df9948..144498391 100644 --- a/src/main/java/org/dita/dost/ant/DITAOTCopy.java +++ b/src/main/java/org/dita/dost/ant/DITAOTCopy.java @@ -13,6 +13,8 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -89,9 +91,16 @@ public final class DITAOTCopy extends Task { if (destDir == null) { throw new BuildException("Destination directory not defined"); } - if (!destDir.exists() && !destDir.mkdirs()) { - throw new BuildException(new IOException("Destination directory " + destDir + " cannot be created")); + if (!destDir.exists()) { + try { + Files.createDirectories(destDir.toPath()); + } catch (FileAlreadyExistsException e) { + // Ignore + } catch (IOException e) { + throw new BuildException(e); + } } + try { final FileUtils fileUtils = FileUtils.newFileUtils(); final List<String> incs = getIncludes(); diff --git a/src/main/java/org/dita/dost/module/TopicMergeModule.java b/src/main/java/org/dita/dost/module/TopicMergeModule.java index cc3e72089..bd814e547 100644 --- a/src/main/java/org/dita/dost/module/TopicMergeModule.java +++ b/src/main/java/org/dita/dost/module/TopicMergeModule.java @@ -22,6 +22,8 @@ import org.dita.dost.util.Job.FileInfo; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE; import static org.dita.dost.util.Constants.*; @@ -84,8 +86,14 @@ final class TopicMergeModule extends AbstractPipelineModuleImpl { } final File outputDir = out.getParentFile(); - if (!outputDir.exists() && !outputDir.mkdirs()) { - logger.error("Failed to create directory " + outputDir.getAbsolutePath()); + if (!outputDir.exists()) { + try { + Files.createDirectories(outputDir.toPath()); + } catch (FileAlreadyExistsException e) { + // Ignore + } catch (IOException e) { + logger.error("Failed to create directory " + outputDir.getAbsolutePath()); + } } try (final OutputStream output = new BufferedOutputStream(job.getStore().getOutputStream(out.toURI()))) { if (style != null) { diff --git a/src/main/java/org/dita/dost/module/filter/TopicBranchFilterModule.java b/src/main/java/org/dita/dost/module/filter/TopicBranchFilterModule.java index f8ea99b66..485b26714 100644 --- a/src/main/java/org/dita/dost/module/filter/TopicBranchFilterModule.java +++ b/src/main/java/org/dita/dost/module/filter/TopicBranchFilterModule.java @@ -21,6 +21,8 @@ import org.xml.sax.XMLFilter; import java.io.File; import java.io.IOException; import java.net.URI; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -128,8 +130,14 @@ public final class TopicBranchFilterModule extends AbstractBranchFilterModule { final List<XMLFilter> pipe = singletonList(writer); final File dstDirUri = new File(dstAbsUri.resolve(".")); - if (!dstDirUri.exists() && !dstDirUri.mkdirs()) { - logger.error("Failed to create directory " + dstDirUri); + if (!dstDirUri.exists()) { + try { + Files.createDirectories(dstDirUri.toPath()); + } catch (FileAlreadyExistsException e) { + // Ignore + } catch (IOException e) { + logger.error("Failed to create directory " + dstDirUri); + } } try { job.getStore().transform(srcAbsUri, dstAbsUri, pipe); diff --git a/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java b/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java index f90100b7f..b55d8ca83 100644 --- a/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java +++ b/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java @@ -29,6 +29,8 @@ import org.xml.sax.helpers.DefaultHandler; import javax.xml.namespace.QName; import java.io.*; import java.net.URI; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; @@ -336,9 +338,15 @@ public abstract class AbstractReaderModule extends AbstractPipelineModuleImpl { final URI rel = tempFileNameScheme.generateTempFileName(currentFile); outputFile = new File(job.tempDirURI.resolve(rel)); final File outputDir = outputFile.getParentFile(); - if (!outputDir.exists() && !outputDir.mkdirs()) { - logger.error("Failed to create output directory " + outputDir.getAbsolutePath()); - return; + if (!outputDir.exists()) { + try { + Files.createDirectories(outputDir.toPath()); + } catch (FileAlreadyExistsException e) { + // Ignore + } catch (IOException e) { + logger.error("Failed to create output directory " + outputDir.getAbsolutePath()); + return; + } } validateMap = Collections.emptyMap(); defaultValueMap = Collections.emptyMap(); diff --git a/src/main/java/org/dita/dost/store/StreamStore.java b/src/main/java/org/dita/dost/store/StreamStore.java index 2a36e1a7b..862f81ba3 100644 --- a/src/main/java/org/dita/dost/store/StreamStore.java +++ b/src/main/java/org/dita/dost/store/StreamStore.java @@ -28,6 +28,7 @@ import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.net.URI; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; @@ -164,11 +165,6 @@ public class StreamStore extends AbstractStore implements Store { @Override void transformURI(final URI input, final URI output, final List<XMLFilter> filters) throws DITAOTException { - final File outputFile = new File(output); - if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { - throw new DITAOTException("Failed to create output directory " + outputFile.getParentFile().getAbsolutePath()); - } - try { XMLReader reader = xmlUtils.getXMLReader(); for (final XMLFilter filter : filters) { @@ -238,8 +234,12 @@ public class StreamStore extends AbstractStore implements Store { Serializer getSerializer(final URI dst) throws IOException { final File outputFile = new File(dst); final File dir = outputFile.getParentFile(); - if (!dir.exists() && !dir.mkdirs()) { - throw new IOException("Failed to create directory " + dir.getAbsolutePath()); + if (!dir.exists()) { + try { + Files.createDirectories(dir.toPath()); + } catch (FileAlreadyExistsException e) { + // Ignore + } } return xmlUtils.getProcessor().newSerializer(outputFile); } diff --git a/src/main/java/org/dita/dost/util/XMLUtils.java b/src/main/java/org/dita/dost/util/XMLUtils.java index 58e6f800e..75062c71b 100644 --- a/src/main/java/org/dita/dost/util/XMLUtils.java +++ b/src/main/java/org/dita/dost/util/XMLUtils.java @@ -32,6 +32,8 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.net.URI; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -650,8 +652,14 @@ public final class XMLUtils { */ @Deprecated private void transformFile(final File inputFile, final File outputFile, final List<XMLFilter> filters) throws DITAOTException { - if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { - throw new DITAOTException("Failed to create output directory " + outputFile.getParentFile().getAbsolutePath()); + if (!outputFile.getParentFile().exists()) { + try { + Files.createDirectories(outputFile.getParentFile().toPath()); + } catch (FileAlreadyExistsException e) { + // Ignore + } catch (IOException e) { + throw new DITAOTException(e); + } } try (final InputStream in = new BufferedInputStream(new FileInputStream(inputFile)); @@ -703,8 +711,14 @@ public final class XMLUtils { @Deprecated private void transformURI(final URI input, final URI output, final List<XMLFilter> filters) throws DITAOTException { final File outputFile = new File(output); - if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { - throw new DITAOTException("Failed to create output directory " + outputFile.getParentFile().getAbsolutePath()); + if (!outputFile.getParentFile().exists()) { + try { + Files.createDirectories(outputFile.getParentFile().toPath()); + } catch (FileAlreadyExistsException e) { + // Ignore + } catch (IOException e) { + throw new DITAOTException(e); + } } try {
['src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java', 'src/main/java/org/dita/dost/ant/DITAOTCopy.java', 'src/main/java/org/dita/dost/util/XMLUtils.java', 'src/main/java/org/dita/dost/module/TopicMergeModule.java', 'src/main/java/org/dita/dost/store/StreamStore.java', 'src/main/java/org/dita/dost/module/filter/TopicBranchFilterModule.java']
{'.java': 6}
6
6
0
0
6
1,932,613
397,368
51,655
247
4,205
764
87
6
626
96
148
22
0
0
1970-01-01T00:27:32
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
136
dita-ot/dita-ot/3943/3934
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3934
https://github.com/dita-ot/dita-ot/pull/3943
https://github.com/dita-ot/dita-ot/pull/3943
1
fixes
DITA-OT 3.6 or above can't handle Input file of non-ASCII path.
## Expected Behavior <!-- If you're describing a bug, tell us what should happen. --> Input file of non-ASCII path should be processed properly. ## Actual Behavior <!-- Tell us what happens instead of the expected behavior. --> When the full path of input file contains non-ASCII characters, a fatal error occurs. This behavior depends on DITA-OT version. - 3.7.2 -> Failed - 3.6.1 -> Failed - 3.5.4 -> Success ## Possible Solution <!-- Optional suggestions on how to fix the issue, or implement the changes. --> <!-- If you know how to fix the issue, please create a pull request instead. --> Probably the direct cause of this error is the encoding of .job.xml file created in Temp directory. The encoding of .job.xml file is Shift-JIS which is the default encoding of Japanese environment. ## Steps to Reproduce <!-- Test case, Gist, set of files or steps required to reproduce the issue. --> 1. Unzip the following sample to some directory. 2. run dita command `dita.bat -i .\\サンプル\\hierarchy.ditamap -f pdf` [DITA-OT_non-ASCII_path_sample.zip](https://github.com/dita-ot/dita-ot/files/8849315/DITA-OT_non-ASCII_path_sample.zip) <!-- Create a Gist via <https://gist.github.com/> to upload your test files. --> <!-- Link to the Gist from the issue or attach a .zip archive of your files. --> ## Copy of the error message, log file or stack trace <!-- Long logs should be attached or in linked Gists, not in the issue body. --> ``` C:\\Temp\\DITA-OT_issue> C:\\apl\\dita-ot-3.7.2\\bin\\dita.bat -i .\\サンプル\\hierarchy.ditamap -f pdf [pipeline] Error reported by XML parser: Invalid byte 1 of 1-byte UTF-8 sequence. [pipeline] Failed to transform document: Failed to transform document: org.xml.sax.SAXParseException; systemId: file:/C:/Users/lis74h/AppData/Local/Temp/temp20220607095738941/.job.xml; lineNumber: 1; columnNumber: 90; Invalid byte 1 of 1-byte UTF-8 sequence. [i18n-preprocess] [Fatal Error] stage2.fo:86:159: XML document structures must start and end within the same entity. Error: The following error occurred while executing this line: C:\\apl\\dita-ot-3.7.2\\plugins\\org.dita.pdf2\\build.xml:337: java.io.IOException: Failed to read document: XML document structures must start and end within the same entity. ``` .job.xml file in Temp directory: [job_xml.zip](https://github.com/dita-ot/dita-ot/files/8849398/job_xml.zip) ## Environment <!-- Include relevant details about the environment you experienced this in. --> * DITA-OT version: 3.7.2 * Operating system and version: Windows 10 21H2 * How did you run DITA-OT? dita command * Transformation type: PDF <!-- Before submitting, check the Preview tab above to verify the XML markup appears correctly and remember you can edit the description later to add information. -->
a9c3ae5dcedb48148983acac752053656bdc3df7
432a61104f85196755100c44062e8ab2b905dd32
https://github.com/dita-ot/dita-ot/compare/a9c3ae5dcedb48148983acac752053656bdc3df7...432a61104f85196755100c44062e8ab2b905dd32
diff --git a/src/main/java/org/dita/dost/util/Job.java b/src/main/java/org/dita/dost/util/Job.java index 0b930f263..dc961eb94 100644 --- a/src/main/java/org/dita/dost/util/Job.java +++ b/src/main/java/org/dita/dost/util/Job.java @@ -27,6 +27,8 @@ import javax.xml.transform.dom.DOMResult; import java.io.*; import java.lang.reflect.Field; import java.net.URI; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.*; @@ -310,7 +312,7 @@ public final class Job { * @throws IOException if writing configuration files failed */ public void write() throws IOException { - try (Writer outStream = new BufferedWriter(new OutputStreamWriter(getStore().getOutputStream(jobFile.toURI())))) { + try (Writer outStream = new BufferedWriter(new OutputStreamWriter(getStore().getOutputStream(jobFile.toURI()), StandardCharsets.UTF_8))) { XMLStreamWriter out = null; try { out = XMLOutputFactory.newInstance().createXMLStreamWriter(outStream); diff --git a/src/test/java/org/dita/dost/util/JobTest.java b/src/test/java/org/dita/dost/util/JobTest.java index 7930e5b6e..1cbda8ebc 100644 --- a/src/test/java/org/dita/dost/util/JobTest.java +++ b/src/test/java/org/dita/dost/util/JobTest.java @@ -12,9 +12,13 @@ import static org.dita.dost.util.Constants.*; import static org.dita.dost.util.URLUtils.*; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Field; import java.net.URI; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -23,7 +27,7 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; - +import org.apache.commons.io.FileUtils; import org.dita.dost.TestUtils; public final class JobTest { @@ -91,6 +95,31 @@ public final class JobTest { final long end = System.currentTimeMillis(); System.out.println(((end - start)) + " ms"); } + + @Test + public void writeUTF8() throws Exception { + //Reset default encoding field in order to re-compute it after setting the file.encoding system property. + Field defaultCSField = Class.forName("java.nio.charset.Charset").getDeclaredField("defaultCharset"); + defaultCSField.setAccessible(true); + defaultCSField.set(null, null); + String initialEncoding = System.getProperty("file.encoding"); + try { + System.getProperties().setProperty("file.encoding", "ASCII"); + job.add(Job.FileInfo.builder() + .src(new File(tempDir, "\\u633F.dita").toURI()) + .uri(new File("\\u633F.dita").toURI()) + .result(new File(tempDir, "\\u633F.html").toURI()) + .format("dita") + .hasKeyref(true) + .hasLink(true) + .build()); + job.write(); + File jobFile = new File(tempDir, ".job.xml"); + assertTrue(FileUtils.readFileToString(jobFile, StandardCharsets.UTF_8).contains("\\u633F.dita")); + } finally { + System.getProperties().setProperty("file.encoding", initialEncoding); + } + } @AfterClass public static void tearDown() throws IOException {
['src/main/java/org/dita/dost/util/Job.java', 'src/test/java/org/dita/dost/util/JobTest.java']
{'.java': 2}
2
2
0
0
2
1,933,791
397,552
51,702
247
348
67
4
1
2,801
384
725
56
3
1
1970-01-01T00:27:35
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
135
dita-ot/dita-ot/3960/3959
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3959
https://github.com/dita-ot/dita-ot/pull/3960
https://github.com/dita-ot/dita-ot/pull/3960
1
fixes
Guard against possible NPE in XMLUtils.toErrorReporter(DITAOTLogger)
Using an invalid plugin I got this NPE in the XMLUtils.toErrorReporter method: .... java.lang.NullPointerException: Cannot invoke "net.sf.saxon.s9api.Location.getSystemId()" because the return value of "net.sf.saxon.s9api.XmlProcessingError.getLocation()" is null at org.dita.dost.util.XMLUtils.lambda$0(XMLUtils.java:202) at net.sf.saxon.style.Compilation.compileSingletonPackage(Compilation.java:117) at net.sf.saxon.s9api.XsltCompiler.compile(XsltCompiler.java:838) at org.dita.dost.module.XsltModule.execute(XsltModule.java:112) at org.dita.dost.ant.ExtensibleAntInvoker.execute(ExtensibleAntInvoker.java:189) the NPE is caused by a FileNotFoundException thrown somewhere because an XSLT stylesheet is missing in my plugin: .../plugins/com.oxygenxml.webhelp.responsive/xsl/indexterms/extractIndexterms.xsl (No such file or directory) [pipeline] at java.base/java.io.FileInputStream.open0(Native Method) [pipeline] at java.base/java.io.FileInputStream.open(FileInputStream.java:216) [pipeline] at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157) [pipeline] at java.base/java.io.FileInputStream.<init>(FileInputStream.java:111) [pipeline] at java.base/sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:86) [pipeline] at java.base/sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:189) [pipeline] at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:1114) [pipeline] at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source) [pipeline] at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) [pipeline] at org.ditang.relaxng.defaults.RelaxDefaultsParserConfiguration.parse(RelaxDefaultsParserConfiguration.java:119) [pipeline] at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) [pipeline] at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) [pipeline] at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source) [pipeline] at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source) [pipeline] at net.sf.saxon.event.Sender.sendSAXSource(Sender.java:439) [pipeline] at net.sf.saxon.event.Sender.send(Sender.java:168) [pipeline] at net.sf.saxon.style.StylesheetModule.sendStylesheetSource(StylesheetModule.java:157) [pipeline] at net.sf.saxon.style.StylesheetModule.loadStylesheet(StylesheetModule.java:229) [pipeline] at net.sf.saxon.style.Compilation.compileSingletonPackage(Compilation.java:113) [pipeline] at net.sf.saxon.s9api.XsltCompiler.compile(XsltCompiler.java:838) [pipeline] at org.dita.dost.module.XsltModule.execute(XsltModule.java:112) [pipeline] at org.dita.dost.ant.ExtensibleAntInvoker.execute(ExtensibleAntInvoker.java:1
888e376cd2026856aec20ba57ece1a7e07c247de
e18233db00511fa64a21ffd394fa1159cefcc0c7
https://github.com/dita-ot/dita-ot/compare/888e376cd2026856aec20ba57ece1a7e07c247de...e18233db00511fa64a21ffd394fa1159cefcc0c7
diff --git a/src/main/java/org/dita/dost/util/XMLUtils.java b/src/main/java/org/dita/dost/util/XMLUtils.java index e57172dfa..a4c81e88b 100644 --- a/src/main/java/org/dita/dost/util/XMLUtils.java +++ b/src/main/java/org/dita/dost/util/XMLUtils.java @@ -9,11 +9,11 @@ package org.dita.dost.util; import com.google.common.annotations.VisibleForTesting; import net.sf.saxon.expr.instruct.TerminationException; -import net.sf.saxon.lib.*; +import net.sf.saxon.lib.CollationURIResolver; +import net.sf.saxon.lib.ErrorReporter; +import net.sf.saxon.lib.ExtensionFunctionDefinition; import net.sf.saxon.s9api.*; -import net.sf.saxon.s9api.streams.Predicates; import net.sf.saxon.s9api.streams.Step; -import net.sf.saxon.s9api.streams.XdmStream; import org.apache.xml.resolver.tools.CatalogResolver; import org.dita.dost.exception.DITAOTException; import org.dita.dost.log.DITAOTLogger; @@ -197,15 +197,18 @@ public final class XMLUtils { logger.warn(error.getMessage()); } else { if (error.getCause() instanceof FileNotFoundException) { - error.asWarning(); - final StringBuilder buf = new StringBuilder() - .append(error.getLocation().getSystemId()) - .append(":") - .append(error.getLocation().getLineNumber()) - .append(":") - .append(error.getLocation().getColumnNumber()) - .append(": ") - .append(error.getMessage()); + error = error.asWarning(); + final StringBuilder buf = new StringBuilder(); + final Location location = error.getLocation(); + if (location != null) { + buf.append(location.getSystemId()) + .append(":") + .append(location.getLineNumber()) + .append(":") + .append(location.getColumnNumber()) + .append(": "); + } + buf.append(error.getMessage()); logger.warn(buf.toString()); } else { logger.error(error.getMessage());
['src/main/java/org/dita/dost/util/XMLUtils.java']
{'.java': 1}
1
1
0
0
1
1,934,963
397,726
51,710
247
1,416
208
27
1
3,009
132
702
34
0
0
1970-01-01T00:27:36
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
133
dita-ot/dita-ot/3977/3366
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3366
https://github.com/dita-ot/dita-ot/pull/3977
https://github.com/dita-ot/dita-ot/pull/3977
1
fix
NullPointerException in FileUtils.getRelativePath
The stack trace: https://www.oxygenxml.com/forum/viewtopic.php?f=20&t=20682 D:\\Oxygen XML Author 21\\frameworks\\dita\\DITA-OT3.x\\plugins\\org.dita.base\\build_preprocess.xml:87: java.lang.NullPointerException at org.dita.dost.util.FileUtils.getRelativePath(FileUtils.java:169) at org.dita.dost.module.DebugAndFilterModule.getRelativePathFromOut(DebugAndFilterModule.java:532) at org.dita.dost.module.DebugAndFilterModule.getPathtoProject(DebugAndFilterModule.java:514) at org.dita.dost.writer.DitaWriterFilter.startDocument(DitaWriterFilter.java:95) at org.xml.sax.helpers.XMLFilterImpl.startDocument(Unknown Source) at org.dita.dost.writer.TopicFragmentFilter.startDocument(TopicFragmentFil It looks like a side effect of a condition added by @robander in: https://github.com/dita-ot/dita-ot/pull/2797
b2da4f863823a8cb2547dc01737f4e0165375107
edc7c857d4b1aa6c36446bb939b1c8b1bf1995ba
https://github.com/dita-ot/dita-ot/compare/b2da4f863823a8cb2547dc01737f4e0165375107...edc7c857d4b1aa6c36446bb939b1c8b1bf1995ba
diff --git a/src/main/java/org/dita/dost/util/FileUtils.java b/src/main/java/org/dita/dost/util/FileUtils.java index efd70ad3c..e0544f85d 100644 --- a/src/main/java/org/dita/dost/util/FileUtils.java +++ b/src/main/java/org/dita/dost/util/FileUtils.java @@ -166,7 +166,7 @@ public final class FileUtils { * @return relative path, or refPath if different root means no relative path is possible */ public static File getRelativePath(final File basePath, final File refPath) { - if (!basePath.toPath().getRoot().equals(refPath.toPath().getRoot())) { + if (basePath.toPath().getRoot() == null || !basePath.toPath().getRoot().equals(refPath.toPath().getRoot())) { return refPath; } return basePath.toPath().getParent().relativize(refPath.toPath()).toFile(); diff --git a/src/test/java/org/dita/dost/util/TestFileUtils.java b/src/test/java/org/dita/dost/util/TestFileUtils.java index 666547bea..3110579ef 100644 --- a/src/test/java/org/dita/dost/util/TestFileUtils.java +++ b/src/test/java/org/dita/dost/util/TestFileUtils.java @@ -77,11 +77,13 @@ public class TestFileUtils { assertEquals(new File("d:\\\\a.dita"), FileUtils.getRelativePath(new File("c:\\\\map.ditamap"), new File("d:\\\\a.dita"))); assertEquals(new File("a.dita"), FileUtils.getRelativePath(new File("c:\\\\map1\\\\map2\\\\map.ditamap"), new File("c:\\\\map1\\\\map2\\\\a.dita"))); assertEquals(new File("../topic/a.dita"), FileUtils.getRelativePath(new File("c:\\\\map1\\\\map.ditamap"), new File("c:\\\\topic\\\\a.dita"))); + assertEquals(new File("D:\\\\top_level_error\\\\out\\\\pdf-OPENME2\\\\index.html"), FileUtils.getRelativePath(new File("B1\\\\B2\\\\B3\\\\B4\\\\topic.dita"), new File("D:\\\\top_level_error\\\\out\\\\pdf-OPENME2\\\\index.html"))); } else { assertEquals(new File("../a.dita"), FileUtils.getRelativePath(new File("/map/map.ditamap"), new File("/a.dita"))); assertEquals(new File("a.dita"), FileUtils.getRelativePath(new File("/map.ditamap"), new File("/a.dita"))); assertEquals(new File("a.dita"), FileUtils.getRelativePath(new File("/map1/map2/map.ditamap"), new File("/map1/map2/a.dita"))); assertEquals(new File("../topic/a.dita"), FileUtils.getRelativePath(new File("/map1/map.ditamap"), new File("/topic/a.dita"))); + assertEquals(new File("/top_level_error/out/pdf-OPENME2/index.html"), FileUtils.getRelativePath(new File("B1/B2/B3/B4/topic.dita"), new File("/top_level_error/out/pdf-OPENME2/index.html"))); } }
['src/main/java/org/dita/dost/util/FileUtils.java', 'src/test/java/org/dita/dost/util/TestFileUtils.java']
{'.java': 2}
2
2
0
0
2
1,934,728
397,678
51,717
247
198
46
2
1
824
36
214
13
2
0
1970-01-01T00:27:38
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
132
dita-ot/dita-ot/3978/3969
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3969
https://github.com/dita-ot/dita-ot/pull/3978
https://github.com/dita-ot/dita-ot/pull/3978
1
fixes
`<xsl:message>` of an XML element also recursively prints its descendants
## Expected Behavior When I use `<xsl:message>` to print an element: ``` <xsl:template match="*[contains-token(@class, 'topic/p')]"> <xsl:message>***BEGIN***</xsl:message> <xsl:message><xsl:sequence select="."/></xsl:message> <xsl:message>***END***</xsl:message> <xsl:next-match/> </xsl:template> ``` and the element being printed has descendant elements in it: ``` <p>1 <ph>2 <ph>3 <ph>4</ph> 5</ph> 6</ph> 7</p> ``` then I expect the element to be printed, serialized as it exists in the document: ``` [xslt] ***BEGIN*** [xslt] <p xmlns:dita-ot="http://dita-ot.sourceforge.net/ns/201007/dita-ot" xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- topic/p ">1 [xslt] <ph class="- topic/ph ">2 [xslt] <ph class="- topic/ph ">3 [xslt] <ph class="- topic/ph ">4</ph> [xslt] 5</ph> [xslt] 6</ph> [xslt] 7</p> [xslt] ***END*** ``` ## Actual Behavior Somehow the element is printed once normally, then the contents of its descendants are also recursively printed: ``` [xslt] ***BEGIN*** [xslt] <p xmlns:dita-ot="http://dita-ot.sourceforge.net/ns/201007/dita-ot" [xslt] xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" [xslt] class="- topic/p ">1 [xslt] <ph class="- topic/ph ">2 [xslt] <ph class="- topic/ph ">3 [xslt] <ph class="- topic/ph ">4</ph> [xslt] 5</ph> [xslt] 6</ph> [xslt] 7</p>1 [xslt] <ph xmlns:dita-ot="http://dita-ot.sourceforge.net/ns/201007/dita-ot" [xslt] xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" [xslt] class="- topic/ph ">2 [xslt] <ph class="- topic/ph ">3 [xslt] <ph class="- topic/ph ">4</ph> [xslt] 5</ph> [xslt] 6</ph>2 [xslt] <ph xmlns:dita-ot="http://dita-ot.sourceforge.net/ns/201007/dita-ot" [xslt] xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" [xslt] class="- topic/ph ">3 [xslt] <ph class="- topic/ph ">4</ph> [xslt] 5</ph>3 [xslt] <ph xmlns:dita-ot="http://dita-ot.sourceforge.net/ns/201007/dita-ot" [xslt] xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" [xslt] class="- topic/ph ">4</ph>4 [xslt] 5 [xslt] 6 [xslt] 7 [xslt] ***END*** ``` ## Possible Solution I think this is related to the fix for #3662. Note that the "expected behavior" above comes from DITA-OT 3.5.4, before the original bug was introduced. ## Steps to Reproduce 1. Extract the following testcase: [ditaot_message_nested_elements.zip](https://github.com/dita-ot/dita-ot/files/9154617/ditaot_message_nested_elements.zip) 2. Install the plugin: `dita install com.debug.message.zip` 4. Run the following command: `dita -i topic.dita -f html5 -o out -Dgenerate-debug-attributes=no --verbose` 5. Uninstall the plugin: `dita uninstall com.debug.message` ## Environment * DITA-OT version: 3.7.2 * Operating system and version: Linux (Ubuntu 20.04 LTS) * How did you run DITA-OT? `dita` command * Transformation type: any
b2da4f863823a8cb2547dc01737f4e0165375107
e8cacb7ce210633ff75d4a1d2bf5d1a30e2b7d8f
https://github.com/dita-ot/dita-ot/compare/b2da4f863823a8cb2547dc01737f4e0165375107...e8cacb7ce210633ff75d4a1d2bf5d1a30e2b7d8f
diff --git a/src/main/java/org/dita/dost/util/XMLUtils.java b/src/main/java/org/dita/dost/util/XMLUtils.java index 088a553c8..e57172dfa 100644 --- a/src/main/java/org/dita/dost/util/XMLUtils.java +++ b/src/main/java/org/dita/dost/util/XMLUtils.java @@ -160,7 +160,7 @@ public final class XMLUtils { .map(XdmItem::getStringValue) .orElse("INFO"); final String msg = content - .select(descendant( + .select(child( hasLocalName("level").or(hasLocalName("error-code")) .and(hasType(ItemType.PROCESSING_INSTRUCTION_NODE)) .negate())) diff --git a/src/test/java/org/dita/dost/util/XMLUtilsTest.java b/src/test/java/org/dita/dost/util/XMLUtilsTest.java index a9d1687b3..ae1e12c27 100644 --- a/src/test/java/org/dita/dost/util/XMLUtilsTest.java +++ b/src/test/java/org/dita/dost/util/XMLUtilsTest.java @@ -364,6 +364,26 @@ public class XMLUtilsTest { assertEquals(1, act.size()); assertEquals(new Message(Message.Level.ERROR, "message <debug/>", null), act.get(0)); } + + @Test + public void toMessageListenerProperElemsSerialization() throws SaxonApiException { + final CachingLogger logger = new CachingLogger(); + final MessageListener2 listener = XMLUtils.toMessageListener(logger); + + final XdmNode msg = Saplings.doc().withChild( + Saplings.text("abc "), + Saplings.elem("def").withChild(Saplings.elem("hij")) + ) + .toXdmNode(new XMLUtils().getProcessor()); + + listener.message(msg, null, false, null); + + final List<Message> act = logger.getMessages(); + assertEquals(1, act.size()); + assertEquals("abc <def>\\n" + + " <hij/>\\n" + + "</def>", act.get(0).message); + } // @Test // public void transform() throws Exception {
['src/test/java/org/dita/dost/util/XMLUtilsTest.java', 'src/main/java/org/dita/dost/util/XMLUtils.java']
{'.java': 2}
2
2
0
0
2
1,934,728
397,678
51,717
247
84
11
2
1
3,265
294
1,064
90
11
4
1970-01-01T00:27:39
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
130
dita-ot/dita-ot/4053/4043
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/4043
https://github.com/dita-ot/dita-ot/pull/4053
https://github.com/dita-ot/dita-ot/pull/4053
1
fixes
Flagging does not work with specialized attribute
## Expected Behavior When multiple flags apply to a single element, multiple flags should be rendered, typically in the order that they are encountered. https://docs.oasis-open.org/dita/dita/v1.3/errata02/os/complete/part3-all-inclusive/archSpec/base/flagging.html#flagging ## Actual Behavior When multiple flags apply to a single element, some flags are ignored if the attribute is speicalized. In the test case attahced, flagging does not work as expected for last paragraph. Here `newAtt` is specialized from `props`. ``` <p class="- topic/p " platform="windows">1. platform="windows"</p> <p class="- topic/p " audience="novice">2. audience="novice"</p> <p class="- topic/p " newAtt="aaa">3. newAtt="(aaa)"</p> <p class="- topic/p " platform="windows" audience="novice">4. platform="windows" and audience="novice"</p> <p class="- topic/p " platform="windows" newAtt="aaa">5. platform="windows" and newAtt="aaa"</p> ``` ## Possible Solution N/A ## Steps to Reproduce Test case and the project file is attached. [test.zip](https://github.com/dita-ot/dita-ot/files/9977643/test.zip) `dita --project=project.xml` ## Copy of the error message, log file or stack trace N/A ## Environment * DITA-OT version: 3.4.1 * Operating system and version: Windows * How did you run DITA-OT? 'dita' command * Transformation type: PDF
5bee85fcebc6adfe928354c0fe8ddbbc27358c20
37bb69871cbfeddc3743e78fdc54cc7e07c72ec2
https://github.com/dita-ot/dita-ot/compare/5bee85fcebc6adfe928354c0fe8ddbbc27358c20...37bb69871cbfeddc3743e78fdc54cc7e07c72ec2
diff --git a/src/main/java/org/dita/dost/util/FilterUtils.java b/src/main/java/org/dita/dost/util/FilterUtils.java index 8c1f0be93..ce05de7c0 100644 --- a/src/main/java/org/dita/dost/util/FilterUtils.java +++ b/src/main/java/org/dita/dost/util/FilterUtils.java @@ -182,21 +182,19 @@ public final class FilterUtils { } } } - if (res.isEmpty()) { - if (extProps != null && extProps.length != 0) { - for (final QName[] propList : extProps) { - int propListIndex = propList.length - 1; - final QName propName = propList[propListIndex]; - String propValue = atts.getValue(propName.getNamespaceURI(), propName.getLocalPart()); - - while ((propValue == null || propValue.trim().isEmpty()) && propListIndex > 0) { - propListIndex--; - final QName current = propList[propListIndex]; - propValue = getLabelValue(propName, atts.getValue(current.getNamespaceURI(), current.getLocalPart())); - } - if (propValue != null) { - res.addAll(extCheckFlag(propList, Arrays.asList(propValue.split("\\\\s+")))); - } + if (extProps != null && extProps.length != 0) { + for (final QName[] propList : extProps) { + int propListIndex = propList.length - 1; + final QName propName = propList[propListIndex]; + String propValue = atts.getValue(propName.getNamespaceURI(), propName.getLocalPart()); + + while ((propValue == null || propValue.trim().isEmpty()) && propListIndex > 0) { + propListIndex--; + final QName current = propList[propListIndex]; + propValue = getLabelValue(propName, atts.getValue(current.getNamespaceURI(), current.getLocalPart())); + } + if (propValue != null) { + res.addAll(extCheckFlag(propList, Arrays.asList(propValue.split("\\\\s+")))); } } } diff --git a/src/test/java/org/dita/dost/util/FilterUtilsTest.java b/src/test/java/org/dita/dost/util/FilterUtilsTest.java index a55d07cbc..55d10c522 100644 --- a/src/test/java/org/dita/dost/util/FilterUtilsTest.java +++ b/src/test/java/org/dita/dost/util/FilterUtilsTest.java @@ -7,31 +7,28 @@ */ package org.dita.dost.util; -import static java.util.Arrays.asList; -import static java.util.Collections.*; -import static javax.xml.XMLConstants.XML_NS_PREFIX; -import static javax.xml.XMLConstants.XML_NS_URI; -import static org.dita.dost.util.Constants.*; -import static org.junit.Assert.*; - -import java.util.*; -import java.util.stream.Stream; - import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.dita.dost.TestUtils; import org.dita.dost.util.FilterUtils.Action; import org.dita.dost.util.FilterUtils.FilterKey; - import org.dita.dost.util.FilterUtils.Flag; import org.dita.dost.util.XMLUtils.AttributesBuilder; +import org.junit.Test; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; -import org.junit.Test; - -import javax.xml.XMLConstants; import javax.xml.namespace.QName; +import java.util.*; + +import static java.util.Arrays.asList; +import static java.util.Collections.emptySet; +import static java.util.Collections.singleton; +import static javax.xml.XMLConstants.XML_NS_PREFIX; +import static javax.xml.XMLConstants.XML_NS_URI; +import static org.dita.dost.util.Constants.ATTRIBUTE_NAME_PLATFORM; +import static org.dita.dost.util.Constants.ATTRIBUTE_NAME_REV; +import static org.junit.Assert.*; public class FilterUtilsTest { @@ -246,6 +243,23 @@ public class FilterUtilsTest { f.getFlags(attr(PLATFORM, "windows"), new QName[0][0])); } + @Test + public void testGetFlagsForSpecialization() { + final Flag flagBase = new Flag("prop", "red", null, null, null, null, null, null); + final Flag flagSpecialization = new Flag("prop", "blue", null, null, null, null, null, null); + final FilterUtils f = new FilterUtils(false, + ImmutableMap.<FilterKey, Action>builder() + .put(new FilterKey(PLATFORM, "unix"), flagBase) + .put(new FilterKey(OS, "amiga"), flagSpecialization) + .build(), null, null); + f.setLogger(new TestUtils.TestLogger()); + + assertEquals( + Set.of(flagBase, flagSpecialization), + f.getFlags(new AttributesBuilder().add(OS, "amiga").add(PLATFORM, "unix").build(), + new QName[][] {{PROPS, OS}})); + } + // DITA 1.3 @Test
['src/test/java/org/dita/dost/util/FilterUtilsTest.java', 'src/main/java/org/dita/dost/util/FilterUtils.java']
{'.java': 2}
2
2
0
0
2
1,963,361
401,821
52,248
249
1,754
335
28
1
1,364
158
364
34
2
1
1970-01-01T00:27:48
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
129
dita-ot/dita-ot/4080/4071
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/4071
https://github.com/dita-ot/dita-ot/pull/4080
https://github.com/dita-ot/dita-ot/pull/4080
1
fixes
Keyref on longdescref element inside image is not resolved to an href
Started from: https://www.oxygenxml.com/forum/viewtopic.php?p=68639#p68639 Let's say I have an image element with a longdescref inside it having a keyref: <image href="image.jpg"> <longdescref keyref="targetKey"/> </image> I publish the DITA Map to HTML5, look in the temporary files folder at the temp DITA topic and it does not contain an @href on the &lt;longdescref> element. As a possible suggested fix in this field org.dita.dost.writer.KeyrefPaser.keyrefInfos probably an extra definition needs to be added: ki.add(new KeyrefInfo(TOPIC_LONGDESCREF, ATTRIBUTE_NAME_HREF, false, false));
193f0e549420374612339cfd4f5fe3f998bc1a0a
f106bb379459469d937aba6768efc4b4835a9522
https://github.com/dita-ot/dita-ot/compare/193f0e549420374612339cfd4f5fe3f998bc1a0a...f106bb379459469d937aba6768efc4b4835a9522
diff --git a/src/main/java/org/dita/dost/writer/KeyrefPaser.java b/src/main/java/org/dita/dost/writer/KeyrefPaser.java index 92c55a32d..93eecf211 100644 --- a/src/main/java/org/dita/dost/writer/KeyrefPaser.java +++ b/src/main/java/org/dita/dost/writer/KeyrefPaser.java @@ -103,6 +103,7 @@ public final class KeyrefPaser extends AbstractXMLFilter { ki.add(new KeyrefInfo(TOPIC_INDEX_BASE, ATTRIBUTE_NAME_HREF, false, false)); ki.add(new KeyrefInfo(TOPIC_INDEXTERMREF, ATTRIBUTE_NAME_HREF, false, false)); ki.add(new KeyrefInfo(TOPIC_LONGQUOTEREF, ATTRIBUTE_NAME_HREF, false, false)); + ki.add(new KeyrefInfo(TOPIC_LONGDESCREF, ATTRIBUTE_NAME_HREF, false, false)); final Map<String, String> objectAttrs = new HashMap<>(); objectAttrs.put(ATTRIBUTE_NAME_ARCHIVEKEYREFS, ATTRIBUTE_NAME_ARCHIVE); objectAttrs.put(ATTRIBUTE_NAME_CLASSIDKEYREF, ATTRIBUTE_NAME_CLASSID);
['src/main/java/org/dita/dost/writer/KeyrefPaser.java']
{'.java': 1}
1
1
0
0
1
1,963,262
401,812
52,246
249
86
23
1
1
628
74
163
14
1
0
1970-01-01T00:27:50
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
128
dita-ot/dita-ot/4152/3903
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3903
https://github.com/dita-ot/dita-ot/pull/4152
https://github.com/dita-ot/dita-ot/pull/4152
1
fixes
Branch filtering processes nested-topic topic files multiple times
## Expected Behavior When branch filtering is applied to a topic with nested subtopics: ``` <map> <title>Test Map</title> <ditavalref href="filter-A.ditaval"/> <topicref href="topic.dita"> <topicref href="topic.dita#id_1"> <topicref href="topic.dita#id_1_1"/> <topicref href="topic.dita#id_1_2"/> </topicref> <topicref href="topic.dita#id_2"> <topicref href="topic.dita#id_2_1"/> <topicref href="topic.dita#id_2_2"/> </topicref> </topicref> </map> ``` the `branch-filter` step should process each topic file a single time: ``` [branch-filter] Filtering file:/tmp/temp20220319114445274/topic.dita ``` ## Actual Behavior The `branch-filter` step processes each topic file multiple times: ``` [branch-filter] Filtering file:/tmp/temp20220319114445274/topic.dita [branch-filter] Filtering file:/tmp/temp20220319114445274/topic.dita#id_1 [branch-filter] Filtering file:/tmp/temp20220319114445274/topic.dita#id_1_1 [branch-filter] Filtering file:/tmp/temp20220319114445274/topic.dita#id_1_2 [branch-filter] Filtering file:/tmp/temp20220319114445274/topic.dita#id_2 [branch-filter] Filtering file:/tmp/temp20220319114445274/topic.dita#id_2_1 [branch-filter] Filtering file:/tmp/temp20220319114445274/topic.dita#id_2_2 ``` I confirmed that the first branch filtering operation processes the entire file; thus, the subsequent operations perform unnecessary read-modify-write operations. On small testcases, the effect on runtime is negligible. But on a production online help map with many nested topics, branch filtering takes 66% of the `html5` transformation runtime (1050 seconds for branch filtering, out of 1590 seconds total). #3875 is likely related - see the bottom of [this comment](https://github.com/dita-ot/dita-ot/issues/3875#issuecomment-1044208535). ## Possible Solution `BranchFilterModule.java` should be updated to process each file a single time. The solution should handle both omitted root topic `@id` values: ``` <topicref href="topic.dita"> <!-- root topic @id omitted --> <topicref href="topic.dita#id_1"/> <topicref href="topic.dita#id_2"/> </topicref> ``` as well as explicit root topic `@id` values: ``` <topicref href="topic.dita#root_topic_id"> <!-- @id explicitly included --> <topicref href="topic.dita#id_1"/> <topicref href="topic.dita#id_2"/> </topicref> ``` ## Steps to Reproduce You must use a DITA-OT that includes the fix for #3875 (3.7.1 when released, or a development branch before then). 1. Download and extract the following testcase: [3903.zip](https://github.com/dita-ot/dita-ot/files/11067818/3903.zip) 2. Run the following command: `dita -i map.ditamap -f html5 -verbose` A Perl script is included to generate a nested map/topic structure. For example, to try various combinations of 1000 nested topics, ``` make_nested_topic_testcase.pl 1000 dita -i map.ditamap -f html5 -verbose make_nested_topic_testcase.pl 20 50 dita -i map.ditamap -f html5 -verbose make_nested_topic_testcase.pl 10 10 10 dita -i map.ditamap -f html5 -verbose ``` The included testcase was generated with `make_nested_topic_testcase.pl 2 2 2`. ## Environment * DITA-OT version: 3.7.1 * Operating system and version: Linux (Ubuntu 20.04) * How did you run DITA-OT? `dita` command * Transformation type: `html5`
c02de0fb4fabb52d7f55f6fd2a94fea1fb9a7d6e
6100f8b7c456cfae745e54f28d54c2be2afe9bd3
https://github.com/dita-ot/dita-ot/compare/c02de0fb4fabb52d7f55f6fd2a94fea1fb9a7d6e...6100f8b7c456cfae745e54f28d54c2be2afe9bd3
diff --git a/src/main/java/org/dita/dost/module/BranchFilterModule.java b/src/main/java/org/dita/dost/module/BranchFilterModule.java index 5c45a5289..f21f7bda2 100644 --- a/src/main/java/org/dita/dost/module/BranchFilterModule.java +++ b/src/main/java/org/dita/dost/module/BranchFilterModule.java @@ -11,11 +11,9 @@ import static java.util.Collections.singletonList; import static org.dita.dost.util.Constants.*; import static org.dita.dost.util.StringUtils.getExtProps; import static org.dita.dost.util.StringUtils.getExtPropsFromSpecializations; -import static org.dita.dost.util.URLUtils.stripFragment; -import static org.dita.dost.util.URLUtils.toURI; +import static org.dita.dost.util.URLUtils.*; import static org.dita.dost.util.XMLUtils.*; -import java.io.File; import java.io.IOException; import java.net.URI; import java.util.*; @@ -419,7 +417,7 @@ public class BranchFilterModule extends AbstractPipelineModuleImpl { final String href = topicref.getAttribute(ATTRIBUTE_NAME_HREF); final Attr skipFilter = topicref.getAttributeNode(SKIP_FILTER); - final URI srcAbsUri = job.tempDirURI.resolve(map.resolve(href)); + final URI srcAbsUri = setFragment(job.tempDirURI.resolve(map.resolve(href)), null); if ( !fs.isEmpty() && skipFilter == null &&
['src/main/java/org/dita/dost/module/BranchFilterModule.java']
{'.java': 1}
1
1
0
0
1
1,765,680
401,895
52,854
249
334
78
6
1
3,430
350
966
101
2
6
1970-01-01T00:27:59
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
134
dita-ot/dita-ot/3964/3724
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3724
https://github.com/dita-ot/dita-ot/pull/3964
https://github.com/dita-ot/dita-ot/pull/3964
1
fixes
Error in mapref stage when passing dita map as resource
I'm attaching a sample DITA project [chemistry_crash_single_topic.zip](https://github.com/dita-ot/dita-ot/files/6242590/chemistry_crash_single_topic.zip) on Windows I'm running this command line: ```batch dita -i C:\\Users\\radu_coravu\\Downloads\\chemistry_crash_single_topic\\iugux\\installation_preparation\\overview_of_installation_process.dita ^ --resource=C:\\Users\\radu_coravu\\Downloads\\chemistry_crash_single_topic\\iugux.ditamap ^ -f html5 ^ --temp=tmp ^ --clean.temp=no ^ -v ``` then I get an error reported in the "mapref" stage: [mapref] I/O error reported by XML parser processing [mapref] file:/C:/Users/radu_coravu/Desktop/dita-ot-3.6/bin/tmp/C:/Users/radu_coravu/Downloads/chemistry_crash_single_topic/iugux.ditamap: C:\\Users\\radu_coravu\\Desktop\\dita-ot-3.6\\bin\\tmp\\C:\\Users\\radu_coravu\\Downloads\\chemistry_crash_single_topic\\iugux.ditamap (The filename, directory name, or volume label syntax is incorrect) As you can see the absolute path to the dita map gets concatenated to the absolute path to the temporary files folder, producing an invalid file path on Windows. Looking in the .job.xml at the entry for the DITA Map: ```xml <file src="file:/C:/Users/radu_coravu/Downloads/chemistry_crash_single_topic/iugux.ditamap" uri="file:/C:/Users/radu_coravu/Downloads/chemistry_crash_single_topic/iugux.ditamap" path="C:\\Users\\radu_coravu\\Downloads\\chemistry_crash_single_topic\\iugux.ditamap" result="file:/C:/Users/radu_coravu/Downloads/chemistry_crash_single_topic/iugux.ditamap" format="ditamap" resource-only="true"/> ``` it is the only entry with an absolute `@path` attribute. When the method "org.dita.dost.module.MaprefModule.processMap(FileInfo)" gets called, the input file gets computed by appending two absolute file paths one to another: ```java File inputFile = new File(job.tempDir, input.file.getPath()); ``` which is invalid on Windows. The same thing works on Mac because the file path does not contain a drive name and "new File(job.tempDir, input.file.getPath())" manages to produce a valid file path.
6ad3b8f20c1997b506d39816e637b5f1deafbefa
129eb95b93024b20d566bd6666a9ef2fb1ba5ae4
https://github.com/dita-ot/dita-ot/compare/6ad3b8f20c1997b506d39816e637b5f1deafbefa...129eb95b93024b20d566bd6666a9ef2fb1ba5ae4
diff --git a/src/main/java/org/dita/dost/ant/types/JobSourceSet.java b/src/main/java/org/dita/dost/ant/types/JobSourceSet.java index bfa79b2f6..935db7257 100644 --- a/src/main/java/org/dita/dost/ant/types/JobSourceSet.java +++ b/src/main/java/org/dita/dost/ant/types/JobSourceSet.java @@ -7,10 +7,6 @@ */ package org.dita.dost.ant.types; -import static org.dita.dost.util.Constants.*; -import static org.dita.dost.util.FileUtils.supportedImageExtensions; -import static org.dita.dost.util.URLUtils.*; - import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import org.apache.tools.ant.Project; @@ -32,6 +28,11 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.*; +import static org.dita.dost.util.Constants.ATTR_FORMAT_VALUE_DITA; +import static org.dita.dost.util.Constants.ATTR_FORMAT_VALUE_IMAGE; +import static org.dita.dost.util.FileUtils.supportedImageExtensions; +import static org.dita.dost.util.URLUtils.toFile; + /** * Resource collection that finds matching resources from job configuration. */ @@ -59,7 +60,7 @@ public class JobSourceSet extends AbstractFileSet implements ResourceCollection res = new ArrayList<>(); for (final FileInfo f : job.getFileInfo(this::filter)) { log("Scanning for " + f.file.getPath(), Project.MSG_VERBOSE); - final File tempFile = new File(job.tempDir, f.file.getPath()); + final File tempFile = new File(job.tempDirURI.resolve(f.uri)); if (job.getStore().exists(tempFile.toURI())) { log("Found temporary directory file " + tempFile, Project.MSG_VERBOSE); res.add(new StoreResource(job, job.tempDirURI.relativize(f.uri))); diff --git a/src/main/java/org/dita/dost/module/ChunkModule.java b/src/main/java/org/dita/dost/module/ChunkModule.java index 4515662d0..dfc8a4db1 100644 --- a/src/main/java/org/dita/dost/module/ChunkModule.java +++ b/src/main/java/org/dita/dost/module/ChunkModule.java @@ -73,7 +73,7 @@ final public class ChunkModule extends AbstractPipelineModuleImpl { if (transtype.equals(INDEX_TYPE_ECLIPSEHELP) && isEclipseMap(mapFile.toURI())) { for (final FileInfo f : job.getFileInfo()) { if (ATTR_FORMAT_VALUE_DITAMAP.equals(f.format)) { - mapReader.read(new File(job.tempDir, f.file.getPath()).getAbsoluteFile()); + mapReader.read(new File(job.tempDirURI.resolve(f.uri)).getAbsoluteFile()); } } } else { diff --git a/src/main/java/org/dita/dost/module/ConrefPushModule.java b/src/main/java/org/dita/dost/module/ConrefPushModule.java index cbf8310af..a4ba2ccd4 100644 --- a/src/main/java/org/dita/dost/module/ConrefPushModule.java +++ b/src/main/java/org/dita/dost/module/ConrefPushModule.java @@ -8,12 +8,6 @@ */ package org.dita.dost.module; -import java.io.File; -import java.util.Collection; -import java.util.Hashtable; -import java.util.Map; -import java.util.stream.Collectors; - import org.dita.dost.exception.DITAOTException; import org.dita.dost.pipeline.AbstractPipelineInput; import org.dita.dost.pipeline.AbstractPipelineOutput; @@ -23,6 +17,12 @@ import org.dita.dost.util.Job.FileInfo; import org.dita.dost.writer.ConrefPushParser; import org.w3c.dom.DocumentFragment; +import java.io.File; +import java.util.Collection; +import java.util.Hashtable; +import java.util.Map; +import java.util.stream.Collectors; + /** * Conref push module. */ @@ -38,7 +38,7 @@ final class ConrefPushModule extends AbstractPipelineModuleImpl { reader.setLogger(logger); reader.setJob(job); for (final FileInfo f: fis) { - final File file = new File(job.tempDir, f.file.getPath()); + final File file = new File(job.tempDirURI.resolve(f.uri)); logger.info("Reading " + file.toURI()); //FIXME: this reader calculate parent directory reader.read(file.getAbsoluteFile()); diff --git a/src/main/java/org/dita/dost/module/DebugAndFilterModule.java b/src/main/java/org/dita/dost/module/DebugAndFilterModule.java index f063f3c1e..0819699b9 100644 --- a/src/main/java/org/dita/dost/module/DebugAndFilterModule.java +++ b/src/main/java/org/dita/dost/module/DebugAndFilterModule.java @@ -119,7 +119,7 @@ public final class DebugAndFilterModule extends SourceReaderModule { logger.warn("Ignoring a copy-to file " + f.result); return; } - outputFile = new File(job.tempDir, f.file.getPath()); + outputFile = new File(job.tempDirURI.resolve(f.uri)); logger.info("Processing " + f.src + " to " + outputFile.toURI()); final Set<URI> schemaSet = dic.get(f.uri); diff --git a/src/main/java/org/dita/dost/module/GenMapAndTopicListModule.java b/src/main/java/org/dita/dost/module/GenMapAndTopicListModule.java index f9fd0f90b..2dfa77c28 100644 --- a/src/main/java/org/dita/dost/module/GenMapAndTopicListModule.java +++ b/src/main/java/org/dita/dost/module/GenMapAndTopicListModule.java @@ -1035,7 +1035,7 @@ public final class GenMapAndTopicListModule extends SourceReaderModule { // write list attribute to file final String fileKey = REL_FLAGIMAGE_LIST.substring(0, REL_FLAGIMAGE_LIST.lastIndexOf("list")) + "file"; prop.setProperty(fileKey, REL_FLAGIMAGE_LIST.substring(0, REL_FLAGIMAGE_LIST.lastIndexOf("list")) + ".list"); - final File list = new File(job.tempDir, prop.getProperty(fileKey)); + final File list = job.tempDir.toPath().resolve(prop.getProperty(fileKey)).toFile(); try (Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(job.getStore().getOutputStream(list.toURI())))) { final Iterator<URI> it = newSet.iterator(); while (it.hasNext()) { diff --git a/src/main/java/org/dita/dost/module/ImageMetadataModule.java b/src/main/java/org/dita/dost/module/ImageMetadataModule.java index f317b6414..05090974f 100644 --- a/src/main/java/org/dita/dost/module/ImageMetadataModule.java +++ b/src/main/java/org/dita/dost/module/ImageMetadataModule.java @@ -7,7 +7,13 @@ */ package org.dita.dost.module; -import static org.dita.dost.util.Constants.*; +import org.dita.dost.exception.DITAOTException; +import org.dita.dost.pipeline.AbstractPipelineInput; +import org.dita.dost.pipeline.AbstractPipelineOutput; +import org.dita.dost.util.Job.FileInfo; +import org.dita.dost.util.Pool; +import org.dita.dost.writer.ImageMetadataFilter; +import org.xml.sax.Attributes; import java.io.File; import java.io.IOException; @@ -16,15 +22,8 @@ import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; -import java.util.stream.Stream; -import org.dita.dost.exception.DITAOTException; -import org.dita.dost.pipeline.AbstractPipelineInput; -import org.dita.dost.pipeline.AbstractPipelineOutput; -import org.dita.dost.util.Job.FileInfo; -import org.dita.dost.util.Pool; -import org.dita.dost.writer.ImageMetadataFilter; -import org.xml.sax.Attributes; +import static org.dita.dost.util.Constants.*; /** * Image metadata module. @@ -68,7 +67,7 @@ final class ImageMetadataModule extends AbstractPipelineModuleImpl { }); job.getFileInfo(filter).stream() .parallel() - .map(f -> new File(job.tempDir, f.file.getPath()).getAbsoluteFile()) + .map(f -> new File(job.tempDirURI.resolve(f.uri)).getAbsoluteFile()) .forEach(filename -> { final ImageMetadataFilter writer = pool.borrowObject(); try { @@ -82,7 +81,7 @@ final class ImageMetadataModule extends AbstractPipelineModuleImpl { writer.setLogger(logger); writer.setJob(job); for (final FileInfo f : job.getFileInfo(filter)) { - writer.write(new File(job.tempDir, f.file.getPath()).getAbsoluteFile()); + writer.write(new File(job.tempDirURI.resolve(f.uri)).getAbsoluteFile()); } } diff --git a/src/main/java/org/dita/dost/module/KeyrefModule.java b/src/main/java/org/dita/dost/module/KeyrefModule.java index b3a8270fc..edb939e25 100644 --- a/src/main/java/org/dita/dost/module/KeyrefModule.java +++ b/src/main/java/org/dita/dost/module/KeyrefModule.java @@ -32,7 +32,6 @@ import org.dita.dost.writer.KeyrefPaser; import org.dita.dost.writer.TopicFragmentFilter; import org.xml.sax.XMLFilter; -import java.io.File; import java.io.IOException; import java.net.URI; import java.util.*; @@ -499,12 +498,12 @@ final class KeyrefModule extends AbstractPipelineModuleImpl { if (r.out != null) { logger.info("Processing " + job.tempDirURI.resolve(r.in.uri) + " to " + job.tempDirURI.resolve(r.out.uri)); - job.getStore().transform(new File(job.tempDir, r.in.file.getPath()).toURI(), - new File(job.tempDir, r.out.file.getPath()).toURI(), + job.getStore().transform(job.tempDirURI.resolve(r.in.uri), + job.tempDirURI.resolve(r.out.uri), filters); } else { logger.info("Processing " + job.tempDirURI.resolve(r.in.uri)); - job.getStore().transform(new File(job.tempDir, r.in.file.getPath()).toURI(), + job.getStore().transform(job.tempDirURI.resolve(r.in.uri), filters); } // validate resource-only list diff --git a/src/main/java/org/dita/dost/module/MaprefModule.java b/src/main/java/org/dita/dost/module/MaprefModule.java index fd624f997..c6359c124 100644 --- a/src/main/java/org/dita/dost/module/MaprefModule.java +++ b/src/main/java/org/dita/dost/module/MaprefModule.java @@ -87,7 +87,7 @@ final class MaprefModule extends AbstractPipelineModuleImpl { } private void processMap(final FileInfo input) throws DITAOTException { - final File inputFile = new File(job.tempDir, input.file.getPath()); + final File inputFile = new File(job.tempDirURI.resolve(input.uri)); final File outputFile = new File(inputFile.getAbsolutePath() + FILE_EXTENSION_TEMP); logger.info("Processing " + inputFile.toURI()); @@ -160,8 +160,8 @@ final class MaprefModule extends AbstractPipelineModuleImpl { } private void replace(final FileInfo input) throws DITAOTException { - final File inputFile = new File(job.tempDir, input.file.getPath() + FILE_EXTENSION_TEMP); - final File outputFile = new File(job.tempDir, input.file.getPath()); + final File inputFile = new File(job.tempDirURI.resolve(input.uri + FILE_EXTENSION_TEMP)); + final File outputFile = new File(job.tempDirURI.resolve(input.uri)); try { job.getStore().move(inputFile.toURI(), outputFile.toURI()); } catch (final IOException e) { diff --git a/src/main/java/org/dita/dost/module/MoveMetaModule.java b/src/main/java/org/dita/dost/module/MoveMetaModule.java index c24634ce0..3275f2866 100644 --- a/src/main/java/org/dita/dost/module/MoveMetaModule.java +++ b/src/main/java/org/dita/dost/module/MoveMetaModule.java @@ -80,7 +80,7 @@ final class MoveMetaModule extends AbstractPipelineModuleImpl { } for (final FileInfo f : fis) { - final File inputFile = new File(job.tempDir, f.file.getPath()); + final File inputFile = new File(job.tempDirURI.resolve(f.uri)); final File tmp = new File(inputFile.getAbsolutePath() + ".tmp" + Long.toString(System.currentTimeMillis())); logger.info("Processing " + inputFile.toURI()); logger.debug("Processing " + inputFile.toURI() + " to " + tmp.toURI()); @@ -133,7 +133,7 @@ final class MoveMetaModule extends AbstractPipelineModuleImpl { final URI key = stripFragment(entry.getKey()); final FileInfo fi = job.getFileInfo(key); if (fi == null) { - logger.error("File " + new File(job.tempDir, key.getPath()) + " was not found."); + logger.error("File " + job.tempDirURI.resolve(key) + " was not found."); continue; } final URI targetFileName = job.tempDirURI.resolve(fi.uri); @@ -159,7 +159,7 @@ final class MoveMetaModule extends AbstractPipelineModuleImpl { final URI key = stripFragment(entry.getKey()); final FileInfo fi = job.getFileInfo(key); if (fi == null) { - logger.error("File " + new File(job.tempDir, key.getPath()) + " was not found."); + logger.error("File " + job.tempDirURI.resolve(key) + " was not found."); continue; } final URI targetFileName = job.tempDirURI.resolve(fi.uri); @@ -186,7 +186,7 @@ final class MoveMetaModule extends AbstractPipelineModuleImpl { metaReader.setLogger(logger); metaReader.setJob(job); for (final FileInfo f : fis) { - final File mapFile = new File(job.tempDir, f.file.getPath()); + final File mapFile = job.tempDir.toPath().resolve(f.file.toPath()).toFile(); //FIXME: this reader gets the parent path of input file try { metaReader.read(mapFile); diff --git a/src/main/java/org/dita/dost/module/XsltModule.java b/src/main/java/org/dita/dost/module/XsltModule.java index e034a4f11..22c8214ba 100644 --- a/src/main/java/org/dita/dost/module/XsltModule.java +++ b/src/main/java/org/dita/dost/module/XsltModule.java @@ -114,7 +114,7 @@ public final class XsltModule extends AbstractPipelineModuleImpl { final List<Entry<File, File>> tmps = includes.stream().parallel() .map(include -> { try { - final File in = new File(baseDir, include.getPath()); + final File in = baseDir.toPath().resolve(include.toPath()).toFile(); final File out = getOutput(include.getPath()); if (out == null) { return null; @@ -159,7 +159,7 @@ public final class XsltModule extends AbstractPipelineModuleImpl { } private File getOutput(final String path) { - File out = new File(destDir, path); + File out = destDir.toPath().resolve(path).toFile(); if (mapper != null) { final String[] outs = mapper.mapFileName(path); if (outs == null) { @@ -168,7 +168,7 @@ public final class XsltModule extends AbstractPipelineModuleImpl { if (outs.length > 1) { throw new RuntimeException("XSLT module only support one to one output mapping"); } - out = new File(destDir, outs[0]); + out = destDir.toPath().resolve(outs[0]).toFile(); } else if (extension != null) { out = new File(replaceExtension(out.getAbsolutePath(), extension)); } diff --git a/src/main/java/org/dita/dost/module/filter/AbstractBranchFilterModule.java b/src/main/java/org/dita/dost/module/filter/AbstractBranchFilterModule.java index dd5d44c66..f0a7aa88c 100644 --- a/src/main/java/org/dita/dost/module/filter/AbstractBranchFilterModule.java +++ b/src/main/java/org/dita/dost/module/filter/AbstractBranchFilterModule.java @@ -154,7 +154,7 @@ public abstract class AbstractBranchFilterModule extends AbstractPipelineModuleI // write list attribute to file final String fileKey = REL_FLAGIMAGE_LIST.substring(0, REL_FLAGIMAGE_LIST.lastIndexOf("list")) + "file"; prop.setProperty(fileKey, REL_FLAGIMAGE_LIST.substring(0, REL_FLAGIMAGE_LIST.lastIndexOf("list")) + ".list"); - final File list = new File(job.tempDir, prop.getProperty(fileKey)); + final File list = job.tempDir.toPath().resolve(prop.getProperty(fileKey)).toFile(); try (Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(job.getStore().getOutputStream(list.toURI())))) { for (URI aNewSet : newSet) { bufferedWriter.write(aNewSet.getPath()); diff --git a/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java b/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java index b55d8ca83..2e7eec0d7 100644 --- a/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java +++ b/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java @@ -33,7 +33,6 @@ import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Consumer; import java.util.function.Predicate; @@ -915,7 +914,7 @@ public abstract class AbstractReaderModule extends AbstractPipelineModuleImpl { // write list attribute to file final String fileKey = REL_FLAGIMAGE_LIST.substring(0, REL_FLAGIMAGE_LIST.lastIndexOf("list")) + "file"; prop.setProperty(fileKey, REL_FLAGIMAGE_LIST.substring(0, REL_FLAGIMAGE_LIST.lastIndexOf("list")) + ".list"); - final File list = new File(job.tempDir, prop.getProperty(fileKey)); + final File list = job.tempDir.toPath().resolve(prop.getProperty(fileKey)).toFile(); try (Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(job.getStore().getOutputStream(list.toURI())))) { for (URI aNewSet : newSet) { bufferedWriter.write(aNewSet.getPath()); diff --git a/src/main/java/org/dita/dost/reader/MergeMapParser.java b/src/main/java/org/dita/dost/reader/MergeMapParser.java index aae040e70..e484d81ed 100644 --- a/src/main/java/org/dita/dost/reader/MergeMapParser.java +++ b/src/main/java/org/dita/dost/reader/MergeMapParser.java @@ -8,36 +8,29 @@ */ package org.dita.dost.reader; -import static javax.xml.transform.OutputKeys.*; -import static org.dita.dost.chunk.ChunkModule.isLocalScope; -import static org.dita.dost.util.Constants.*; -import static org.dita.dost.util.URLUtils.*; +import org.dita.dost.log.DITAOTLogger; +import org.dita.dost.log.MessageUtils; +import org.dita.dost.util.*; +import org.dita.dost.util.Job.FileInfo; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; +import org.xml.sax.helpers.XMLFilterImpl; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.OutputStream; import java.net.URI; import java.util.Stack; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; - -import org.xml.sax.helpers.XMLFilterImpl; -import org.xml.sax.helpers.AttributesImpl; - -import org.dita.dost.log.DITAOTLogger; -import org.dita.dost.log.MessageUtils; -import org.dita.dost.util.FileUtils; -import org.dita.dost.util.Job; -import org.dita.dost.util.Job.FileInfo; -import org.dita.dost.util.MergeUtils; -import org.dita.dost.util.URLUtils; -import org.dita.dost.util.XMLUtils; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; +import static javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION; +import static org.dita.dost.chunk.ChunkModule.isLocalScope; +import static org.dita.dost.util.Constants.*; +import static org.dita.dost.util.URLUtils.*; /** * MergeMapParser reads the ditamap file after preprocessing and merges @@ -250,14 +243,14 @@ public final class MergeMapParser extends XMLFilterImpl { String element = f.file.getPath(); if (!dirPath.equals(tempdir)) { element = FileUtils.getRelativeUnixPath(new File(dirPath,"a.ditamap").getAbsolutePath(), - new File(tempdir, element).getAbsolutePath()); + tempdir.toPath().resolve(element).toAbsolutePath().toString()); } final URI abs = job.tempDirURI.resolve(f.uri); if (!util.isVisited(abs)) { util.visit(abs); if (!f.isResourceOnly) { //ensure the file exists - final File file = new File(dirPath, element); + final File file = dirPath.toPath().resolve(element).toFile(); if (job.getStore().exists(file.toURI())) { topicParser.parse(element, dirPath); } else { diff --git a/src/main/java/org/dita/dost/reader/MergeTopicParser.java b/src/main/java/org/dita/dost/reader/MergeTopicParser.java index 8ce4a4191..010715af4 100644 --- a/src/main/java/org/dita/dost/reader/MergeTopicParser.java +++ b/src/main/java/org/dita/dost/reader/MergeTopicParser.java @@ -8,17 +8,6 @@ */ package org.dita.dost.reader; -import static javax.xml.XMLConstants.*; -import static org.dita.dost.chunk.ChunkModule.isLocalScope; -import static org.dita.dost.reader.MergeMapParser.*; -import static org.dita.dost.util.Constants.*; -import static org.dita.dost.util.FileUtils.*; -import static org.dita.dost.util.URLUtils.*; -import static org.dita.dost.util.URLUtils.setFragment; - -import java.io.File; -import java.net.URI; - import org.dita.dost.log.DITAOTLogger; import org.dita.dost.util.Job; import org.dita.dost.util.MergeUtils; @@ -29,6 +18,17 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLFilterImpl; +import java.io.File; +import java.net.URI; + +import static javax.xml.XMLConstants.XML_NS_URI; +import static org.dita.dost.chunk.ChunkModule.isLocalScope; +import static org.dita.dost.reader.MergeMapParser.ATTRIBUTE_NAME_OHREF; +import static org.dita.dost.reader.MergeMapParser.ATTRIBUTE_NAME_OID; +import static org.dita.dost.util.Constants.*; +import static org.dita.dost.util.FileUtils.stripFragment; +import static org.dita.dost.util.URLUtils.*; + /** * MergeTopicParser reads topic file and transform the references to other dita * files into internal references. The parse result of MergeTopicParser will be @@ -174,7 +174,7 @@ public final class MergeTopicParser extends XMLFilterImpl { filePath = stripFragment(filename); dirPath = dir; try { - final URI f = new File(dir, filePath).getAbsoluteFile().toURI(); + final URI f = dir.toPath().resolve(filePath).toAbsolutePath().toFile().toURI(); logger.info("Processing " + f); job.getStore().transform(f, this); } catch (final RuntimeException e) { @@ -251,7 +251,7 @@ public final class MergeTopicParser extends XMLFilterImpl { * @return rewritten href value */ private URI handleLocalHref(final URI attValue) { - final URI current = new File(dirPath, filePath).toURI().normalize(); + final URI current = dirPath.toPath().resolve(filePath).toUri().normalize(); final URI reference = current.resolve(attValue); final URI merge = output.toURI(); return getRelativePath(merge, reference); diff --git a/src/main/java/org/dita/dost/util/FileUtils.java b/src/main/java/org/dita/dost/util/FileUtils.java index e0544f85d..1bd6ee369 100644 --- a/src/main/java/org/dita/dost/util/FileUtils.java +++ b/src/main/java/org/dita/dost/util/FileUtils.java @@ -8,13 +8,13 @@ */ package org.dita.dost.util; -import static org.apache.commons.io.FilenameUtils.*; -import static org.dita.dost.util.Constants.*; - import java.io.File; import java.net.URI; import java.util.*; +import static org.apache.commons.io.FilenameUtils.normalize; +import static org.dita.dost.util.Constants.*; + /** * Static file utilities. * diff --git a/src/test/java/org/dita/dost/util/TestFileUtils.java b/src/test/java/org/dita/dost/util/TestFileUtils.java index 3110579ef..85a06d56a 100644 --- a/src/test/java/org/dita/dost/util/TestFileUtils.java +++ b/src/test/java/org/dita/dost/util/TestFileUtils.java @@ -7,16 +7,15 @@ */ package org.dita.dost.util; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; - -import java.io.*; - +import org.dita.dost.TestUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.dita.dost.TestUtils; +import java.io.File; +import java.io.IOException; + +import static org.junit.Assert.*; public class TestFileUtils {
['src/main/java/org/dita/dost/module/MoveMetaModule.java', 'src/main/java/org/dita/dost/module/ImageMetadataModule.java', 'src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java', 'src/main/java/org/dita/dost/ant/types/JobSourceSet.java', 'src/main/java/org/dita/dost/module/MaprefModule.java', 'src/main/java/org/dita/dost/module/DebugAndFilterModule.java', 'src/main/java/org/dita/dost/reader/MergeTopicParser.java', 'src/main/java/org/dita/dost/util/FileUtils.java', 'src/main/java/org/dita/dost/module/filter/AbstractBranchFilterModule.java', 'src/main/java/org/dita/dost/module/ConrefPushModule.java', 'src/main/java/org/dita/dost/module/KeyrefModule.java', 'src/main/java/org/dita/dost/module/GenMapAndTopicListModule.java', 'src/main/java/org/dita/dost/reader/MergeMapParser.java', 'src/main/java/org/dita/dost/module/ChunkModule.java', 'src/main/java/org/dita/dost/module/XsltModule.java', 'src/test/java/org/dita/dost/util/TestFileUtils.java']
{'.java': 16}
16
16
0
0
16
1,934,732
397,677
51,714
247
8,569
1,776
159
15
2,155
180
589
38
1
3
1970-01-01T00:27:37
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
143
dita-ot/dita-ot/3825/2641
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/2641
https://github.com/dita-ot/dita-ot/pull/3825
https://github.com/dita-ot/dita-ot/pull/3825
1
fixes
Integrator should fail more often
In my plugin.xml has something like this inside: <feature extension="dita.conductor.target.relative" file="integrator.xml"/> but there is no "integrator.xml" in the plugin folder, the integrator complains: [integrate] D:\\DITA-OT2.x\\plugins\\my.plugin\\integrator.xml (The system cannot find the file specified) but it is still successful.
3fcfd890fefb0854d8906111614c716321981410
c7de05d00214a669cf6c9c3fb7a717c190918e18
https://github.com/dita-ot/dita-ot/compare/3fcfd890fefb0854d8906111614c716321981410...c7de05d00214a669cf6c9c3fb7a717c190918e18
diff --git a/src/main/java/org/dita/dost/platform/FileGenerator.java b/src/main/java/org/dita/dost/platform/FileGenerator.java index f33897e91..33128074b 100644 --- a/src/main/java/org/dita/dost/platform/FileGenerator.java +++ b/src/main/java/org/dita/dost/platform/FileGenerator.java @@ -170,9 +170,10 @@ final class FileGenerator extends XMLFilterImpl { } getContentHandler().startElement(uri, localName, qName, atts.build()); } + } catch (SAXException | RuntimeException e) { + throw e; } catch (final Exception e) { - e.printStackTrace(); - logger.error(e.getMessage(), e) ; + throw new RuntimeException(e); } } diff --git a/src/main/java/org/dita/dost/platform/InsertAction.java b/src/main/java/org/dita/dost/platform/InsertAction.java index c1acfa2ba..7f99b56f6 100644 --- a/src/main/java/org/dita/dost/platform/InsertAction.java +++ b/src/main/java/org/dita/dost/platform/InsertAction.java @@ -8,6 +8,9 @@ */ package org.dita.dost.platform; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.UncheckedIOException; import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.List; @@ -72,12 +75,16 @@ class InsertAction extends XMLFilterImpl implements IAction { public void getResult(final ContentHandler retBuf) throws SAXException { setContentHandler(retBuf); try { - for (final Value fileName: fileNameSet) { + for (final Value fileName : fileNameSet) { currentFile = fileName.value; reader.parse(currentFile); } - } catch (final Exception e) { - logger.error(e.getMessage(), e) ; + } catch (SAXException | RuntimeException e) { + throw e; + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (Exception e) { + throw new RuntimeException(e); } } diff --git a/src/test/java/org/dita/dost/platform/IntegratorTest.java b/src/test/java/org/dita/dost/platform/IntegratorTest.java index 7e56b4304..85df8b5ad 100644 --- a/src/test/java/org/dita/dost/platform/IntegratorTest.java +++ b/src/test/java/org/dita/dost/platform/IntegratorTest.java @@ -11,10 +11,9 @@ import static org.dita.dost.TestUtils.assertXMLEqual; import static org.dita.dost.util.Constants.CONF_SUPPORTED_IMAGE_EXTENSIONS; import static org.junit.Assert.*; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.Properties; @@ -110,7 +109,25 @@ public class IntegratorTest { new InputSource(new File(tempDir, "xsl" + File.separator + "shell.xsl").toURI().toString())); assertXMLEqual(new InputSource(new File(expDir, "plugins" + File.separator + "dummy" + File.separator + "xsl" + File.separator + "shell.xsl").toURI().toString()), new InputSource(new File(tempDir, "plugins" + File.separator + "dummy" + File.separator + "xsl" + File.separator + "shell.xsl").toURI().toString())); + } + + @Test(expected = UncheckedIOException.class) + public void testExecute_missingFile() throws Exception { + Files.delete(tempDir.toPath().resolve(Paths.get("plugins", "dummy", "build.xml"))); + + final File libDir = new File(tempDir, "lib"); + if (!libDir.exists() && !libDir.mkdirs()) { + throw new IOException("Failed to create directory " + libDir); + } + final File resourcesDir = new File(tempDir, "resources"); + if (!resourcesDir.exists() && !resourcesDir.mkdirs()) { + throw new IOException("Failed to create directory " + resourcesDir); + } + final Integrator i = new Integrator(tempDir); + i.setProperties(new File(tempDir, "integrator.properties")); + i.setLogger(new TestUtils.TestLogger(false)); + i.execute(); } private Properties getProperties(final File f) throws IOException {
['src/main/java/org/dita/dost/platform/FileGenerator.java', 'src/main/java/org/dita/dost/platform/InsertAction.java', 'src/test/java/org/dita/dost/platform/IntegratorTest.java']
{'.java': 3}
3
3
0
0
3
1,927,237
396,350
51,529
247
740
138
18
2
361
37
85
9
0
0
1970-01-01T00:27:16
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
142
dita-ot/dita-ot/3871/3858
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3858
https://github.com/dita-ot/dita-ot/pull/3871
https://github.com/dita-ot/dita-ot/pull/3871
1
fixes
Strict mode doesn't cause failure when images are missing, though it reports that as an ERROR
## Expected Behavior When processing-mode=strict, builds fail when any missing file is reported (error [DOTX008E][ERROR]) ## Actual Behavior When using strict, I get build failures when a file referenced by a topicref in a ditamap isn't found. But I don't get failures for missing images, although strict mode is supposed to fail on any error. ## Copy of the error message, log file or stack trace [dita-ot] [topic-reader] [DOTX008E][ERROR] File 'file:/C:/workgit/dt-pipeline/dita-test/content/images/NONEXISTENTnote.png' does not exist or cannot be loaded. ## Environment <!-- Include relevant details about the environment you experienced this in. --> * DITA-OT version: 3.6.1 * Operating system and version: Windows 10, LInux * How did you run DITA-OT? command line * Transformation type: HTML and PDF
a21e75f7fed5879f8fc97c94a1f78b2119024a05
3f94d608635bf92a02632b28c5270e18c4f7bb11
https://github.com/dita-ot/dita-ot/compare/a21e75f7fed5879f8fc97c94a1f78b2119024a05...3f94d608635bf92a02632b28c5270e18c4f7bb11
diff --git a/src/main/java/org/dita/dost/module/reader/TopicReaderModule.java b/src/main/java/org/dita/dost/module/reader/TopicReaderModule.java index 01542c227..3176209e3 100644 --- a/src/main/java/org/dita/dost/module/reader/TopicReaderModule.java +++ b/src/main/java/org/dita/dost/module/reader/TopicReaderModule.java @@ -12,12 +12,14 @@ import net.sf.saxon.s9api.QName; import net.sf.saxon.s9api.XdmNode; import org.dita.dost.exception.DITAOTException; import org.dita.dost.exception.DITAOTXMLErrorHandler; +import org.dita.dost.exception.UncheckedDITAOTException; import org.dita.dost.log.MessageUtils; import org.dita.dost.module.filter.SubjectScheme; import org.dita.dost.pipeline.AbstractPipelineInput; import org.dita.dost.pipeline.AbstractPipelineOutput; import org.dita.dost.reader.GenListModuleReader.Reference; import org.dita.dost.reader.SubjectSchemeReader; +import org.dita.dost.util.Configuration; import org.dita.dost.util.Job.FileInfo; import org.dita.dost.writer.DebugFilter; import org.dita.dost.writer.NormalizeFilter; @@ -296,7 +298,11 @@ public final class TopicReaderModule extends AbstractReaderModule { } else if (ATTR_FORMAT_VALUE_IMAGE.equals(file.format)) { formatSet.add(file); if (!exists(file.filename)) { - logger.warn(MessageUtils.getMessage("DOTX008E", file.filename.toString()).toString()); + if (processingMode == Configuration.Mode.STRICT) { + throw new UncheckedDITAOTException(MessageUtils.getMessage("DOTX008E", file.filename.toString()).toException()); + } else { + logger.warn(MessageUtils.getMessage("DOTX008E", file.filename.toString()).toString()); + } } } else { htmlSet.put(file.format, file.filename);
['src/main/java/org/dita/dost/module/reader/TopicReaderModule.java']
{'.java': 1}
1
1
0
0
1
1,927,608
396,414
51,537
247
582
102
8
1
833
118
208
20
0
0
1970-01-01T00:27:23
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
141
dita-ot/dita-ot/3884/3877
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3877
https://github.com/dita-ot/dita-ot/pull/3884
https://github.com/dita-ot/dita-ot/pull/3884
1
fixes
Build log should provide the name of the file where the issue was found
## Expected Behavior When DITA OT encounters a `keyref ERROR [DOTJ046E]` and a `filter WARNING [DOTJ049W]`, it should provide the name of the file where the issue was found. ## Actual Behavior The build log shows only the following messages, without providing the name of the file where the issue was found: ``` [keyref] [DOTJ046E][ERROR] Conkeyref="cloud/cloudPlatformFull" can not be resolved because it does not contain a key or the key is not defined. The build will use the conref attribute for fallback, if one exists. ``` ``` [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content ``` ## Possible Solution Extend the build log to provide clear information on where the issue was found ## Copy of the error message, log file or stack trace ``` 13:26:40 [keyref] [DOTJ046E][ERROR] Conkeyref="cloud/csBookTitle" can not be resolved because it does not contain a key or the key is not defined. The build will use the conref attribute for fallback, if one exists. 13:27:00    [keyref] [DOTJ046E][ERROR] Conkeyref="cloud/productNameSuffix" can not be resolved because it does not contain a key or the key is not defined. The build will use the conref attribute for fallback, if one exists. 13:27:00    [keyref] [DOTJ046E][ERROR] Conkeyref="cloud/productNameSuffix" can not be resolved because it does not contain a key or the key is not defined. The build will use the conref attribute for fallback, if one exists. 13:27:07    [keyref] [DOTJ046E][ERROR] Conkeyref="cloud/productNameSuffix" can not be resolved because it does not contain a key or the key is not defined. The build will use the conref attribute for fallback, if one exists. 13:27:07    [keyref] [DOTJ046E][ERROR] Conkeyref="cloud/productNameSuffix" can not be resolved because it does not contain a key or the key is not defined. The build will use the conref attribute for fallback, if one exists. ``` ``` 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the chunk attribute: select-branch to-content by-content 12:31:27    [filter] [DOTJ049W][WARN] The attribute value chunk="to-content" on element "chapter" does not comply with the specified subject scheme. According to the subject scheme map, the following 12:33:11    [filter] [DOTJ049W][WARN] The attribute value audience="release" on element "topichead" does not comply with the specified subject scheme. According to the subject scheme map, the following values are valid for the audience attribute: internal,external,earlyaccess,reviewer ``` ## Environment * DITA-OT version: 3.4.1 * Operating system and version: Docker image created from the `adoptopenjdk:11-jdk-hotspot` image * How did you run DITA-OT? `dita` command * Transformation type: Customized Oxygen Webhelp responsive
a21e75f7fed5879f8fc97c94a1f78b2119024a05
56cad0a328a4015f868b0731ac2afbd9278bb833
https://github.com/dita-ot/dita-ot/compare/a21e75f7fed5879f8fc97c94a1f78b2119024a05...56cad0a328a4015f868b0731ac2afbd9278bb833
diff --git a/src/main/java/org/dita/dost/reader/ConrefPushReader.java b/src/main/java/org/dita/dost/reader/ConrefPushReader.java index 12f37f7a7..ea19ba687 100644 --- a/src/main/java/org/dita/dost/reader/ConrefPushReader.java +++ b/src/main/java/org/dita/dost/reader/ConrefPushReader.java @@ -269,7 +269,7 @@ public final class ConrefPushReader extends AbstractXMLReader { final String fragment = target.getFragment(); if (fragment == null) { //if there is no '#' in target string, report error - logger.error(MessageUtils.getMessage("DOTJ041E", target.toString()).toString()); + logger.error(MessageUtils.getMessage("DOTJ041E", target.toString()).setLocation(atts).toString()); } else { String id; //has element id diff --git a/src/main/java/org/dita/dost/reader/CopyToReader.java b/src/main/java/org/dita/dost/reader/CopyToReader.java index 1d4176775..752e5ee6b 100644 --- a/src/main/java/org/dita/dost/reader/CopyToReader.java +++ b/src/main/java/org/dita/dost/reader/CopyToReader.java @@ -162,7 +162,8 @@ public final class CopyToReader extends AbstractXMLFilter { final URI copyToSourceAbs = copyToMap.get(targetAbs); if (copyToSourceAbs != null) { if (!sourceAbs.equals(copyToSourceAbs)) { - logger.warn(MessageUtils.getMessage("DOTX065W", source.toString(), targetAbs.toString()).toString()); + logger.warn(MessageUtils.getMessage("DOTX065W", source.toString(), targetAbs.toString()) + .setLocation(atts).toString()); } } else if (atts.getValue(ATTRIBUTE_NAME_CHUNK) != null && atts.getValue(ATTRIBUTE_NAME_CHUNK).contains(CHUNK_TO_CONTENT)) { diff --git a/src/main/java/org/dita/dost/reader/DitaValReader.java b/src/main/java/org/dita/dost/reader/DitaValReader.java index f05ec2776..21d810971 100644 --- a/src/main/java/org/dita/dost/reader/DitaValReader.java +++ b/src/main/java/org/dita/dost/reader/DitaValReader.java @@ -179,7 +179,7 @@ public final class DitaValReader implements AbstractReader { action = readFlag(elem); break; default: - throw new IllegalArgumentException(MessageUtils.getMessage("DOTJ077F", attAction).toString()); + throw new IllegalArgumentException(MessageUtils.getMessage("DOTJ077F", attAction).setLocation(elem).toString()); } if (action != null) { final QName attName; @@ -205,7 +205,7 @@ public final class DitaValReader implements AbstractReader { } if (attName != null && attName.equals(REV) && !filterAttributes.isEmpty() && !filterAttributes.contains(REV)) { - logger.warn(MessageUtils.getMessage("DOTJ074W").toString()); + logger.warn(MessageUtils.getMessage("DOTJ074W").setLocation((elem)).toString()); return; } } diff --git a/src/main/java/org/dita/dost/reader/KeydefFilter.java b/src/main/java/org/dita/dost/reader/KeydefFilter.java index be8727746..eff88d0cc 100644 --- a/src/main/java/org/dita/dost/reader/KeydefFilter.java +++ b/src/main/java/org/dita/dost/reader/KeydefFilter.java @@ -144,7 +144,7 @@ public final class KeydefFilter extends AbstractXMLFilter { keysDefMap.put(key, new KeyDef(key, null, null, null, null, null)); } } else { - logger.info(MessageUtils.getMessage("DOTJ045I", key).toString()); + logger.info(MessageUtils.getMessage("DOTJ045I", key).setLocation(atts).toString()); } } } diff --git a/src/main/java/org/dita/dost/reader/MergeMapParser.java b/src/main/java/org/dita/dost/reader/MergeMapParser.java index 3c9b0553d..aae040e70 100644 --- a/src/main/java/org/dita/dost/reader/MergeMapParser.java +++ b/src/main/java/org/dita/dost/reader/MergeMapParser.java @@ -227,7 +227,9 @@ public final class MergeMapParser extends XMLFilterImpl { XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_FIRST_TOPIC_ID, firstTopicId.toString()); } else { final URI fileName = URLUtils.toDirURI(dirPath).resolve(attValue); - logger.error(MessageUtils.getMessage("DOTX008E", fileName.toString()).toString()); + logger.error(MessageUtils.getMessage("DOTX008E", fileName.toString()) + .setLocation(attributes) + .toString()); } } } diff --git a/src/main/java/org/dita/dost/writer/ConkeyrefFilter.java b/src/main/java/org/dita/dost/writer/ConkeyrefFilter.java index ffe86137c..0d67b5696 100644 --- a/src/main/java/org/dita/dost/writer/ConkeyrefFilter.java +++ b/src/main/java/org/dita/dost/writer/ConkeyrefFilter.java @@ -75,10 +75,10 @@ public final class ConkeyrefFilter extends AbstractXMLFilter { } XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_CONREF, target.toString()); } else { - logger.warn(MessageUtils.getMessage("DOTJ060W", key, conkeyref).toString()); + logger.warn(MessageUtils.getMessage("DOTJ060W", key, conkeyref).setLocation(atts).toString()); } } else { - logger.error(MessageUtils.getMessage("DOTJ046E", conkeyref).toString()); + logger.error(MessageUtils.getMessage("DOTJ046E", conkeyref).setLocation(atts).toString()); } } getContentHandler().startElement(uri, localName, name, resAtts != null ? resAtts : atts); diff --git a/src/main/java/org/dita/dost/writer/ValidationFilter.java b/src/main/java/org/dita/dost/writer/ValidationFilter.java index 617f54905..cb3f06f9c 100644 --- a/src/main/java/org/dita/dost/writer/ValidationFilter.java +++ b/src/main/java/org/dita/dost/writer/ValidationFilter.java @@ -304,7 +304,9 @@ public final class ValidationFilter extends AbstractXMLFilter { for (final String s : keylist) { if (!StringUtils.isEmptyString(s) && !valueSet.contains(s)) { logger.warn(MessageUtils.getMessage("DOTJ049W", - attrName.toString(), qName, attrValue, StringUtils.join(valueSet, COMMA)).toString()); + attrName.toString(), qName, attrValue, StringUtils.join(valueSet, COMMA)) + .setLocation(atts) + .toString()); } } } diff --git a/src/main/java/org/dita/dost/writer/include/IncludeText.java b/src/main/java/org/dita/dost/writer/include/IncludeText.java index 79690145b..e4cff074d 100644 --- a/src/main/java/org/dita/dost/writer/include/IncludeText.java +++ b/src/main/java/org/dita/dost/writer/include/IncludeText.java @@ -42,7 +42,7 @@ final class IncludeText { boolean include(final Attributes atts) { final URI hrefValue = toURI(atts.getValue(ATTRIBUTE_NAME_HREF)); - final Charset charset = getCharset(atts.getValue(ATTRIBUTE_NAME_FORMAT), atts.getValue(ATTRIBUTE_NAME_ENCODING)); + final Charset charset = getCharset(atts); final Range range = getRange(hrefValue); final File codeFile = getFile(hrefValue); if (codeFile != null) { @@ -125,11 +125,12 @@ final class IncludeText { /** * Get code file charset. * - * @param format format attribute value, may be {@code null} - * @param encoding encoding attribute balue, may be {@code null} * @return charset if set, otherwise default charset */ - private Charset getCharset(final String format, final String encoding) { + + private Charset getCharset(Attributes atts) { + final String format = atts.getValue(ATTRIBUTE_NAME_FORMAT); + final String encoding = atts.getValue(ATTRIBUTE_NAME_ENCODING); Charset c = null; try { if (encoding != null) { @@ -141,7 +142,7 @@ final class IncludeText { } } } catch (final RuntimeException e) { - logger.error(MessageUtils.getMessage("DOTJ052E", encoding).toString()); + logger.error(MessageUtils.getMessage("DOTJ052E", encoding).setLocation(atts).toString()); } if (c == null) { final String defaultCharset = Configuration.configuration.get("default.coderef-charset");
['src/main/java/org/dita/dost/writer/ValidationFilter.java', 'src/main/java/org/dita/dost/reader/ConrefPushReader.java', 'src/main/java/org/dita/dost/writer/include/IncludeText.java', 'src/main/java/org/dita/dost/writer/ConkeyrefFilter.java', 'src/main/java/org/dita/dost/reader/KeydefFilter.java', 'src/main/java/org/dita/dost/reader/DitaValReader.java', 'src/main/java/org/dita/dost/reader/MergeMapParser.java', 'src/main/java/org/dita/dost/reader/CopyToReader.java']
{'.java': 8}
8
8
0
0
8
1,927,608
396,414
51,537
247
3,009
530
34
8
5,125
701
1,241
46
0
4
1970-01-01T00:27:25
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
140
dita-ot/dita-ot/3893/3662
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3662
https://github.com/dita-ot/dita-ot/pull/3893
https://github.com/dita-ot/dita-ot/pull/3893
1
fixes
<xsl:message> (in plugin XSLT files) no longer shows element structure
## Expected Behavior When I add the following XSLT template via a DITA-OT plugin: ``` <xsl:template match="*" priority="1000"> <xsl:message>BEGIN--<xsl:copy-of select="."/>--END</xsl:message> <xsl:next-match/> </xsl:template> ``` I expect to see XML copies of the elements matched by that template. ## Actual Behavior In 3.5.4 and earlier releases, I see the XML structure: ``` [mapref] BEGIN--<keywords xmlns:dita-ot="http://dita-ot.sourceforge.net/ns/201007/dita-ot" xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- topic/keywords " xtrc="keywords:1;7:17" xtrf="file:/home/chrispy/BUG/map.ditamap"> [mapref] <keyword class="- topic/keyword " xtrc="keyword:1;8:18" xtrf="file:/home/chrispy/BUG/map.ditamap">ProductA</keyword> [mapref] </keywords>--END [mapref] BEGIN--<keyword xmlns:dita-ot="http://dita-ot.sourceforge.net/ns/201007/dita-ot" xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- topic/keyword " xtrc="keyword:1;8:18" xtrf="file:/home/chrispy/BUG/map.ditamap">ProductA</keyword>--END ``` Starting with 3.6, I see only text node contents: ``` [mapref] BEGIN-- [mapref] ProductA [mapref] --END [mapref] BEGIN--ProductA--END [mapref] BEGIN----END ``` ## Steps to Reproduce 1. Unarchive the attached testcase. 2. Run the `do.sh` script (bash script, for linux environment) 3. In `do.out`, examine the `mapref` messages from 3.5.4 and 3.6. [BUG.zip](https://github.com/dita-ot/dita-ot/files/5757487/BUG.zip) ## Environment * DITA-OT version: 3.6 * Operating system and version: Windows 10, running Ubuntu 18.04 LTS via WSL * Ran via: `dita` command line * Transformation type: `dita`
dc1b631a2a4d4978617300ef582321fa90bfd9f7
1400618952ed28b91f5e70535c356eb1b61011a0
https://github.com/dita-ot/dita-ot/compare/dc1b631a2a4d4978617300ef582321fa90bfd9f7...1400618952ed28b91f5e70535c356eb1b61011a0
diff --git a/src/main/java/org/dita/dost/util/XMLUtils.java b/src/main/java/org/dita/dost/util/XMLUtils.java index 8cf929206..58e6f800e 100644 --- a/src/main/java/org/dita/dost/util/XMLUtils.java +++ b/src/main/java/org/dita/dost/util/XMLUtils.java @@ -11,7 +11,9 @@ import com.google.common.annotations.VisibleForTesting; import net.sf.saxon.expr.instruct.TerminationException; import net.sf.saxon.lib.*; import net.sf.saxon.s9api.*; +import net.sf.saxon.s9api.streams.Predicates; import net.sf.saxon.s9api.streams.Step; +import net.sf.saxon.s9api.streams.XdmStream; import org.apache.xml.resolver.tools.CatalogResolver; import org.dita.dost.exception.DITAOTException; import org.dita.dost.log.DITAOTLogger; @@ -31,6 +33,7 @@ import javax.xml.transform.stream.StreamSource; import java.io.*; import java.net.URI; import java.util.*; +import java.util.stream.Collectors; import java.util.stream.Stream; import static javax.xml.XMLConstants.DEFAULT_NS_PREFIX; @@ -154,7 +157,13 @@ public final class XMLUtils { .findAny() .map(XdmItem::getStringValue) .orElse("INFO"); - final String msg = content.getStringValue(); + final String msg = content + .select(descendant( + hasLocalName("level").or(hasLocalName("error-code")) + .and(hasType(ItemType.PROCESSING_INSTRUCTION_NODE)) + .negate())) + .map(n -> n.toString()) + .collect(Collectors.joining()); switch (level) { case "FATAL": final TerminationException err = new TerminationException(msg); diff --git a/src/test/java/org/dita/dost/util/XMLUtilsTest.java b/src/test/java/org/dita/dost/util/XMLUtilsTest.java index 1f1a5ec9d..a9d1687b3 100644 --- a/src/test/java/org/dita/dost/util/XMLUtilsTest.java +++ b/src/test/java/org/dita/dost/util/XMLUtilsTest.java @@ -8,8 +8,14 @@ package org.dita.dost.util; import net.sf.saxon.Configuration; +import net.sf.saxon.expr.instruct.TerminationException; import net.sf.saxon.lib.CollationURIResolver; import net.sf.saxon.om.StructuredQName; +import net.sf.saxon.s9api.MessageListener2; +import net.sf.saxon.s9api.SaxonApiException; +import net.sf.saxon.s9api.SaxonApiUncheckedException; +import net.sf.saxon.s9api.XdmNode; +import net.sf.saxon.sapling.Saplings; import net.sf.saxon.trans.SymbolicName; import org.dita.dost.TestUtils; import org.dita.dost.TestUtils.CachingLogger; @@ -27,18 +33,11 @@ import org.xml.sax.helpers.AttributesImpl; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; -import java.io.StringReader; -import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; +import java.util.List; import static javax.xml.XMLConstants.NULL_NS_URI; import static javax.xml.XMLConstants.XML_NS_URI; @@ -267,6 +266,105 @@ public class XMLUtilsTest { assertTrue(XMLUtils.nonDitaContext(classes)); } + @Test + public void toMessageListener() throws SaxonApiException { + final CachingLogger logger = new CachingLogger(); + final MessageListener2 listener = XMLUtils.toMessageListener(logger); + + final XdmNode msg = Saplings.doc().withChild( + Saplings.text("message "), + Saplings.elem("debug") + ) + .toXdmNode(new XMLUtils().getProcessor()); + + listener.message(msg, null, false, null); + + final List<Message> act = logger.getMessages(); + assertEquals(1, act.size()); + assertEquals(new Message(Message.Level.INFO, "message <debug/>", null), act.get(0)); + } + + @Test + public void toMessageListener_withLevelAndErrorCode() throws SaxonApiException { + final CachingLogger logger = new CachingLogger(); + final MessageListener2 listener = XMLUtils.toMessageListener(logger); + + final XdmNode msg = Saplings.doc().withChild( + Saplings.pi("error-code", "DOTX037W"), + Saplings.pi("level", "WARN"), + Saplings.text("message "), + Saplings.elem("debug") + ) + .toXdmNode(new XMLUtils().getProcessor()); + + listener.message(msg, null, false, null); + + final List<Message> act = logger.getMessages(); + assertEquals(1, act.size()); + assertEquals(new Message(Message.Level.WARN, "message <debug/>", null), act.get(0)); + } + + @Test + public void toMessageListener_withErrorCode() throws SaxonApiException { + final CachingLogger logger = new CachingLogger(); + final MessageListener2 listener = XMLUtils.toMessageListener(logger); + + final XdmNode msg = Saplings.doc().withChild( + Saplings.pi("error-code", "DOTX037W"), + Saplings.text("message "), + Saplings.elem("debug") + ) + .toXdmNode(new XMLUtils().getProcessor()); + + listener.message(msg, null, false, null); + + final List<Message> act = logger.getMessages(); + assertEquals(1, act.size()); + assertEquals(new Message(Message.Level.INFO, "message <debug/>", null), act.get(0)); + } + + @Test + public void toMessageListener_withFatalErrorCode() throws SaxonApiException { + final CachingLogger logger = new CachingLogger(); + final MessageListener2 listener = XMLUtils.toMessageListener(logger); + + final XdmNode msg = Saplings.doc().withChild( + Saplings.pi("error-code", "DOTX037W"), + Saplings.pi("level", "WARN"), + Saplings.text("message "), + Saplings.elem("debug") + ) + .toXdmNode(new XMLUtils().getProcessor()); + + try { + listener.message(msg, null, true, null); + fail(); + } catch (SaxonApiUncheckedException e) { + final TerminationException cause = (TerminationException) e.getCause(); + assertEquals("DOTX037W", cause.getErrorCodeLocalPart()); + assertEquals("message <debug/>", cause.getMessage()); + } + } + + @Test + public void toMessageListener_withLevel() throws SaxonApiException { + final CachingLogger logger = new CachingLogger(); + final MessageListener2 listener = XMLUtils.toMessageListener(logger); + + final XdmNode msg = Saplings.doc().withChild( + Saplings.pi("level", "ERROR"), + Saplings.text("message "), + Saplings.elem("debug") + ) + .toXdmNode(new XMLUtils().getProcessor()); + + listener.message(msg, null, false, null); + + final List<Message> act = logger.getMessages(); + assertEquals(1, act.size()); + assertEquals(new Message(Message.Level.ERROR, "message <debug/>", null), act.get(0)); + } + // @Test // public void transform() throws Exception { // copyFile(new File(srcDir, "test.dita"), new File(tempDir, "test.dita"));
['src/test/java/org/dita/dost/util/XMLUtilsTest.java', 'src/main/java/org/dita/dost/util/XMLUtils.java']
{'.java': 2}
2
2
0
0
2
1,927,969
396,480
51,543
247
610
105
11
1
1,750
159
559
45
5
3
1970-01-01T00:27:25
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
124
dita-ot/dita-ot/3880/2844
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/2844
https://github.com/dita-ot/dita-ot/pull/3880
https://github.com/dita-ot/dita-ot/issues/2844#issuecomment-1041136435
2
fixed
Error in HTML publishing if any topic has apostrophe in its name
Create a topic with apostrophe in its name e.g. i'm_topic.dita. Put it in ditamap and publish. PDF works fine but xhtml and html5 give NullPointerException.
1c488e86830c66f3d3787f29677ea56fcbee4379
41efb7e19ce5ec0707e63c0b8bf52d828823a77d
https://github.com/dita-ot/dita-ot/compare/1c488e86830c66f3d3787f29677ea56fcbee4379...41efb7e19ce5ec0707e63c0b8bf52d828823a77d
diff --git a/src/main/java/org/dita/dost/util/URLUtils.java b/src/main/java/org/dita/dost/util/URLUtils.java index 3915bb3ca..1e5e7e0a7 100644 --- a/src/main/java/org/dita/dost/util/URLUtils.java +++ b/src/main/java/org/dita/dost/util/URLUtils.java @@ -313,7 +313,10 @@ public final class URLUtils { //'%', '"', '{', '}', //'?', - '|', '\\\\', '^', '~', '[', ']', '`', '\\'', + '|', '\\\\', '^', + //'~', + '[', ']', '`', + //'\\'', //'&' }; char ch; diff --git a/src/test/java/org/dita/dost/util/URLUtilsTest.java b/src/test/java/org/dita/dost/util/URLUtilsTest.java index fa1b43f4d..b89e5d03f 100644 --- a/src/test/java/org/dita/dost/util/URLUtilsTest.java +++ b/src/test/java/org/dita/dost/util/URLUtilsTest.java @@ -140,6 +140,7 @@ public class URLUtilsTest { assertEquals(new URI("foo%20bar.txt"), URLUtils.toURI("foo bar.txt")); assertEquals(new URI("foo/bar.txt"), URLUtils.toURI("foo" + Constants.WINDOWS_SEPARATOR + "bar.txt")); assertEquals(new URI("foo%20bar.txt"), URLUtils.toURI(" foo bar.txt ")); + assertEquals(new URI("user's%20manual.txt"), URLUtils.toURI("user's manual.txt")); assertEquals(new URI("http://www.example.com/"), URLUtils.toURI(" http://www.example.com/ ")); }
['src/test/java/org/dita/dost/util/URLUtilsTest.java', 'src/main/java/org/dita/dost/util/URLUtils.java']
{'.java': 2}
2
2
0
0
2
1,927,363
396,371
51,531
247
172
39
5
1
157
25
39
2
0
0
1970-01-01T00:27:24
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
138
dita-ot/dita-ot/3912/3730
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3730
https://github.com/dita-ot/dita-ot/pull/3912
https://github.com/dita-ot/dita-ot/pull/3912
1
fixes
ValidationFilter stage breaks with unexpected error for invalid URL
I have this link in a DITA topic: <xref href="http://www,oxygenxml.com" format="html" scope="external"/> notice there is a comma in the href attribute value instead of a dot. I publish to HTML5, the publishing breaks with: D:\\projects\\DITA-OT3.x\\plugins\\org.dita.base\\build_preprocess.xml:96: java.lang.RuntimeException: Expected scheme-specific part at index 5: http: at org.dita.dost.util.URLUtils.setFragment(URLUtils.java:559) at org.dita.dost.util.URLUtils.stripFragment(URLUtils.java:541) at org.dita.dost.writer.ValidationFilter.validateReference(ValidationFilter.java:199) at org.dita.dost.writer.ValidationFilter.startElement(ValidationFilter.java:96) at org.dita.dost.writer.ProfilingFilter.startElement(ProfilingFilter.java:121) at org.xml.sax.helpers.XMLFilterImpl.startElement(Unknown Source) at org.dita.dost.writer.DebugFilter.startElement(DebugFilter.java:78) at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source) at org.apache.xerces.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source) The URL is not really invalid according to the URI standard, so you can create an URI over it: new URI("http://www,oxygenxml.com")
3ad51f08724488a53651b8d88ec0f619bc9b2568
e952f5e2bd892d3423c917d40f9979cd98283565
https://github.com/dita-ot/dita-ot/compare/3ad51f08724488a53651b8d88ec0f619bc9b2568...e952f5e2bd892d3423c917d40f9979cd98283565
diff --git a/src/main/java/org/dita/dost/util/URLUtils.java b/src/main/java/org/dita/dost/util/URLUtils.java index 94f40fd20..8eb0b87f0 100644 --- a/src/main/java/org/dita/dost/util/URLUtils.java +++ b/src/main/java/org/dita/dost/util/URLUtils.java @@ -572,7 +572,11 @@ public final class URLUtils { */ public static URI setQuery(final URI path, final String query) { try { - return new URI(path.getScheme(), path.getUserInfo(), path.getHost(), path.getPort(), path.getPath(), query, path.getFragment()); + if (path.getPath() != null) { + return new URI(path.getScheme(), path.getUserInfo(), path.getHost(), path.getPort(), path.getPath(), query, path.getFragment()); + } else { + return new URI(path.getScheme(), path.getSchemeSpecificPart(), path.getFragment()); + } } catch (final URISyntaxException e) { throw new RuntimeException(e.getMessage(), e); } diff --git a/src/main/java/org/dita/dost/writer/ValidationFilter.java b/src/main/java/org/dita/dost/writer/ValidationFilter.java index 585fbdc36..0c4cc91b8 100644 --- a/src/main/java/org/dita/dost/writer/ValidationFilter.java +++ b/src/main/java/org/dita/dost/writer/ValidationFilter.java @@ -197,9 +197,9 @@ public final class ValidationFilter extends AbstractXMLFilter { if (href != null) { try { final URI uri = new URI(href); - final URI abs = URLUtils.setQuery(URLUtils.stripFragment(currentFile.resolve(uri)).normalize(), null); - if (abs.getScheme() != null && abs.getScheme().equals("file")) { - final File p = new File(abs); + final URI abs = currentFile.resolve(uri).normalize(); + if (Objects.equals(abs.getScheme(), "file")) { + final File p = new File(URLUtils.setQuery(URLUtils.stripFragment(abs), null)); try { final File canFile = p.getCanonicalFile(); final String absPath = p.getAbsolutePath(); diff --git a/src/test/java/org/dita/dost/util/URLUtilsTest.java b/src/test/java/org/dita/dost/util/URLUtilsTest.java index f82d36fdf..a24d71cb9 100644 --- a/src/test/java/org/dita/dost/util/URLUtilsTest.java +++ b/src/test/java/org/dita/dost/util/URLUtilsTest.java @@ -188,6 +188,11 @@ public class URLUtilsTest { assertEquals(new URI("urn:foo:bar"), URLUtils.setFragment(new URI("urn:foo:bar"), null)); } + @Test + public void setFragment_mailto() { + assertEquals(URI.create("mailto:[email protected]?subject=Email"), URLUtils.setFragment(URI.create("mailto:[email protected]?subject=Email"), null)); + } + @Test public void testRemoveFragment() throws URISyntaxException { assertEquals(new URI("foo"), URLUtils.removeFragment(new URI("foo#bar"))); @@ -291,4 +296,9 @@ public class URLUtilsTest { assertEquals(URI.create("foo"), URLUtils.setQuery(URI.create("foo?bar"), null)); assertEquals(URI.create("foo?baz"), URLUtils.setQuery(URI.create("foo?bar"), "baz")); } + + @Test + public void setQuery_mailto() { + assertEquals(URI.create("mailto:[email protected]?subject=Email"), URLUtils.setQuery(URI.create("mailto:[email protected]?subject=Email"), null)); + } }
['src/main/java/org/dita/dost/writer/ValidationFilter.java', 'src/test/java/org/dita/dost/util/URLUtilsTest.java', 'src/main/java/org/dita/dost/util/URLUtils.java']
{'.java': 3}
3
3
0
0
3
1,931,569
397,167
51,632
247
955
182
12
2
1,216
85
286
21
2
0
1970-01-01T00:27:29
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
125
dita-ot/dita-ot/4257/4064
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/4064
https://github.com/dita-ot/dita-ot/pull/4257
https://github.com/dita-ot/dita-ot/pull/4257
1
fixes
Chunk to content on DITA Map fails when the DITA Map has spaces in file name
I have a DITA Map with spaces in its file name "flowers by season_map.ditamap" which has chunk=to-content set on the root element. Publishing it to HTML5 fails with: /.../plugins/org.dita.base/build_preprocess.xml:260: java.lang.IllegalArgumentException: Illegal character in path at index 7: flowers by season_map.dita at java.base/java.net.URI.create(URI.java:906) at java.base/java.net.URI.resolve(URI.java:1089) at org.dita.dost.reader.ChunkMapReader.chunkMap(ChunkMapReader.java:209) at org.dita.dost.reader.ChunkMapReader.process(ChunkMapReader.java:136) at org.dita.dost.writer.AbstractDomFilter.read(AbstractDomFilter.java:41) [flowers22.zip](https://github.com/dita-ot/dita-ot/files/10089903/flowers22.zip)
4485c1d50d4c1a966f4fe691af6c0fd4c65c3acc
bdee5383a62675b2a37283b3d6a4d3f42fa17e44
https://github.com/dita-ot/dita-ot/compare/4485c1d50d4c1a966f4fe691af6c0fd4c65c3acc...bdee5383a62675b2a37283b3d6a4d3f42fa17e44
diff --git a/src/main/java/org/dita/dost/reader/ChunkMapReader.java b/src/main/java/org/dita/dost/reader/ChunkMapReader.java index c28621c16..584e596e2 100644 --- a/src/main/java/org/dita/dost/reader/ChunkMapReader.java +++ b/src/main/java/org/dita/dost/reader/ChunkMapReader.java @@ -35,6 +35,7 @@ import org.dita.dost.module.reader.TempFileNameScheme; import org.dita.dost.util.DitaClass; import org.dita.dost.util.Job; import org.dita.dost.util.Job.FileInfo; +import org.dita.dost.util.URLUtils; import org.dita.dost.util.XMLSerializer; import org.dita.dost.writer.AbstractDomFilter; import org.dita.dost.writer.ChunkTopicParser; @@ -208,11 +209,11 @@ public final class ChunkMapReader extends AbstractDomFilter { */ private void chunkMap(final Element root) { // create the reference to the new file on root element. - String newFilename = replaceExtension(new File(currentFile).getName(), FILE_EXTENSION_DITA); + URI newFilename = URLUtils.toURI(replaceExtension(new File(currentFile).getName(), FILE_EXTENSION_DITA)); URI newFile = currentFile.resolve(newFilename); if (job.getStore().exists(newFile)) { final URI oldFile = newFile; - newFilename = chunkFilenameGenerator.generateFilename(CHUNK_PREFIX, FILE_EXTENSION_DITA); + newFilename = URLUtils.toURI(chunkFilenameGenerator.generateFilename(CHUNK_PREFIX, FILE_EXTENSION_DITA)); newFile = currentFile.resolve(newFilename); // Mark up the possible name changing, in case that references might be updated. conflictTable.put(newFile, oldFile.normalize()); @@ -222,7 +223,7 @@ public final class ChunkMapReader extends AbstractDomFilter { // change the class attribute to "topicref" final String origCls = root.getAttribute(ATTRIBUTE_NAME_CLASS); root.setAttribute(ATTRIBUTE_NAME_CLASS, origCls + MAP_TOPICREF.matcher); - root.setAttribute(ATTRIBUTE_NAME_HREF, toURI(newFilename).toString()); + root.setAttribute(ATTRIBUTE_NAME_HREF, newFilename.toString()); createTopicStump(newFile);
['src/main/java/org/dita/dost/reader/ChunkMapReader.java']
{'.java': 1}
1
1
0
0
1
1,784,279
405,995
53,390
253
600
122
7
1
744
51
193
13
1
0
1970-01-01T00:28:11
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
127
dita-ot/dita-ot/4248/4240
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/4240
https://github.com/dita-ot/dita-ot/pull/4248
https://github.com/dita-ot/dita-ot/pull/4248
1
fixes
DITAOTXMLErrorHandler no longer shows line/column number for error messages
On the callback method "org.dita.dost.exception.DITAOTXMLErrorHandler.error(SAXParseException)" if the processing is not strict, line column information is no longer logged in the console. So for example if there are validator errors in the XML document, their message is shown in the console but not their system id, line and column information. I suggest we replace: public void error(final SAXParseException saxException) throws SAXException { if (mode == Configuration.Mode.STRICT) { throw new SAXExceptionWrapper(filePath, saxException); } else { logger.error(new SAXExceptionWrapper(filePath, saxException).getMessage(), saxException); } } with: public void error(final SAXParseException saxException) throws SAXException { SAXExceptionWrapper ex = new SAXExceptionWrapper(filePath, saxException); if (mode == Configuration.Mode.STRICT) { throw ex; } else { logger.error(ex.getMessage(), saxException); } }
7ab347e8862da8c6ede87966b236739386b372e7
80639433c6e78650ef27fe35951f07d5f3b40b8b
https://github.com/dita-ot/dita-ot/compare/7ab347e8862da8c6ede87966b236739386b372e7...80639433c6e78650ef27fe35951f07d5f3b40b8b
diff --git a/src/main/java/org/dita/dost/exception/DITAOTXMLErrorHandler.java b/src/main/java/org/dita/dost/exception/DITAOTXMLErrorHandler.java index 09bc39c7b..e913b2d30 100644 --- a/src/main/java/org/dita/dost/exception/DITAOTXMLErrorHandler.java +++ b/src/main/java/org/dita/dost/exception/DITAOTXMLErrorHandler.java @@ -45,10 +45,11 @@ public final class DITAOTXMLErrorHandler implements ErrorHandler { */ @Override public void error(final SAXParseException saxException) throws SAXException { + final SAXExceptionWrapper ex = new SAXExceptionWrapper(filePath, saxException); if (mode == Configuration.Mode.STRICT) { - throw new SAXExceptionWrapper(filePath, saxException); + throw ex; } else { - logger.error(saxException.getMessage(), saxException); + logger.error(ex.getMessage(), ex); } }
['src/main/java/org/dita/dost/exception/DITAOTXMLErrorHandler.java']
{'.java': 1}
1
1
0
0
1
1,776,644
404,263
53,172
251
267
50
5
1
1,027
108
202
22
0
0
1970-01-01T00:28:09
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
126
dita-ot/dita-ot/4255/3718
dita-ot
dita-ot
https://github.com/dita-ot/dita-ot/issues/3718
https://github.com/dita-ot/dita-ot/pull/4255
https://github.com/dita-ot/dita-ot/pull/4255
1
fixes
PDF2 build breakes due to an invalid xref's URI
Not sure if this is to be treated as a bug, an improvment or not at all, but in dita-3.3.3 one could generate a pdf2 document which contained an xref with an invalid URI, e.g. `<xref format="pdf" href="file://ccm/temp/diff.pdf" scope="external">file</xref>` The URI misses a 3 slash so that the authority component would be empty, instead it is //ccm/ which was not intended. It should have beed file:///ccm/temp/diff.pdf. However, dita-3.6.1. aborts the build with an exception: ``` BUILD FAILED C:\\bin\\dita-ot-3.6.1\\plugins\\org.dita.base\\build.xml:29: The following error occurred while executing this line: C:\\bin\\dita-ot-3.6.1\\plugins\\org.dita.base\\build_preprocess2.xml:171: java.lang.IllegalArgumentException: URI has an authority component at java.io.File.<init>(File.java:423) at org.dita.dost.writer.ValidationFilter.validateReference(ValidationFilter.java:201) at org.dita.dost.writer.ValidationFilter.startElement(ValidationFilter.java:96) at org.dita.dost.writer.ProfilingFilter.startElement(ProfilingFilter.java:121) at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source) ``` ## Expected Behavior Depending on the processing-mode, e.g. lax, a PDF2 document is generated ## Actual Behavior Build aborts with an exception ## Steps to Reproduce Build the attached document ## Copy of the error message, log file or stack trace ``` BUILD FAILED C:\\bin\\dita-ot-3.6.1\\plugins\\org.dita.base\\build.xml:29: The following error occurred while executing this line: C:\\bin\\dita-ot-3.6.1\\plugins\\org.dita.base\\build_preprocess2.xml:171: java.lang.IllegalArgumentException: URI has an authority component at java.io.File.<init>(File.java:423) at org.dita.dost.writer.ValidationFilter.validateReference(ValidationFilter.java:201) at org.dita.dost.writer.ValidationFilter.startElement(ValidationFilter.java:96) at org.dita.dost.writer.ProfilingFilter.startElement(ProfilingFilter.java:121) at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source) ``` ## Environment <!-- Include relevant details about the environment you experienced this in. --> * DITA-OT version: 3.6.1 * Operating system and version: Windows * How did you run DITA-OT? ant-launcher * Transformation type: PDF [authoring.zip](https://github.com/dita-ot/dita-ot/files/6181752/authoring.zip)
5edd854d18d15c90678e6ceff4de1013b2ada62d
ad030478c946bb1a15e5f93a8c7c13971e0c6fd5
https://github.com/dita-ot/dita-ot/compare/5edd854d18d15c90678e6ceff4de1013b2ada62d...ad030478c946bb1a15e5f93a8c7c13971e0c6fd5
diff --git a/src/main/java/org/dita/dost/writer/ValidationFilter.java b/src/main/java/org/dita/dost/writer/ValidationFilter.java index 371066c37..e887303e7 100644 --- a/src/main/java/org/dita/dost/writer/ValidationFilter.java +++ b/src/main/java/org/dita/dost/writer/ValidationFilter.java @@ -198,7 +198,7 @@ public final class ValidationFilter extends AbstractXMLFilter { try { final URI uri = new URI(href); final URI abs = currentFile.resolve(uri).normalize(); - if (Objects.equals(abs.getScheme(), "file")) { + if (Objects.equals(abs.getScheme(), "file") && (abs.getAuthority() == null || abs.getAuthority().isEmpty())) { final File p = new File(URLUtils.setQuery(URLUtils.stripFragment(abs), null)); try { final File canFile = p.getCanonicalFile(); diff --git a/src/test/java/org/dita/dost/writer/ValidationFilterTest.java b/src/test/java/org/dita/dost/writer/ValidationFilterTest.java index c279e853a..c16837233 100644 --- a/src/test/java/org/dita/dost/writer/ValidationFilterTest.java +++ b/src/test/java/org/dita/dost/writer/ValidationFilterTest.java @@ -63,7 +63,7 @@ public class ValidationFilterTest { } @Test - public void testHref() throws SAXException, URISyntaxException { + public void testHref() throws SAXException { final List<String> res = new ArrayList<>(); f.setContentHandler( new DefaultHandler() { @@ -103,7 +103,35 @@ public class ValidationFilterTest { } @Test - public void testConref() throws SAXException, URISyntaxException { + public void testHref_networkFile() throws SAXException { + final List<String> res = new ArrayList<>(); + f.setContentHandler( + new DefaultHandler() { + @Override + public void startElement(final String uri, final String localName, final String qName, final Attributes atts) { + res.add(atts.getValue(ATTRIBUTE_NAME_HREF)); + } + } + ); + final TestUtils.CachingLogger l = new TestUtils.CachingLogger(); + f.setLogger(l); + + f.startElement( + NULL_NS_URI, + TOPIC_XREF.localName, + TOPIC_XREF.localName, + new AttributesBuilder() + .add(ATTRIBUTE_NAME_HREF, "file://example.com/foo") + .add(ATTRIBUTE_NAME_SCOPE, ATTR_SCOPE_VALUE_EXTERNAL) + .build() + ); + + assertTrue(l.getMessages().isEmpty()); + assertEquals("file://example.com/foo", res.get(0)); + } + + @Test + public void testConref() throws SAXException { final List<String> res = new ArrayList<>(); f.setContentHandler( new DefaultHandler() { @@ -137,7 +165,7 @@ public class ValidationFilterTest { } @Test - public void testScope() throws SAXException, URISyntaxException { + public void testScope() throws SAXException { final List<String> res = new ArrayList<>(); f.setContentHandler( new DefaultHandler() { @@ -173,7 +201,7 @@ public class ValidationFilterTest { } @Test - public void testId() throws SAXException, URISyntaxException { + public void testId() throws SAXException { f.setContentHandler(new DefaultHandler()); final TestUtils.CachingLogger l = new TestUtils.CachingLogger(); f.setLogger(l); @@ -221,7 +249,7 @@ public class ValidationFilterTest { } @Test - public void testKeys() throws SAXException, URISyntaxException { + public void testKeys() throws SAXException { f.setContentHandler(new DefaultHandler()); final TestUtils.CachingLogger l = new TestUtils.CachingLogger(); f.setLogger(l); @@ -268,7 +296,7 @@ public class ValidationFilterTest { } @Test - public void testKeyscope() throws SAXException, URISyntaxException { + public void testKeyscope() throws SAXException { f.setContentHandler(new DefaultHandler()); final TestUtils.CachingLogger l = new TestUtils.CachingLogger(); f.setLogger(l);
['src/main/java/org/dita/dost/writer/ValidationFilter.java', 'src/test/java/org/dita/dost/writer/ValidationFilterTest.java']
{'.java': 2}
2
2
0
0
2
1,784,215
405,980
53,390
253
175
41
2
1
2,362
213
616
48
1
2
1970-01-01T00:28:11
349
Java
{'Java': 2476766, 'XSLT': 2016428, 'HTML': 1407059, 'SCSS': 34437, 'CSS': 27432, 'Shell': 15542, 'Batchfile': 11111, 'C': 4336, 'JavaScript': 2246, 'Dockerfile': 1771}
Apache License 2.0
412
wikidata/wikidata-toolkit/241/240
wikidata
wikidata-toolkit
https://github.com/Wikidata/Wikidata-Toolkit/issues/240
https://github.com/Wikidata/Wikidata-Toolkit/pull/241
https://github.com/Wikidata/Wikidata-Toolkit/pull/241
1
closes
Deserialization failure on dumps with redirects
The Wikidata daily XML dumps contains serialization for redirects. Wikidata Toolkit 0.7 fails when deserializing them: ``` java GRAVE: Failed to map JSON for item Q26790101: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type' that is to contain type id (for class org.wikidata.wdtk.datamodel.json.jackson.JacksonItemDocument) at [Source: {"entity":"Q26790101","redirect":"Q21863925"}; line: 1, column: 45] com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type' that is to contain type id (for class org.wikidata.wdtk.datamodel.json.jackson.JacksonItemDocument) at [Source: {"entity":"Q26790101","redirect":"Q21863925"}; line: 1, column: 45] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) at com.fasterxml.jackson.databind.DeserializationContext.wrongTokenException(DeserializationContext.java:927) at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedUsingDefaultImpl(AsPropertyTypeDeserializer.java:151) at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:103) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeWithType(BeanDeserializerBase.java:966) at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:42) at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1443) at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1081) at org.wikidata.wdtk.dumpfiles.WikibaseRevisionProcessor.readValue(WikibaseRevisionProcessor.java:160) at org.wikidata.wdtk.dumpfiles.WikibaseRevisionProcessor.processItemRevision(WikibaseRevisionProcessor.java:97) at org.wikidata.wdtk.dumpfiles.WikibaseRevisionProcessor.processRevision(WikibaseRevisionProcessor.java:88) at org.wikidata.wdtk.dumpfiles.MwRevisionProcessorBroker.notifyMwRevisionProcessors(MwRevisionProcessorBroker.java:183) at org.wikidata.wdtk.dumpfiles.MwRevisionProcessorBroker.processRevision(MwRevisionProcessorBroker.java:147) at org.wikidata.wdtk.dumpfiles.MwRevisionDumpFileProcessor.processXmlRevision(MwRevisionDumpFileProcessor.java:427) at org.wikidata.wdtk.dumpfiles.MwRevisionDumpFileProcessor.processXmlPage(MwRevisionDumpFileProcessor.java:345) at org.wikidata.wdtk.dumpfiles.MwRevisionDumpFileProcessor.tryProcessXmlPage(MwRevisionDumpFileProcessor.java:282) at org.wikidata.wdtk.dumpfiles.MwRevisionDumpFileProcessor.processXmlMediawiki(MwRevisionDumpFileProcessor.java:202) at org.wikidata.wdtk.dumpfiles.MwRevisionDumpFileProcessor.processDumpFileContents(MwRevisionDumpFileProcessor.java:155) at org.wikidata.wdtk.dumpfiles.DumpProcessingController.processDumpFile(DumpProcessingController.java:546) at org.wikidata.wdtk.dumpfiles.DumpProcessingController.processAllRecentRevisionDumps(DumpProcessingController.java:389) ```
297160438fecb86e7b86ae05cee3c46eae44797d
8ad18ae7759374b0658a1427b80ab1964a97f833
https://github.com/wikidata/wikidata-toolkit/compare/297160438fecb86e7b86ae05cee3c46eae44797d...8ad18ae7759374b0658a1427b80ab1964a97f833
diff --git a/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/WikibaseRevisionProcessor.java b/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/WikibaseRevisionProcessor.java index e8d77387..a9c79d3d 100644 --- a/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/WikibaseRevisionProcessor.java +++ b/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/WikibaseRevisionProcessor.java @@ -22,6 +22,7 @@ package org.wikidata.wdtk.dumpfiles; import java.io.IOException; import java.util.Map; +import java.util.regex.Pattern; import com.fasterxml.jackson.databind.DeserializationFeature; import org.slf4j.Logger; @@ -93,6 +94,10 @@ public class WikibaseRevisionProcessor implements MwRevisionProcessor { } public void processItemRevision(MwRevision mwRevision) { + if(isWikibaseRedirection(mwRevision)) { + return; + } + try { JacksonItemDocument document = readValue(mwRevision.getText(), JacksonItemDocument.class); document.setSiteIri(this.siteIri); @@ -123,6 +128,10 @@ public class WikibaseRevisionProcessor implements MwRevisionProcessor { } public void processPropertyRevision(MwRevision mwRevision) { + if(isWikibaseRedirection(mwRevision)) { + return; + } + try { JacksonPropertyDocument document = readValue(mwRevision.getText(), JacksonPropertyDocument.class); document.setSiteIri(this.siteIri); @@ -154,6 +163,10 @@ public class WikibaseRevisionProcessor implements MwRevisionProcessor { } + private boolean isWikibaseRedirection(MwRevision mwRevision) { + return mwRevision.getText().contains("\\"redirect\\":"); //Hacky but fast + } + public <T> T readValue(String content, Class<T> valueType) throws IOException { return mapper.reader(valueType) .with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT)
['wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/WikibaseRevisionProcessor.java']
{'.java': 1}
1
1
0
0
1
1,255,332
300,606
40,544
233
302
75
13
1
3,068
116
699
31
0
1
1970-01-01T00:24:33
343
Java
{'Java': 2468830, 'HTML': 40410}
Apache License 2.0
411
wikidata/wikidata-toolkit/418/417
wikidata
wikidata-toolkit
https://github.com/Wikidata/Wikidata-Toolkit/issues/417
https://github.com/Wikidata/Wikidata-Toolkit/pull/418
https://github.com/Wikidata/Wikidata-Toolkit/pull/418
1
closes
Regression: serialization of Statements
We have a problem with Statement serialization: statement values should only be serialized as part of the mainsnak, but they are also serialized at the Statement root: Our tests currently specify this serialization: ```json { "rank": "preferred", "value": { "value": { "id": "Q42", "numeric-id": 42, "entity-type": "item" }, "type": "wikibase-entityid" }, "id": "MyId", "mainsnak": { "property": "P42", "datatype": "wikibase-item", "datavalue": { "value": { "id": "Q42", "numeric-id": 42, "entity-type": "item" }, "type": "wikibase-entityid" }, "snaktype": "value" }, "type": "statement" } ``` The correct serialization should be: ```json { "rank": "preferred", "id": "MyId", "mainsnak": { "property": "P42", "datatype": "wikibase-item", "datavalue": { "value": { "id": "Q42", "numeric-id": 42, "entity-type": "item" }, "type": "wikibase-entityid" }, "snaktype": "value" }, "type": "statement" } ``` This was introduced by the addition of Claim methods to the Statement class, #330, where a `@JsonIgnore` was forgotten. The faulty test was introduced in 5d34b3a0c.
45b58c9841c601db9fb217f0f9a1c18d1c764518
856c4fbb7056b649fe6efd08bddb7b21ba194b1a
https://github.com/wikidata/wikidata-toolkit/compare/45b58c9841c601db9fb217f0f9a1c18d1c764518...856c4fbb7056b649fe6efd08bddb7b21ba194b1a
diff --git a/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/StatementImpl.java b/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/StatementImpl.java index fef0bfcc..fbb9c267 100644 --- a/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/StatementImpl.java +++ b/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/StatementImpl.java @@ -222,6 +222,7 @@ public class StatementImpl implements Statement { } @Override + @JsonProperty("references") public List<Reference> getReferences() { return references; } @@ -233,6 +234,7 @@ public class StatementImpl implements Statement { } @Override + @JsonIgnore public Value getValue() { return mainSnak.getValue(); } diff --git a/wdtk-datamodel/src/test/java/org/wikidata/wdtk/datamodel/implementation/StatementImplTest.java b/wdtk-datamodel/src/test/java/org/wikidata/wdtk/datamodel/implementation/StatementImplTest.java index 3777c680..bd2350f4 100644 --- a/wdtk-datamodel/src/test/java/org/wikidata/wdtk/datamodel/implementation/StatementImplTest.java +++ b/wdtk-datamodel/src/test/java/org/wikidata/wdtk/datamodel/implementation/StatementImplTest.java @@ -48,11 +48,11 @@ public class StatementImplTest { qualifiers, references, subjet); private final Statement s2 = new StatementImpl("MyId", StatementRank.PREFERRED, mainSnak, qualifiers, references, subjet); - private final String JSON_STATEMENT = "{\\"rank\\":\\"preferred\\",\\"references\\":[{\\"snaks\\":{\\"P42\\":[{\\"property\\":\\"P42\\",\\"datatype\\":\\"wikibase-item\\",\\"datavalue\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"snaktype\\":\\"value\\"}]},\\"snaks-order\\":[\\"P42\\"]}],\\"value\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"id\\":\\"MyId\\",\\"mainsnak\\":{\\"property\\":\\"P42\\",\\"datatype\\":\\"wikibase-item\\",\\"datavalue\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"snaktype\\":\\"value\\"},\\"qualifiers-order\\":[\\"P42\\"],\\"type\\":\\"statement\\",\\"qualifiers\\":{\\"P42\\":[{\\"property\\":\\"P42\\",\\"datatype\\":\\"wikibase-item\\",\\"datavalue\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"snaktype\\":\\"value\\"}]}}"; + private final String JSON_STATEMENT = "{\\"rank\\":\\"preferred\\",\\"references\\":[{\\"snaks\\":{\\"P42\\":[{\\"property\\":\\"P42\\",\\"datatype\\":\\"wikibase-item\\",\\"datavalue\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"snaktype\\":\\"value\\"}]},\\"snaks-order\\":[\\"P42\\"]}],\\"id\\":\\"MyId\\",\\"mainsnak\\":{\\"property\\":\\"P42\\",\\"datatype\\":\\"wikibase-item\\",\\"datavalue\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"snaktype\\":\\"value\\"},\\"qualifiers-order\\":[\\"P42\\"],\\"type\\":\\"statement\\",\\"qualifiers\\":{\\"P42\\":[{\\"property\\":\\"P42\\",\\"datatype\\":\\"wikibase-item\\",\\"datavalue\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"snaktype\\":\\"value\\"}]}}"; private final Statement smallStatement = new StatementImpl("MyId", StatementRank.PREFERRED, mainSnak, Collections.emptyList(), Collections.emptyList(), subjet); - private final String JSON_SMALL_STATEMENT = "{\\"rank\\":\\"preferred\\",\\"value\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"id\\":\\"MyId\\",\\"mainsnak\\":{\\"property\\":\\"P42\\",\\"datatype\\":\\"wikibase-item\\",\\"datavalue\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"snaktype\\":\\"value\\"},\\"type\\":\\"statement\\"}"; + private final String JSON_SMALL_STATEMENT = "{\\"rank\\":\\"preferred\\",\\"id\\":\\"MyId\\",\\"mainsnak\\":{\\"property\\":\\"P42\\",\\"datatype\\":\\"wikibase-item\\",\\"datavalue\\":{\\"value\\":{\\"id\\":\\"Q42\\",\\"numeric-id\\":42,\\"entity-type\\":\\"item\\"},\\"type\\":\\"wikibase-entityid\\"},\\"snaktype\\":\\"value\\"},\\"type\\":\\"statement\\"}"; @Test public void gettersWorking() {
['wdtk-datamodel/src/test/java/org/wikidata/wdtk/datamodel/implementation/StatementImplTest.java', 'wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/StatementImpl.java']
{'.java': 2}
2
2
0
0
2
1,335,016
320,225
42,485
220
43
9
2
1
1,301
144
362
56
0
2
1970-01-01T00:26:00
343
Java
{'Java': 2468830, 'HTML': 40410}
Apache License 2.0
413
wikidata/wikidata-toolkit/102/101
wikidata
wikidata-toolkit
https://github.com/Wikidata/Wikidata-Toolkit/issues/101
https://github.com/Wikidata/Wikidata-Toolkit/pull/102
https://github.com/Wikidata/Wikidata-Toolkit/pull/102
1
fixes
EntityDocumentProcessors called twice when using JSON dumps
Entity processors can be registered for specific content models. However, since JSON dumps do not provide content models, they just call all registered entity document processors on each document. The broker component that manages this does not check for duplicates, and as a result, a processor that is registered individually for item and property content will be called twice. This is a critical bug that causes unnecessary work and leads to inflated outputs, in particular in the RDF dumps. As a workaround, users should register their processors for one content model only (or simply for null) when using the JSON dumps.
ca795bae5af21856ab15574e74a1a0db2165bb0d
49ad771f5014e77e5835f5b9b6d4fd8116306395
https://github.com/wikidata/wikidata-toolkit/compare/ca795bae5af21856ab15574e74a1a0db2165bb0d...49ad771f5014e77e5835f5b9b6d4fd8116306395
diff --git a/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/interfaces/EntityDocumentProcessorBroker.java b/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/interfaces/EntityDocumentProcessorBroker.java index 9afdff19..3522b65f 100644 --- a/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/interfaces/EntityDocumentProcessorBroker.java +++ b/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/interfaces/EntityDocumentProcessorBroker.java @@ -9,9 +9,9 @@ package org.wikidata.wdtk.datamodel.interfaces; * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,6 +21,7 @@ package org.wikidata.wdtk.datamodel.interfaces; */ import java.util.ArrayList; +import java.util.HashSet; import java.util.List; /** @@ -33,17 +34,23 @@ import java.util.List; public class EntityDocumentProcessorBroker implements EntityDocumentProcessor { final List<EntityDocumentProcessor> entityDocumentProcessors = new ArrayList<EntityDocumentProcessor>(); + final HashSet<EntityDocumentProcessor> entityDocumentProcessorRegistry = new HashSet<>(); /** * Registers a listener which will be called for all entity documents that - * are processed. + * are processed. The method avoids duplicates in the sense that the exact + * same object cannot be registered twice. * * @param entityDocumentProcessor * the listener to register */ public void registerEntityDocumentProcessor( EntityDocumentProcessor entityDocumentProcessor) { - this.entityDocumentProcessors.add(entityDocumentProcessor); + if (!this.entityDocumentProcessorRegistry + .contains(entityDocumentProcessor)) { + this.entityDocumentProcessors.add(entityDocumentProcessor); + this.entityDocumentProcessorRegistry.add(entityDocumentProcessor); + } } @Override diff --git a/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java b/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java index 19072f0e..0a4545a7 100644 --- a/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java +++ b/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java @@ -9,9 +9,9 @@ package org.wikidata.wdtk.dumpfiles; * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -153,7 +153,7 @@ public class DumpProcessingController { /** * Broker object to distribute entity documents to several listeners. This * will be the main object that distributes revisions on any document-based - * processing run. + * processing run (in particular for JSON dumps). */ EntityDocumentProcessorBroker entityDocumentProcessorBroker = new EntityDocumentProcessorBroker(); @@ -238,8 +238,11 @@ public class DumpProcessingController { * Registers an MwRevisionProcessor, which will henceforth be notified of * all revisions that are encountered in the dump. * <p> + * This only is used when processing dumps that contain revisions. In + * particular, plain JSON dumps contain no revision information. + * <p> * Importantly, the {@link MwRevision} that the registered processors will - * receive is is valid only during the execution of + * receive is valid only during the execution of * {@link MwRevisionProcessor#processRevision(MwRevision)}, but it will not * be permanent. If the data is to be retained permanently, the revision * processor needs to make its own copy. @@ -266,6 +269,12 @@ public class DumpProcessingController { /** * Registers an EntityDocumentProcessor, which will henceforth be notified * of all entity documents that are encountered in the dump. + * <p> + * It is possible to register processors for specific content types and to + * use either all revisions or only the most current ones. This + * functionality is only available when processing dumps that contain this + * information. In particular, plain JSON dumps do not specify content + * models at all and have only one (current) revision of each entity. * * @param entityDocumentProcessor * the entity document processor to register
['wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/interfaces/EntityDocumentProcessorBroker.java', 'wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java']
{'.java': 2}
2
2
0
0
2
925,033
225,155
29,509
197
1,286
265
32
2
628
101
114
6
0
0
1970-01-01T00:23:34
343
Java
{'Java': 2468830, 'HTML': 40410}
Apache License 2.0
330
spring-projects/spring-ldap/609/489
spring-projects
spring-ldap
https://github.com/spring-projects/spring-ldap/issues/489
https://github.com/spring-projects/spring-ldap/pull/609
https://github.com/spring-projects/spring-ldap/pull/609
1
fixes
LDAP connection not closed due to DefaultDirContextValidator
`DefaultDirContextValidator` class doesn't close `NamingEnumeration` searchResults. As a consequence, the LDAP connection associated with the `DirContext `can't be closed when requested by the pool. It's conform to the documentation : [https://docs.oracle.com/javase/tutorial/jndi/ldap/close.html](https://docs.oracle.com/javase/tutorial/jndi/ldap/close.html) _"If the Context instance is sharing a connection with other Context and unterminated NamingEnumeration instances, the connection will not be closed until close() has been invoked on all such Context and NamingEnumeration instances"_ `DefaultDirContextValidator` should close the `NamingEnumeration` searchResults in a finally block : ``` NamingEnumeration<SearchResult> = null; ... try { searchResults = dirContext.search(this.base, this.filter, this.searchControls); ... } finally { if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { } } } ```
06d01e51161456200420e786ef96feb4c899c3a1
366c7c9d60522528737d2f9ebaca577d66bfff90
https://github.com/spring-projects/spring-ldap/compare/06d01e51161456200420e786ef96feb4c899c3a1...366c7c9d60522528737d2f9ebaca577d66bfff90
diff --git a/core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java b/core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java index 22f31f99..53db23ed 100644 --- a/core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java +++ b/core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java @@ -22,6 +22,7 @@ import org.springframework.ldap.pool.DirContextType; import org.springframework.util.Assert; import javax.naming.NamingEnumeration; +import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; @@ -165,9 +166,10 @@ public class DefaultDirContextValidator implements DirContextValidator { public boolean validateDirContext(DirContextType contextType, DirContext dirContext) { Assert.notNull(contextType, "contextType may not be null"); Assert.notNull(dirContext, "dirContext may not be null"); - + + NamingEnumeration<SearchResult> searchResults = null; try { - final NamingEnumeration<SearchResult> searchResults = dirContext.search(this.base, this.filter, this.searchControls); + searchResults = dirContext.search(this.base, this.filter, this.searchControls); if (searchResults.hasMore()) { this.logger.debug("DirContext '{}' passed validation.", dirContext); @@ -179,6 +181,14 @@ public class DefaultDirContextValidator implements DirContextValidator { this.logger.debug("DirContext '{}' failed validation with an exception.", dirContext, e); return false; } + finally { + if (searchResults != null) { + try { + searchResults.close(); + } catch (NamingException namingException) { + } + } + } this.logger.debug("DirContext '{}' failed validation.", dirContext); return false; diff --git a/core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java b/core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java index 716fb97e..8fb655c8 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java +++ b/core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java @@ -22,6 +22,7 @@ import org.springframework.ldap.pool2.DirContextType; import org.springframework.util.Assert; import javax.naming.NamingEnumeration; +import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; @@ -166,12 +167,13 @@ public class DefaultDirContextValidator implements DirContextValidator { Assert.notNull(contextType, "contextType may not be null"); Assert.notNull(dirContext, "dirContext may not be null"); + NamingEnumeration<SearchResult> searchResults = null; try { - final NamingEnumeration<SearchResult> searchResults = dirContext.search(this.base, this.filter, this.searchControls); + searchResults = dirContext.search(this.base, this.filter, this.searchControls); if (searchResults.hasMore()) { this.logger.debug("DirContext '{}' passed validation.", dirContext); - + return true; } } @@ -179,6 +181,14 @@ public class DefaultDirContextValidator implements DirContextValidator { this.logger.debug("DirContext '{}' failed validation with an exception.", dirContext, e); return false; } + finally { + if (searchResults != null) { + try { + searchResults.close(); + } catch (NamingException namingException) { + } + } + } this.logger.debug("DirContext '{}' failed validation.", dirContext); return false;
['core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java', 'core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java']
{'.java': 2}
2
2
0
0
2
1,268,204
276,291
36,511
304
1,140
198
28
2
983
108
211
27
1
1
1970-01-01T00:27:21
320
Java
{'Java': 2590392, 'Groovy': 45028, 'FreeMarker': 6116, 'HTML': 4222, 'XSLT': 1222, 'CSS': 727, 'Shell': 547, 'Ruby': 531, 'PHP': 368}
Apache License 2.0
1,162
microsoftgraph/msgraph-sdk-java/470/275
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/275
https://github.com/microsoftgraph/msgraph-sdk-java/pull/470
https://github.com/microsoftgraph/msgraph-sdk-java/pull/470
2
fixes
Error when trying to download .JSON files from OneDrive
I am trying to download a .json file from OneDrive. The following request patterns get the intended behavior (the file is downloaded) for other file types but none work for .json files. InputStream driveItemInputStream = getGraphServiceClient().drives(driveId).items(driveItemId).content().buildRequest().get(); InputStream driveItemInputStream = getGraphServiceClient().drives().byId(driveId).items().byId(driveItemId).content().buildRequest().get(); InputStream driveItemInputStream = getGraphServiceClient().customRequest(("/drives/"+driveId+"/items/"+driveItemId+"/content"), InputStream.class).buildRequest().get(); Expected behavior For the file to be downloaded. Actual behavior Error response: com.microsoft.graph.core.ClientException: Error during http request at com.microsoft.graph.http.DefaultHttpProvider.sendRequestInternal(DefaultHttpProvider.java:368) at com.microsoft.graph.http.DefaultHttpProvider.send(DefaultHttpProvider.java:204) at com.microsoft.graph.http.DefaultHttpProvider.send(DefaultHttpProvider.java:184) at com.microsoft.graph.http.BaseStreamRequest.send(BaseStreamRequest.java:81) at com.microsoft.graph.requests.extensions.DriveItemStreamRequest.get(DriveItemStreamRequest.java:55) ... Caused by: java.lang.RuntimeException: Failed to invoke public java.io.InputStream() with no args at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:113) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:212) at com.google.gson.Gson.fromJson(Gson.java:927) at com.google.gson.Gson.fromJson(Gson.java:892) at com.google.gson.Gson.fromJson(Gson.java:841) at com.google.gson.Gson.fromJson(Gson.java:813) at com.microsoft.graph.serializer.DefaultSerializer.deserializeObject(DefaultSerializer.java:78) at com.microsoft.graph.http.DefaultHttpProvider.handleJsonResponse(DefaultHttpProvider.java:417) at com.microsoft.graph.http.DefaultHttpProvider.sendRequestInternal(DefaultHttpProvider.java:342) ... 46 more Steps to reproduce the behavior Use the SDK to make a GET request on a .json file in a user or group OneDrive using any of the request patterns above. [AB#6032](https://microsoftgraph.visualstudio.com/0985d294-5762-4bc2-a565-161ef349ca3e/_workitems/edit/6032)
6e7acc8eac62a8cd8a59e2c535f132d60acd9f6f
d32a129bab480dd52a20413fcb7df947d445a40f
https://github.com/microsoftgraph/msgraph-sdk-java/compare/6e7acc8eac62a8cd8a59e2c535f132d60acd9f6f...d32a129bab480dd52a20413fcb7df947d445a40f
diff --git a/src/main/java/com/microsoft/graph/http/CoreHttpProvider.java b/src/main/java/com/microsoft/graph/http/CoreHttpProvider.java index 1cb2cf2db9..d10f8cb610 100644 --- a/src/main/java/com/microsoft/graph/http/CoreHttpProvider.java +++ b/src/main/java/com/microsoft/graph/http/CoreHttpProvider.java @@ -417,20 +417,20 @@ public class CoreHttpProvider implements IHttpProvider { final Map<String, String> headers = CoreHttpProvider.getResponseHeadersAsMapStringString(response); + if(response.body() == null || response.body().contentLength() == 0) + return (Result) null; + final String contentType = headers.get(Constants.CONTENT_TYPE_HEADER_NAME); - if (contentType != null && contentType.contains(Constants.JSON_CONTENT_TYPE)) { + if (contentType != null && resultClass != InputStream.class && + contentType.contains(Constants.JSON_CONTENT_TYPE)) { logger.logDebug("Response json"); return handleJsonResponse(in, CoreHttpProvider.getResponseHeadersAsMapOfStringList(response), resultClass); - } else { + } else if (resultClass == InputStream.class) { logger.logDebug("Response binary"); isBinaryStreamInput = true; - if (resultClass == InputStream.class) { - return (Result) handleBinaryStream(in); - } else if(response.body() != null && response.body().contentLength() > 0) { // some services reply in text/plain with a JSON representation... - return handleJsonResponse(in, CoreHttpProvider.getResponseHeadersAsMapOfStringList(response), resultClass); - } else { - return (Result) null; - } + return (Result) handleBinaryStream(in); + } else { + return (Result) null; } } finally { if (!isBinaryStreamInput) { diff --git a/src/test/java/com/microsoft/graph/functional/OneDriveTests.java b/src/test/java/com/microsoft/graph/functional/OneDriveTests.java index e1d57aafb6..a0792f2e1a 100644 --- a/src/test/java/com/microsoft/graph/functional/OneDriveTests.java +++ b/src/test/java/com/microsoft/graph/functional/OneDriveTests.java @@ -1,18 +1,23 @@ package com.microsoft.graph.functional; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import com.google.gson.JsonPrimitive; import com.microsoft.graph.concurrency.ChunkedUploadProvider; import com.microsoft.graph.concurrency.IProgressCallback; import com.microsoft.graph.core.ClientException; +import com.microsoft.graph.http.CoreHttpProvider; import com.microsoft.graph.models.extensions.DriveItem; import com.microsoft.graph.models.extensions.DriveItemUploadableProperties; import com.microsoft.graph.models.extensions.UploadSession; @@ -25,7 +30,25 @@ public class OneDriveTests { public void setUp() { testBase = new TestBase(); } - + + IProgressCallback<DriveItem> callback = new IProgressCallback<DriveItem> () { + @Override + public void progress(final long current, final long max) { + //Check progress + } + @Override + public void success(final DriveItem result) { + //Handle the successful response + String finishedItemId = result.id; + Assert.assertNotNull(finishedItemId); + } + + @Override + public void failure(final ClientException ex) { + //Handle the failed upload + Assert.fail("Upload session failed"); + } + }; /** * Test large file upload. * https://github.com/OneDrive/onedrive-sdk-csharp/blob/master/docs/chunked-uploads.md @@ -41,25 +64,6 @@ public class OneDriveTests { InputStream uploadFile = OneDriveTests.class.getClassLoader().getResourceAsStream("hamilton.jpg"); long fileSize = (long) uploadFile.available(); - IProgressCallback<DriveItem> callback = new IProgressCallback<DriveItem> () { - @Override - public void progress(final long current, final long max) { - //Check progress - } - @Override - public void success(final DriveItem result) { - //Handle the successful response - String finishedItemId = result.id; - Assert.assertNotNull(finishedItemId); - } - - @Override - public void failure(final ClientException ex) { - //Handle the failed upload - Assert.fail("Upload session failed"); - } - }; - UploadSession uploadSession = testBase .graphClient .me() @@ -85,4 +89,43 @@ public class OneDriveTests { assertFalse("stream should not be empty", stream.read() == -1); } } + @Test + public void downloadJsonFileFromOneDrive() throws Exception { + final DriveItemUploadableProperties item = new DriveItemUploadableProperties(); + item.name = "test.json"; + item.additionalDataManager().put("@microsoft.graph.conflictBehavior", new JsonPrimitive("replace")); + + final InputStream uploadFile = new ByteArrayInputStream("{\\"hehe\\":\\"haha\\"}".getBytes(StandardCharsets.UTF_8)); + + final long fileSize = (long) uploadFile.available(); + + final UploadSession session = testBase.graphClient.me() + .drive() + .root() + .itemWithPath(item.name) + .createUploadSession(item) + .buildRequest() + .post(); + + ChunkedUploadProvider<DriveItem> chunkedUploadProvider = new ChunkedUploadProvider<DriveItem>( + session, + testBase.graphClient, + uploadFile, + fileSize, + DriveItem.class); + + chunkedUploadProvider.upload(callback); + + final InputStream stream = testBase.graphClient.me() + .drive() + .root() + .itemWithPath(item.name) + .content() + .buildRequest() + .get(); + + final String fileContent = CoreHttpProvider.streamToString(stream); + + assertTrue(fileContent.length() > 0); + } }
['src/test/java/com/microsoft/graph/functional/OneDriveTests.java', 'src/main/java/com/microsoft/graph/http/CoreHttpProvider.java']
{'.java': 2}
2
2
0
0
2
23,777,893
4,441,295
639,428
8,024
880
194
18
1
2,298
136
495
32
1
0
1970-01-01T00:26:40
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,168
microsoftgraph/msgraph-sdk-java/33/32
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/32
https://github.com/microsoftgraph/msgraph-sdk-java/pull/33
https://github.com/microsoftgraph/msgraph-sdk-java/pull/33
1
fixes
Provide way to convert returned objects of derived types
Some calls to Graph return a variety of derived objects. For example, a call to `me/messages/id/attachments/id` can return either a `fileAttachment` or an `itemAttachment`. Currently, there is no way to access the unique properties on these derived types because the library only returns the base type. See more in the thread @davidmoten started in #21.
ec0d644cdc83cc0d1e863c43e8b483b2de90d447
86cc46b28a0203367abe702d25bacbe8d4793d28
https://github.com/microsoftgraph/msgraph-sdk-java/compare/ec0d644cdc83cc0d1e863c43e8b483b2de90d447...86cc46b28a0203367abe702d25bacbe8d4793d28
diff --git a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java index 8b8999d66b..71ab06f0f4 100644 --- a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java @@ -22,6 +22,7 @@ package com.microsoft.graph.serializer; +import com.google.common.base.CaseFormat; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -58,19 +59,26 @@ public class DefaultSerializer implements ISerializer { * Deserialize an object from the input string. * * @param inputString The string that stores the representation of the item. - * @param clazz The .class of the item to be deserialized. + * @param clazz The class of the item to be deserialized. * @param <T> The type of the item to be deserialized. * @return The deserialized item from the input string. */ @Override public <T> T deserializeObject(final String inputString, final Class<T> clazz) { - final T jsonObject = gson.fromJson(inputString, clazz); + T jsonObject = gson.fromJson(inputString, clazz); - // Populate the json backed fields for any annotations that are not in the object model + // Populate the JSON-backed fields for any annotations that are not in the object model if (jsonObject instanceof IJsonBackedObject) { logger.logDebug("Deserializing type " + clazz.getSimpleName()); final IJsonBackedObject jsonBackedObject = (IJsonBackedObject) jsonObject; final JsonObject rawObject = gson.fromJson(inputString, JsonObject.class); + + // If there is a derived class, try to get it and deserialize to it + Class derivedClass = this.getDerivedClass(rawObject, clazz); + if (derivedClass != null) { + jsonObject = (T) gson.fromJson(inputString, derivedClass); + } + jsonBackedObject.setRawObject(this, rawObject); jsonBackedObject.additionalDataManager().setAdditionalData(rawObject); } else { @@ -116,4 +124,38 @@ public class DefaultSerializer implements ISerializer { private boolean fieldIsOdataTransient(Map.Entry<String, JsonElement> entry) { return entry.getKey().startsWith("@"); } + + /** + * Get the derived class for the given JSON object + * This covers scenarios in which the service may return one of several derived types + * of a base object, which it defines using the odata.type parameter + * @param jsonObject The raw JSON object of the response + * @param parentClass The parent class the derived class should inherit from + * @return The derived class if found, or null if not applicable + */ + private Class getDerivedClass(JsonObject jsonObject, Class parentClass) { + //Identify the odata.type information if provided + if (jsonObject.get("@odata.type") != null) { + String odataType = jsonObject.get("@odata.type").getAsString(); + String derivedType = odataType.substring(odataType.lastIndexOf('.') + 1); //Remove microsoft.graph prefix + derivedType = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, derivedType); + derivedType = "com.microsoft.graph.models.extensions." + derivedType; //Add full package path + + try { + Class derivedClass = Class.forName(derivedType); + //Check that the derived class inherits from the given parent class + if (parentClass.isAssignableFrom(derivedClass)) { + return derivedClass; + } + return null; + } catch (ClassNotFoundException e) { + logger.logDebug("Unable to find a corresponding class for derived type " + derivedType + ". Falling back to parent class."); + //If we cannot determine the derived type to cast to, return null + //This may happen if the API and the SDK are out of sync + return null; + } + } + //If there is no defined OData type, return null + return null; + } } diff --git a/src/test/java/com/microsoft/graph/serializer/DefaultSeralizerTests.java b/src/test/java/com/microsoft/graph/serializer/DefaultSeralizerTests.java index e8550ca50b..29aac1edc0 100644 --- a/src/test/java/com/microsoft/graph/serializer/DefaultSeralizerTests.java +++ b/src/test/java/com/microsoft/graph/serializer/DefaultSeralizerTests.java @@ -7,9 +7,11 @@ import org.junit.Before; import org.junit.Test; import com.microsoft.graph.models.extensions.Drive; +import com.microsoft.graph.models.extensions.FileAttachment; import com.microsoft.graph.models.generated.RecurrenceRangeType; import com.microsoft.graph.models.generated.BaseRecurrenceRange; import com.microsoft.graph.logger.DefaultLogger; +import com.microsoft.graph.models.extensions.Attachment; import com.microsoft.graph.models.extensions.DateOnly; public class DefaultSeralizerTests { @@ -64,5 +66,16 @@ public class DefaultSeralizerTests { assertNotNull(jsonOut); assertEquals(expected, jsonOut); } - + + @Test + public void testDeserializeDerivedType() throws Exception { + final DefaultSerializer serializer = new DefaultSerializer(new DefaultLogger()); + String source = "{\\"@odata.context\\": \\"/attachments/$entity\\",\\"@odata.type\\": \\"#microsoft.graph.fileAttachment\\",\\"id\\": \\"AAMkAGQ0MjBmNWVkLTYxZjUtNDRmYi05Y2NiLTBlYjIwNzJjNmM1NgBGAAAAAAC6ff7latYeQqu_gLrhSAIhBwCF7iGjpaOmRqVwbZc-xXzwAAAAAAEMAACF7iGjpaOmRqVwbZc-xXzwAABQStA0AAABEgAQAFbGmeisbjtLnQdp7kC_9Fk=\\",\\"lastModifiedDateTime\\": \\"2018-01-23T21:50:22Z\\",\\"name\\": \\"Test Book.xlsx\\",\\"contentType\\": \\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\\",\\"size\\": 8457,\\"isInline\\": false,\\"contentId\\": null,\\"contentLocation\\": null,\\"contentBytes\\": \\"bytedata\\"}"; + Attachment result = serializer.deserializeObject(source, Attachment.class); + + assert(result instanceof FileAttachment); + + FileAttachment fileAttachment = (FileAttachment) result; + assertNotNull(fileAttachment.contentBytes); + } }
['src/test/java/com/microsoft/graph/serializer/DefaultSeralizerTests.java', 'src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java']
{'.java': 2}
2
2
0
0
2
14,711,923
2,597,510
412,251
7,633
2,552
539
48
1
353
55
78
1
0
0
1970-01-01T00:25:16
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,157
microsoftgraph/msgraph-sdk-java/566/565
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/565
https://github.com/microsoftgraph/msgraph-sdk-java/pull/566
https://github.com/microsoftgraph/msgraph-sdk-java/pull/566
2
fixes
NoSuchElementException when there is no content in the response in case of an error
<!-- Read me before you submit this issue First off, thank you for taking the time to open this issue! We do appreciate it. Please bear with us if we don't get to this right away. If this is a question about the Microsoft Graph service API, or a question about how to use this SDK, please post your question to StackOverflow with the [microsoftgraph] tag. https://stackoverflow.com/questions/tagged/microsoft-graph This repo is for the Microsoft Graph Java SDK. Issues opened in this repo should only target this SDK. Before you open this issue, did you: - Search the issues to determine whether someone already opened this issue? - Search StackOverflow for an answer? - Capture the repro steps and gather the information requested in the steps below to reproduce your scenario? - Review the samples under github.com/microsoftgraph? They can help for some scenarios. - Take a look at the functional tests in this repo? They may have an example for you. See the [functional tests](https://github.com/microsoftgraph/msgraph-sdk-java/tree/master/src/test/java/com/microsoft/graph/functional) Please provide the following before submitting this issue: - Expected behavior. Please provide **links to the specific [Microsoft Graph documentation](https://developer.microsoft.com/en-us/graph/docs/concepts/overview)** you used to determine the expected behavior. - Actual behavior. Provide error codes, stack information, and a [Fiddler](http://www.telerik.com/fiddler) capture of the request and response (please remove personally identifiable information before posting). - Steps to reproduce the behavior. Include your code, IDE versions, client library versions, and any other information that might be helpful to understand your scenario. --> ### Expected behavior The library should not throw an exception even in the case when there is no body in case of an error. ### Actual behavior The library is throwing an exception when there is no content in the response in case of error. ``` Caused by: java.util.NoSuchElementException ERROR|1119-172601634|pool-6-thread-5286 at java.base/java.util.Scanner.throwFor(Scanner.java:937) ERROR|1119-172601634|pool-6-thread-5286 at java.base/java.util.Scanner.next(Scanner.java:1478) ERROR|1119-172601634|pool-6-thread-5286 at com.microsoft.graph.http.DefaultHttpProvider.streamToString(DefaultHttpProvider.java:473) ERROR|1119-172601634|pool-6-thread-5286 at com.microsoft.graph.http.GraphServiceException.createFromConnection(GraphServiceException.java:424) ERROR|1119-172601634|pool-6-thread-5286 at com.microsoft.graph.http.CoreHttpProvider.handleErrorResponse(CoreHttpProvider.java:487) ERROR|1119-172601634|pool-6-thread-5286 at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal(CoreHttpProvider.java:376) ``` ### Steps to reproduce the behavior Steps wise not sure how to reproduce it as we are seeing this error when calling a graph endpoint. Looks like we are not checking the [iterator](https://github.com/microsoftgraph/msgraph-sdk-java/blob/dev/src/main/java/com/microsoft/graph/http/DefaultHttpProvider.java#L470) before accessing `next`. ``` public static String streamToString(final InputStream input) { final String httpStreamEncoding = "UTF-8"; final String endOfFile = "\\\\A"; final Scanner scanner = new Scanner(input, httpStreamEncoding); String scannerString = ""; try { scanner.useDelimiter(endOfFile); scannerString = scanner.next(); } finally { scanner.close(); } return scannerString; } ``` I think we should have ``` if(scanner.hasNext()){ scannerString = scanner.next(); } ``` If it is ok, I can raise the MR with the fix. Thanks
08abb6bc350d7e134de8438c80f0ec953fb0e2ac
9ed8de320a7b1af7792ba24e0fa0cd010c4e1100
https://github.com/microsoftgraph/msgraph-sdk-java/compare/08abb6bc350d7e134de8438c80f0ec953fb0e2ac...9ed8de320a7b1af7792ba24e0fa0cd010c4e1100
diff --git a/src/main/java/com/microsoft/graph/http/CoreHttpProvider.java b/src/main/java/com/microsoft/graph/http/CoreHttpProvider.java index 4489b81410..725327cecf 100644 --- a/src/main/java/com/microsoft/graph/http/CoreHttpProvider.java +++ b/src/main/java/com/microsoft/graph/http/CoreHttpProvider.java @@ -555,13 +555,12 @@ public class CoreHttpProvider implements IHttpProvider { public static String streamToString(final InputStream input) { final String httpStreamEncoding = "UTF-8"; final String endOfFile = "\\\\A"; - final Scanner scanner = new Scanner(input, httpStreamEncoding); String scannerString = ""; - try { + try (final Scanner scanner = new Scanner(input, httpStreamEncoding)) { scanner.useDelimiter(endOfFile); - scannerString = scanner.next(); - } finally { - scanner.close(); + if (scanner.hasNext()) { + scannerString = scanner.next(); + } } return scannerString; } diff --git a/src/main/java/com/microsoft/graph/http/DefaultHttpProvider.java b/src/main/java/com/microsoft/graph/http/DefaultHttpProvider.java index 093b64771b..08e4f1e5d2 100644 --- a/src/main/java/com/microsoft/graph/http/DefaultHttpProvider.java +++ b/src/main/java/com/microsoft/graph/http/DefaultHttpProvider.java @@ -470,13 +470,12 @@ public class DefaultHttpProvider implements IHttpProvider { public static String streamToString(final InputStream input) { final String httpStreamEncoding = "UTF-8"; final String endOfFile = "\\\\A"; - final Scanner scanner = new Scanner(input, httpStreamEncoding); String scannerString = ""; - try { - scanner.useDelimiter(endOfFile); - scannerString = scanner.next(); - } finally { - scanner.close(); + try (final Scanner scanner = new Scanner(input, httpStreamEncoding)) { + scanner.useDelimiter(endOfFile); + if (scanner.hasNext()) { + scannerString = scanner.next(); + } } return scannerString; } diff --git a/src/main/java/com/microsoft/graph/http/GraphServiceException.java b/src/main/java/com/microsoft/graph/http/GraphServiceException.java index 1ed0124f88..08e24886c1 100644 --- a/src/main/java/com/microsoft/graph/http/GraphServiceException.java +++ b/src/main/java/com/microsoft/graph/http/GraphServiceException.java @@ -366,7 +366,7 @@ public class GraphServiceException extends ClientException { final String responseMessage = connection.getResponseMessage(); String rawOutput = "{}"; if(connection.getInputStream() != null) { - rawOutput = DefaultHttpProvider.streamToString(connection.getInputStream()); + rawOutput = CoreHttpProvider.streamToString(connection.getInputStream()); } GraphErrorResponse error; try { diff --git a/src/test/java/com/microsoft/graph/http/CoreHttpProviderTests.java b/src/test/java/com/microsoft/graph/http/CoreHttpProviderTests.java index dea29b5014..c8c22c8c09 100644 --- a/src/test/java/com/microsoft/graph/http/CoreHttpProviderTests.java +++ b/src/test/java/com/microsoft/graph/http/CoreHttpProviderTests.java @@ -5,10 +5,17 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.junit.Ignore; import org.junit.Test; @@ -28,6 +35,7 @@ public class CoreHttpProviderTests { private MockAuthenticationProvider mAuthenticationProvider; private CoreHttpProvider mProvider; + private Gson GSON = new GsonBuilder().create(); @Test public void testErrorResponse() throws Exception { @@ -96,7 +104,27 @@ public class CoreHttpProviderTests { HeaderOption h = new HeaderOption("name", "value"); assertFalse(DefaultHttpProvider.hasHeader(Arrays.asList(h), "blah")); } - + + @Test + public void testStreamToStringReturnsData() { + String data = GSON.toJson(Maps.newHashMap( + ImmutableMap.<String, String>builder() + .put("key", "value") + .build())); + final InputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + + String convertedData = CoreHttpProvider.streamToString(inputStream); + assertEquals(data, convertedData); + } + + @Test + public void testStreamToStringReturnsEmpty() { + final InputStream inputStream = new ByteArrayInputStream(new byte[0]); + + String convertedData = CoreHttpProvider.streamToString(inputStream); + assertEquals("", convertedData); + } + /** * Configures the http provider for test cases diff --git a/src/test/java/com/microsoft/graph/http/DefaultHttpProviderTests.java b/src/test/java/com/microsoft/graph/http/DefaultHttpProviderTests.java index ae4c671a27..70c5d325d3 100644 --- a/src/test/java/com/microsoft/graph/http/DefaultHttpProviderTests.java +++ b/src/test/java/com/microsoft/graph/http/DefaultHttpProviderTests.java @@ -28,13 +28,19 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.junit.Test; import com.google.gson.JsonObject; @@ -58,6 +64,7 @@ public class DefaultHttpProviderTests { private MockAuthenticationProvider mAuthenticationProvider; private DefaultHttpProvider mProvider; + private Gson GSON = new GsonBuilder().create(); @Test public void testNoContentType() throws Exception { @@ -369,6 +376,26 @@ public class DefaultHttpProviderTests { HeaderOption h = new HeaderOption("name", "value"); assertFalse(DefaultHttpProvider.hasHeader(Arrays.asList(h), "blah")); } + + @Test + public void testStreamToStringReturnsData() { + String data = GSON.toJson(Maps.newHashMap( + ImmutableMap.<String, String>builder() + .put("key", "value") + .build())); + final InputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + + String convertedData = DefaultHttpProvider.streamToString(inputStream); + assertEquals(data, convertedData); + } + + @Test + public void testStreamToStringReturnsEmpty() { + final InputStream inputStream = new ByteArrayInputStream(new byte[0]); + + String convertedData = DefaultHttpProvider.streamToString(inputStream); + assertEquals("", convertedData); + } /**
['src/test/java/com/microsoft/graph/http/CoreHttpProviderTests.java', 'src/main/java/com/microsoft/graph/http/GraphServiceException.java', 'src/test/java/com/microsoft/graph/http/DefaultHttpProviderTests.java', 'src/main/java/com/microsoft/graph/http/CoreHttpProvider.java', 'src/main/java/com/microsoft/graph/http/DefaultHttpProvider.java']
{'.java': 5}
5
5
0
0
5
25,371,131
4,730,635
670,141
8,422
914
171
22
3
3,796
414
810
72
5
3
1970-01-01T00:26:45
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,153
microsoftgraph/msgraph-sdk-java/588/587
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/587
https://github.com/microsoftgraph/msgraph-sdk-java/pull/588
https://github.com/microsoftgraph/msgraph-sdk-java/pull/588
2
fixes
Java enum template needs to include SerializableName for each member
https://github.com/microsoftgraph/MSGraph-SDK-Code-Generator/blob/dev/Templates/Java/models_generated/Enum.java.tt ```java public void testGetMailtips() { TestBase testBase = new TestBase(); ArrayList<String> users = new ArrayList<String>(); users.add("[email protected]"); users.add("[email protected]"); EnumSet<MailTipsType> mailtips = EnumSet.of(MailTipsType.MAILBOX_FULL_STATUS, MailTipsType.MAX_MESSAGE_SIZE); UserGetMailTipsCollectionPage page = testBase.graphClient.me().getMailTips(users, mailtips).buildRequest().post(); assertNotNull(page); } ``` results in the following body: ```json { "emailAddresses": ["[email protected]", "[email protected]"], "mailTipsOptions": "MAILBOX_FULL_STATUS,MAX_MESSAGE_SIZE" } ``` expected: ```json { "emailAddresses": ["[email protected]", "[email protected]"], "mailTipsOptions": "mailboxFullStatus,maxMessageSize" } ```
664aa57621bf49592b089401a9f38f9f7ae50c0f
7f5764104f3445bd4397c11272ebd9fce587d957
https://github.com/microsoftgraph/msgraph-sdk-java/compare/664aa57621bf49592b089401a9f38f9f7ae50c0f...7f5764104f3445bd4397c11272ebd9fce587d957
diff --git a/src/main/java/com/microsoft/graph/serializer/EnumSetSerializer.java b/src/main/java/com/microsoft/graph/serializer/EnumSetSerializer.java index b7ee710748..daf345c531 100644 --- a/src/main/java/com/microsoft/graph/serializer/EnumSetSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/EnumSetSerializer.java @@ -22,7 +22,9 @@ package com.microsoft.graph.serializer; import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import com.google.gson.JsonPrimitive; +import com.microsoft.graph.logger.ILogger; import java.lang.reflect.Type; import java.util.EnumSet; @@ -36,39 +38,43 @@ import java.util.Iterator; */ public class EnumSetSerializer { + private final Gson gson; /** * Not available for instantiation */ - private EnumSetSerializer() { + public EnumSetSerializer(final ILogger logger) { + gson = new GsonBuilder().registerTypeAdapterFactory(new FallbackTypeAdapterFactory(logger)).create(); } /** * Deserializes a comma-delimited string of enum values - * + * * @param type the type * @param jsonStrToDeserialize the string to deserialize * @return EnumSet of values */ - public static EnumSet<?> deserialize(Type type, String jsonStrToDeserialize) { - Gson gson = new Gson(); - String arrayString = "[" + jsonStrToDeserialize + "]"; + public EnumSet<?> deserialize(Type type, String jsonStrToDeserialize) { + final String arrayString = "[" + jsonStrToDeserialize + "]"; return jsonStrToDeserialize == null ? null : (EnumSet<?>) gson.fromJson(arrayString, type); } /** * Serializes an EnumSet into a comma-delimited string - * + * * @param src the source EnumSet * @return a comma-delimited string of enum values */ - public static JsonPrimitive serialize(EnumSet<?> src) { - String serializedString = ""; + public JsonPrimitive serialize(EnumSet<?> src) { + final StringBuilder serializedStringBuilder = new StringBuilder(); - Iterator<?> i = src.iterator(); + final Iterator<?> i = src.iterator(); while (i.hasNext()) { - serializedString += i.next().toString() + ","; + final String jsonValue = gson.toJson(i.next()); + serializedStringBuilder.append(jsonValue.substring(1, jsonValue.length() -1)); + if(i.hasNext()) { + serializedStringBuilder.append(","); + } } - serializedString = serializedString.substring(0, serializedString.length()-1); - return new JsonPrimitive(serializedString); + return new JsonPrimitive(serializedStringBuilder.toString()); } } diff --git a/src/main/java/com/microsoft/graph/serializer/GsonFactory.java b/src/main/java/com/microsoft/graph/serializer/GsonFactory.java index 02c433ad2b..746825efbd 100644 --- a/src/main/java/com/microsoft/graph/serializer/GsonFactory.java +++ b/src/main/java/com/microsoft/graph/serializer/GsonFactory.java @@ -51,7 +51,7 @@ import javax.xml.datatype.Duration; final class GsonFactory { private static String PARSING_MESSAGE = "Parsing issue on "; - + /** * Default constructor */ @@ -163,6 +163,7 @@ final class GsonFactory { } } }; + final EnumSetSerializer eSetSerializer = new EnumSetSerializer(logger); final JsonSerializer<EnumSet<?>> enumSetJsonSerializer = new JsonSerializer<EnumSet<?>>() { @Override @@ -173,7 +174,7 @@ final class GsonFactory { return null; } - return EnumSetSerializer.serialize(src); + return eSetSerializer.serialize(src); } }; @@ -186,7 +187,7 @@ final class GsonFactory { return null; } - return EnumSetSerializer.deserialize(typeOfT, json.getAsString()); + return eSetSerializer.deserialize(typeOfT, json.getAsString()); } }; @@ -211,7 +212,7 @@ final class GsonFactory { } } }; - + final JsonSerializer<BaseCollectionPage<?,?>> collectionPageSerializer = new JsonSerializer<BaseCollectionPage<?,?>>() { @Override public JsonElement serialize(final BaseCollectionPage<?,?> src, @@ -229,7 +230,7 @@ final class GsonFactory { return CollectionPageSerializer.deserialize(json, typeOfT, logger); } }; - + final JsonDeserializer<TimeOfDay> timeOfDayJsonDeserializer = new JsonDeserializer<TimeOfDay>() { @Override public TimeOfDay deserialize(final JsonElement json, diff --git a/src/test/java/com/microsoft/graph/serializer/DefaultSerializerTests.java b/src/test/java/com/microsoft/graph/serializer/DefaultSerializerTests.java index bcd63ef043..5ffaff18a8 100644 --- a/src/test/java/com/microsoft/graph/serializer/DefaultSerializerTests.java +++ b/src/test/java/com/microsoft/graph/serializer/DefaultSerializerTests.java @@ -4,11 +4,17 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumSet; + import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.microsoft.graph.callrecords.models.extensions.MediaStream; +import com.microsoft.graph.functional.TestBase; +import com.microsoft.graph.http.HttpMethod; import com.microsoft.graph.http.MockConnection; import com.microsoft.graph.logger.DefaultLogger; import com.microsoft.graph.models.extensions.Attachment; @@ -17,11 +23,18 @@ import com.microsoft.graph.models.extensions.Drive; import com.microsoft.graph.models.extensions.FileAttachment; import com.microsoft.graph.models.extensions.RecurrenceRange; import com.microsoft.graph.models.extensions.User; +import com.microsoft.graph.models.extensions.UserGetMailTipsBody; +import com.microsoft.graph.models.generated.MailTipsType; import com.microsoft.graph.models.generated.RecurrenceRangeType; import com.microsoft.graph.requests.extensions.DriveItemDeltaCollectionResponse; import com.microsoft.graph.models.extensions.UploadSession; + +import org.junit.Assert; import org.junit.Test; +import okhttp3.Request; +import okio.Buffer; + public class DefaultSerializerTests { /** @@ -111,19 +124,19 @@ public class DefaultSerializerTests { assertNotNull(jsonOut); assertEquals(expected, jsonOut); } - + @Test public void testResponseHeaders() throws Exception { MockConnection connection = new MockConnection(null); final DefaultSerializer serializer = new DefaultSerializer(new DefaultLogger()); User user = serializer.deserializeObject("{\\"id\\":\\"1\\"}", User.class, connection.getResponseHeaders()); - + JsonElement responseHeaders = user.additionalDataManager().get("graphResponseHeaders"); assertNotNull(responseHeaders); - + JsonElement responseHeader = responseHeaders.getAsJsonObject().get("header1"); assertNotNull(responseHeader); - + assertEquals("value1", responseHeader.getAsJsonArray().get(0).getAsString()); } @@ -132,25 +145,25 @@ public class DefaultSerializerTests { final DefaultSerializer serializer = new DefaultSerializer(new DefaultLogger()); final String source = "{\\"@odata.context\\": \\"/attachments/$entity\\",\\"@odata.type\\": \\"#microsoft.graph.fileAttachment\\",\\"id\\": \\"AAMkAGQ0MjBmNWVkLTYxZjUtNDRmYi05Y2NiLTBlYjIwNzJjNmM1NgBGAAAAAAC6ff7latYeQqu_gLrhSAIhBwCF7iGjpaOmRqVwbZc-xXzwAAAAAAEMAACF7iGjpaOmRqVwbZc-xXzwAABQStA0AAABEgAQAFbGmeisbjtLnQdp7kC_9Fk=\\",\\"lastModifiedDateTime\\": \\"2018-01-23T21:50:22Z\\",\\"name\\": \\"Test Book.xlsx\\",\\"contentType\\": \\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\\",\\"size\\": 8457,\\"isInline\\": false,\\"contentId\\": null,\\"contentLocation\\": null,\\"contentBytes\\": \\"bytedata\\"}"; final Attachment result = serializer.deserializeObject(source, Attachment.class); - + assert(result instanceof FileAttachment); - + final FileAttachment fileAttachment = (FileAttachment) result; assertNotNull(fileAttachment.contentBytes); final JsonObject o = fileAttachment.getRawObject(); assertNotNull(o); assertEquals("#microsoft.graph.fileAttachment", o. get("@odata.type").getAsString()); } - + @Test public void testSerializerCanSerializeVoidWithoutEmittingWarning() { // Unfortunately does not assert for existence of Java 9 illegal access warnings - // which seem to written to the console without use of System.err/System.out (so cannot be captured AFAIK). + // which seem to written to the console without use of System.err/System.out (so cannot be captured AFAIK). // @davidmoten final DefaultSerializer serializer = new DefaultSerializer(new DefaultLogger()); HasVoidMember t = new HasVoidMember(); String json = serializer.serializeObject(t); - // this line will emit a warning from Java 9 about illegal access to the constructor of Void + // this line will emit a warning from Java 9 about illegal access to the constructor of Void // if gson TypeAdapterFactory is not handling Void properly HasVoidMember t2 = serializer.deserializeObject(json, HasVoidMember.class); assertEquals(t.x, t2.x); @@ -173,12 +186,28 @@ public class DefaultSerializerTests { assertNotNull(result); assertNotNull(result.maxRoundTripTime); } - + @Test + public void testEnumActionParameterDeserialization() throws IOException { + final ArrayList<String> users = new ArrayList<String>(); + users.add("[email protected]"); + final EnumSet<MailTipsType> mailtips = EnumSet.of(MailTipsType.MAILBOX_FULL_STATUS, MailTipsType.MAX_MESSAGE_SIZE); + final UserGetMailTipsBody body = new UserGetMailTipsBody(); + body.emailAddresses = users; + body.mailTipsOptions = mailtips; + final DefaultSerializer serializer = new DefaultSerializer(new DefaultLogger()); + final String serialized = serializer.serializeObject(body); + Assert.assertTrue("result contains camelCasedValues", serialized.contains("mailboxFullStatus")); + + final UserGetMailTipsBody deserialized = serializer.deserializeObject(serialized, UserGetMailTipsBody.class); + + Assert.assertEquals(2, deserialized.mailTipsOptions.size()); + } + public static final class HasVoidMember { @SerializedName("x") @Expose int x = 1; - + @SerializedName("y") @Expose Void y;
['src/main/java/com/microsoft/graph/serializer/EnumSetSerializer.java', 'src/test/java/com/microsoft/graph/serializer/DefaultSerializerTests.java', 'src/main/java/com/microsoft/graph/serializer/GsonFactory.java']
{'.java': 3}
3
3
0
0
3
25,371,135
4,730,635
670,139
8,422
1,915
345
41
2
1,011
55
279
27
1
3
1970-01-01T00:26:47
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,167
microsoftgraph/msgraph-sdk-java/397/396
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/396
https://github.com/microsoftgraph/msgraph-sdk-java/pull/397
https://github.com/microsoftgraph/msgraph-sdk-java/pull/397
1
fixes
OneDrive Chunked Upload - Chunk size is not taken into consideration in case of customized input stream
### Expected behavior Large files should be uploaded in chunks using the specified chunk size according to the following Javadoc comment of the upload method in **ChunkedUploadProvider** class. /** * Uploads content to remote upload session based on the input stream * * @param options the upload options * @param callback the progress callback invoked during uploading * @param **_configs the optional configurations for the upload options. [0] should be the customized chunk_** * **_size_** and [1] should be the maxRetry for upload retry. * @throws IOException the IO exception that occurred during upload */ ChunkedUploadProvider.upload(final List<Option> options, final IProgressCallback<UploadType> callback, final int... configs) ### Actual behavior In enterprise product environment with high parallelism, input streams are often controlled on global level setting data to be read in smaller chunks, like 32 KB. For example the **InputStream read(byte[] buffer)** method reads implicitly less than the specified buffer/chunk size (e.g. reads 32 KB while chunk size is 5 MB). Currently the chunks that are being uploaded are with size equal to what is read from the stream - 32 KB. This behavior leads to too many requests in case of large files. ### Steps to reproduce the behavior 1. Use the sample code described [here](https://docs.microsoft.com/en-us/graph/sdks/large-file-upload?tabs=java) but specify 5 MB chunk size. 2. Use following custom stream in the sample: `InputStream fileStream = new MyInputStream(new FileInputStream(file))` instead of: `InputStream fileStream = new FileInputStream(file);` public class MyInputStream extends InputStream { private InputStream sourceIs; public MyInputStream(InputStream sourceIs) { this.sourceIs = sourceIs; } public int read() throws IOException { return sourceIs.read(); } @Override public int read(byte[] b) throws IOException { return super.read(b, 0, 32 * 1024); } } 3. Run the sample code. **Sample output:** Connecting... Uploaded 0 bytes of 5.296497344970703 MB. Uploaded 32.0 KB of 5.296497344970703 MB. Uploaded 64.0 KB of 5.296497344970703 MB. Uploaded 96.0 KB of 5.296497344970703 MB. ... **Client library versions used are:** - microsoft-graph 1.8.0 - microsoft-graph-core 1.0.1 - microsoft-graph-auth 0.2.0 Pull request: https://github.com/microsoftgraph/msgraph-sdk-java/pull/397
14dad555e5fc5ac74067d1e3da34f3d44c20d1eb
795362ad234efead2cd1c738abddee99b1a48dcc
https://github.com/microsoftgraph/msgraph-sdk-java/compare/14dad555e5fc5ac74067d1e3da34f3d44c20d1eb...795362ad234efead2cd1c738abddee99b1a48dcc
diff --git a/src/main/java/com/microsoft/graph/concurrency/ChunkedUploadProvider.java b/src/main/java/com/microsoft/graph/concurrency/ChunkedUploadProvider.java index c9d7ee2611..c75f494aee 100644 --- a/src/main/java/com/microsoft/graph/concurrency/ChunkedUploadProvider.java +++ b/src/main/java/com/microsoft/graph/concurrency/ChunkedUploadProvider.java @@ -168,14 +168,20 @@ public class ChunkedUploadProvider<UploadType> { byte[] buffer = new byte[chunkSize]; while (this.readSoFar < this.streamSize) { - int read = this.inputStream.read(buffer); - - if (read == -1) { - break; + int buffRead = 0; + + // inner loop is to work-around the case where read buffer size is limited to less than chunk size by a global setting + while (buffRead < chunkSize) { + int read = 0; + read = this.inputStream.read(buffer, buffRead, chunkSize - buffRead); + if (read == -1) { + break; + } + buffRead += read; } ChunkedUploadRequest request = - new ChunkedUploadRequest(this.uploadUrl, this.client, options, buffer, read, + new ChunkedUploadRequest(this.uploadUrl, this.client, options, buffer, buffRead, maxRetry, this.readSoFar, this.streamSize); ChunkedUploadResult<UploadType> result = request.upload(this.responseHandler); @@ -190,7 +196,7 @@ public class ChunkedUploadProvider<UploadType> { break; } - this.readSoFar += read; + this.readSoFar += buffRead; } }
['src/main/java/com/microsoft/graph/concurrency/ChunkedUploadProvider.java']
{'.java': 1}
1
1
0
0
1
20,762,557
3,862,868
578,101
7,812
833
167
18
1
2,586
323
580
59
2
0
1970-01-01T00:26:34
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,152
microsoftgraph/msgraph-sdk-java/654/652
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/652
https://github.com/microsoftgraph/msgraph-sdk-java/pull/654
https://github.com/microsoftgraph/msgraph-sdk-java/pull/654
2
fixes
GraphError#isError(GraphErrorCodes .ITEM_NOT_FOUND)
### Expected behavior GraphError#isError should return true when the exception has the code "itemNotFound" and the provided GraphErrorCodes is ITEM_NOT_FOUND ### Actual behavior It returns false since the strings "ITEM_NOT_FOUND" and "itemNotFound" don't match ### Steps to reproduce the behavior Make a Microsoft Graph call returning a "itemNotFound" error: For example, in Graph Explorer (https://developer.microsoft.com/en-us/graph/graph-explorer) GET https://graph.microsoft.com/v1.0/me/drive/items/NOT_A_REAL_VALUE Sample exception: { "error": { "code": "itemNotFound", "message": "The resource could not be found.", "innerError": { "date": "2021-02-08T09:56:08", "request-id": "31395976-ea18-42ee-8f9a-c19d9bbb9987", "client-request-id": "420329db-d36f-d313-4191-01b4124b8aa7" } } } SDK Version: 2.6.0 Sample code: ``` IGraphServiceClient graphClient = <init graph client> ; try { graphClient.me().drive().items("NOT_A_REAL_VALUE").buildRequest().get(); Assert.fail(); } catch (GraphServiceException e) { boolean isItemNotFound = e.getError().error.isError(GraphErrorCodes.ITEM_NOT_FOUND); Assert.assertTrue(isItemNotFound); } ``` [AB#8036](https://microsoftgraph.visualstudio.com/0985d294-5762-4bc2-a565-161ef349ca3e/_workitems/edit/8036)
ff459ab028730b631b3ae690833f69a98f60a194
3202b604a2ceece2794c72236a5239e2daf2b114
https://github.com/microsoftgraph/msgraph-sdk-java/compare/ff459ab028730b631b3ae690833f69a98f60a194...3202b604a2ceece2794c72236a5239e2daf2b114
diff --git a/src/main/java/com/microsoft/graph/http/GraphError.java b/src/main/java/com/microsoft/graph/http/GraphError.java index 78d1f4a733..6ea84a54e2 100644 --- a/src/main/java/com/microsoft/graph/http/GraphError.java +++ b/src/main/java/com/microsoft/graph/http/GraphError.java @@ -26,6 +26,7 @@ import com.google.gson.annotations.SerializedName; import com.microsoft.graph.core.GraphErrorCodes; import com.google.gson.annotations.Expose; +import com.google.common.base.CaseFormat; public class GraphError { @@ -47,16 +48,24 @@ public class GraphError { * @return <b>true</b> if the error code matches, and <b>false</b> if there was no match */ public boolean isError(final GraphErrorCodes expectedCode) { - if (code.equalsIgnoreCase(expectedCode.toString())) { + if (transformErrorCodeCase(code).equalsIgnoreCase(expectedCode.toString())) { return true; } GraphInnerError innerError = innererror; while (null != innerError) { - if (innerError.code.equalsIgnoreCase(expectedCode.toString())) { + if (transformErrorCodeCase(innerError.code).equalsIgnoreCase(expectedCode.toString())) { return true; } innerError = innerError.innererror; } return false; } + /** + * Transforms the text error code into the format expected by the value of the enum + * @param original original lowser Camel cased error code + * @return the resulting upper undescore cased error code + */ + protected String transformErrorCodeCase(final String original) { + return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, original); + } } diff --git a/src/test/java/com/microsoft/graph/http/GraphErrorTests.java b/src/test/java/com/microsoft/graph/http/GraphErrorTests.java index 0d8087e596..69916c913f 100644 --- a/src/test/java/com/microsoft/graph/http/GraphErrorTests.java +++ b/src/test/java/com/microsoft/graph/http/GraphErrorTests.java @@ -15,7 +15,7 @@ public class GraphErrorTests { public void testIsError(){ String expectedMessage = "test error message"; GraphError error = new GraphError(); - error.code = GraphErrorCodes.ACCESS_DENIED.toString(); + error.code = "accessDenied"; // the code prop is lower camel cased https://docs.microsoft.com/en-us/graph/errors#code-property error.message = expectedMessage; assertTrue(error.isError(GraphErrorCodes.ACCESS_DENIED)); assertEquals(expectedMessage, error.message);
['src/test/java/com/microsoft/graph/http/GraphErrorTests.java', 'src/main/java/com/microsoft/graph/http/GraphError.java']
{'.java': 2}
2
2
0
0
2
25,924,928
4,844,200
681,497
8,455
764
146
13
1
1,390
112
363
42
3
1
1970-01-01T00:26:52
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
839
cloudnetservice/cloudnet-v3/126/116
cloudnetservice
cloudnet-v3
https://github.com/CloudNetService/CloudNet-v3/issues/116
https://github.com/CloudNetService/CloudNet-v3/pull/126
https://github.com/CloudNetService/CloudNet-v3/pull/126
1
fixes
Wrapper log on startup doesn't contain line breaks
**Describe the bug**<br> If you use "System.out.println" more than once in the Wrapper before the application (e. g. spigot) is running, all lines are printed in one line, only if you add the line seperator to the end of the string, all lines are printed seperately. **Steps for reproducing**<br> 1. print some lines on wrapper startup (in a module in the wrapper on the STARTED or LOADED state or directly in the wrapper) 2. see the log using the screen command or in temp/services/SERVICE/.wrapper/logs/ (or for static services in local/services) **Expected behavior**<br> The printed lines using "System.out.println" should all be printed seperately without the line seperator at the end of the string **Please provide us information about your environment and used assets** System specs: CPU = Intel i7 6700k, RAM = 16 GB DDR4 2400 MHz OS: Windows 10 Version: Current dev version
253fb4888ffe7995f8987ea4bd506828efae15e7
e99b144841425cbfed466953f3ce2e33cec59982
https://github.com/cloudnetservice/cloudnet-v3/compare/253fb4888ffe7995f8987ea4bd506828efae15e7...e99b144841425cbfed466953f3ce2e33cec59982
diff --git a/cloudnet/src/main/java/de/dytanic/cloudnet/console/JLine2Console.java b/cloudnet/src/main/java/de/dytanic/cloudnet/console/JLine2Console.java index e6391d49f..b4888cfb8 100644 --- a/cloudnet/src/main/java/de/dytanic/cloudnet/console/JLine2Console.java +++ b/cloudnet/src/main/java/de/dytanic/cloudnet/console/JLine2Console.java @@ -1,6 +1,7 @@ package de.dytanic.cloudnet.console; import jline.console.ConsoleReader; +import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; public final class JLine2Console implements IConsole { @@ -51,7 +52,7 @@ public final class JLine2Console implements IConsole { text = ConsoleColor.toColouredString('&', text); try { - this.consoleReader.print(ConsoleReader.RESET_LINE + text + ConsoleColor.DEFAULT); + this.consoleReader.print(Ansi.ansi().eraseLine(Ansi.Erase.ALL).toString() + ConsoleReader.RESET_LINE + text + ConsoleColor.DEFAULT); this.consoleReader.flush(); } catch (Exception ex) { ex.printStackTrace(); @@ -73,7 +74,7 @@ public final class JLine2Console implements IConsole { } try { - this.consoleReader.print(ConsoleReader.RESET_LINE + text + ConsoleColor.DEFAULT); + this.consoleReader.print(Ansi.ansi().eraseLine(Ansi.Erase.ALL).toString() + ConsoleReader.RESET_LINE + text + ConsoleColor.DEFAULT); this.consoleReader.drawLine(); this.consoleReader.flush(); } catch (Exception exception) { @@ -126,4 +127,4 @@ public final class JLine2Console implements IConsole { public void setScreenName(String screenName) { this.screenName = screenName; } -} \\ No newline at end of file +}
['cloudnet/src/main/java/de/dytanic/cloudnet/console/JLine2Console.java']
{'.java': 1}
1
1
0
0
1
2,157,739
405,482
58,841
786
521
109
7
1
903
143
217
16
0
0
1970-01-01T00:26:09
317
Java
{'Java': 5151361, 'Kotlin': 74901, 'Shell': 1480, 'Dockerfile': 420, 'Batchfile': 419}
Apache License 2.0
838
cloudnetservice/cloudnet-v3/428/366
cloudnetservice
cloudnet-v3
https://github.com/CloudNetService/CloudNet-v3/issues/366
https://github.com/CloudNetService/CloudNet-v3/pull/428
https://github.com/CloudNetService/CloudNet-v3/pull/428
1
fixed
Command system does unnecessary work
**Description of the bug:** The command system executes the validation condition for a command multiple times to filter for the invalid message. **Steps to reproduce this bug:** For example use the ``perms <user>`` command, this will check multiple times if the user exists, which might take some time when having a bigger database.
f4f0cbfc92e140605258ef60540e32c0c1e270bb
0296863e4717fc0e3c79bc419629ac1d1505c107
https://github.com/cloudnetservice/cloudnet-v3/compare/f4f0cbfc92e140605258ef60540e32c0c1e270bb...0296863e4717fc0e3c79bc419629ac1d1505c107
diff --git a/cloudnet/src/main/java/de/dytanic/cloudnet/command/sub/SubCommandHandler.java b/cloudnet/src/main/java/de/dytanic/cloudnet/command/sub/SubCommandHandler.java index 374c62a87..c35c82836 100644 --- a/cloudnet/src/main/java/de/dytanic/cloudnet/command/sub/SubCommandHandler.java +++ b/cloudnet/src/main/java/de/dytanic/cloudnet/command/sub/SubCommandHandler.java @@ -9,7 +9,10 @@ import de.dytanic.cloudnet.common.Properties; import de.dytanic.cloudnet.common.collection.Pair; import de.dytanic.cloudnet.common.language.LanguageManager; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Objects; import java.util.stream.Collectors; public class SubCommandHandler extends Command implements ITabCompleter { @@ -66,33 +69,35 @@ public class SubCommandHandler extends Command implements ITabCompleter { @Override public void execute(ICommandSender sender, String command, String[] args, String commandLine, Properties properties) { - Optional<Pair<SubCommand, SubCommandArgument<?>[]>> optionalSubCommand = this.subCommands.stream() - .map(subCommand -> new Pair<>(subCommand, subCommand.parseArgs(args))) - .filter(pair -> pair.getSecond() != null && pair.getSecond().length != 0) - .findFirst(); - - if (!optionalSubCommand.isPresent()) { - Optional<String> optionalInvalidMessage = this.subCommands.stream() - .map(subCommand -> subCommand.getInvalidArgumentMessage(args)) - .filter(Objects::nonNull) - .filter(pair -> pair.getSecond() == 0) // all static values must match - .findFirst() - .map(Pair::getFirst); - - if (optionalInvalidMessage.isPresent()) { - sender.sendMessage(optionalInvalidMessage.get()); - } else { - this.sendHelp(sender); + SubCommand subCommand = null; + SubCommandArgument<?>[] arguments = null; + + for (SubCommand registeredCommand : this.subCommands) { + arguments = registeredCommand.parseArgs(args); + if (arguments != null && arguments.length > 0) { + subCommand = registeredCommand; + break; + } + } + + if (subCommand == null) { + for (SubCommand registeredCommand : this.subCommands) { + Pair<String, Integer> invalidArgumentMessage = registeredCommand.getInvalidArgumentMessage(args); + if (invalidArgumentMessage != null && invalidArgumentMessage.getSecond() == 0) { + sender.sendMessage(invalidArgumentMessage.getFirst()); + return; + } } + this.sendHelp(sender); return; } - Pair<SubCommand, SubCommandArgument<?>[]> subCommandPair = optionalSubCommand.get(); - - SubCommand subCommand = subCommandPair.getFirst(); - SubCommandArgument<?>[] parsedArgs = subCommandPair.getSecond(); + this.executeCommand(sender, command, args, commandLine, subCommand, arguments); + } + protected void executeCommand(ICommandSender sender, String command, String[] args, String commandLine, + SubCommand subCommand, SubCommandArgument<?>[] parsedArgs) { if (subCommand.isOnlyConsole() && !(sender instanceof ConsoleCommandSender)) { sender.sendMessage(LanguageManager.getMessage("command-sub-only-console")); return;
['cloudnet/src/main/java/de/dytanic/cloudnet/command/sub/SubCommandHandler.java']
{'.java': 1}
1
1
0
0
1
2,887,094
543,911
78,231
966
2,456
444
49
1
339
53
68
6
0
0
1970-01-01T00:26:58
317
Java
{'Java': 5151361, 'Kotlin': 74901, 'Shell': 1480, 'Dockerfile': 420, 'Batchfile': 419}
Apache License 2.0
1,165
microsoftgraph/msgraph-sdk-java/448/391
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/391
https://github.com/microsoftgraph/msgraph-sdk-java/pull/448
https://github.com/microsoftgraph/msgraph-sdk-java/pull/448
2
fixes
Fail to PATCH event
Hello I just upgraded to the latest 1.8.0 version from 1.7.1 and using https://graph.microsoft.com/v1.0 service root. However when I try to update an event it gives the following error message. Cannot invoke the action, eventually got an error: com.microsoft.graph.http.GraphServiceException: Error code: RequestBodyRead Error message: The property 'graphResponseHeaders' does not exist on type 'Microsoft.OutlookServices.Event'. Make sure to only use property names that are defined by the type or mark the type as open type. PATCH https://graph.microsoft.com/v1.0/users/aa6683ae-427a-44e7-836b-ec0741fc717a/events/AAMkADEwMjU3OGYyLWU0NTktNDgyNy05ODUxLWRlYzQ5OWE4MmU5MwBGAAAAAACSVpJrwKxgR5K20zCB8fQRBwC98SkOlY-sRoGpzahBToGYAAAw0TA4AAC98SkOlY-sRoGpzahBToGYAAAw0TgTAAA= SdkVersion : graph-java/v1.7.1 Authorization : Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI[...] {"originalStartTimeZone":"Pacific Standard Time","[...] 400 : Bad Request [...] [Some information was truncated for brevity, enable debug logging for more details]
d3f9294899e63bfb5bacdc7f95d56a8cf47c1023
7a82de2f56cb196ca8b626543c1d6cf4d9608f75
https://github.com/microsoftgraph/msgraph-sdk-java/compare/d3f9294899e63bfb5bacdc7f95d56a8cf47c1023...7a82de2f56cb196ca8b626543c1d6cf4d9608f75
diff --git a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java index cb4fd614ee..7e93e795c0 100644 --- a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java @@ -72,7 +72,7 @@ public class DefaultSerializer implements ISerializer { public <T> T deserializeObject(final String inputString, final Class<T> clazz) { return deserializeObject(inputString, clazz, null); } - + private static final String graphResponseHeadersKey = "graphResponseHeaders"; @SuppressWarnings("unchecked") @Override public <T> T deserializeObject(final String inputString, final Class<T> clazz, Map<String, java.util.List<String>> responseHeaders) { @@ -97,7 +97,7 @@ public class DefaultSerializer implements ISerializer { if (responseHeaders != null) { JsonElement convertedHeaders = gson.toJsonTree(responseHeaders); - jsonBackedObject.additionalDataManager().put("graphResponseHeaders", convertedHeaders); + jsonBackedObject.additionalDataManager().put(graphResponseHeadersKey, convertedHeaders); } jsonBackedObject.additionalDataManager().setAdditionalData(rawObject); @@ -271,7 +271,9 @@ public class DefaultSerializer implements ISerializer { */ private void addAdditionalDataToJson(AdditionalDataManager additionalDataManager, JsonObject jsonNode) { for (Map.Entry<String, JsonElement> entry : additionalDataManager.entrySet()) { + if(!entry.getKey().equals(graphResponseHeadersKey)) { jsonNode.add(entry.getKey(), entry.getValue()); + } } }
['src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java']
{'.java': 1}
1
1
0
0
1
22,498,613
4,178,353
606,171
8,023
375
65
6
1
1,042
102
329
17
2
0
1970-01-01T00:26:39
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,160
microsoftgraph/msgraph-sdk-java/490/489
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/489
https://github.com/microsoftgraph/msgraph-sdk-java/pull/490
https://github.com/microsoftgraph/msgraph-sdk-java/pull/490
2
fixes
The condition at line 188 of ChunkedUploadProvider.java is never satisfied so the success callback is never called.
The condition at line 188 of ChunkedUploadProvider.java is never satisfied so the success callback is never called. ```Java if (result.uploadCompleted()) { callback.progress(this.streamSize, this.streamSize); callback.success((UploadType) result.getItem()); break; } ``` _Originally posted by @RegisStGelais in https://github.com/microsoftgraph/msgraph-sdk-java/issues/472#issuecomment-696696095_
7a55ff3026958651f73453cc76bff1d574249ded
1558e36b78e7bcb5399a7d4322cad608851de7d6
https://github.com/microsoftgraph/msgraph-sdk-java/compare/7a55ff3026958651f73453cc76bff1d574249ded...1558e36b78e7bcb5399a7d4322cad608851de7d6
diff --git a/src/main/java/com/microsoft/graph/concurrency/ChunkedUploadResponseHandler.java b/src/main/java/com/microsoft/graph/concurrency/ChunkedUploadResponseHandler.java index eaee8434f0..3f4a210634 100644 --- a/src/main/java/com/microsoft/graph/concurrency/ChunkedUploadResponseHandler.java +++ b/src/main/java/com/microsoft/graph/concurrency/ChunkedUploadResponseHandler.java @@ -176,7 +176,7 @@ public class ChunkedUploadResponseHandler<UploadType> in = new BufferedInputStream(response.body().byteStream()); final String rawJson = DefaultHttpProvider.streamToString(in); final UploadSession session = serializer.deserializeObject(rawJson, UploadSession.class); - if(session == null) { + if(session == null || session.nextExpectedRanges == null) { logger.logDebug("Upload session is completed (ODSP), uploaded item returned."); final UploadType uploadedItem = serializer.deserializeObject(rawJson, this.deserializeTypeClass); return new ChunkedUploadResult<UploadType>(uploadedItem);
['src/main/java/com/microsoft/graph/concurrency/ChunkedUploadResponseHandler.java']
{'.java': 1}
1
1
0
0
1
24,581,502
4,587,539
656,822
8,129
93
21
2
1
478
34
97
10
1
1
1970-01-01T00:26:40
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,161
microsoftgraph/msgraph-sdk-java/471/468
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/468
https://github.com/microsoftgraph/msgraph-sdk-java/pull/471
https://github.com/microsoftgraph/msgraph-sdk-java/pull/471
2
fixes
Conflict behavior parameter set via AdditionalDataManager on DriveItemUploadableProperties is not serialized correctly in the request body
Unfortunately the fix for #393 in 2.1.0 is not okay. Expected behavior { "item": { "@microsoft.graph.conflictBehavior": "rename", "name": "vacation.gif" } } See API reference. Actual behavior { "item": { "name": "vacation.gif" } "@microsoft.graph.conflictBehavior": "rename" } The @microsoft.graph.conflictBehavior property is ignored by the service. Steps to reproduce the behavior DriveItemUploadableProperties upProps = new DriveItemUploadableProperties(); upProps.name = "vacation.gif"; upProps.additionalDataManager().put("@microsoft.graph.conflictBehavior", new JsonPrimitive("rename")); // Create an upload session UploadSession uploadSession = graphClient .me() .drive() .root() // itemPath like "/Folder/file.txt" // does not need to be a path to an existing item .itemWithPath(itemPath) .createUploadSession(upProps) .buildRequest() .post(); Proposed fix Add @microsoft.graph.conflictBehavior to the DriveItemUploadableProperties class just like @odata.type: @SerializedName("@microsoft.graph.conflictBehavior") @Expose public String conflictBehavior; Then we can set the conflict behavior by upProps.conflictBehavior = "rename"; and the parameter gets added to the item property correctly. [AB#6034](https://microsoftgraph.visualstudio.com/0985d294-5762-4bc2-a565-161ef349ca3e/_workitems/edit/6034)
6e7acc8eac62a8cd8a59e2c535f132d60acd9f6f
77f240a401f1b0a07b641e140bfe1333fa5129c0
https://github.com/microsoftgraph/msgraph-sdk-java/compare/6e7acc8eac62a8cd8a59e2c535f132d60acd9f6f...77f240a401f1b0a07b641e140bfe1333fa5129c0
diff --git a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java index 822ed586b4..bbac784612 100644 --- a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java @@ -196,9 +196,10 @@ public class DefaultSerializer implements ISerializer { if(outJson.has(field.getName())) { final Type[] interfaces = field.getType().getGenericInterfaces(); for(Type interfaceType : interfaces) { - if(interfaceType == IJsonBackedObject.class) { + if(interfaceType == IJsonBackedObject.class && outJson.get(field.getName()).isJsonObject()) { try { - outJsonTree = getDataFromAdditionalDataManager(outJsonTree, field.get(serializableObject)); + final JsonElement outdatedValue = outJson.remove(field.getName()); + outJson.add(field.getName(), getDataFromAdditionalDataManager(outdatedValue.getAsJsonObject(), field.get(serializableObject))); } catch (IllegalAccessException ex ) { logger.logDebug("Couldn't access prop" + field.getName()); } diff --git a/src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java b/src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java index 3a068d3971..76534625ff 100644 --- a/src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java +++ b/src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java @@ -3,14 +3,19 @@ package com.microsoft.graph.serializer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; +import okhttp3.Request; + import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; +import com.microsoft.graph.functional.TestBase; +import com.microsoft.graph.http.HttpMethod; import com.microsoft.graph.logger.DefaultLogger; import com.microsoft.graph.models.extensions.Drive; import com.microsoft.graph.models.extensions.DriveItemCreateUploadSessionBody; @@ -66,7 +71,7 @@ public class AdditionalDataTests { final DriveItemCreateUploadSessionBody body = new DriveItemCreateUploadSessionBody(); body.item = upProps; String serializedObject = serializer.serializeObject(body); - assertEquals("{\\"item\\":{\\"name\\":\\"vacation.gif\\"},\\"@microsoft.graph.conflictBehavior\\":\\"rename\\"}", serializedObject); + assertEquals("{\\"item\\":{\\"name\\":\\"vacation.gif\\",\\"@microsoft.graph.conflictBehavior\\":\\"rename\\"}}", serializedObject); } @Test
['src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java', 'src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java']
{'.java': 2}
2
2
0
0
2
23,777,893
4,441,295
639,428
8,024
576
90
5
1
1,384
129
344
44
1
0
1970-01-01T00:26:40
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,148
microsoftgraph/msgraph-sdk-java/689/685
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/685
https://github.com/microsoftgraph/msgraph-sdk-java/pull/689
https://github.com/microsoftgraph/msgraph-sdk-java/pull/689
2
fixes
Changing password request is logging out sensitive information
I am currently using the Microsoft Graph Java SDK to change a user's password like so: ``` graphServiceClient .me() .changePassword(currentPassword, newPassword) .buildRequest() .post(); ``` However, when the Graph API throws an exception, the change password request is written to the log with the passwords displaying in plain text! Is there a way of hiding this sensitive information? For now, I have added a custom logger the Graph Server Client which in effect suppresses logging but I was wondering if there was something more fine grained in the SDK?
f4ea64134466363544aa970212f80257c824794f
204babfbbaac332a42debb5424b52b98a271b790
https://github.com/microsoftgraph/msgraph-sdk-java/compare/f4ea64134466363544aa970212f80257c824794f...204babfbbaac332a42debb5424b52b98a271b790
diff --git a/src/main/java/com/microsoft/graph/http/GraphServiceException.java b/src/main/java/com/microsoft/graph/http/GraphServiceException.java index 08e24886c1..199436d36e 100644 --- a/src/main/java/com/microsoft/graph/http/GraphServiceException.java +++ b/src/main/java/com/microsoft/graph/http/GraphServiceException.java @@ -1,16 +1,16 @@ // ------------------------------------------------------------------------------ // Copyright (c) 2017 Microsoft Corporation -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sub-license, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -174,7 +174,7 @@ public class GraphServiceException extends ClientException { public String getMessage() { return getMessage(verbose); } - + /** * Gets the HTTP status code * @@ -215,7 +215,7 @@ public class GraphServiceException extends ClientException { public String getUrl() { return url; } - + /** * Gets the request headers * @return the request headers @@ -255,12 +255,7 @@ public class GraphServiceException extends ClientException { if (verbose) { sb.append(requestBody); } else { - final int bodyLength = Math.min(MAX_BREVITY_LENGTH, requestBody.length()); - final String truncatedBody = requestBody.substring(0, bodyLength); - sb.append(truncatedBody); - if (truncatedBody.length() == MAX_BREVITY_LENGTH) { - sb.append(TRUNCATION_MARKER); - } + sb.append(TRUNCATION_MARKER); } } sb.append(NEW_LINE).append(NEW_LINE); @@ -402,7 +397,7 @@ public class GraphServiceException extends ClientException { error, isVerbose); } - + /** * Creates a Graph service exception from a given failed HTTP request * diff --git a/src/main/java/com/microsoft/graph/requests/extensions/ChunkedUploadResult.java b/src/main/java/com/microsoft/graph/requests/extensions/ChunkedUploadResult.java index 9dc884e3d3..0e481bfa16 100644 --- a/src/main/java/com/microsoft/graph/requests/extensions/ChunkedUploadResult.java +++ b/src/main/java/com/microsoft/graph/requests/extensions/ChunkedUploadResult.java @@ -66,7 +66,7 @@ public class ChunkedUploadResult<UploadType> { * @param exception The exception received from server. */ public ChunkedUploadResult(GraphServiceException exception) { - this(new ClientException(exception.getMessage(/* verbose */ true), exception)); + this(new ClientException(exception.getMessage(), exception)); } /** @@ -122,4 +122,4 @@ public class ChunkedUploadResult<UploadType> { public ClientException getError() { return this.error; } -} \\ No newline at end of file +} diff --git a/src/test/java/com/microsoft/graph/http/GraphServiceExceptionTests.java b/src/test/java/com/microsoft/graph/http/GraphServiceExceptionTests.java index 58485bb246..6cccead655 100644 --- a/src/test/java/com/microsoft/graph/http/GraphServiceExceptionTests.java +++ b/src/test/java/com/microsoft/graph/http/GraphServiceExceptionTests.java @@ -31,7 +31,7 @@ public class GraphServiceExceptionTests { assertTrue(message.indexOf("truncated") > 0); assertEquals(error,exception.getServiceError()); } - + @Test public void testVerboseError() { GraphErrorResponse errorResponse = new GraphErrorResponse(); @@ -82,7 +82,7 @@ public class GraphServiceExceptionTests { assertTrue(message.indexOf("Error code: Unable to parse error response message") == 0); assertTrue(message.indexOf("http://localhost") > 0); } - + @Test public void testNullConnection() { DefaultLogger logger = new DefaultLogger(); @@ -124,5 +124,24 @@ public class GraphServiceExceptionTests { assertTrue(message.indexOf("Error code: Unable to parse error response message") == 0); assertTrue(message.indexOf("http://localhost") > 0); } - + @Test + public void requestPayloadShouldNotBePartOfMessageWhenNotVerbose(){ + final GraphErrorResponse errorResponse = new GraphErrorResponse(); + final GraphError error = new GraphError(); + error.code = GraphErrorCodes.UNAUTHENTICATED.toString(); + errorResponse.error = error; + final GraphServiceException exception = new GraphServiceException(null,null,new ArrayList<String>(),"requestPayload",401,"Unauthorized",new ArrayList<String>(),errorResponse, false); + final String message = exception.getMessage(); + assertFalse(message.indexOf("requestPayload") > 0); + } + @Test + public void requestPayloadShouldBePartOfMessageWhenVerbose(){ + final GraphErrorResponse errorResponse = new GraphErrorResponse(); + final GraphError error = new GraphError(); + error.code = GraphErrorCodes.UNAUTHENTICATED.toString(); + errorResponse.error = error; + final GraphServiceException exception = new GraphServiceException(null,null,new ArrayList<String>(),"requestPayload",401,"Unauthorized",new ArrayList<String>(),errorResponse, true); + final String message = exception.getMessage(); + assertTrue(message.indexOf("requestPayload") > 0); + } }
['src/main/java/com/microsoft/graph/http/GraphServiceException.java', 'src/main/java/com/microsoft/graph/requests/extensions/ChunkedUploadResult.java', 'src/test/java/com/microsoft/graph/http/GraphServiceExceptionTests.java']
{'.java': 3}
3
3
0
0
3
27,987,949
5,219,587
733,014
9,074
620
112
23
2
578
88
121
11
0
1
1970-01-01T00:26:54
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
1,150
microsoftgraph/msgraph-sdk-java/662/659
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/659
https://github.com/microsoftgraph/msgraph-sdk-java/pull/662
https://github.com/microsoftgraph/msgraph-sdk-java/pull/662
1
fixes
Calling setMaxRetries on BaseCollectionRequest sets maxRedirects on baseRequest
### Expected behavior maxRetries is set correctly ### Actual behavior maxRedirects is set when calling setMaxRetries on BaseCollectionRequest There seems to be a typo at https://github.com/microsoftgraph/msgraph-sdk-java/blob/ee1678b0dd2a96ade4844833626f51edaa8af992/src/main/java/com/microsoft/graph/http/BaseCollectionRequest.java#L274 [AB#8085](https://microsoftgraph.visualstudio.com/0985d294-5762-4bc2-a565-161ef349ca3e/_workitems/edit/8085)
9472f99017a445137478fbce44e441cb3866e7c0
0909802421a5824cffbaa33fc3673d14ba990ee4
https://github.com/microsoftgraph/msgraph-sdk-java/compare/9472f99017a445137478fbce44e441cb3866e7c0...0909802421a5824cffbaa33fc3673d14ba990ee4
diff --git a/src/main/java/com/microsoft/graph/http/BaseCollectionRequest.java b/src/main/java/com/microsoft/graph/http/BaseCollectionRequest.java index 9e648e6019..916241200e 100644 --- a/src/main/java/com/microsoft/graph/http/BaseCollectionRequest.java +++ b/src/main/java/com/microsoft/graph/http/BaseCollectionRequest.java @@ -271,7 +271,7 @@ public abstract class BaseCollectionRequest<T1, T2> implements IHttpRequest { * @param maxRetries Max retries for a request */ public void setMaxRetries(int maxRetries) { - baseRequest.setMaxRedirects(maxRetries); + baseRequest.setMaxRetries(maxRetries); } /**
['src/main/java/com/microsoft/graph/http/BaseCollectionRequest.java']
{'.java': 1}
1
1
0
0
1
26,409,542
4,926,926
692,344
8,573
91
20
2
1
472
27
132
16
2
0
1970-01-01T00:26:52
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
723
refinedmods/refinedstorage/3199/2730
refinedmods
refinedstorage
https://github.com/refinedmods/refinedstorage/issues/2730
https://github.com/refinedmods/refinedstorage/pull/3199
https://github.com/refinedmods/refinedstorage/pull/3199
1
fixes
Processing recipes ignore first slot when transferred into crafting grid
#### Issue description: Processing recipes ignore first slot when transferred into crafting grid #### Steps to reproduce: 1. transfer processing recipe through JEI 2. 3. ... #### Version (make sure you are on the latest version before reporting): - Minecraft: 1.16.3 - Forge: 34.1.25 - Refined Storage: 1.9.8 Crafting recipes put the output as first slot. That slot is being skipped here: https://github.com/refinedmods/refinedstorage/blob/512077e88011d8d9ceaef408706e75c5253084d5/src/main/java/com/refinedmods/refinedstorage/network/grid/GridTransferMessage.java#L55 Not sure what a good solution would be.
82ad38b085692138712f0c70d404f0ef0aee52db
e0fab68fd3957ee5081a0a709b7fb7c6f7c704a9
https://github.com/refinedmods/refinedstorage/compare/82ad38b085692138712f0c70d404f0ef0aee52db...e0fab68fd3957ee5081a0a709b7fb7c6f7c704a9
diff --git a/src/main/java/com/refinedmods/refinedstorage/apiimpl/network/grid/CraftingGridBehavior.java b/src/main/java/com/refinedmods/refinedstorage/apiimpl/network/grid/CraftingGridBehavior.java index 1b64827bd..0ce7ad08f 100644 --- a/src/main/java/com/refinedmods/refinedstorage/apiimpl/network/grid/CraftingGridBehavior.java +++ b/src/main/java/com/refinedmods/refinedstorage/apiimpl/network/grid/CraftingGridBehavior.java @@ -211,7 +211,7 @@ public class CraftingGridBehavior implements ICraftingGridBehavior { // If we are connected, first try to get the possibilities from the network if (network != null && grid.isGridActive()) { for (ItemStack possibility : possibilities) { - ItemStack took = network.extractItem(possibility, 1, IComparer.COMPARE_NBT, Action.PERFORM); + ItemStack took = network.extractItem(possibility, possibility.getCount(), IComparer.COMPARE_NBT, Action.PERFORM); if (!took.isEmpty()) { grid.getCraftingMatrix().setInventorySlotContents(i, took); diff --git a/src/main/java/com/refinedmods/refinedstorage/integration/jei/GridRecipeTransferHandler.java b/src/main/java/com/refinedmods/refinedstorage/integration/jei/GridRecipeTransferHandler.java index bbb321d63..5213465cc 100644 --- a/src/main/java/com/refinedmods/refinedstorage/integration/jei/GridRecipeTransferHandler.java +++ b/src/main/java/com/refinedmods/refinedstorage/integration/jei/GridRecipeTransferHandler.java @@ -153,7 +153,8 @@ public class GridRecipeTransferHandler implements IRecipeTransferHandler<GridCon private void move(GridContainer gridContainer, IRecipeLayout recipeLayout) { RS.NETWORK_HANDLER.sendToServer(new GridTransferMessage( recipeLayout.getItemStacks().getGuiIngredients(), - gridContainer.inventorySlots.stream().filter(s -> s.inventory instanceof CraftingInventory).collect(Collectors.toList()) + gridContainer.inventorySlots.stream().filter(s -> s.inventory instanceof CraftingInventory).collect(Collectors.toList()), + recipeLayout.getRecipeCategory().getUid().equals(VanillaRecipeCategoryUid.CRAFTING) )); } diff --git a/src/main/java/com/refinedmods/refinedstorage/network/grid/GridTransferMessage.java b/src/main/java/com/refinedmods/refinedstorage/network/grid/GridTransferMessage.java index 684dd5bc4..18b6f2b67 100644 --- a/src/main/java/com/refinedmods/refinedstorage/network/grid/GridTransferMessage.java +++ b/src/main/java/com/refinedmods/refinedstorage/network/grid/GridTransferMessage.java @@ -19,15 +19,17 @@ import java.util.function.Supplier; public class GridTransferMessage { private Map<Integer, ? extends IGuiIngredient<ItemStack>> inputs; private List<Slot> slots; + boolean isCraftingRecipe; private final ItemStack[][] recipe = new ItemStack[9][]; public GridTransferMessage() { } - public GridTransferMessage(Map<Integer, ? extends IGuiIngredient<ItemStack>> inputs, List<Slot> slots) { + public GridTransferMessage(Map<Integer, ? extends IGuiIngredient<ItemStack>> inputs, List<Slot> slots, boolean isCraftingRecipe) { this.inputs = inputs; this.slots = slots; + this.isCraftingRecipe = isCraftingRecipe; } public static GridTransferMessage decode(PacketBuffer buf) { @@ -52,7 +54,7 @@ public class GridTransferMessage { buf.writeInt(message.slots.size()); for (Slot slot : message.slots) { - IGuiIngredient<ItemStack> ingredient = message.inputs.get(slot.getSlotIndex() + 1); + IGuiIngredient<ItemStack> ingredient = message.inputs.get(slot.getSlotIndex() + (message.isCraftingRecipe ? 1 : 0)); List<ItemStack> ingredients = new ArrayList<>();
['src/main/java/com/refinedmods/refinedstorage/apiimpl/network/grid/CraftingGridBehavior.java', 'src/main/java/com/refinedmods/refinedstorage/integration/jei/GridRecipeTransferHandler.java', 'src/main/java/com/refinedmods/refinedstorage/network/grid/GridTransferMessage.java']
{'.java': 3}
3
3
0
0
3
1,999,736
421,651
55,570
637
1,187
239
11
3
630
71
161
18
1
0
1970-01-01T00:27:20
317
Java
{'Java': 2021464, 'Shell': 456}
MIT License
837
cloudnetservice/cloudnet-v3/171/169
cloudnetservice
cloudnet-v3
https://github.com/CloudNetService/CloudNet-v3/issues/169
https://github.com/CloudNetService/CloudNet-v3/pull/171
https://github.com/CloudNetService/CloudNet-v3/pull/171#issuecomment-552184427
1
fixes
SyncProxyModule only checks whitelist
The sync proxy modules does only check if the player is on the whitelist on maintenance and ignores that the player might have the permission to join.
fb6e64efbb8ba7af53d32d3d0518ef4dc0dc51b9
bd40a0653a27f4ca0972c2028bb6da57c8ea5bf9
https://github.com/cloudnetservice/cloudnet-v3/compare/fb6e64efbb8ba7af53d32d3d0518ef4dc0dc51b9...bd40a0653a27f4ca0972c2028bb6da57c8ea5bf9
diff --git a/cloudnet-modules/cloudnet-cloudperms/src/main/java/de/dytanic/cloudnet/ext/cloudperms/bungee/listener/BungeeCloudNetCloudPermissionsPlayerListener.java b/cloudnet-modules/cloudnet-cloudperms/src/main/java/de/dytanic/cloudnet/ext/cloudperms/bungee/listener/BungeeCloudNetCloudPermissionsPlayerListener.java index b6bbd70b0..dbd9b0e19 100644 --- a/cloudnet-modules/cloudnet-cloudperms/src/main/java/de/dytanic/cloudnet/ext/cloudperms/bungee/listener/BungeeCloudNetCloudPermissionsPlayerListener.java +++ b/cloudnet-modules/cloudnet-cloudperms/src/main/java/de/dytanic/cloudnet/ext/cloudperms/bungee/listener/BungeeCloudNetCloudPermissionsPlayerListener.java @@ -11,6 +11,8 @@ import net.md_5.bungee.api.event.PlayerDisconnectEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.UUID; public final class BungeeCloudNetCloudPermissionsPlayerListener implements Listener { @@ -24,9 +26,21 @@ public final class BungeeCloudNetCloudPermissionsPlayerListener implements Liste public void handle(PermissionCheckEvent event) { CommandSender sender = event.getSender(); + UUID uniqueId = null; + if (sender instanceof ProxiedPlayer) { - UUID uniqueId = ((ProxiedPlayer) sender).getUniqueId(); + uniqueId = ((ProxiedPlayer) sender).getUniqueId(); + } else { + try { + Method method = sender.getClass().getDeclaredMethod("getUniqueId"); + uniqueId = (UUID) method.invoke(sender); + } catch (NoSuchMethodException ignored) { + } catch (IllegalAccessException | InvocationTargetException exception) { + exception.printStackTrace(); + } + } + if (uniqueId != null) { IPermissionUser permissionUser = CloudPermissionsPermissionManagement.getInstance().getUser(uniqueId); if (permissionUser != null) { diff --git a/cloudnet-modules/cloudnet-syncproxy/src/main/java/de/dytanic/cloudnet/ext/syncproxy/bungee/util/LoginPendingConnectionCommandSender.java b/cloudnet-modules/cloudnet-syncproxy/src/main/java/de/dytanic/cloudnet/ext/syncproxy/bungee/util/LoginPendingConnectionCommandSender.java index e4260cf27..ee8e2c80d 100644 --- a/cloudnet-modules/cloudnet-syncproxy/src/main/java/de/dytanic/cloudnet/ext/syncproxy/bungee/util/LoginPendingConnectionCommandSender.java +++ b/cloudnet-modules/cloudnet-syncproxy/src/main/java/de/dytanic/cloudnet/ext/syncproxy/bungee/util/LoginPendingConnectionCommandSender.java @@ -98,7 +98,7 @@ public class LoginPendingConnectionCommandSender implements CommandSender { } public PendingConnection getPendingConnection() { - return pendingConnection; + return this.pendingConnection; } public UUID getUniqueId() {
['cloudnet-modules/cloudnet-syncproxy/src/main/java/de/dytanic/cloudnet/ext/syncproxy/bungee/util/LoginPendingConnectionCommandSender.java', 'cloudnet-modules/cloudnet-cloudperms/src/main/java/de/dytanic/cloudnet/ext/cloudperms/bungee/listener/BungeeCloudNetCloudPermissionsPlayerListener.java']
{'.java': 2}
2
2
0
0
2
2,271,993
426,094
61,074
817
752
133
18
2
150
27
28
1
0
0
1970-01-01T00:26:12
317
Java
{'Java': 5151361, 'Kotlin': 74901, 'Shell': 1480, 'Dockerfile': 420, 'Batchfile': 419}
Apache License 2.0
1,164
microsoftgraph/msgraph-sdk-java/451/393
microsoftgraph
msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java/issues/393
https://github.com/microsoftgraph/msgraph-sdk-java/pull/451
https://github.com/microsoftgraph/msgraph-sdk-java/pull/451
2
fixes
Properties set via AdditionalDataManager on DriveItemUploadableProperties are not serialized in the request body
Repro: - Configure your project to use Fiddler so you can capture the request - Use code like this: ``` DriveItemUploadableProperties upProps = new DriveItemUploadableProperties(); upProps.name = "vacation.gif"; upProps.additionalDataManager().put("@microsoft.graph.conflictBehavior", new JsonPrimitive("rename")); // Create an upload session UploadSession uploadSession = graphClient .me() .drive() .root() // itemPath like "/Folder/file.txt" // does not need to be a path to an existing item .itemWithPath(itemPath) .createUploadSession(upProps) .buildRequest() .post(); ``` - Review the request body in Fiddler Result: The `name` property is seralized, but not `@microsoft.graph.conflictBehavior`. ``` {"item":{"name":"vacation.gif"}} ```
566d653db1dc9f4db4a5a0ee9e055426b3e51f67
c917635bf90ba94d79f1647e604a21641f5773aa
https://github.com/microsoftgraph/msgraph-sdk-java/compare/566d653db1dc9f4db4a5a0ee9e055426b3e51f67...c917635bf90ba94d79f1647e604a21641f5773aa
diff --git a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java index 7e93e795c0..822ed586b4 100644 --- a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java @@ -29,6 +29,9 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.graph.logger.ILogger; + +import java.lang.reflect.Field; +import java.lang.reflect.Type; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -185,23 +188,46 @@ public class DefaultSerializer implements ISerializer { JsonElement outJsonTree = gson.toJsonTree(serializableObject); if (serializableObject instanceof IJsonBackedObject) { - IJsonBackedObject serializableJsonObject = (IJsonBackedObject) serializableObject; - - AdditionalDataManager additionalData = serializableJsonObject.additionalDataManager(); - - // If the item is a valid Graph object, add its additional data - if (outJsonTree.isJsonObject()) { - JsonObject outJson = outJsonTree.getAsJsonObject(); - - addAdditionalDataToJson(additionalData, outJson); - outJson = getChildAdditionalData(serializableJsonObject, outJson); - - outJsonTree = outJson; + outJsonTree = getDataFromAdditionalDataManager(outJsonTree, serializableObject); + } else if (outJsonTree.isJsonObject()) { + final Field[] fields = serializableObject.getClass().getDeclaredFields(); + JsonObject outJson = outJsonTree.getAsJsonObject(); + for(Field field : fields) { + if(outJson.has(field.getName())) { + final Type[] interfaces = field.getType().getGenericInterfaces(); + for(Type interfaceType : interfaces) { + if(interfaceType == IJsonBackedObject.class) { + try { + outJsonTree = getDataFromAdditionalDataManager(outJsonTree, field.get(serializableObject)); + } catch (IllegalAccessException ex ) { + logger.logDebug("Couldn't access prop" + field.getName()); + } + break; + } + } + } } } return outJsonTree.toString(); } + private <T> JsonElement getDataFromAdditionalDataManager(JsonElement outJsonTree, final T serializableObject) { + IJsonBackedObject serializableJsonObject = (IJsonBackedObject) serializableObject; + + AdditionalDataManager additionalData = serializableJsonObject.additionalDataManager(); + + // If the item is a valid Graph object, add its additional data + if (outJsonTree.isJsonObject()) { + JsonObject outJson = outJsonTree.getAsJsonObject(); + + addAdditionalDataToJson(additionalData, outJson); + outJson = getChildAdditionalData(serializableJsonObject, outJson); + + return outJson; + } else { + return outJsonTree; + } + } /** * Recursively populates additional data for each child object diff --git a/src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java b/src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java index 6bdce918f0..3a068d3971 100644 --- a/src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java +++ b/src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java @@ -13,6 +13,8 @@ import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.microsoft.graph.logger.DefaultLogger; import com.microsoft.graph.models.extensions.Drive; +import com.microsoft.graph.models.extensions.DriveItemCreateUploadSessionBody; +import com.microsoft.graph.models.extensions.DriveItemUploadableProperties; import com.microsoft.graph.models.extensions.Entity; import com.microsoft.graph.models.extensions.PlannerAssignment; import com.microsoft.graph.models.extensions.PlannerAssignments; @@ -55,6 +57,17 @@ public class AdditionalDataTests { assertEquals("{\\"manager\\":{\\"id\\":\\"1\\",\\"additionalData\\":\\"additionalValue\\"},\\"id\\":\\"2\\"}", serializedObject); } + + @Test + public void testPropsAdditionalDataOnNonIJSONObjects() { + final DriveItemUploadableProperties upProps = new DriveItemUploadableProperties(); + upProps.name = "vacation.gif"; + upProps.additionalDataManager().put("@microsoft.graph.conflictBehavior", new JsonPrimitive("rename")); + final DriveItemCreateUploadSessionBody body = new DriveItemCreateUploadSessionBody(); + body.item = upProps; + String serializedObject = serializer.serializeObject(body); + assertEquals("{\\"item\\":{\\"name\\":\\"vacation.gif\\"},\\"@microsoft.graph.conflictBehavior\\":\\"rename\\"}", serializedObject); + } @Test public void testHashMapChildAnnotationData() { @@ -93,8 +106,7 @@ public class AdditionalDataTests { String serialized = serializer.serializeObject(deserializedObject); - JsonParser parser = new JsonParser(); - JsonObject jsonObject = parser.parse(serialized).getAsJsonObject(); + JsonObject jsonObject = JsonParser.parseString(serialized).getAsJsonObject(); assertNotNull(jsonObject.get("checklist").getAsJsonObject().get("1234")); assertNull(jsonObject.get("checklist").getAsJsonObject().get("1234").getAsJsonObject().get("1234")); assertNull(jsonObject.get("checklist").getAsJsonObject().get("1234").getAsJsonObject().get("66442"));
['src/test/java/com/microsoft/graph/serializer/AdditionalDataTests.java', 'src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java']
{'.java': 2}
2
2
0
0
2
23,140,957
4,311,730
621,145
8,023
2,541
428
50
1
877
83
201
31
0
2
1970-01-01T00:26:39
317
Java
{'Java': 32327681, 'PowerShell': 5635}
MIT License
725
refinedmods/refinedstorage/387/386
refinedmods
refinedstorage
https://github.com/refinedmods/refinedstorage/issues/386
https://github.com/refinedmods/refinedstorage/pull/387
https://github.com/refinedmods/refinedstorage/pull/387
1
fixes
Server Crash after inserting disk into Disk Manipulator when output slots full
#### Issue description: Server crashed immediately after a disk drive was inserted into the disk manipulator when it was already full in the output slots. To note, the disk drive was already empty with 0 bytes in it. #### What happens: Server crashes horribly. #### What you expected to happen: No crash, and it wouldn't move to output. #### Steps to reproduce: 1. Disk manipulator with 6 drives in the output 2. Insert empty disk 3. Crash ... #### Version (Make sure you are on the latest version before reporting): - Minecraft: 1.10.2 - Forge: 2094 - Refined Storage: refinedstorage{1.0.5} [Refined Storage](refinedstorage-1.0.5.jar) Does this issue occur on a server? yes, and SP #### If a (crash)log is relevant for this issue, link it here: Server pastebin: http://pastebin.com/CRpday1c Single player pastebin: http://pastebin.com/FpZADr19
c9a9c52e3b81c5ef4bdf66448321bc1ccee3ad66
7f973f5537e0baf40a7f1d3fa36ac1c22813f198
https://github.com/refinedmods/refinedstorage/compare/c9a9c52e3b81c5ef4bdf66448321bc1ccee3ad66...7f973f5537e0baf40a7f1d3fa36ac1c22813f198
diff --git a/src/main/java/refinedstorage/tile/TileDiskManipulator.java b/src/main/java/refinedstorage/tile/TileDiskManipulator.java index 610f54ea1..db2187b8d 100755 --- a/src/main/java/refinedstorage/tile/TileDiskManipulator.java +++ b/src/main/java/refinedstorage/tile/TileDiskManipulator.java @@ -379,7 +379,7 @@ public class TileDiskManipulator extends TileNode implements IComparable, IFilte if (disk != null) { int i = 6; - while (disks.getStackInSlot(i) != null && i < 12) { + while (i < 12 && disks.getStackInSlot(i) != null) { i++; }
['src/main/java/refinedstorage/tile/TileDiskManipulator.java']
{'.java': 1}
1
1
0
0
1
853,184
183,158
26,022
349
129
39
2
1
856
131
228
25
2
0
1970-01-01T00:24:34
317
Java
{'Java': 2021464, 'Shell': 456}
MIT License
724
refinedmods/refinedstorage/445/435
refinedmods
refinedstorage
https://github.com/refinedmods/refinedstorage/issues/435
https://github.com/refinedmods/refinedstorage/pull/445
https://github.com/refinedmods/refinedstorage/pull/445
1
fix
Interface not working correctly
#### Issue description: You can pump items into the bottom of the interface circumventing the slow import of items #### What happens: Interface accepts items from the bottom importing items instantly #### What you expected to happen: Interface doesn't accept items from the bottom or puts them in the normal import inventory of the interface #### Steps to reproduce: 1. Pump items into an Interface from the bottom ( I used enderIO item conduits ) 2.watch the interface 3. ... #### Version (Make sure you are on the latest version before reporting): - Minecraft: 1.10.2 - Forge: - Refined Storage:1.1.1 Does this issue occur on a server? [yes/no] yes #### If a (crash)log is relevant for this issue, link it here: [pastebin/gist/etc link here]
40e54334132af5e012c2e10316783340031bfdbd
4379f536ee794246ba55e3bed1ccf68fb4090410
https://github.com/refinedmods/refinedstorage/compare/40e54334132af5e012c2e10316783340031bfdbd...4379f536ee794246ba55e3bed1ccf68fb4090410
diff --git a/src/main/java/refinedstorage/inventory/ItemHandlerBasic.java b/src/main/java/refinedstorage/inventory/ItemHandlerBasic.java index cb65b2210..641beaec1 100755 --- a/src/main/java/refinedstorage/inventory/ItemHandlerBasic.java +++ b/src/main/java/refinedstorage/inventory/ItemHandlerBasic.java @@ -43,4 +43,8 @@ public class ItemHandlerBasic extends ItemStackHandler { tile.markDirty(); } } + + public ItemStack extractItemInternal(int slot, int amount, boolean simulate) { + return super.extractItem(slot, amount, simulate); + } } diff --git a/src/main/java/refinedstorage/tile/TileInterface.java b/src/main/java/refinedstorage/tile/TileInterface.java index 4f15051b8..faedbbf74 100755 --- a/src/main/java/refinedstorage/tile/TileInterface.java +++ b/src/main/java/refinedstorage/tile/TileInterface.java @@ -20,9 +20,21 @@ public class TileInterface extends TileNode implements IComparable { private static final String NBT_COMPARE = "Compare"; - private ItemHandlerBasic importItems = new ItemHandlerBasic(9, this); + private ItemHandlerBasic importItems = new ItemHandlerBasic(9, this) { + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + return null; + } + }; + private ItemHandlerBasic exportSpecimenItems = new ItemHandlerBasic(9, this); - private ItemHandlerBasic exportItems = new ItemHandlerBasic(9, this); + private ItemHandlerBasic exportItems = new ItemHandlerBasic(9, this) { + @Override + public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { + return stack; + } + }; + private ItemHandlerUpgrade upgrades = new ItemHandlerUpgrade(4, this, ItemUpgrade.TYPE_SPEED, ItemUpgrade.TYPE_STACK, ItemUpgrade.TYPE_CRAFTING); private int compare = IComparer.COMPARE_NBT | IComparer.COMPARE_DAMAGE; @@ -54,9 +66,10 @@ public class TileInterface extends TileNode implements IComparable { ItemStack remainder = network.insertItem(slot, size, false); if (remainder == null) { - importItems.extractItem(currentSlot, size, false); + importItems.extractItemInternal(currentSlot, size, false); } else { - importItems.extractItem(currentSlot, size - remainder.stackSize, false); + importItems.extractItemInternal(currentSlot, size - remainder.stackSize, false); + currentSlot++; } } @@ -165,11 +178,7 @@ public class TileInterface extends TileNode implements IComparable { @Override public <T> T getCapability(Capability<T> capability, EnumFacing facing) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { - if (facing == EnumFacing.DOWN) { - return (T) exportItems; - } else { - return (T) importItems; - } + return facing == EnumFacing.DOWN ? (T) exportItems : (T) importItems; } return super.getCapability(capability, facing);
['src/main/java/refinedstorage/inventory/ItemHandlerBasic.java', 'src/main/java/refinedstorage/tile/TileInterface.java']
{'.java': 2}
2
2
0
0
2
848,302
183,013
26,165
355
1,392
294
31
2
759
124
180
25
0
0
1970-01-01T00:24:36
317
Java
{'Java': 2021464, 'Shell': 456}
MIT License
836
cloudnetservice/cloudnet-v3/150/138
cloudnetservice
cloudnet-v3
https://github.com/CloudNetService/CloudNet-v3/issues/138
https://github.com/CloudNetService/CloudNet-v3/pull/150
https://github.com/CloudNetService/CloudNet-v3/pull/150#issuecomment-546725824
1
fixes
Exception when creating a permission group
**Describe the bug**<br> https://pastes.cf/Yr2teTGV24/ **Steps for reproducing**<br> 1. Type "perms create group NAME 0" into the console 2. See the exception from above in every screen **Expected behavior**<br> The group should be created (which it it), but without any errors **Please provide us information about your environment and used assets** This shouldn't matter, but: System specs: CPU = Intel i7 6700k; DDR 4 2400 MHz 16 GB HyperX RAM; 2 TB Seagate HDD OS: Windows 10 Version: https://github.com/CloudNetService/CloudNet-v3/tree/6530b93faf1eca66d0468ead61036d76b38ffec0
566c0b81ba1d130b7330ee0978711be933825200
4ab4b3c70e08799d7bbffd8743adc9dc328b4a67
https://github.com/cloudnetservice/cloudnet-v3/compare/566c0b81ba1d130b7330ee0978711be933825200...4ab4b3c70e08799d7bbffd8743adc9dc328b4a67
diff --git a/cloudnet/src/main/java/de/dytanic/cloudnet/permission/DefaultDatabasePermissionManagement.java b/cloudnet/src/main/java/de/dytanic/cloudnet/permission/DefaultDatabasePermissionManagement.java index aa3d73162..f513e6ace 100644 --- a/cloudnet/src/main/java/de/dytanic/cloudnet/permission/DefaultDatabasePermissionManagement.java +++ b/cloudnet/src/main/java/de/dytanic/cloudnet/permission/DefaultDatabasePermissionManagement.java @@ -194,11 +194,13 @@ public final class DefaultDatabasePermissionManagement implements IPermissionMan Validate.checkNotNull(group); IPermissionGroup permissionGroup = permissionGroupsMap.remove(group); - if (permissionManagementHandler != null) { - permissionManagementHandler.handleDeleteGroup(this, permissionGroup); - } + if (permissionGroup != null) { + if (permissionManagementHandler != null) { + permissionManagementHandler.handleDeleteGroup(this, permissionGroup); + } - saveGroups(); + saveGroups(); + } } @Override @@ -328,4 +330,4 @@ public final class DefaultDatabasePermissionManagement implements IPermissionMan public void setPermissionManagementHandler(IPermissionManagementHandler permissionManagementHandler) { this.permissionManagementHandler = permissionManagementHandler; } -} \\ No newline at end of file +}
['cloudnet/src/main/java/de/dytanic/cloudnet/permission/DefaultDatabasePermissionManagement.java']
{'.java': 1}
1
1
0
0
1
2,165,709
406,999
59,062
788
409
69
12
1
611
78
178
20
2
0
1970-01-01T00:26:12
317
Java
{'Java': 5151361, 'Kotlin': 74901, 'Shell': 1480, 'Dockerfile': 420, 'Batchfile': 419}
Apache License 2.0
586
movingblocks/destinationsol/620/615
movingblocks
destinationsol
https://github.com/MovingBlocks/DestinationSol/issues/615
https://github.com/MovingBlocks/DestinationSol/pull/620
https://github.com/MovingBlocks/DestinationSol/pull/620
1
fix
Zoom in / zoom out hot keys are broken on the map screen
Simple * Open map screen (maybe as part of the tutorial) * Notice how mousewheel (and pgup / pgdn?) does not zoom in/out as advertised Hunt down the related UI logic and try to fix it!
babe861ad5c0cb0ad1ca5d74a24c72e1518cc258
210f3987e40388b6622bee8914c9de44b4627534
https://github.com/movingblocks/destinationsol/compare/babe861ad5c0cb0ad1ca5d74a24c72e1518cc258...210f3987e40388b6622bee8914c9de44b4627534
diff --git a/engine/src/main/java/org/destinationsol/GameOptions.java b/engine/src/main/java/org/destinationsol/GameOptions.java index eeb68cc4..d8493f5f 100644 --- a/engine/src/main/java/org/destinationsol/GameOptions.java +++ b/engine/src/main/java/org/destinationsol/GameOptions.java @@ -117,6 +117,8 @@ public Volume advance() { public static final String DEFAULT_HIRE_SHIP = "H"; public static final String DEFAULT_MERCENARY_INTERACTION = "M"; public static final String DEFAULT_FREE_CAMERA_MOVEMENT = "V"; + public static final String DEFAULT_ZOOM_IN = "Page Up"; + public static final String DEFAULT_ZOOM_OUT = "Page Down"; public static final int DEFAULT_AXIS_SHOOT = 1; public static final int DEFAULT_AXIS_SHOOT2 = 0; public static final int DEFAULT_AXIS_ABILITY = -1; @@ -163,6 +165,8 @@ public Volume advance() { private String keyHireShipMenuName; private String keyMercenaryInteractionName; private String keyFreeCameraMovementName; + private String keyZoomInName; + private String keyZoomOutName; private int controllerAxisShoot; private int controllerAxisShoot2; private int controllerAxisAbility; @@ -212,6 +216,8 @@ public GameOptions(boolean mobile, SolFileReader solFileReader) { keyHireShipMenuName = reader.getString("keyHireShipMenu", DEFAULT_HIRE_SHIP); keyMercenaryInteractionName = reader.getString("keyMercenaryInteraction", DEFAULT_MERCENARY_INTERACTION); keyFreeCameraMovementName = reader.getString("keyFreeCameraMovement", DEFAULT_FREE_CAMERA_MOVEMENT); + keyZoomInName = reader.getString("keyZoomIn", DEFAULT_ZOOM_IN); + keyZoomOutName = reader.getString("keyZoomOut", DEFAULT_ZOOM_OUT); controllerAxisShoot = reader.getInt("controllerAxisShoot", DEFAULT_AXIS_SHOOT); controllerAxisShoot2 = reader.getInt("controllerAxisShoot2", DEFAULT_AXIS_SHOOT2); controllerAxisAbility = reader.getInt("controllerAxisAbility", DEFAULT_AXIS_ABILITY); @@ -291,6 +297,7 @@ public void save() { "keyAbility", getKeyAbilityName(), "keyEscape", getKeyEscapeName(), "keyMap", keyMapName, "keyInventory", keyInventoryName, "keyTalk", getKeyTalkName(), "keyPause", getKeyPauseName(), "keyDrop", getKeyDropName(), "keySellMenu", getKeySellMenuName(), "keyBuyMenu", getKeyBuyMenuName(), "keyChangeShipMenu", getKeyChangeShipMenuName(), "keyHireShipMenu", getKeyHireShipMenuName(), + "keyZoomIn", getKeyZoomInName(), "keyZoomOut", getKeyZoomOutName(), "controllerAxisShoot", getControllerAxisShoot(), "controllerAxisShoot2", getControllerAxisShoot2(), "controllerAxisAbility", getControllerAxisAbility(), "controllerAxisLeftRight", getControllerAxisLeftRight(), "isControllerAxisLeftRightInverted", isControllerAxisLeftRightInverted(), "controllerAxisUpDown", getControllerAxisUpDown(), @@ -637,33 +644,43 @@ public int getKeyChangeShip() { } /** - * Get the defined key for zooming out on the map. - * This is currently set to the same key as KeyUp + * Get the defined key for zooming in on the map. + * This is currently set to Page Up * * @return int The keycode as defined in Input.Keys */ public int getKeyZoomIn() { - return getKeyUp(); + return Input.Keys.valueOf(keyZoomInName); } /** - * Get the readable name of the defined key for zooming out on the map. - * This is currently set to the same key as KeyUp + * Get the readable name of the defined key for zooming in on the map. + * This is currently set to Page Up * * @return String The readable name as defined in Input.Keys */ public String getKeyZoomInName() { - return getKeyUpName(); + return keyZoomInName; } /** * Get the defined key for zooming out on the map. - * This is currently set to the same key as KeyDown + * This is currently set to Page Down * * @return int The keycode as defined in Input.Keys */ public int getKeyZoomOut() { - return getKeyDown(); + return Input.Keys.valueOf(keyZoomOutName); + } + + /** + * Get the readable name of the defined key for zooming out on the map. + * This is currently set to Page Down + * + * @return String The readable name as defined in Input.Keys + */ + public String getKeyZoomOutName() { + return keyZoomOutName; } /**
['engine/src/main/java/org/destinationsol/GameOptions.java']
{'.java': 1}
1
1
0
0
1
1,988,335
428,363
54,510
469
1,503
347
33
1
191
36
48
6
0
0
1970-01-01T00:27:13
309
Java
{'Java': 2210853, 'Groovy': 45867, 'Shell': 6005, 'Batchfile': 4149}
Apache License 2.0
587
movingblocks/destinationsol/618/615
movingblocks
destinationsol
https://github.com/MovingBlocks/DestinationSol/issues/615
https://github.com/MovingBlocks/DestinationSol/pull/618
https://github.com/MovingBlocks/DestinationSol/pull/618
1
fix
Zoom in / zoom out hot keys are broken on the map screen
Simple * Open map screen (maybe as part of the tutorial) * Notice how mousewheel (and pgup / pgdn?) does not zoom in/out as advertised Hunt down the related UI logic and try to fix it!
babe861ad5c0cb0ad1ca5d74a24c72e1518cc258
210f3987e40388b6622bee8914c9de44b4627534
https://github.com/movingblocks/destinationsol/compare/babe861ad5c0cb0ad1ca5d74a24c72e1518cc258...210f3987e40388b6622bee8914c9de44b4627534
diff --git a/engine/src/main/java/org/destinationsol/GameOptions.java b/engine/src/main/java/org/destinationsol/GameOptions.java index eeb68cc4..d8493f5f 100644 --- a/engine/src/main/java/org/destinationsol/GameOptions.java +++ b/engine/src/main/java/org/destinationsol/GameOptions.java @@ -117,6 +117,8 @@ public Volume advance() { public static final String DEFAULT_HIRE_SHIP = "H"; public static final String DEFAULT_MERCENARY_INTERACTION = "M"; public static final String DEFAULT_FREE_CAMERA_MOVEMENT = "V"; + public static final String DEFAULT_ZOOM_IN = "Page Up"; + public static final String DEFAULT_ZOOM_OUT = "Page Down"; public static final int DEFAULT_AXIS_SHOOT = 1; public static final int DEFAULT_AXIS_SHOOT2 = 0; public static final int DEFAULT_AXIS_ABILITY = -1; @@ -163,6 +165,8 @@ public Volume advance() { private String keyHireShipMenuName; private String keyMercenaryInteractionName; private String keyFreeCameraMovementName; + private String keyZoomInName; + private String keyZoomOutName; private int controllerAxisShoot; private int controllerAxisShoot2; private int controllerAxisAbility; @@ -212,6 +216,8 @@ public GameOptions(boolean mobile, SolFileReader solFileReader) { keyHireShipMenuName = reader.getString("keyHireShipMenu", DEFAULT_HIRE_SHIP); keyMercenaryInteractionName = reader.getString("keyMercenaryInteraction", DEFAULT_MERCENARY_INTERACTION); keyFreeCameraMovementName = reader.getString("keyFreeCameraMovement", DEFAULT_FREE_CAMERA_MOVEMENT); + keyZoomInName = reader.getString("keyZoomIn", DEFAULT_ZOOM_IN); + keyZoomOutName = reader.getString("keyZoomOut", DEFAULT_ZOOM_OUT); controllerAxisShoot = reader.getInt("controllerAxisShoot", DEFAULT_AXIS_SHOOT); controllerAxisShoot2 = reader.getInt("controllerAxisShoot2", DEFAULT_AXIS_SHOOT2); controllerAxisAbility = reader.getInt("controllerAxisAbility", DEFAULT_AXIS_ABILITY); @@ -291,6 +297,7 @@ public void save() { "keyAbility", getKeyAbilityName(), "keyEscape", getKeyEscapeName(), "keyMap", keyMapName, "keyInventory", keyInventoryName, "keyTalk", getKeyTalkName(), "keyPause", getKeyPauseName(), "keyDrop", getKeyDropName(), "keySellMenu", getKeySellMenuName(), "keyBuyMenu", getKeyBuyMenuName(), "keyChangeShipMenu", getKeyChangeShipMenuName(), "keyHireShipMenu", getKeyHireShipMenuName(), + "keyZoomIn", getKeyZoomInName(), "keyZoomOut", getKeyZoomOutName(), "controllerAxisShoot", getControllerAxisShoot(), "controllerAxisShoot2", getControllerAxisShoot2(), "controllerAxisAbility", getControllerAxisAbility(), "controllerAxisLeftRight", getControllerAxisLeftRight(), "isControllerAxisLeftRightInverted", isControllerAxisLeftRightInverted(), "controllerAxisUpDown", getControllerAxisUpDown(), @@ -637,33 +644,43 @@ public int getKeyChangeShip() { } /** - * Get the defined key for zooming out on the map. - * This is currently set to the same key as KeyUp + * Get the defined key for zooming in on the map. + * This is currently set to Page Up * * @return int The keycode as defined in Input.Keys */ public int getKeyZoomIn() { - return getKeyUp(); + return Input.Keys.valueOf(keyZoomInName); } /** - * Get the readable name of the defined key for zooming out on the map. - * This is currently set to the same key as KeyUp + * Get the readable name of the defined key for zooming in on the map. + * This is currently set to Page Up * * @return String The readable name as defined in Input.Keys */ public String getKeyZoomInName() { - return getKeyUpName(); + return keyZoomInName; } /** * Get the defined key for zooming out on the map. - * This is currently set to the same key as KeyDown + * This is currently set to Page Down * * @return int The keycode as defined in Input.Keys */ public int getKeyZoomOut() { - return getKeyDown(); + return Input.Keys.valueOf(keyZoomOutName); + } + + /** + * Get the readable name of the defined key for zooming out on the map. + * This is currently set to Page Down + * + * @return String The readable name as defined in Input.Keys + */ + public String getKeyZoomOutName() { + return keyZoomOutName; } /**
['engine/src/main/java/org/destinationsol/GameOptions.java']
{'.java': 1}
1
1
0
0
1
1,988,335
428,363
54,510
469
1,503
347
33
1
191
36
48
6
0
0
1970-01-01T00:27:13
309
Java
{'Java': 2210853, 'Groovy': 45867, 'Shell': 6005, 'Batchfile': 4149}
Apache License 2.0
588
movingblocks/destinationsol/504/486
movingblocks
destinationsol
https://github.com/MovingBlocks/DestinationSol/issues/486
https://github.com/MovingBlocks/DestinationSol/pull/504
https://github.com/MovingBlocks/DestinationSol/pull/504
1
fixes
Game Crashes When Resuming Previous Game After Upgrade from v1.4
### What you were trying to do Resume the previous game after upgrading from version 1.4.1 (the current Steam version) to version 2.0.0. ### What actually happened The game crashed after choosing "continue" ### How to reproduce The hull values have changed in prevShip.ini between v1.4.1 and v2.0.0. Upgrading from v1.4.1 to v2.0.0 is the proper way to reproduce this issue, however the following steps allow you to reproduce this issue Step 1 - In the prevShip.ini file, change the value of hull to imperialSmall instead of core:imperialSmall Step 2 - Run the game and choose Play Game and then Continue. ### Log details and game version ``` java.lang.RuntimeException: Invalid resource name (missing namespace?) `imperialSmall` at org.destinationsol.assets.Assets.parsePath(Assets.java:69) at org.destinationsol.assets.Assets.getJson(Assets.java:156) at org.destinationsol.assets.json.Validator.getValidatedJSON(Validator.java:34) at org.destinationsol.files.HullConfigManager.read(HullConfigManager.java:115) at org.destinationsol.files.HullConfigManager.getConfig(HullConfigManager.java:96) at org.destinationsol.game.SaveManager.readShip(SaveManager.java:209) at org.destinationsol.game.SolGame.readShipFromConfigOrLoadFromSaveIfNull(SolGame.java:238) at org.destinationsol.game.SolGame.createGame(SolGame.java:221) at org.destinationsol.game.SolGame.<init>(SolGame.java:198) at org.destinationsol.SolApplication.play(SolApplication.java:255) at org.destinationsol.menu.LoadingScreen.updateCustom(LoadingScreen.java:47) at org.destinationsol.ui.SolInputManager.update(SolInputManager.java:238) at org.destinationsol.SolApplication.update(SolApplication.java:204) at org.destinationsol.SolApplication.safeUpdate(SolApplication.java:182) at org.destinationsol.SolApplication.render(SolApplication.java:146) at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Window.update(Lwjgl3Window.java:392) at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application.loop(Lwjgl3Application.java:137) at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application.<init>(Lwjgl3Application.java:111) at org.destinationsol.desktop.SolDesktop.main(SolDesktop.java:149) ``` ### Computer details N/A
f5528842b84325c8e323e914a4f45b1126f3a1d2
f4582dcb46628b535f1970ec96bdfc58f238b7c9
https://github.com/movingblocks/destinationsol/compare/f5528842b84325c8e323e914a4f45b1126f3a1d2...f4582dcb46628b535f1970ec96bdfc58f238b7c9
diff --git a/engine/src/main/java/org/destinationsol/Const.java b/engine/src/main/java/org/destinationsol/Const.java index 0585d918..d8c8b166 100644 --- a/engine/src/main/java/org/destinationsol/Const.java +++ b/engine/src/main/java/org/destinationsol/Const.java @@ -37,4 +37,8 @@ public class Const { public static final float CAM_VIEW_DIST_JOURNEY = 8.6f; public static final float DEFAULT_AI_SPD = 4f; public static final float BIG_AI_SPD = 2f; + + public static final String SAVE_FILE_NAME = "prevShip.ini"; + public static final String MERC_SAVE_FILE = "mercenaries.json"; + public static final String WORLD_SAVE_FILE_NAME = "world.json"; } diff --git a/engine/src/main/java/org/destinationsol/game/SaveManager.java b/engine/src/main/java/org/destinationsol/game/SaveManager.java index 201c9ed2..833e8b92 100644 --- a/engine/src/main/java/org/destinationsol/game/SaveManager.java +++ b/engine/src/main/java/org/destinationsol/game/SaveManager.java @@ -23,6 +23,7 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; +import org.destinationsol.Const; import org.destinationsol.IniReader; import org.destinationsol.common.SolRandom; import org.destinationsol.files.HullConfigManager; @@ -47,9 +48,6 @@ import java.util.List; public class SaveManager { - protected static final String SAVE_FILE_NAME = "prevShip.ini"; - protected static final String MERC_SAVE_FILE = "mercenaries.json"; - protected static final String WORLD_SAVE_FILE_NAME = "world.json"; private static Logger logger = LoggerFactory.getLogger(SaveManager.class); @@ -66,7 +64,8 @@ public static void writeShips(HullConfig hull, float money, List<SolItem> itemsL String waypoints = waypointsToString(hero.getWaypoints()); - IniReader.write(SAVE_FILE_NAME, "hull", hullName, "money", (int) money, "items", items, "x", pos.x, "y", pos.y, "waypoints", waypoints); + IniReader.write(Const.SAVE_FILE_NAME, "hull", hullName, "money", (int) money, "items", items, + "x", pos.x, "y", pos.y, "waypoints", waypoints, "version", Const.VERSION); } private static String waypointsToString(ArrayList<Waypoint> waypoints) { @@ -156,7 +155,7 @@ private static void writeMercs(Hero hero, HullConfigManager hullConfigManager) { // Using PrintWriter because it truncates the file if it exists or creates a new one if it doesn't // And truncation is good because we don't want dead mercs respawning try { - writer = new PrintWriter(getResourcePath(MERC_SAVE_FILE), "UTF-8"); + writer = new PrintWriter(getResourcePath(Const.MERC_SAVE_FILE), "UTF-8"); writer.write(stringToWrite); writer.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { @@ -189,17 +188,23 @@ public static boolean resourceExists(String fileName) { } /** - * Tests is the game has a previous ship (a game to continue) + * Tests if the game has a compatible previous ship (a game to continue) */ - public static boolean hasPrevShip(String fileName) { - return resourceExists(fileName); + public static boolean hasPreviousCompatibleShip() { + if (!resourceExists(Const.SAVE_FILE_NAME)) { + return false; + } + IniReader reader = new IniReader(Const.SAVE_FILE_NAME, null); + String saveMajorVersion = reader.getString("version", "").split("\\\\.")[0]; + String gameMajorVersion = Const.VERSION.split("\\\\.")[0]; + return saveMajorVersion.equals(gameMajorVersion); } /** * Load last saved ship from file */ public static ShipConfig readShip(HullConfigManager hullConfigs, ItemManager itemManager) { - IniReader ir = new IniReader(SAVE_FILE_NAME, null); + IniReader ir = new IniReader(Const.SAVE_FILE_NAME, null); String hullName = ir.getString("hull", null); if (hullName == null) { @@ -229,7 +234,7 @@ public static ShipConfig readShip(HullConfigManager hullConfigs, ItemManager ite */ public static void saveWorld(int numberOfSystems) { Long seed = SolRandom.getSeed(); - String fileName = SaveManager.getResourcePath(WORLD_SAVE_FILE_NAME); + String fileName = SaveManager.getResourcePath(Const.WORLD_SAVE_FILE_NAME); JsonObject world = new JsonObject(); world.addProperty("seed", seed); @@ -257,11 +262,11 @@ public static void saveWorld(int numberOfSystems) { * Load the last saved world from file, or returns null if there is no file */ public static WorldConfig loadWorld() { - if (SaveManager.resourceExists(WORLD_SAVE_FILE_NAME)) { + if (SaveManager.resourceExists(Const.WORLD_SAVE_FILE_NAME)) { WorldConfig config = new WorldConfig(); JsonReader reader = null; try { - reader = new com.google.gson.stream.JsonReader(new FileReader(SaveManager.getResourcePath(WORLD_SAVE_FILE_NAME))); + reader = new com.google.gson.stream.JsonReader(new FileReader(SaveManager.getResourcePath(Const.WORLD_SAVE_FILE_NAME))); reader.setLenient(true); // without this it will fail with strange errors JsonObject world = new JsonParser().parse(reader).getAsJsonObject(); diff --git a/engine/src/main/java/org/destinationsol/menu/NewGameScreen.java b/engine/src/main/java/org/destinationsol/menu/NewGameScreen.java index 86494669..9ef2f156 100644 --- a/engine/src/main/java/org/destinationsol/menu/NewGameScreen.java +++ b/engine/src/main/java/org/destinationsol/menu/NewGameScreen.java @@ -58,7 +58,7 @@ public class NewGameScreen extends SolUiBaseScreen { @Override public void onAdd(SolApplication solApplication) { - continueControl.setEnabled(SaveManager.hasPrevShip("prevShip.ini")); + continueControl.setEnabled(SaveManager.hasPreviousCompatibleShip()); } @Override
['engine/src/main/java/org/destinationsol/menu/NewGameScreen.java', 'engine/src/main/java/org/destinationsol/game/SaveManager.java', 'engine/src/main/java/org/destinationsol/Const.java']
{'.java': 3}
3
3
0
0
3
1,531,344
332,999
42,552
367
2,483
535
35
3
2,223
158
540
39
0
1
1970-01-01T00:26:25
309
Java
{'Java': 2210853, 'Groovy': 45867, 'Shell': 6005, 'Batchfile': 4149}
Apache License 2.0
585
movingblocks/destinationsol/651/650
movingblocks
destinationsol
https://github.com/MovingBlocks/DestinationSol/issues/650
https://github.com/MovingBlocks/DestinationSol/pull/651
https://github.com/MovingBlocks/DestinationSol/pull/651
1
fix
Sound Volume Button changes the volume of Music
<!-- Thanks for taking the time to submit a thorough issue report for Destionation Sol! :-) 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/destination-sol.57/ Bug reports and crashes likely resulting from bugs in the engine go here on GitHub. --> ### What you were trying to do Tried changing the sound volume using the Options menu ### What actually happened The Music volume changed instead. Both buttons are hooked up to change music volume only. ### How to reproduce * Step 1 Open game options from the Main Menu Screen * Step 2 Try changing Sound Volume * Step 3 Then try changing Music Volume...see it jump two levels in 1 click. https://user-images.githubusercontent.com/73862377/154787048-226b52f8-98da-4036-9155-cf0584d44a58.mp4
62b07db8660e388c68973d17fb002ecd8a2c7600
a04f8371be4948cd9c8212fc41c722edb339069c
https://github.com/movingblocks/destinationsol/compare/62b07db8660e388c68973d17fb002ecd8a2c7600...a04f8371be4948cd9c8212fc41c722edb339069c
diff --git a/engine/src/main/java/org/destinationsol/ui/nui/screens/mainMenu/OptionsScreen.java b/engine/src/main/java/org/destinationsol/ui/nui/screens/mainMenu/OptionsScreen.java index 314cbbd9..4eec6080 100644 --- a/engine/src/main/java/org/destinationsol/ui/nui/screens/mainMenu/OptionsScreen.java +++ b/engine/src/main/java/org/destinationsol/ui/nui/screens/mainMenu/OptionsScreen.java @@ -49,7 +49,7 @@ public void initialise() { UIButton soundVolumeButton = find("soundVolumeButton", UIButton.class); soundVolumeButton.setText("Sound Volume: " + solApplication.getOptions().sfxVolume.getName()); soundVolumeButton.subscribe(button -> { - solApplication.getOptions().advanceMusicVolMul(); + solApplication.getOptions().advanceSoundVolMul(); soundVolumeButton.setText("Sound Volume: " + solApplication.getOptions().sfxVolume.getName()); }); @@ -103,6 +103,15 @@ public void initialise() { }); } + @Override + public void onAdded() { + UIButton musicVolumeButton = find("musicVolumeButton", UIButton.class); + musicVolumeButton.setText("Music Volume: " + solApplication.getOptions().musicVolume.getName()); + + UIButton soundVolumeButton = find("soundVolumeButton", UIButton.class); + soundVolumeButton.setText("Sound Volume: " + solApplication.getOptions().sfxVolume.getName()); + } + @Override public void update(float delta) { super.update(delta);
['engine/src/main/java/org/destinationsol/ui/nui/screens/mainMenu/OptionsScreen.java']
{'.java': 1}
1
1
0
0
1
1,991,796
428,945
54,635
475
552
107
11
1
895
130
208
20
2
0
1970-01-01T00:27:25
309
Java
{'Java': 2210853, 'Groovy': 45867, 'Shell': 6005, 'Batchfile': 4149}
Apache License 2.0
584
movingblocks/destinationsol/598/645
movingblocks
destinationsol
https://github.com/MovingBlocks/DestinationSol/issues/645
https://github.com/MovingBlocks/DestinationSol/pull/598
https://github.com/MovingBlocks/DestinationSol/issues/645#issuecomment-1031897273
1
fixed
Weapons failing to fire.
### What I was trying to do I was attempting to fire the Wave Gun in the Federal Tiny vessel. ### What actually happened The Wave Gun fired, but no shot emerged. ### How to reproduce * Step 0 (optional) Back up your save file. * Step 1 Start a new game. Be sure to pick the "Federal Tiny". * Step 2 Obtain a Wave Gun by any means. This could mean taking on a Techie turret, or you could just edit your save file directly if you know how. * Step 3 Equip and attempt to fire the Wave Gun. * Step 4 (optional) Obtain another ship. Whether you buy it from a base or by editing your save file is none of my concern. * Step 5 (optional) Attempt to fire the Wave Gun again. ### Log details and game version It will drain energy from the capacitor and the sound effect will play, but no shot will emerge from your front. This is probably because the wave impacts the front end of your ship, and, being the fact that it's your own ship, doesn't do any damage. Destination Sol 2.0.0, Steam. ### Computer details Microsoft Windows 10 Notebook, 64-bit OS [prevShip.ini.txt](https://github.com/MovingBlocks/DestinationSol/files/8011268/prevShip.ini.txt) My save file has been added, but you will note that I have already upgraded my ship to be a Wasp. I'm afraid that you will have to edit the save to see the bug in action. You are also going to have to rename the file, as github doesn't like to have .ini files attached to an issue.
ddeb0dd88a46bd2205a0e39cc4146889bb9d39fd
f211c2b6cdb9ea559df99f7e9e29903baea2007a
https://github.com/movingblocks/destinationsol/compare/ddeb0dd88a46bd2205a0e39cc4146889bb9d39fd...f211c2b6cdb9ea559df99f7e9e29903baea2007a
diff --git a/engine/src/main/java/org/destinationsol/game/projectile/Projectile.java b/engine/src/main/java/org/destinationsol/game/projectile/Projectile.java index d855798a..4a8bfbd1 100644 --- a/engine/src/main/java/org/destinationsol/game/projectile/Projectile.java +++ b/engine/src/main/java/org/destinationsol/game/projectile/Projectile.java @@ -320,6 +320,10 @@ public boolean shouldCollide(SolObject object, Fixture fixture, FactionManager f return shield != null && shield.canAbsorb(config.dmgType); } return true; + } else if (object instanceof Projectile) { + // Projectiles from the same sources are allowed to overlap + Projectile projectile = (Projectile) object; + return projectile.ship != this.ship; } return true;
['engine/src/main/java/org/destinationsol/game/projectile/Projectile.java']
{'.java': 1}
1
1
0
0
1
1,833,636
396,267
50,624
438
232
40
4
1
1,463
263
356
33
1
0
1970-01-01T00:27:05
309
Java
{'Java': 2210853, 'Groovy': 45867, 'Shell': 6005, 'Batchfile': 4149}
Apache License 2.0
583
neo4j/neo4j-java-driver/147/146
neo4j
neo4j-java-driver
https://github.com/neo4j/neo4j-java-driver/issues/146
https://github.com/neo4j/neo4j-java-driver/pull/147
https://github.com/neo4j/neo4j-java-driver/pull/147
1
fixes
NullPointerException at org.neo4j.driver.internal.InternalSession$2.run when an invalid Cypher query is executed
With 1.0.0-M05, this exception is thrown ``` Exception in thread "main" java.lang.NullPointerException at org.neo4j.driver.internal.InternalSession$2.run(InternalSession.java:140) at org.neo4j.driver.internal.pool.PooledConnection.onDelegateException(PooledConnection.java:197) at org.neo4j.driver.internal.pool.PooledConnection.receiveOne(PooledConnection.java:146) at org.neo4j.driver.internal.InternalStatementResult.tryFetching(InternalStatementResult.java:344) at org.neo4j.driver.internal.InternalStatementResult.hasNext(InternalStatementResult.java:190) ``` when you attempt to execute an invalid Cypher query using session.run. This only happens when a previous transaction has been carried out in the same session. ``` Session session = driver.session(); //Must have a transaction first Transaction tx = session.beginTransaction(); StatementResult result = tx.run("CREATE (n) RETURN n"); if (result.hasNext()) { result.next(); } result.consume(); tx.success(); tx.close(); //Now the bad query StatementResult badResult = session.run("CREAT (n) RETURN n"); if (badResult.hasNext()) { badResult.next(); } ``` Without the previous `tx`, `badResult` is executed and produces `Exception in thread "main" org.neo4j.driver.v1.exceptions.ClientException: Invalid input ' ': expected 'e/E' (line 1, column 6 (offset: 5))` as expected. If `badResult` was a valid query `badResult = session.run("CREATE (n) RETURN n");` then both execute fine.
af9083fae30cdbe2f623cef592ec53a2d09dc44c
86af35d3923d796e21137b15d52b270e6aaf9854
https://github.com/neo4j/neo4j-java-driver/compare/af9083fae30cdbe2f623cef592ec53a2d09dc44c...86af35d3923d796e21137b15d52b270e6aaf9854
diff --git a/driver/src/main/java/org/neo4j/driver/internal/InternalSession.java b/driver/src/main/java/org/neo4j/driver/internal/InternalSession.java index bd259fe3..7f71f6b3 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/InternalSession.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalSession.java @@ -137,9 +137,13 @@ public class InternalSession implements Session @Override public void run() { - currentTransaction.markAsRolledBack(); - currentTransaction = null; - connection.onError( null ); + //must check if transaction has been closed + if (currentTransaction != null) + { + currentTransaction.markAsRolledBack(); + currentTransaction = null; + connection.onError( null ); + } } }); return currentTransaction; diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java index 34346f1f..511efb61 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java @@ -54,7 +54,7 @@ public class TransactionIT // Then the outcome of both statements should be visible StatementResult result = session.run( "MATCH (n) RETURN count(n)" ); long nodes = result.single().get( "count(n)" ).asLong(); - assertThat( nodes, equalTo( 2l ) ); + assertThat( nodes, equalTo( 2L ) ); } @Test @@ -70,7 +70,7 @@ public class TransactionIT // Then there should be no visible effect of the transaction StatementResult cursor = session.run( "MATCH (n) RETURN count(n)" ); long nodes = cursor.single().get( "count(n)" ).asLong(); - assertThat( nodes, equalTo( 0l ) ); + assertThat( nodes, equalTo( 0L ) ); } @Test @@ -146,4 +146,22 @@ public class TransactionIT } + //See GH #146 + @Test + public void shouldHandleFailureAfterClosingTransaction() + { + // GIVEN a successful query in a transaction + Transaction tx = session.beginTransaction(); + StatementResult result = tx.run("CREATE (n) RETURN n"); + result.consume(); + tx.success(); + tx.close(); + + // EXPECT + exception.expect( ClientException.class ); + + //WHEN running a malformed query in the original session + session.run("CREAT (n) RETURN n").consume(); + } + }
['driver/src/main/java/org/neo4j/driver/internal/InternalSession.java', 'driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java']
{'.java': 2}
2
2
0
0
2
504,073
110,236
16,431
142
449
64
10
1
1,477
139
345
38
0
2
1970-01-01T00:24:18
303
Java
{'Java': 4418442, 'Python': 2424, 'Dockerfile': 2159, 'Shell': 218}
Apache License 2.0
581
techreborn/techreborn/961/935
techreborn
techreborn
https://github.com/TechReborn/TechReborn/issues/935
https://github.com/TechReborn/TechReborn/pull/961
https://github.com/TechReborn/TechReborn/pull/961
1
fixes
[1.10.2] Minetweaker recipes not showing up in JEI
All these versions are most recent available on the curse launcher at the time of this posting JEI-1.10.2-3.14.3.403 Techreborn-1.10.2-2.1.2.160 RebornCore-1.10.2-2.13.2.114 Crafttweaker -1.10.2-3.0.17 Forge 2221 I've only tried a few different ones, but it seems that any MT machine recipes that I add won't show up in JEI after refreshing, but will still function correctly. I haven't taken a peek at the relevant code yet, but I suspect it's related to crafttweaker API updates (see [here](https://github.com/jaredlll08/CraftTweaker/issues/136) and [here](https://github.com/SonarSonic/Calculator/issues/202) for what seems to be a similar case)
5aebc4e70bc20a09ad2aebd36b75d7c21d432e94
7ae3ab5d87a24d2ae48f83b78626d3db7943f8bf
https://github.com/techreborn/techreborn/compare/5aebc4e70bc20a09ad2aebd36b75d7c21d432e94...7ae3ab5d87a24d2ae48f83b78626d3db7943f8bf
diff --git a/src/main/java/techreborn/compat/minetweaker/MTGeneric.java b/src/main/java/techreborn/compat/minetweaker/MTGeneric.java index eb9163538..41e299980 100644 --- a/src/main/java/techreborn/compat/minetweaker/MTGeneric.java +++ b/src/main/java/techreborn/compat/minetweaker/MTGeneric.java @@ -32,6 +32,7 @@ public class MTGeneric { @Override public void apply() { RecipeHandler.addRecipe(recipe); + MineTweakerAPI.getIjeiRecipeRegistry().addRecipe(recipe); } @Override @@ -42,6 +43,7 @@ public class MTGeneric { @Override public void undo() { RecipeHandler.recipeList.remove(recipe); + MineTweakerAPI.getIjeiRecipeRegistry().removeRecipe(recipe); } @Override @@ -77,6 +79,7 @@ public class MTGeneric { if (ItemUtils.isItemEqual(stack, output, true, false)) { removedRecipes.add((BaseRecipe) recipeType); RecipeHandler.recipeList.remove(recipeType); + MineTweakerAPI.getIjeiRecipeRegistry().removeRecipe(recipeType); break; } } @@ -89,6 +92,7 @@ public class MTGeneric { for (BaseRecipe recipe : removedRecipes) { if (recipe != null) { RecipeHandler.addRecipe(recipe); + MineTweakerAPI.getIjeiRecipeRegistry().addRecipe(recipe); } } } @@ -147,6 +151,7 @@ public class MTGeneric { for (BaseRecipe recipe : removedRecipes) { if (recipe != null) { RecipeHandler.addRecipe(recipe); + MineTweakerAPI.getIjeiRecipeRegistry().addRecipe(recipe); } } }
['src/main/java/techreborn/compat/minetweaker/MTGeneric.java']
{'.java': 1}
1
1
0
0
1
1,294,432
340,268
39,572
507
328
91
5
1
656
85
205
8
2
0
1970-01-01T00:24:46
301
Java
{'Java': 2177268, 'Groovy': 243121}
MIT License
580
techreborn/techreborn/2760/2759
techreborn
techreborn
https://github.com/TechReborn/TechReborn/issues/2759
https://github.com/TechReborn/TechReborn/pull/2760
https://github.com/TechReborn/TechReborn/pull/2760
1
fixes
Ore Exp Bug
**Describe the bug** TR ores give no exp after digging/smelting **Steps to Reproduce** Steps to reproduce the behavior: - Dig ore(ruby,sapphire) - No exp - be sad **Environment (please complete the following information with the version):** - Minecraft: 1.18.1 Valhesia Enchanced Vanilla - Mod Loader: Fabric
55eb70742fb742ef69a5408fd87dc6c5966abdc9
f4c0cf9e8eaf44ae8c96343e465e345a99cccaa1
https://github.com/techreborn/techreborn/compare/55eb70742fb742ef69a5408fd87dc6c5966abdc9...f4c0cf9e8eaf44ae8c96343e465e345a99cccaa1
diff --git a/src/main/java/techreborn/init/TRContent.java b/src/main/java/techreborn/init/TRContent.java index 17c258587..8888da7b0 100644 --- a/src/main/java/techreborn/init/TRContent.java +++ b/src/main/java/techreborn/init/TRContent.java @@ -32,6 +32,7 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemConvertible; import net.minecraft.item.ItemStack; import net.minecraft.sound.BlockSoundGroup; +import net.minecraft.util.math.intprovider.UniformIntProvider; import org.jetbrains.annotations.Nullable; import reborncore.api.blockentity.IUpgrade; import reborncore.common.fluid.FluidValue; @@ -427,20 +428,25 @@ public class TRContent { public final Block block; public final OreDistribution distribution; - Ores(OreDistribution distribution) { + Ores(OreDistribution distribution, UniformIntProvider experienceDroppedFallback) { name = this.toString().toLowerCase(Locale.ROOT); block = new OreBlock(FabricBlockSettings.of(Material.STONE) .requiresTool() .sounds(name.startsWith("deepslate") ? BlockSoundGroup.DEEPSLATE : BlockSoundGroup.STONE) - .strength(2f, 2f) + .strength(2f, 2f), + distribution != null ? distribution.experienceDropped : experienceDroppedFallback ); InitUtils.setup(block, name + "_ore"); this.distribution = distribution; } + Ores(OreDistribution distribution) { + this(distribution, null); + } + Ores(TRContent.Ores stoneOre) { - this((OreDistribution) null); + this(null, stoneOre.distribution != null ? stoneOre.distribution.experienceDropped : null); deepslateMap.put(stoneOre, this); unDeepslateMap.put(this, stoneOre); } diff --git a/src/main/java/techreborn/world/OreDistribution.java b/src/main/java/techreborn/world/OreDistribution.java index 09da4c331..5fe1f0874 100644 --- a/src/main/java/techreborn/world/OreDistribution.java +++ b/src/main/java/techreborn/world/OreDistribution.java @@ -24,7 +24,11 @@ package techreborn.world; +import net.minecraft.util.math.intprovider.UniformIntProvider; import net.minecraft.world.gen.YOffset; +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; public enum OreDistribution { BAUXITE(6, 12, YOffset.aboveBottom(0), 20, TargetDimension.OVERWORLD), @@ -32,10 +36,10 @@ public enum OreDistribution { GALENA(8, 12, YOffset.aboveBottom(25), 40, TargetDimension.OVERWORLD), IRIDIUM(3, 4, YOffset.aboveBottom(0), 0, TargetDimension.OVERWORLD), LEAD(6, 16, YOffset.aboveBottom(40), 40, TargetDimension.OVERWORLD), - PERIDOT(6, 6, YOffset.aboveBottom(0), 360, TargetDimension.END), + PERIDOT(6, 6, YOffset.aboveBottom(0), 360, TargetDimension.END, UniformIntProvider.create(2,6)), PYRITE(6, 6, YOffset.aboveBottom(0), 128, TargetDimension.NETHER), - RUBY(6, 8, YOffset.fixed(20), 120, TargetDimension.OVERWORLD), - SAPPHIRE(6, 7, YOffset.fixed(20), 120, TargetDimension.OVERWORLD), + RUBY(6, 8, YOffset.fixed(20), 120, TargetDimension.OVERWORLD, UniformIntProvider.create(2,6)), + SAPPHIRE(6, 7, YOffset.fixed(20), 120, TargetDimension.OVERWORLD, UniformIntProvider.create(2,6)), SHELDONITE(6, 4, YOffset.aboveBottom(0), 360, TargetDimension.END), SILVER(6, 16, YOffset.aboveBottom(40), 60,TargetDimension.OVERWORLD), SODALITE(6, 4, YOffset.aboveBottom(0), 360, TargetDimension.END), @@ -47,13 +51,19 @@ public enum OreDistribution { public final int veinsPerChunk; public final YOffset minOffset; public final int maxY; // Max height of ore in numbers of blocks from the bottom of the world + public @NotNull final UniformIntProvider experienceDropped; public final TargetDimension dimension; - OreDistribution(int veinSize, int veinsPerChunk, YOffset minOffset, int maxY, TargetDimension dimension) { + OreDistribution(int veinSize, int veinsPerChunk, YOffset minOffset, int maxY, TargetDimension dimension, UniformIntProvider experienceDropped) { this.veinSize = veinSize; this.veinsPerChunk = veinsPerChunk; this.minOffset = minOffset; this.maxY = maxY; + this.experienceDropped = Objects.requireNonNullElse(experienceDropped, UniformIntProvider.create(0,0)); this.dimension = dimension; } + + OreDistribution(int veinSize, int veinsPerChunk, YOffset minOffset, int maxY, TargetDimension dimension) { + this(veinSize, veinsPerChunk, minOffset, maxY, dimension, null); + } }
['src/main/java/techreborn/world/OreDistribution.java', 'src/main/java/techreborn/init/TRContent.java']
{'.java': 2}
2
2
0
0
2
1,991,720
473,730
53,295
486
1,774
474
30
2
335
46
80
18
0
0
1970-01-01T00:27:22
301
Java
{'Java': 2177268, 'Groovy': 243121}
MIT License
582
techreborn/techreborn/679/658
techreborn
techreborn
https://github.com/TechReborn/TechReborn/issues/658
https://github.com/TechReborn/TechReborn/pull/679
https://github.com/TechReborn/TechReborn/pull/679
1
fixes
Cannot automatically remove products of Extractor
1.9.4-1.3.2.120-universal Running in 1.10 Cannot automatically remove products of Extractor using any method.
48cbda6453568517c0ef46a24c73d0c7b842bb4b
1fb668cad47a4bee619c06028611523bf563c4e0
https://github.com/techreborn/techreborn/compare/48cbda6453568517c0ef46a24c73d0c7b842bb4b...1fb668cad47a4bee619c06028611523bf563c4e0
diff --git a/src/main/java/techreborn/client/GuiHandler.java b/src/main/java/techreborn/client/GuiHandler.java index c5e20c032..7904262be 100644 --- a/src/main/java/techreborn/client/GuiHandler.java +++ b/src/main/java/techreborn/client/GuiHandler.java @@ -168,7 +168,7 @@ public class GuiHandler implements IGuiHandler return new ContainerGenerator((TileGenerator) world.getTileEntity(new BlockPos(x, y, z)), player); } else if (ID == extractorID) { - return new ContainerExtractor((TileExtractor) world.getTileEntity(new BlockPos(x, y, z)), player); + container = new ContainerExtractor(); } else if (ID == compressorID) { return new ContainerCompressor((TileCompressor) world.getTileEntity(new BlockPos(x, y, z)), player); diff --git a/src/main/java/techreborn/client/container/ContainerExtractor.java b/src/main/java/techreborn/client/container/ContainerExtractor.java index f6385573d..74ad03583 100644 --- a/src/main/java/techreborn/client/container/ContainerExtractor.java +++ b/src/main/java/techreborn/client/container/ContainerExtractor.java @@ -1,34 +1,48 @@ package techreborn.client.container; +import java.util.List; + +import javax.annotation.Nullable; + import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.EnumFacing; +import reborncore.api.tile.IContainerLayout; import reborncore.client.gui.BaseSlot; +import reborncore.client.gui.SlotInput; import reborncore.client.gui.SlotOutput; import techreborn.api.gui.SlotUpgrade; import techreborn.tiles.teir1.TileExtractor; -public class ContainerExtractor extends ContainerCrafting +public class ContainerExtractor extends ContainerCrafting implements IContainerLayout<TileExtractor> { public int connectionStatus; EntityPlayer player; - TileExtractor tile; + TileExtractor tileExtractor; - public ContainerExtractor(TileExtractor tileGrinder, EntityPlayer player) + + @Override + public boolean canInteractWith(EntityPlayer p_75145_1_) { - super(tileGrinder.crafter); - tile = tileGrinder; - this.player = player; + return true; + } + + @Override + public void addInventorySlots() { // input - this.addSlotToContainer(new BaseSlot(tileGrinder.inventory, 0, 56, 34)); - this.addSlotToContainer(new SlotOutput(tileGrinder.inventory, 1, 116, 34)); + this.addSlotToContainer(new SlotInput(tileExtractor.inventory, 0, 56, 34)); + this.addSlotToContainer(new SlotOutput(tileExtractor.inventory, 1, 116, 34)); // upgrades - this.addSlotToContainer(new SlotUpgrade(tileGrinder.inventory, 2, 152, 8)); - this.addSlotToContainer(new SlotUpgrade(tileGrinder.inventory, 3, 152, 26)); - this.addSlotToContainer(new SlotUpgrade(tileGrinder.inventory, 4, 152, 44)); - this.addSlotToContainer(new SlotUpgrade(tileGrinder.inventory, 5, 152, 62)); + this.addSlotToContainer(new SlotUpgrade(tileExtractor.inventory, 2, 152, 8)); + this.addSlotToContainer(new SlotUpgrade(tileExtractor.inventory, 3, 152, 26)); + this.addSlotToContainer(new SlotUpgrade(tileExtractor.inventory, 4, 152, 44)); + this.addSlotToContainer(new SlotUpgrade(tileExtractor.inventory, 5, 152, 62)); + } + @Override + public void addPlayerSlots() { int i; for (i = 0; i < 3; ++i) @@ -46,35 +60,30 @@ public class ContainerExtractor extends ContainerCrafting } @Override - public boolean canInteractWith(EntityPlayer p_75145_1_) - { - return true; + public void setTile(TileExtractor tile) { + this.tileExtractor = tile; + setCrafter(tile.crafter); + } + + @Override + public TileExtractor getTile() { + return tileExtractor; } - // @Override - // public void addListener(IContainerListener crafting) { - // super.addListener(crafting); - // crafting.sendProgressBarUpdate(this, 0, (int) tile.getProgressScaled(0)); - // crafting.sendProgressBarUpdate(this, 2, (int) tile.getEnergy()); - // } - // - // @SideOnly(Side.CLIENT) - // @Override - // public void updateProgressBar(int id, int value) { - // if (id == 0) { - // this.progress = value; - // } - // else if (id == 2) { - // this.energy = value; - // } - // this.tile.setEnergy(energy); - // } - - // @SideOnly(Side.CLIENT) - // @Override - // public void updateProgressBar(int id, int value) { - // if (id == 10) { - // this.connectionStatus = value; - // } - // } + @Override + public void setPlayer(EntityPlayer player) { + this.player = player; + + } + + @Override + public EntityPlayer getPlayer() { + return player; + } + + @Nullable + @Override + public List<Integer> getSlotsForSide(EnumFacing facing) { + return null; + } } diff --git a/src/main/java/techreborn/client/gui/GuiExtractor.java b/src/main/java/techreborn/client/gui/GuiExtractor.java index 1fab87035..310407473 100644 --- a/src/main/java/techreborn/client/gui/GuiExtractor.java +++ b/src/main/java/techreborn/client/gui/GuiExtractor.java @@ -5,6 +5,7 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.translation.I18n; +import reborncore.common.container.RebornContainer; import techreborn.client.container.ContainerExtractor; import techreborn.tiles.teir1.TileExtractor; @@ -14,15 +15,15 @@ public class GuiExtractor extends GuiContainer public static final ResourceLocation texture = new ResourceLocation("techreborn", "textures/gui/compressor.png"); TileExtractor extractor; - ContainerExtractor containerGrinder; + ContainerExtractor containerExtractor; - public GuiExtractor(EntityPlayer player, TileExtractor tilegrinder) + public GuiExtractor(EntityPlayer player, TileExtractor tileExtractor) { - super(new ContainerExtractor(tilegrinder, player)); + super(RebornContainer.createContainer(ContainerExtractor.class, tileExtractor, player)); this.xSize = 176; this.ySize = 167; - extractor = tilegrinder; - containerGrinder = (ContainerExtractor) this.inventorySlots; + this.extractor = tileExtractor; + containerExtractor = (ContainerExtractor) this.inventorySlots; } @Override diff --git a/src/main/java/techreborn/client/gui/GuiGrinder.java b/src/main/java/techreborn/client/gui/GuiGrinder.java index 717f619fb..0e4dbadd5 100644 --- a/src/main/java/techreborn/client/gui/GuiGrinder.java +++ b/src/main/java/techreborn/client/gui/GuiGrinder.java @@ -22,7 +22,7 @@ public class GuiGrinder extends GuiContainer super(RebornContainer.createContainer(ContainerGrinder.class, tilegrinder, player)); this.xSize = 176; this.ySize = 167; - grinder = tilegrinder; + this.grinder = tilegrinder; containerGrinder = (ContainerGrinder) this.inventorySlots; } diff --git a/src/main/java/techreborn/tiles/teir1/TileExtractor.java b/src/main/java/techreborn/tiles/teir1/TileExtractor.java index d7e9976af..cfa374b95 100644 --- a/src/main/java/techreborn/tiles/teir1/TileExtractor.java +++ b/src/main/java/techreborn/tiles/teir1/TileExtractor.java @@ -1,6 +1,8 @@ package techreborn.tiles.teir1; -import reborncore.common.IWrenchable;import reborncore.common.IWrenchable; +import reborncore.common.IWrenchable; +import reborncore.common.container.RebornContainer; +import reborncore.common.IWrenchable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; @@ -8,14 +10,17 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import reborncore.api.power.EnumPowerTier; import reborncore.api.recipe.IRecipeCrafterProvider; +import reborncore.api.tile.IContainerProvider; import reborncore.api.tile.IInventoryProvider; import reborncore.common.powerSystem.TilePowerAcceptor; import reborncore.common.recipes.RecipeCrafter; import reborncore.common.util.Inventory; import techreborn.api.Reference; +import techreborn.client.container.ContainerExtractor; +import techreborn.client.container.ContainerGrinder; import techreborn.init.ModBlocks; -public class TileExtractor extends TilePowerAcceptor implements IWrenchable,IInventoryProvider, ISidedInventory, IRecipeCrafterProvider +public class TileExtractor extends TilePowerAcceptor implements IWrenchable,IInventoryProvider, IRecipeCrafterProvider, IContainerProvider { public Inventory inventory = new Inventory(6, "TileExtractor", 64, this); @@ -91,27 +96,6 @@ public class TileExtractor extends TilePowerAcceptor implements IWrenchable,IInv return tagCompound; } - // ISidedInventory - @Override - public int[] getSlotsForFace(EnumFacing side) - { - return side == EnumFacing.DOWN ? new int[] { 0, 1, 2 } : new int[] { 0, 1, 2 }; - } - - @Override - public boolean canInsertItem(int slotIndex, ItemStack itemStack, EnumFacing side) - { - if (slotIndex == 2) - return false; - return isItemValidForSlot(slotIndex, itemStack); - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemStack, EnumFacing side) - { - return slotIndex == 2; - } - public int getProgressScaled(int scale) { if (crafter.currentTickTime != 0) @@ -166,4 +150,9 @@ public class TileExtractor extends TilePowerAcceptor implements IWrenchable,IInv public RecipeCrafter getRecipeCrafter() { return crafter; } + + @Override + public RebornContainer getContainer() { + return RebornContainer.getContainerFromClass(ContainerExtractor.class, this); + } }
['src/main/java/techreborn/client/gui/GuiExtractor.java', 'src/main/java/techreborn/client/gui/GuiGrinder.java', 'src/main/java/techreborn/client/container/ContainerExtractor.java', 'src/main/java/techreborn/tiles/teir1/TileExtractor.java', 'src/main/java/techreborn/client/GuiHandler.java']
{'.java': 5}
5
5
0
0
5
1,372,435
363,352
45,687
510
5,037
1,227
141
5
112
13
34
4
0
0
1970-01-01T00:24:28
301
Java
{'Java': 2177268, 'Groovy': 243121}
MIT License
9,829
mojohaus/versions/188/187
mojohaus
versions
https://github.com/mojohaus/versions/issues/187
https://github.com/mojohaus/versions/pull/188
https://github.com/mojohaus/versions/pull/188
1
fixed
dependency updates report generation in xml does not create target directory
On clean project: ``` [master|⚑ 11] $ mvn org.codehaus.mojo:versions-maven-plugin:2.5-SNAPSHOT:dependency-updates-report -DdependencyUpdateReportFormats=xml [INFO] Scanning for projects... [INFO] ... [INFO] BUILD FAILURE ... [ERROR] Failed to execute goal org.codehaus.mojo:versions-maven-plugin:2.5-SNAPSHOT:dependency-updates-report (default-cli) on project geo-calc-job: An error has occurred in Dependency Updates Report report generation.: Cannot create xml report. /home/idubinin/git/geo-calc/job/target/dependency-updates-report.xml (No such file or directory) -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException ``` But when target directory exist: ``` [master|⚑ 11] $ mkdir target [master|⚑ 11] $ mvn org.codehaus.mojo:versions-maven-plugin:2.5-SNAPSHOT:dependency-updates-report -DdependencyUpdateReportFormats=xml [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ ... [INFO] [INFO] --- versions-maven-plugin:2.5-SNAPSHOT:dependency-updates-report (default-cli) @ geo-calc-job --- [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.883 s [INFO] Finished at: 2017-07-13T15:04:11+01:00 [INFO] Final Memory: 19M/323M [INFO] ------------------------------------------------------------------------ ```
54dd6310cca2fa28ff445ab58e17446e0182c21d
37404a8a7bc37dbab581d0fc70189a8d4ba9a811
https://github.com/mojohaus/versions/compare/54dd6310cca2fa28ff445ab58e17446e0182c21d...37404a8a7bc37dbab581d0fc70189a8d4ba9a811
diff --git a/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReport.java b/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReport.java index 6fce16eb..31802e83 100644 --- a/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReport.java +++ b/src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReport.java @@ -165,8 +165,13 @@ public class DependencyUpdatesReport } else if ( "xml".equals( format ) ) { + File outputDir = new File(getProject().getBuild().getDirectory()); + if (!outputDir.exists()) + { + outputDir.mkdirs(); + } String outputFile = - getProject().getBuild().getDirectory() + File.separator + getOutputName() + ".xml"; + outputDir.getAbsolutePath() + File.separator + getOutputName() + ".xml"; DependencyUpdatesXmlRenderer xmlGenerator = new DependencyUpdatesXmlRenderer( dependencyUpdates, dependencyManagementUpdates, outputFile ); xmlGenerator.render(); diff --git a/src/main/java/org/codehaus/mojo/versions/PluginUpdatesReport.java b/src/main/java/org/codehaus/mojo/versions/PluginUpdatesReport.java index 0a73b480..e4b43b6e 100644 --- a/src/main/java/org/codehaus/mojo/versions/PluginUpdatesReport.java +++ b/src/main/java/org/codehaus/mojo/versions/PluginUpdatesReport.java @@ -122,8 +122,13 @@ public class PluginUpdatesReport } else if ( "xml".equals( format ) ) { + File outputDir = new File(getProject().getBuild().getDirectory()); + if (!outputDir.exists()) + { + outputDir.mkdirs(); + } String outputFile = - getProject().getBuild().getDirectory() + File.separator + getOutputName() + ".xml"; + outputDir.getAbsolutePath() + File.separator + getOutputName() + ".xml"; PluginUpdatesXmlRenderer xmlGenerator = new PluginUpdatesXmlRenderer( pluginUpdates, pluginManagementUpdates, outputFile ); xmlGenerator.render();
['src/main/java/org/codehaus/mojo/versions/DependencyUpdatesReport.java', 'src/main/java/org/codehaus/mojo/versions/PluginUpdatesReport.java']
{'.java': 2}
2
2
0
0
2
779,064
154,248
21,237
81
860
142
14
2
1,795
159
440
35
1
2
1970-01-01T00:24:59
298
Java
{'Java': 1329705, 'Groovy': 46826, 'Batchfile': 2091, 'Shell': 1618}
Apache License 2.0
604
paritytrading/philadelphia/128/117
paritytrading
philadelphia
https://github.com/paritytrading/philadelphia/issues/117
https://github.com/paritytrading/philadelphia/pull/128
https://github.com/paritytrading/philadelphia/pull/128
1
closes
philadelphia-client: Fix 'wait' command
The `wait` command is broken: it does not look at all received messages since being issued but just the last received message after each wait interval. This means that if `wait A` has been invoked and two messages with MsgType(35) values A and B, respectively, are received within one wait interval, the command only sees the MsgType(35) value B of the second message and continues waiting. Fix the `wait` command so that it looks at all received messages since being issued.
b97496eb71ad656157e0a533a44a8c8cf256c031
7fde13233ba6c4b0e9e27fd5184d4a31cbd558de
https://github.com/paritytrading/philadelphia/compare/b97496eb71ad656157e0a533a44a8c8cf256c031...7fde13233ba6c4b0e9e27fd5184d4a31cbd558de
diff --git a/applications/client/src/main/java/com/paritytrading/philadelphia/client/WaitCommand.java b/applications/client/src/main/java/com/paritytrading/philadelphia/client/WaitCommand.java index 5a9588b..9d0d161 100644 --- a/applications/client/src/main/java/com/paritytrading/philadelphia/client/WaitCommand.java +++ b/applications/client/src/main/java/com/paritytrading/philadelphia/client/WaitCommand.java @@ -15,6 +15,8 @@ */ package com.paritytrading.philadelphia.client; +import static java.util.stream.Collectors.*; + import java.util.List; import java.util.Scanner; @@ -32,11 +34,13 @@ class WaitCommand implements Command { if (arguments.hasNext()) throw new IllegalArgumentException(); + int fromIndex = client.getMessages().collect().size(); + while (true) { try { Thread.sleep(WAIT_TIME_MILLIS); - if (msgType.equals(getLastMsgType(client.getMessages()))) + if (getMsgTypes(client.getMessages(), fromIndex).contains(msgType)) break; } catch (InterruptedException e) { @@ -60,13 +64,12 @@ class WaitCommand implements Command { return "wait <msg-type>"; } - private static String getLastMsgType(Messages messages) { - List<Message> collection = messages.collect(); - - if (collection.isEmpty()) - return null; - - return collection.get(collection.size() - 1).getMsgType(); + private static List<String> getMsgTypes(Messages messages, int fromIndex) { + return messages.collect() + .stream() + .skip(fromIndex) + .map(Message::getMsgType) + .collect(toList()); } }
['applications/client/src/main/java/com/paritytrading/philadelphia/client/WaitCommand.java']
{'.java': 1}
1
1
0
0
1
1,563,114
308,022
37,137
67
766
145
19
1
478
81
102
3
0
0
1970-01-01T00:26:22
294
Java
{'Java': 2857695, 'Python': 32593, 'Shell': 6113}
Apache License 2.0
605
paritytrading/philadelphia/106/103
paritytrading
philadelphia
https://github.com/paritytrading/philadelphia/issues/103
https://github.com/paritytrading/philadelphia/pull/106
https://github.com/paritytrading/philadelphia/pull/106
1
fixes
philadelphia-client: Fix command completion
Currently, command completion in Philadelphia Terminal Client is broken. Command completion should only take place on the first token. For example: ``` # Input: > sen<TAB> # Output: > send ``` However, currently it takes place on subsequent tokens as well. This doesn't make sense, because the command is always the first token. For example: ``` # Input: > send sen<TAB> # Output: > send send ``` It looks like this bug got introduced when we upgraded from JLine 2 to JLine 3 (369f7754d1c6a71b30f963232cb1777ce65475da).
dfa591473bf81c621690f940d1e072fc55e07273
1fb67798519568afb6d13f49c96a651e570ed503
https://github.com/paritytrading/philadelphia/compare/dfa591473bf81c621690f940d1e072fc55e07273...1fb67798519568afb6d13f49c96a651e570ed503
diff --git a/applications/client/src/main/java/com/paritytrading/philadelphia/client/TerminalClient.java b/applications/client/src/main/java/com/paritytrading/philadelphia/client/TerminalClient.java index 784cfb9..93dea2a 100644 --- a/applications/client/src/main/java/com/paritytrading/philadelphia/client/TerminalClient.java +++ b/applications/client/src/main/java/com/paritytrading/philadelphia/client/TerminalClient.java @@ -39,6 +39,8 @@ import org.jline.reader.EndOfFileException; import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; import org.jline.reader.UserInterruptException; +import org.jline.reader.impl.completer.ArgumentCompleter; +import org.jline.reader.impl.completer.NullCompleter; import org.jline.reader.impl.completer.StringsCompleter; import org.jvirtanen.config.Configs; @@ -88,7 +90,9 @@ class TerminalClient implements Closeable { void run(List<String> lines) throws IOException { LineReader reader = LineReaderBuilder.builder() - .completer(new StringsCompleter(COMMAND_NAMES)) + .completer(new ArgumentCompleter( + new StringsCompleter(COMMAND_NAMES), + new NullCompleter())) .build(); if (lines.isEmpty())
['applications/client/src/main/java/com/paritytrading/philadelphia/client/TerminalClient.java']
{'.java': 1}
1
1
0
0
1
1,562,801
307,857
37,122
68
330
64
6
1
537
84
137
17
0
2
1970-01-01T00:26:00
294
Java
{'Java': 2857695, 'Python': 32593, 'Shell': 6113}
Apache License 2.0
8,602
graphwalker/graphwalker-project/125/77
graphwalker
graphwalker-project
https://github.com/GraphWalker/graphwalker-project/issues/77
https://github.com/GraphWalker/graphwalker-project/pull/125
https://github.com/GraphWalker/graphwalker-project/pull/125
1
fixes
Using the name context for a variable, does not work.
The unit test in core below will fail. ``` diff --git a/graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java b/graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java index 1dc8f2d..461b1ee 100644 --- a/graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java +++ b/graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java @@ -136,6 +136,20 @@ public class SimpleMachineTest { assertThat(context.getProfiler().getTotalVisitCount(), is(5L)); } + @Test + public void executeActionWithVariableNameContext() { + Vertex vertex1 = new Vertex(); + Vertex vertex2 = new Vertex(); + Model model = new Model() + .addEdge(new Edge().setSourceVertex(vertex1).setTargetVertex(vertex2)) + .addEdge(new Edge().setSourceVertex(vertex2).setTargetVertex(vertex1)); + model.addAction(new Action("context = 1;")); + Context context = new TestExecutionContext(model, new RandomPath(new EdgeCoverage(100))); + context.setNextElement(vertex1); + Machine machine = new SimpleMachine(context); + assertThat(machine.getCurrentContext().getKeys().containsKey("context"), is(true)); + } + @Test(expected = MachineException.class) public void honorGuard() { Vertex vertex1 = new Vertex(); ```
9da6d96c1d8cfd2eba0c46c6cdd48124b8ecd4a2
8e6a93b9f7dea7e4e4170c130ea0bdb06a202a1e
https://github.com/graphwalker/graphwalker-project/compare/9da6d96c1d8cfd2eba0c46c6cdd48124b8ecd4a2...8e6a93b9f7dea7e4e4170c130ea0bdb06a202a1e
diff --git a/graphwalker-core/src/main/java/org/graphwalker/core/machine/ExecutionContext.java b/graphwalker-core/src/main/java/org/graphwalker/core/machine/ExecutionContext.java index 349c1295..97179fee 100644 --- a/graphwalker-core/src/main/java/org/graphwalker/core/machine/ExecutionContext.java +++ b/graphwalker-core/src/main/java/org/graphwalker/core/machine/ExecutionContext.java @@ -360,6 +360,6 @@ public abstract class ExecutionContext extends SimpleScriptContext implements Co } private boolean isVariable(String key, List<String> methods) { - return !"impl".equals(key) && !methods.contains(key) && !"print".equals(key) && !"println".equals(key) && !"context".equals(key); + return !"impl".equals(key) && !methods.contains(key) && !"print".equals(key) && !"println".equals(key); } } diff --git a/graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java b/graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java index 1dc8f2db..9c6dfcae 100644 --- a/graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java +++ b/graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java @@ -356,4 +356,17 @@ public class SimpleMachineTest { assertArrayEquals(expectedPath.toArray(), context.getProfiler().getPath().toArray()); } + @Test + public void executeActionWithVariableNameContext() { + Vertex vertex1 = new Vertex(); + Vertex vertex2 = new Vertex(); + Model model = new Model() + .addEdge(new Edge().setSourceVertex(vertex1).setTargetVertex(vertex2)) + .addEdge(new Edge().setSourceVertex(vertex2).setTargetVertex(vertex1)); + model.addAction(new Action("context = 1;")); + Context context = new TestExecutionContext(model, new RandomPath(new EdgeCoverage(100))); + context.setNextElement(vertex1); + Machine machine = new SimpleMachine(context); + assertThat(machine.getCurrentContext().getKeys().containsKey("context"), is(true)); + } }
['graphwalker-core/src/main/java/org/graphwalker/core/machine/ExecutionContext.java', 'graphwalker-core/src/test/java/org/graphwalker/core/machine/SimpleMachineTest.java']
{'.java': 2}
2
2
0
0
2
493,264
106,068
14,621
150
243
63
2
1
1,331
103
324
30
0
1
1970-01-01T00:24:48
293
Java
{'Java': 1121867, 'JavaScript': 46375, 'ANTLR': 8311, 'CSS': 1884, 'HTML': 348}
MIT License
744
diennea/herddb/530/529
diennea
herddb
https://github.com/diennea/herddb/issues/529
https://github.com/diennea/herddb/pull/530
https://github.com/diennea/herddb/pull/530#issuecomment-571493020
1
resolve
TableSpace recovery : Corrupted transaction, syncing on a position smaller ((1504,17371917)) than transaction last sequence number ((1504,17371917))
Is this a question, a feature request or a bug report? - Is a bug report **BUG REPORT** 1. Please describe the issue you observed: During recovery of a tablespace i get this error: ``` 19-12-23-15-55-47 herddb.core.DBManager Dec 23, 2019 3:55:47 PM herddb.core.DBManager manageTableSpaces SEVERE: cannot handle tablespace q1 herddb.log.LogNotAvailableException: java.lang.IllegalStateException: Corrupted transaction, syncing on a position smaller ((1504,17371917)) than transaction last sequence number ((1504,17371917)) at herddb.cluster.BookkeeperCommitLog.recovery(BookkeeperCommitLog.java:502) at herddb.core.TableSpaceManager.recover(TableSpaceManager.java:294) at herddb.core.TableSpaceManager.start(TableSpaceManager.java:231) at herddb.core.DBManager.handleTableSpace(DBManager.java:537) at herddb.core.DBManager.manageTableSpaces(DBManager.java:1120) at herddb.core.DBManager.executeActivator(DBManager.java:1066) at herddb.core.DBManager.access$500(DBManager.java:113) at herddb.core.DBManager$Activator.run(DBManager.java:1009) at java.base/java.lang.Thread.run(Thread.java:830) Caused by: java.lang.IllegalStateException: Corrupted transaction, syncing on a position smaller ((1504,17371917)) than transaction last sequence number ((1504,17371917)) at herddb.model.Transaction.sync(Transaction.java:567) at herddb.core.TableSpaceManager.apply(TableSpaceManager.java:359) at herddb.core.TableSpaceManager$ApplyEntryOnRecovery.accept(TableSpaceManager.java:1843) at herddb.core.TableSpaceManager$ApplyEntryOnRecovery.accept(TableSpaceManager.java:1832) at herddb.cluster.BookkeeperCommitLog.recovery(BookkeeperCommitLog.java:470) ... 8 more ``` - What did you do? It happened during a checkpoint. From my observations: The checkpint started in position (1504,17371916) and ended in position (1504,17372323). During the checkpoint activity, however, there was an already started transaction that continued to go even during the checkpoint. The transaction finished in position (1504,17371917). - What did you expect to see? I expected that before checkpoint started, all transaction are finished, and then not see a "**corrupted transaction**".
88c9550d1fdf210b008098623dddee7d9f8a54a0
795a56ec50c1d8fc16413d98e224dcc7b5c57973
https://github.com/diennea/herddb/compare/88c9550d1fdf210b008098623dddee7d9f8a54a0...795a56ec50c1d8fc16413d98e224dcc7b5c57973
diff --git a/herddb-core/src/main/java/herddb/cluster/BookkeeperCommitLog.java b/herddb-core/src/main/java/herddb/cluster/BookkeeperCommitLog.java index b4c3a3db..f0230270 100644 --- a/herddb-core/src/main/java/herddb/cluster/BookkeeperCommitLog.java +++ b/herddb-core/src/main/java/herddb/cluster/BookkeeperCommitLog.java @@ -298,12 +298,19 @@ public class BookkeeperCommitLog extends CommitLog { } } ); - res.thenAccept((pos) -> { + // publish the lastSequenceNumber + // we must return a new CompletableFuture that completes only + // AFTER lastSequenceNumber is updated + // otherwise while doing a checkpoint we could observe + // an old value for lastSequenceNumber + // in case of a slow system + res = res.thenApply((pos) -> { if (lastLedgerId == pos.ledgerId) { lastSequenceNumber.accumulateAndGet(pos.offset, EnsureLongIncrementAccumulator.INSTANCE); } notifyListeners(pos, edit); + return pos; } ); } diff --git a/herddb-core/src/main/java/herddb/core/TableSpaceManager.java b/herddb-core/src/main/java/herddb/core/TableSpaceManager.java index 77543882..99338778 100644 --- a/herddb-core/src/main/java/herddb/core/TableSpaceManager.java +++ b/herddb-core/src/main/java/herddb/core/TableSpaceManager.java @@ -267,7 +267,7 @@ public class TableSpaceManager { } dataStorageManager.loadTransactions(logSequenceNumber, tableSpaceUUID, t -> { transactions.put(t.transactionId, t); - LOGGER.log(Level.FINER, "{0} {1} tx {2} at boot", new Object[]{nodeId, tableSpaceName, t.transactionId}); + LOGGER.log(Level.FINER, "{0} {1} tx {2} at boot lsn {3}", new Object[]{nodeId, tableSpaceName, t.transactionId, t.lastSequenceNumber}); try { if (t.newTables != null) { for (Table table : t.newTables.values()) { @@ -1632,7 +1632,14 @@ public class TableSpaceManager { throw new DataStorageManagerException("actualLogSequenceNumber cannot be null"); } // TODO: transactions checkpoint is not atomic - actions.addAll(dataStorageManager.writeTransactionsAtCheckpoint(tableSpaceUUID, logSequenceNumber, new ArrayList<>(transactions.values()))); + Collection<Transaction> currentTransactions = new ArrayList<>(transactions.values()); + for (Transaction t : currentTransactions) { + LogSequenceNumber txLsn = t.lastSequenceNumber; + if (txLsn != null && txLsn.after(logSequenceNumber)) { + LOGGER.log(Level.SEVERE, "Found transaction {0} with LSN {1} in the future", new Object[]{t.transactionId, txLsn}); + } + } + actions.addAll(dataStorageManager.writeTransactionsAtCheckpoint(tableSpaceUUID, logSequenceNumber, currentTransactions)); actions.addAll(writeTablesOnDataStorageManager(new CommitLogResult(logSequenceNumber, false, true), true)); // we checkpoint all data to disk and save the actual log sequence number diff --git a/herddb-core/src/main/java/herddb/log/CommitLog.java b/herddb-core/src/main/java/herddb/log/CommitLog.java index 9c64dc09..7e6a451c 100644 --- a/herddb-core/src/main/java/herddb/log/CommitLog.java +++ b/herddb-core/src/main/java/herddb/log/CommitLog.java @@ -87,7 +87,7 @@ public abstract class CommitLog implements AutoCloseable { protected synchronized void notifyListeners(LogSequenceNumber logPos, LogEntry edit) { if (listeners != null) { for (CommitLogListener l : listeners) { - LOG.log(Level.SEVERE, "notifyListeners {0}, {1}", new Object[]{logPos, edit}); + LOG.log(Level.INFO, "notifyListeners {0}, {1}", new Object[]{logPos, edit}); l.logEntry(logPos, edit); } }
['herddb-core/src/main/java/herddb/log/CommitLog.java', 'herddb-core/src/main/java/herddb/core/TableSpaceManager.java', 'herddb-core/src/main/java/herddb/cluster/BookkeeperCommitLog.java']
{'.java': 3}
3
3
0
0
3
2,688,723
529,205
73,194
439
1,699
345
22
3
2,329
187
544
41
0
1
1970-01-01T00:26:17
281
Java
{'Java': 5736477, 'CSS': 125107, 'Shell': 40956, 'JavaScript': 29064, 'HTML': 28704, 'Batchfile': 2759, 'TSQL': 938}
Apache License 2.0
9,343
janssenproject/jans/4452/4428
janssenproject
jans
https://github.com/JanssenProject/jans/issues/4428
https://github.com/JanssenProject/jans/pull/4452
https://github.com/JanssenProject/jans/pull/4452
1
closes
fix (jans-config-api): we need to restart jans-auth-server to reflect the changes in custom script
**Describe the bug** We need to restart the `jans-auth-server` to reflect the changes in the custom script done using `jans-config-api`. **To Reproduce** Steps to reproduce the behavior: 1. Make changes in a Custom Script using `jans-config-api` `PUT` `/jans-config-api/api/v1/config/scripts` 2. Check persistence to verify if the changes are saved. I found the save works perfectly. 3. Test the implementation of the changes in the script. It will not work. 4. Restart `jans-auth-server` 5. The script changes work after restart.
15568b91d66b782066e5836d088ba6d7c1710d14
e828d5ee516e358bbec96f9f8c684c2569c8fb06
https://github.com/janssenproject/jans/compare/15568b91d66b782066e5836d088ba6d7c1710d14...e828d5ee516e358bbec96f9f8c684c2569c8fb06
diff --git a/jans-config-api/server/src/main/java/io/jans/configapi/rest/resource/auth/CustomScriptResource.java b/jans-config-api/server/src/main/java/io/jans/configapi/rest/resource/auth/CustomScriptResource.java index 2e0460ce16..28cd76f097 100644 --- a/jans-config-api/server/src/main/java/io/jans/configapi/rest/resource/auth/CustomScriptResource.java +++ b/jans-config-api/server/src/main/java/io/jans/configapi/rest/resource/auth/CustomScriptResource.java @@ -199,7 +199,7 @@ public class CustomScriptResource extends ConfigBaseResource { // validate Script LocationType value validateScriptLocationType(customScript); - + updateRevision(customScript, null); customScript.setDn(customScriptService.buildDn(inum)); customScript.setInum(inum); customScriptService.add(customScript); @@ -224,6 +224,7 @@ public class CustomScriptResource extends ConfigBaseResource { CustomScript existingScript = customScriptService.getScriptByInum(customScript.getInum()); checkResourceNotNull(existingScript, CUSTOM_SCRIPT); customScript.setInum(existingScript.getInum()); + updateRevision(customScript, existingScript); logger.debug("Custom Script to be updated {}", customScript); customScriptService.update(customScript); @@ -281,6 +282,7 @@ public class CustomScriptResource extends ConfigBaseResource { CustomScript existingScript = customScriptService.getScriptByInum(inum); checkResourceNotNull(existingScript, CUSTOM_SCRIPT); existingScript = Jackson.applyPatch(pathString, existingScript); + updateRevision(existingScript, existingScript); customScriptService.update(existingScript); existingScript = customScriptService.getScriptByInum(inum); @@ -327,5 +329,29 @@ public class CustomScriptResource extends ConfigBaseResource { throwBadRequestException("Invalid value for '"+customScript.LOCATION_TYPE_MODEL_PROPERTY+"' in request is 'ldap' which is deprecated. Use '"+ScriptLocationType.DB.getValue()+"' instead."); } } + + private CustomScript updateRevision(CustomScript customScript, CustomScript existingScript) { + logger.info("Update script revision - customScript:{}, existingScript:{}", customScript, existingScript); + + if (customScript == null) { + return customScript; + } + + logger.trace("validate customScript.getRevision():{}", customScript.getRevision()); + + if (existingScript == null) { + customScript.setRevision(1); + return customScript; + } + logger.trace("validate customScript.getRevision():{}, existingScript.getRevision():{}", customScript.getRevision(), existingScript.getRevision()); + if (customScript.getRevision() <=0 && existingScript.getRevision() <=0 ) { + customScript.setRevision(1); + } else { + customScript.setRevision(existingScript.getRevision() + 1); + } + + logger.debug("script revision after update - customScript.getRevision():{}", customScript.getRevision()); + return customScript; + } }
['jans-config-api/server/src/main/java/io/jans/configapi/rest/resource/auth/CustomScriptResource.java']
{'.java': 1}
1
1
0
0
1
8,513,882
1,766,489
241,204
1,956
1,252
231
28
1
543
78
128
11
0
0
1970-01-01T00:28:00
268
Java
{'Java': 15604078, 'Python': 2131424, 'HTML': 1463732, 'Go': 648262, 'JavaScript': 551298, 'Gherkin': 153931, 'Shell': 94250, 'Dockerfile': 66591, 'CSS': 64899, 'Mustache': 28733, 'HCL': 13464, 'Makefile': 8953, 'FreeMarker': 7953, 'ANTLR': 5959, 'Inno Setup': 4271, 'Groovy': 265, 'Roff': 220, 'Ruby': 96, 'Batchfile': 78}
Apache License 2.0
742
spotify/styx/27/24
spotify
styx
https://github.com/spotify/styx/issues/24
https://github.com/spotify/styx/pull/27
https://github.com/spotify/styx/pull/27
1
fixes
Changing Workflow partitioning causes trigger time offsets
When changing a Workflows partitioning configuration, the previously stored `nextNaturalTrigger` time is kept, which potentially leads to an offset trigger time. Reproducing - found an hourly Workflow that was enabled - nextNaturalTrigger: 2016-12-08 (19:00:00.000) UTC - changed to daily - it was triggered at 2016-12-08 (19:00:00.000) UTC - nextNaturalTrigger: 2016-12-09 (19:00:00.000) UTC The workflow is now offset to 19:00 UTC instead of 00:00 which a daily workflow would trigger at normally.
f0e1f706a836dd3edd5462d8daa89f4b4c163b1c
62d03e8dc90510c4478a44b0cfedc02f0aeccf23
https://github.com/spotify/styx/compare/f0e1f706a836dd3edd5462d8daa89f4b4c163b1c...62d03e8dc90510c4478a44b0cfedc02f0aeccf23
diff --git a/styx-api-service/src/test/java/com/spotify/styx/api/WorkflowResourceTest.java b/styx-api-service/src/test/java/com/spotify/styx/api/WorkflowResourceTest.java index 7d47ebbe..c11a0ded 100644 --- a/styx-api-service/src/test/java/com/spotify/styx/api/WorkflowResourceTest.java +++ b/styx-api-service/src/test/java/com/spotify/styx/api/WorkflowResourceTest.java @@ -270,7 +270,9 @@ public class WorkflowResourceTest { assertNoJson(response, "docker_image"); assertNoJson(response, "commit_sha"); - storage.patchState(WORKFLOW.id(), WorkflowState.all(true, "tina:ranic", "470a229b49a14e7682af2abfdac3b881a8aacdf9")); + storage.patchState(WORKFLOW.id(), + WorkflowState.builder().enabled(true).dockerImage("tina:ranic") + .commitSha("470a229b49a14e7682af2abfdac3b881a8aacdf9").build()); response = awaitResponse(serviceHelper.request("GET", path("/foo/bar/state"))); diff --git a/styx-common/src/main/java/com/spotify/styx/model/WorkflowState.java b/styx-common/src/main/java/com/spotify/styx/model/WorkflowState.java index 6f7bbe46..7af85f78 100644 --- a/styx-common/src/main/java/com/spotify/styx/model/WorkflowState.java +++ b/styx-common/src/main/java/com/spotify/styx/model/WorkflowState.java @@ -20,12 +20,11 @@ package com.spotify.styx.model; -import static java.util.Optional.of; - import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; +import java.time.Instant; import java.util.Optional; /** @@ -44,27 +43,53 @@ public abstract class WorkflowState { @JsonProperty public abstract Optional<String> commitSha(); + @JsonProperty + public abstract Optional<Instant> nextNaturalTrigger(); + + public abstract Builder toBuilder(); + + public static Builder builder() { + return new AutoValue_WorkflowState.Builder(); + } + + @AutoValue.Builder + public abstract static class Builder { + + public abstract Builder enabled(boolean enabled); + public abstract Builder dockerImage(String dockerImage); + public abstract Builder commitSha(String commitSha); + public abstract Builder nextNaturalTrigger(Instant nextNaturalTrigger); + + public abstract WorkflowState build(); + } + @JsonCreator public static WorkflowState create( @JsonProperty("enabled") Optional<Boolean> enabled, @JsonProperty("docker_image") Optional<String> dockerImage, - @JsonProperty("commit_sha") Optional<String> commitSha) { - return new AutoValue_WorkflowState(enabled, dockerImage, commitSha); + @JsonProperty("commit_sha") Optional<String> commitSha, + @JsonProperty("next_natural_trigger") Optional<Instant> nextNaturalTrigger) { + Builder builder = builder(); + enabled.ifPresent(builder::enabled); + dockerImage.ifPresent(builder::dockerImage); + commitSha.ifPresent(builder::commitSha); + nextNaturalTrigger.ifPresent(builder::nextNaturalTrigger); + return builder.build(); } public static WorkflowState all(boolean enabled, String dockerImage, String commitSha) { - return create(of(enabled), of(dockerImage), of(commitSha)); + return builder().enabled(enabled).dockerImage(dockerImage).commitSha(commitSha).build(); } public static WorkflowState empty() { - return create(Optional.empty(), Optional.empty(), Optional.empty()); + return builder().build(); } public static WorkflowState patchDockerImage(String dockerImage) { - return create(Optional.empty(), of(dockerImage), Optional.empty()); + return builder().dockerImage(dockerImage).build(); } public static WorkflowState patchEnabled(boolean enabled) { - return create(of(enabled), Optional.empty(), Optional.empty()); + return builder().enabled(enabled).build(); } } diff --git a/styx-common/src/main/java/com/spotify/styx/storage/DatastoreStorage.java b/styx-common/src/main/java/com/spotify/styx/storage/DatastoreStorage.java index 8cffa1fc..f374493b 100644 --- a/styx-common/src/main/java/com/spotify/styx/storage/DatastoreStorage.java +++ b/styx-common/src/main/java/com/spotify/styx/storage/DatastoreStorage.java @@ -75,7 +75,7 @@ class DatastoreStorage { public static final String PROPERTY_CONFIG_DOCKER_RUNNER_ID = "dockerRunnerId"; public static final String PROPERTY_WORKFLOW_JSON = "json"; public static final String PROPERTY_WORKFLOW_ENABLED = "enabled"; - public static final String PROPERTY_NEXT_EXECUTION = "nextNaturalTrigger"; + public static final String PROPERTY_NEXT_NATURAL_TRIGGER = "nextNaturalTrigger"; public static final String PROPERTY_DOCKER_IMAGE = "dockerImage"; public static final String PROPERTY_COUNTER = "counter"; public static final String PROPERTY_COMPONENT = "component"; @@ -227,7 +227,7 @@ class DatastoreStorage { final Entity.Builder builder = Entity .builder(workflowOpt.get()) - .set(PROPERTY_NEXT_EXECUTION, instantToDatetime(nextNaturalTrigger)); + .set(PROPERTY_NEXT_NATURAL_TRIGGER, instantToDatetime(nextNaturalTrigger)); return transaction.put(builder.build()); })); } @@ -250,8 +250,8 @@ class DatastoreStorage { continue; } map.put(workflow, - entity.contains(PROPERTY_NEXT_EXECUTION) - ? Optional.of(datetimeToInstant(entity.getDateTime(PROPERTY_NEXT_EXECUTION))) + entity.contains(PROPERTY_NEXT_NATURAL_TRIGGER) + ? Optional.of(datetimeToInstant(entity.getDateTime(PROPERTY_NEXT_NATURAL_TRIGGER))) : Optional.empty()); } return map; @@ -321,7 +321,8 @@ class DatastoreStorage { state.enabled().ifPresent(x -> builder.set(PROPERTY_WORKFLOW_ENABLED, x)); state.dockerImage().ifPresent(x -> builder.set(PROPERTY_DOCKER_IMAGE, x)); state.commitSha().ifPresent(x -> builder.set(PROPERTY_COMMIT_SHA, x)); - + state.nextNaturalTrigger() + .ifPresent(x -> builder.set(PROPERTY_NEXT_NATURAL_TRIGGER, instantToDatetime(x))); return transaction.put(builder.build()); })); } @@ -359,11 +360,10 @@ class DatastoreStorage { } public WorkflowState workflowState(WorkflowId workflowId) throws IOException { - return - WorkflowState.create( - Optional.of(enabled(workflowId)), - getDockerImage(workflowId), - getCommitSha(workflowId)); + WorkflowState.Builder builder = WorkflowState.builder().enabled(enabled(workflowId)); + getDockerImage(workflowId).ifPresent(builder::dockerImage); + getCommitSha(workflowId).ifPresent(builder::commitSha); + return builder.build(); } private Optional<String> getCommitSha(WorkflowId workflowId) { diff --git a/styx-common/src/main/java/com/spotify/styx/storage/InMemStorage.java b/styx-common/src/main/java/com/spotify/styx/storage/InMemStorage.java index 759c04c8..e92e7097 100644 --- a/styx-common/src/main/java/com/spotify/styx/storage/InMemStorage.java +++ b/styx-common/src/main/java/com/spotify/styx/storage/InMemStorage.java @@ -187,7 +187,7 @@ public class InMemStorage implements Storage, EventStorage { return workflowStatePerWorkflowId.getOrDefault( workflowId, - WorkflowState.create(Optional.of(false), Optional.empty(), Optional.empty())); + WorkflowState.patchEnabled(false)); } @Override diff --git a/styx-common/src/main/java/com/spotify/styx/util/WorkflowStateUtil.java b/styx-common/src/main/java/com/spotify/styx/util/WorkflowStateUtil.java index 16db26df..e60af87e 100644 --- a/styx-common/src/main/java/com/spotify/styx/util/WorkflowStateUtil.java +++ b/styx-common/src/main/java/com/spotify/styx/util/WorkflowStateUtil.java @@ -30,11 +30,17 @@ public final class WorkflowStateUtil { public static WorkflowState patchWorkflowState( final Optional<WorkflowState> originalWorkflowState, final WorkflowState patch) { + return originalWorkflowState.map( - o -> WorkflowState.create( - Optional.of(patch.enabled().orElse(o.enabled().orElse(false))), - patch.dockerImage().isPresent() ? patch.dockerImage() : o.dockerImage(), - patch.commitSha().isPresent() ? patch.commitSha() : o.commitSha()) + o -> { + WorkflowState.Builder builder = o.toBuilder() + .enabled(patch.enabled().orElse(o.enabled().orElse(false))); + patch.dockerImage().ifPresent(dockerImage -> builder.dockerImage(dockerImage)); + patch.commitSha().ifPresent(commitSha -> builder.commitSha(commitSha)); + patch.nextNaturalTrigger() + .ifPresent(nextNaturalTrigger -> builder.nextNaturalTrigger(nextNaturalTrigger)); + return builder.build(); + } ).orElse(patch); } } diff --git a/styx-common/src/test/java/com/spotify/styx/storage/DatastoreStorageTest.java b/styx-common/src/test/java/com/spotify/styx/storage/DatastoreStorageTest.java index 2b3a9c73..12ad1ac4 100644 --- a/styx-common/src/test/java/com/spotify/styx/storage/DatastoreStorageTest.java +++ b/styx-common/src/test/java/com/spotify/styx/storage/DatastoreStorageTest.java @@ -211,7 +211,7 @@ public class DatastoreStorageTest { @Test public void shouldPersistCommitShaPerComponent() throws Exception { - WorkflowState state = WorkflowState.create(empty(), empty(), of(COMMIT_SHA)); + WorkflowState state = WorkflowState.builder().commitSha(COMMIT_SHA).build(); storage.store(Workflow.create(WORKFLOW_ID1.componentId(), URI.create("http://foo"), DATA_ENDPOINT_EMPTY_CONF)); storage.patchState(WORKFLOW_ID1.componentId(), state); @@ -236,7 +236,7 @@ public class DatastoreStorageTest { storage.store(Workflow.create(WORKFLOW_ID1.componentId(), URI.create("http://foo"), DataEndpoint .create(WORKFLOW_ID1.endpointId(), Partitioning.DAYS, Optional.empty(), Optional.empty(), Optional.empty(), emptyList()))); - storage.patchState(WORKFLOW_ID1, WorkflowState.create(empty(), empty(), of(COMMIT_SHA))); + storage.patchState(WORKFLOW_ID1, WorkflowState.builder().commitSha(COMMIT_SHA).build()); WorkflowState retrieved = storage.workflowState(WORKFLOW_ID1); assertThat(retrieved.commitSha(), is(Optional.of(COMMIT_SHA))); @@ -254,7 +254,7 @@ public class DatastoreStorageTest { public void shouldReturnEmptyWorkflowStateExceptEnabledWhenWorkflowStateDoesNotExist() throws Exception { storage.store(WORKFLOW_NO_STATE); WorkflowState retrieved = storage.workflowState(WORKFLOW_ID_NO_STATE); - assertThat(retrieved, is(WorkflowState.create(Optional.of(false),Optional.empty(), Optional.empty()))); + assertThat(retrieved, is(WorkflowState.patchEnabled(false))); } @Test @@ -486,7 +486,11 @@ public class DatastoreStorageTest { storage.store(Workflow.create(WORKFLOW_ID1.componentId(), URI.create("http://not/important"), DataEndpoint .create(WORKFLOW_ID1.endpointId(), Partitioning.DAYS, Optional.empty(), Optional.empty(), Optional.empty(), emptyList()))); - WorkflowState state = WorkflowState.all(true, DOCKER_IMAGE.get() , COMMIT_SHA); + WorkflowState state = WorkflowState.builder() + .enabled(true) + .dockerImage(DOCKER_IMAGE.get()) + .commitSha(COMMIT_SHA) + .build(); storage.patchState(WORKFLOW_ID1, state); WorkflowState retrieved = storage.workflowState(WORKFLOW_ID1); diff --git a/styx-common/src/test/java/com/spotify/styx/util/WorkflowStateUtilTest.java b/styx-common/src/test/java/com/spotify/styx/util/WorkflowStateUtilTest.java index b2978915..54c9e8b7 100644 --- a/styx-common/src/test/java/com/spotify/styx/util/WorkflowStateUtilTest.java +++ b/styx-common/src/test/java/com/spotify/styx/util/WorkflowStateUtilTest.java @@ -50,7 +50,7 @@ public class WorkflowStateUtilTest { @Test public void patchEnabledFieldReturnsPatchedOriginal() { - WorkflowState patch = WorkflowState.create(Optional.of(false), Optional.empty(), Optional.empty()); + WorkflowState patch = WorkflowState.builder().enabled(false).build(); WorkflowState patchedState = WorkflowStateUtil.patchWorkflowState( Optional.of(FULLY_POPULATED_STATE), patch); @@ -62,17 +62,17 @@ public class WorkflowStateUtilTest { WorkflowState patch = WorkflowState.empty(); WorkflowState patchedState = WorkflowStateUtil.patchWorkflowState( Optional.of( - WorkflowState.create( - Optional.empty(), - Optional.of("original_docker_image"), - Optional.of(ORIGINAL_COMMIT_SHA))), + WorkflowState.builder() + .dockerImage("original_docker_image") + .commitSha(ORIGINAL_COMMIT_SHA) + .build()), patch); assertThat(patchedState, equalTo(WorkflowState.all(false, "original_docker_image", ORIGINAL_COMMIT_SHA))); } @Test public void patchDockerImageFieldReturnsPatchedOriginal() { - WorkflowState patch = WorkflowState.create(Optional.empty(), Optional.of("patched_docker_image"), Optional.empty()); + WorkflowState patch = WorkflowState.builder().dockerImage("patched_docker_image").build(); WorkflowState patchedState = WorkflowStateUtil.patchWorkflowState( Optional.of(FULLY_POPULATED_STATE), patch); @@ -81,11 +81,13 @@ public class WorkflowStateUtilTest { @Test public void patchCommitShaFieldReturnsPatchedOriginal() { - WorkflowState patch = WorkflowState.create(Optional.empty(), Optional.empty(), Optional.of(PATCHED_COMMIT_SHA)); + WorkflowState patch = WorkflowState.builder().commitSha(PATCHED_COMMIT_SHA).build(); WorkflowState patchedState = WorkflowStateUtil.patchWorkflowState( Optional.of(FULLY_POPULATED_STATE), patch); - assertThat(patchedState, equalTo(WorkflowState.all(true, "original_docker_image", PATCHED_COMMIT_SHA))); + assertThat(patchedState, equalTo( + WorkflowState.builder().enabled(true).dockerImage("original_docker_image") + .commitSha(PATCHED_COMMIT_SHA).build())); } } diff --git a/styx-scheduler-service/src/main/java/com/spotify/styx/StyxScheduler.java b/styx-scheduler-service/src/main/java/com/spotify/styx/StyxScheduler.java index b906a84c..dab9bee1 100644 --- a/styx-scheduler-service/src/main/java/com/spotify/styx/StyxScheduler.java +++ b/styx-scheduler-service/src/main/java/com/spotify/styx/StyxScheduler.java @@ -24,6 +24,8 @@ import static com.spotify.styx.util.Connections.createBigTableConnection; import static com.spotify.styx.util.Connections.createDatastore; import static com.spotify.styx.util.ReplayEvents.replayActiveStates; import static com.spotify.styx.util.ReplayEvents.transitionLogger; +import static com.spotify.styx.workflow.ParameterUtil.incrementInstant; +import static com.spotify.styx.workflow.ParameterUtil.truncateInstant; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toMap; @@ -50,9 +52,11 @@ import com.spotify.styx.api.SchedulerResource; import com.spotify.styx.docker.DockerRunner; import com.spotify.styx.docker.WorkflowValidator; import com.spotify.styx.model.Event; +import com.spotify.styx.model.Partitioning; import com.spotify.styx.model.Workflow; import com.spotify.styx.model.WorkflowId; import com.spotify.styx.model.WorkflowInstance; +import com.spotify.styx.model.WorkflowState; import com.spotify.styx.monitoring.MeteredDockerRunner; import com.spotify.styx.monitoring.MeteredEventStorage; import com.spotify.styx.monitoring.MeteredStorage; @@ -92,6 +96,7 @@ import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.ExecutorService; @@ -323,7 +328,7 @@ public class StyxScheduler implements AppInit { final WorkflowCache cache = new InMemWorkflowCache(); final Consumer<Workflow> workflowChangeListener = workflowChanged(cache, storage, - stats, stateManager); + stats, stateManager, time); final Consumer<Workflow> workflowRemoveListener = workflowRemoved(storage); restoreState(eventStorage, outputHandlers, stateManager); @@ -485,7 +490,8 @@ public class StyxScheduler implements AppInit { WorkflowCache cache, Storage storage, Stats stats, - StateManager stateManager) { + StateManager stateManager, + Time time) { return (workflow) -> { stats.registerActiveStates( @@ -494,7 +500,21 @@ public class StyxScheduler implements AppInit { cache.store(workflow); try { + Optional<Workflow> optWorkflow = storage.workflow(workflow.id()); storage.store(workflow); + + // update nextNaturalTrigger only when partitioning specification changes. + final Partitioning partitioning = workflow.schedule().partitioning(); + if (optWorkflow.isPresent() && !optWorkflow.get().schedule().partitioning() + .equals(partitioning)) { + final Instant nextNaturalTrigger = + incrementInstant(truncateInstant(time.get(), partitioning), + partitioning); + storage.patchState(workflow.id(), + WorkflowState.builder() + .nextNaturalTrigger(nextNaturalTrigger) + .build()); + } } catch (IOException e) { LOG.warn("Failed to store workflow " + workflow, e); } diff --git a/styx-scheduler-service/src/test/java/com/spotify/styx/StyxSchedulerServiceFixture.java b/styx-scheduler-service/src/test/java/com/spotify/styx/StyxSchedulerServiceFixture.java index 39d85ec0..c791f400 100644 --- a/styx-scheduler-service/src/test/java/com/spotify/styx/StyxSchedulerServiceFixture.java +++ b/styx-scheduler-service/src/test/java/com/spotify/styx/StyxSchedulerServiceFixture.java @@ -187,6 +187,18 @@ public class StyxSchedulerServiceFixture { workflowRemoveListener.accept(workflow); } + /** + * Fast forwards the time without any execution in-between. + */ + void timeJumps(int n, TimeUnit unit) { + LOG.info("{} {} passes", n, unit); + now = now.plusMillis(unit.toMillis(n)); + printTime(); + } + + /** + * Fast forwards the time by executing all tasks in-between according to the executor's delay. + */ void timePasses(int n, TimeUnit unit) { LOG.info("{} {} passes", n, unit); now = now.plusMillis(unit.toMillis(n)); @@ -247,6 +259,12 @@ public class StyxSchedulerServiceFixture { await().until(() -> dockerRuns.size() == n); } + void awaitNumberOfDockerRunsWontChange(int n) { + await().pollDelay(1, TimeUnit.SECONDS).until(() -> { + return dockerRuns.size() == n; + }); + } + void awaitWorkflowInstanceState(WorkflowInstance instance, RunState.State state) { await().until(() -> { final RunState runState = getState(instance); @@ -254,6 +272,10 @@ public class StyxSchedulerServiceFixture { }); } + void awaitWorkflowInstanceCompletion(WorkflowInstance workflowInstance) { + await().until(() -> getState(workflowInstance) == null); + } + private void printTime() { LOG.info("The time is {}", now); } diff --git a/styx-scheduler-service/src/test/java/com/spotify/styx/SystemTest.java b/styx-scheduler-service/src/test/java/com/spotify/styx/SystemTest.java index 50106d91..6495cddb 100644 --- a/styx-scheduler-service/src/test/java/com/spotify/styx/SystemTest.java +++ b/styx-scheduler-service/src/test/java/com/spotify/styx/SystemTest.java @@ -25,6 +25,8 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.empty; import static java.util.Optional.of; +import static java.util.concurrent.TimeUnit.DAYS; +import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.Matchers.contains; @@ -44,22 +46,30 @@ import com.spotify.styx.state.handlers.TerminationHandler; import com.spotify.styx.testdata.TestData; import java.time.Instant; import java.util.Arrays; +import java.util.Optional; import org.junit.Test; public class SystemTest extends StyxSchedulerServiceFixture { - private static final DataEndpoint DATA_ENDPOINT = DataEndpoint.create( + private static final DataEndpoint DATA_ENDPOINT_HOURLY = DataEndpoint.create( "styx.TestEndpoint", Partitioning.HOURS, of("busybox"), of(asList("--hour", "{}")), empty(), emptyList()); + private static final DataEndpoint DATA_ENDPOINT_DAILY = DataEndpoint.create( + "styx.TestEndpoint", Partitioning.DAYS, of("busybox"), of(asList("--hour", "{}")), + empty(), emptyList()); private static final String TEST_EXECUTION_ID_1 = "execution_1"; private static final String TEST_DOCKER_IMAGE = "busybox:1.1"; private static final Workflow HOURLY_WORKFLOW = Workflow.create( "styx", TestData.WORKFLOW_URI, - DATA_ENDPOINT); + DATA_ENDPOINT_HOURLY); private static final ExecutionDescription TEST_EXECUTION_DESCRIPTION = ExecutionDescription.create( TEST_DOCKER_IMAGE, Arrays.asList("--date", "{}", "--bar"), empty(), empty()); + private static final Workflow DAILY_WORKFLOW = Workflow.create( + "styx", + TestData.WORKFLOW_URI, + DATA_ENDPOINT_DAILY); @Test public void shouldCatchUpWithNaturalTriggers() throws Exception { @@ -132,6 +142,110 @@ public class SystemTest extends StyxSchedulerServiceFixture { assertThat(getState(instance2), is(nullValue())); } + @Test + public void updatesNextNaturalTriggerWhenWFPartitioningChangesFromFinerToCoarser() throws Exception { + givenTheTimeIs("2016-03-14T15:30:00Z"); + givenTheGlobalEnableFlagIs(true); + givenWorkflow(HOURLY_WORKFLOW); + givenWorkflowEnabledStateIs(HOURLY_WORKFLOW, true); + WorkflowInstance workflowInstance = + WorkflowInstance.create(HOURLY_WORKFLOW.id(), "2016-03-14T14"); + + styxStarts(); + timePasses(1, SECONDS); + awaitWorkflowInstanceState(workflowInstance, RunState.State.QUEUED); + timePasses(1, SECONDS); + awaitNumberOfDockerRuns(1); + + workflowInstance = dockerRuns.get(0)._1; + RunSpec runSpec = dockerRuns.get(0)._2; + assertThat(workflowInstance.workflowId(), is(HOURLY_WORKFLOW.id())); + assertThat(runSpec, is(RunSpec.simple("busybox", "--hour", "2016-03-14T14"))); + + workflowInstance = WorkflowInstance.create(HOURLY_WORKFLOW.id(), "2016-03-14"); + // this should store a new value for nextNaturalTrigger, 2016-03-15. + workflowChanges(DAILY_WORKFLOW); + timeJumps(1, DAYS); + timePasses(1, SECONDS); + awaitWorkflowInstanceState(workflowInstance, RunState.State.QUEUED); + timePasses(1, SECONDS); + awaitNumberOfDockerRuns(2); + + workflowInstance = dockerRuns.get(1)._1; + runSpec = dockerRuns.get(1)._2; + assertThat(workflowInstance.workflowId(), is(DAILY_WORKFLOW.id())); + assertThat(runSpec, is(RunSpec.simple("busybox", "--hour", "2016-03-14"))); + } + + @Test + public void updatesNextNaturalTriggerWhenWFPartitioningChangesFromCoarserToFiner() throws Exception { + givenTheTimeIs("2016-03-14T15:30:00Z"); + givenTheGlobalEnableFlagIs(true); + givenWorkflow(DAILY_WORKFLOW); + givenWorkflowEnabledStateIs(DAILY_WORKFLOW, true); + WorkflowInstance workflowInstance = WorkflowInstance.create(DAILY_WORKFLOW.id(), "2016-03-13"); + + styxStarts(); + timePasses(1, SECONDS); + awaitWorkflowInstanceState(workflowInstance, RunState.State.QUEUED); + timePasses(1, SECONDS); + awaitNumberOfDockerRuns(1); + + workflowInstance = dockerRuns.get(0)._1; + RunSpec runSpec = dockerRuns.get(0)._2; + assertThat(workflowInstance.workflowId(), is(DAILY_WORKFLOW.id())); + assertThat(runSpec, is(RunSpec.simple("busybox", "--hour", "2016-03-13"))); + + workflowInstance = WorkflowInstance.create(HOURLY_WORKFLOW.id(), "2016-03-14T15"); + // this should store a new value for nextNaturalTrigger, 2016-03-14T16. + workflowChanges(HOURLY_WORKFLOW); + timeJumps(1, HOURS); + timePasses(1, SECONDS); + awaitWorkflowInstanceState(workflowInstance, RunState.State.QUEUED); + timePasses(1, SECONDS); + + awaitNumberOfDockerRuns(2); + workflowInstance = dockerRuns.get(1)._1; + runSpec = dockerRuns.get(1)._2; + assertThat(workflowInstance.workflowId(), is(DAILY_WORKFLOW.id())); + assertThat(runSpec, is(RunSpec.simple("busybox", "--hour", "2016-03-14T15"))); + } + + @Test + public void doesntUpdateNextNaturalTriggerWhenPartitioningDoesntChange() throws Exception { + givenTheTimeIs("2016-03-14T15:30:00Z"); + givenTheGlobalEnableFlagIs(true); + givenWorkflow(DAILY_WORKFLOW); + givenWorkflowEnabledStateIs(DAILY_WORKFLOW, true); + WorkflowInstance workflowInstance = + WorkflowInstance.create(DAILY_WORKFLOW.id(), "2016-03-13"); + + styxStarts(); + timePasses(1, SECONDS); + awaitWorkflowInstanceState(workflowInstance, RunState.State.QUEUED); + timePasses(1, SECONDS); + awaitNumberOfDockerRuns(1); + + workflowInstance = dockerRuns.get(0)._1; + RunSpec runSpec = dockerRuns.get(0)._2; + assertThat(workflowInstance.workflowId(), is(DAILY_WORKFLOW.id())); + assertThat(runSpec, is(RunSpec.simple("busybox", "--hour", "2016-03-13"))); + + injectEvent(Event.started(workflowInstance)); + injectEvent(Event.terminate(workflowInstance, 0)); + awaitWorkflowInstanceCompletion(workflowInstance); + + workflowChanges(Workflow.create(DAILY_WORKFLOW.componentId(), + DAILY_WORKFLOW.componentUri(), + DataEndpoint.create(DATA_ENDPOINT_DAILY.id(), DATA_ENDPOINT_DAILY.partitioning(), + Optional.of("freebox"), DATA_ENDPOINT_DAILY.dockerArgs(), + DATA_ENDPOINT_DAILY.secret(), emptyList()))); + timePasses(StyxScheduler.SCHEDULER_TICK_INTERVAL_SECONDS, SECONDS); + awaitNumberOfDockerRunsWontChange(1); + + assertThat(dockerRuns.size(), is(1)); + } + @Test public void runsDockerImageWithArgsTemplate() throws Exception { givenTheTimeIs("2016-03-14T15:59:00Z"); @@ -172,8 +286,8 @@ public class SystemTest extends StyxSchedulerServiceFixture { awaitWorkflowInstanceState(workflowInstance, RunState.State.QUEUED); DataEndpoint changedDataEndpoint = DataEndpoint.create( - DATA_ENDPOINT.id(), Partitioning.HOURS, of("busybox:v777"), of(asList("other", "args")), - empty(), emptyList()); + DATA_ENDPOINT_HOURLY.id(), Partitioning.HOURS, of("busybox:v777"), + of(asList("other", "args")), empty(), emptyList()); Workflow changedWorkflow = Workflow.create( HOURLY_WORKFLOW.componentId(), diff --git a/styx-scheduler-service/src/test/java/com/spotify/styx/state/handlers/ExecutionDescriptionHandlerTest.java b/styx-scheduler-service/src/test/java/com/spotify/styx/state/handlers/ExecutionDescriptionHandlerTest.java index 0348cdce..632e4dbe 100644 --- a/styx-scheduler-service/src/test/java/com/spotify/styx/state/handlers/ExecutionDescriptionHandlerTest.java +++ b/styx-scheduler-service/src/test/java/com/spotify/styx/state/handlers/ExecutionDescriptionHandlerTest.java @@ -70,8 +70,11 @@ public class ExecutionDescriptionHandlerTest { @Test public void shouldTransitionIntoSubmitting() throws Exception { Workflow workflow = Workflow.create("id", TestData.WORKFLOW_URI, dataEndpoint("--date", "{}", "--bar")); - WorkflowState workflowState = WorkflowState.create( - Optional.of(true), Optional.of(DOCKER_IMAGE), Optional.of(COMMIT_SHA)); + WorkflowState workflowState = WorkflowState.builder() + .enabled(true) + .dockerImage(DOCKER_IMAGE) + .commitSha(COMMIT_SHA) + .build(); WorkflowInstance workflowInstance = WorkflowInstance.create(workflow.id(), "2016-03-14"); RunState runState = RunState.fresh(workflowInstance, toTest); @@ -94,8 +97,11 @@ public class ExecutionDescriptionHandlerTest { @Test public void shouldTransitionIntoFailedIfStorageError() throws Exception { Workflow workflow = Workflow.create("id", TestData.WORKFLOW_URI, dataEndpoint("--date", "{}", "--bar")); - WorkflowState workflowState = WorkflowState.create( - Optional.of(true), Optional.of(DOCKER_IMAGE), Optional.of(COMMIT_SHA)); + WorkflowState workflowState = WorkflowState.builder() + .enabled(true) + .dockerImage(DOCKER_IMAGE) + .commitSha(COMMIT_SHA) + .build(); WorkflowInstance workflowInstance = WorkflowInstance.create(workflow.id(), "2016-03-14"); Storage storageSpy = Mockito.spy(storage);
['styx-api-service/src/test/java/com/spotify/styx/api/WorkflowResourceTest.java', 'styx-scheduler-service/src/test/java/com/spotify/styx/StyxSchedulerServiceFixture.java', 'styx-common/src/main/java/com/spotify/styx/storage/DatastoreStorage.java', 'styx-common/src/main/java/com/spotify/styx/util/WorkflowStateUtil.java', 'styx-common/src/main/java/com/spotify/styx/storage/InMemStorage.java', 'styx-scheduler-service/src/main/java/com/spotify/styx/StyxScheduler.java', 'styx-scheduler-service/src/test/java/com/spotify/styx/SystemTest.java', 'styx-common/src/test/java/com/spotify/styx/util/WorkflowStateUtilTest.java', 'styx-common/src/main/java/com/spotify/styx/model/WorkflowState.java', 'styx-scheduler-service/src/test/java/com/spotify/styx/state/handlers/ExecutionDescriptionHandlerTest.java', 'styx-common/src/test/java/com/spotify/styx/storage/DatastoreStorageTest.java']
{'.java': 11}
11
11
0
0
11
380,676
80,096
11,610
103
5,055
932
101
5
510
71
143
10
0
0
1970-01-01T00:24:41
267
Java
{'Java': 2439309, 'Shell': 2149, 'Dockerfile': 878, 'Python': 544}
Apache License 2.0
743
spotify/styx/14/11
spotify
styx
https://github.com/spotify/styx/issues/11
https://github.com/spotify/styx/pull/14
https://github.com/spotify/styx/pull/14
1
fixes
Halting and re-triggering in short succession causes premature state termination
When an actively running Execution is halted (through the cli or api) Styx will `delete` the Pod in k8s. This process takes some time to complete as the container have to receive the `SIGTERM` signal and exit. It will get some time to exit gracefully (the so called grace period). If the same Workflow Instance is triggered and a new Execution is started during this shutdown period, there will be two Pods in k8s which are associated with the same Workflow Instance (through a Pod annotation). When finally the first Pod exits (usually with status code 137, 128 + `SIGTERM(9)`), a `terminate(137)` event is generated for that Workflow Instance. This event is dispatched to the currently active state and we see a premature state transition. At this point, the second execution Pod is orphaned. A sequence of events outlining this scenario: ``` 2016-11-28T14:39:57 triggerExecution Trigger id: ad-hoc-cli-1480343996990-18517 2016-11-28T14:39:57 submit Execution description: ExecutionDescription{dockerImage=stagger:3, dockerArgs=[{}], secret=Optional.empty, commitSha=Optional.empty} 2016-11-28T14:39:57 submitted Execution id: styx-run-0ab59615-979b-4717-80f3-deab984d1074 2016-11-28T14:40:00 started 2016-11-28T14:41:17 halt 2016-11-28T14:41:22 triggerExecution Trigger id: ad-hoc-cli-1480344082837-41704 2016-11-28T14:41:23 submit Execution description: ExecutionDescription{dockerImage=stagger:3, dockerArgs=[{}], secret=Optional.empty, commitSha=Optional.empty} 2016-11-28T14:41:23 submitted Execution id: styx-run-12994ebb-c7f7-4083-8844-952ecd63b3f8 2016-11-28T14:41:27 started 2016-11-28T14:41:48 terminate Exit code: 137 2016-11-28T14:41:48 retryAfter Delay (seconds): 180 ``` The `terminate` event at the end is actually coming from the first execution, `styx-run-0ab59615-979b-4717-80f3-deab984d1074`.
8540d2dde574af3d0f4ab1b41fd8dd7a29dabc99
d6bafd1b3b8a18eb139f8c0bdbed6c17c70925e0
https://github.com/spotify/styx/compare/8540d2dde574af3d0f4ab1b41fd8dd7a29dabc99...d6bafd1b3b8a18eb139f8c0bdbed6c17c70925e0
diff --git a/styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java b/styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java index e735b7f5..4515be8e 100644 --- a/styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java +++ b/styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java @@ -49,6 +49,7 @@ import java.net.ProtocolException; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -192,8 +193,9 @@ class KubernetesDockerRunner implements DockerRunner { private void inspectPod(Watcher.Action action, Pod pod) { final Map<String, String> annotations = pod.getMetadata().getAnnotations(); + final String podName = pod.getMetadata().getName(); if (!annotations.containsKey(KubernetesDockerRunner.STYX_WORKFLOW_INSTANCE_ANNOTATION)) { - LOG.warn("Got pod without workflow instance annotation {}", pod.getMetadata().getName()); + LOG.warn("Got pod without workflow instance annotation {}", podName); return; } @@ -206,6 +208,19 @@ class KubernetesDockerRunner implements DockerRunner { return; } + final Optional<String> executionIdOpt = runState.executionId(); + if (!executionIdOpt.isPresent()) { + LOG.warn("Pod event for state with no current executionId: {}", podName); + return; + } + + final String executionId = executionIdOpt.get(); + if (!podName.equals(executionId)) { + LOG.warn("Pod event not matching current exec id, current:{} != pod:{}", + executionId, podName); + return; + } + final List<Event> events = translate(workflowInstance, runState, action, pod); for (Event event : events) { diff --git a/styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerPodResourceTest.java b/styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerPodResourceTest.java index b20489ae..589866f2 100644 --- a/styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerPodResourceTest.java +++ b/styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerPodResourceTest.java @@ -20,10 +20,12 @@ package com.spotify.styx.docker; +import static com.jcabi.matchers.RegexMatchers.matchesPattern; import static com.spotify.styx.docker.KubernetesDockerRunner.STYX_WORKFLOW_INSTANCE_ANNOTATION; import static java.util.Optional.empty; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; @@ -32,6 +34,7 @@ import com.spotify.styx.model.DataEndpoint; import com.spotify.styx.model.WorkflowInstance; import com.spotify.styx.testdata.TestData; import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.EnvVar; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Volume; import io.fabric8.kubernetes.api.model.VolumeMount; @@ -42,6 +45,9 @@ import org.junit.Test; public class KubernetesDockerRunnerPodResourceTest { + private static final String UUID_REGEX = + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; + private static final WorkflowInstance WORKFLOW_INSTANCE = WorkflowInstance.create(TestData.WORKFLOW_ID, "2016-04-04"); @@ -155,4 +161,35 @@ public class KubernetesDockerRunnerPodResourceTest { assertThat(volumeMount.getMountPath(), is("/etc/secrets")); assertThat(volumeMount.getReadOnly(), is(true)); } + + @Test + public void shouldConfigureEnvironmentVariables() throws Exception { + Pod pod = KubernetesDockerRunner.createPod( + WORKFLOW_INSTANCE, + DockerRunner.RunSpec.create("busybox", ImmutableList.of(), Optional.empty())); + List<EnvVar> envVars = pod.getSpec().getContainers().get(0).getEnv(); + + EnvVar endpoint = new EnvVar(); + endpoint.setName(KubernetesDockerRunner.ENDPOINT_ID); + endpoint.setValue(WORKFLOW_INSTANCE.workflowId().endpointId()); + EnvVar workflow = new EnvVar(); + workflow.setName(KubernetesDockerRunner.WORKFLOW_ID); + workflow.setValue(WORKFLOW_INSTANCE.workflowId().endpointId()); + EnvVar component = new EnvVar(); + component.setName(KubernetesDockerRunner.COMPONENT_ID); + component.setValue(WORKFLOW_INSTANCE.workflowId().componentId()); + EnvVar parameter = new EnvVar(); + parameter.setName(KubernetesDockerRunner.PARAMETER); + parameter.setValue(WORKFLOW_INSTANCE.parameter()); + EnvVar execution = envVars.get(4); + + assertThat(envVars.size(), is(5)); + assertThat(envVars, hasItem(component)); + assertThat(envVars, hasItem(workflow)); + assertThat(envVars, hasItem(endpoint)); + assertThat(envVars, hasItem(parameter)); + assertThat(execution.getName(),is(KubernetesDockerRunner.EXECUTION_ID)); + assertThat(execution.getValue(), + matchesPattern(KubernetesDockerRunner.STYX_RUN + "-" + UUID_REGEX)); + } } diff --git a/styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerTest.java b/styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerTest.java index 24e10b19..309bd4ec 100644 --- a/styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerTest.java +++ b/styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerTest.java @@ -20,12 +20,10 @@ package com.spotify.styx.docker; -import static com.jcabi.matchers.RegexMatchers.matchesPattern; import static com.spotify.styx.docker.KubernetesPodEventTranslatorTest.podStatusNoContainer; import static com.spotify.styx.docker.KubernetesPodEventTranslatorTest.running; import static com.spotify.styx.docker.KubernetesPodEventTranslatorTest.terminated; import static com.spotify.styx.docker.KubernetesPodEventTranslatorTest.waiting; -import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; @@ -44,7 +42,6 @@ import com.spotify.styx.state.StateManager; import com.spotify.styx.state.SyncStateManager; import com.spotify.styx.testdata.TestData; import io.fabric8.kubernetes.api.model.DoneablePod; -import io.fabric8.kubernetes.api.model.EnvVar; import io.fabric8.kubernetes.api.model.ListMeta; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodList; @@ -55,7 +52,6 @@ import io.fabric8.kubernetes.client.dsl.ClientMixedOperation; import io.fabric8.kubernetes.client.dsl.ClientPodResource; import io.fabric8.kubernetes.client.dsl.Watchable; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.After; @@ -73,8 +69,6 @@ import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class KubernetesDockerRunnerTest { - private static final String UUID_REGEX = - "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; private static final String POD_NAME = "test-pod-1"; private static final WorkflowInstance WORKFLOW_INSTANCE = WorkflowInstance.create(TestData.WORKFLOW_ID, "foo"); private static final RunSpec RUN_SPEC = RunSpec.create("busybox", ImmutableList.of(), Optional.empty()); @@ -123,7 +117,7 @@ public class KubernetesDockerRunnerTest { createdPod.getMetadata().setName(POD_NAME); createdPod.getMetadata().setResourceVersion("1001"); - stateManager.initialize(RunState.create(WORKFLOW_INSTANCE, RunState.State.SUBMITTED)); + stateManager.initialize(RunState.create(WORKFLOW_INSTANCE, POD_NAME, RunState.State.SUBMITTED)); when(pods.create(any(Pod.class))).thenReturn(createdPod); @@ -136,33 +130,6 @@ public class KubernetesDockerRunnerTest { kdr.close(); } - @Test - public void shouldReturnEnvironmentVariablesForCreatedPod() throws Exception { - List<EnvVar> envVars = createdPod.getSpec().getContainers().get(0).getEnv(); - EnvVar endpoint = new EnvVar(); - endpoint.setName(KubernetesDockerRunner.ENDPOINT_ID); - endpoint.setValue(WORKFLOW_INSTANCE.workflowId().endpointId()); - EnvVar workflow = new EnvVar(); - workflow.setName(KubernetesDockerRunner.WORKFLOW_ID); - workflow.setValue(WORKFLOW_INSTANCE.workflowId().endpointId()); - EnvVar component = new EnvVar(); - component.setName(KubernetesDockerRunner.COMPONENT_ID); - component.setValue(WORKFLOW_INSTANCE.workflowId().componentId()); - EnvVar parameter = new EnvVar(); - parameter.setName(KubernetesDockerRunner.PARAMETER); - parameter.setValue(WORKFLOW_INSTANCE.parameter()); - EnvVar execution = envVars.get(4); - - assertThat(envVars.size(), is(5)); - assertThat(envVars, hasItem(component)); - assertThat(envVars, hasItem(workflow)); - assertThat(envVars, hasItem(endpoint)); - assertThat(envVars, hasItem(parameter)); - assertThat(execution.getName(),is(KubernetesDockerRunner.EXECUTION_ID)); - assertThat(execution.getValue(), - matchesPattern(KubernetesDockerRunner.STYX_RUN + "-" + UUID_REGEX)); - } - @Test public void shouldCompleteWithStatusCodeOnSucceeded() throws Exception { createdPod.setStatus(terminated("Succeeded", 20)); @@ -230,7 +197,7 @@ public class KubernetesDockerRunnerTest { @Test public void shouldGenerateStartedWhenContainerIsReady() throws Exception { - stateManager.initialize(RunState.create(WORKFLOW_INSTANCE, RunState.State.SUBMITTED)); + stateManager.initialize(RunState.create(WORKFLOW_INSTANCE, POD_NAME, RunState.State.SUBMITTED)); createdPod.setStatus(running(/* ready= */ false)); podWatcher.eventReceived(Watcher.Action.MODIFIED, createdPod); assertThat(stateManager.get(WORKFLOW_INSTANCE).state(), is(RunState.State.SUBMITTED)); @@ -239,4 +206,15 @@ public class KubernetesDockerRunnerTest { podWatcher.eventReceived(Watcher.Action.MODIFIED, createdPod); assertThat(stateManager.get(WORKFLOW_INSTANCE).state(), is(RunState.State.RUNNING)); } + + @Test + public void shouldDiscardChangesForOldExecutions() throws Exception { + // simulate event from different pod, but still with the same workflow instance annotation + createdPod.getMetadata().setName(POD_NAME + "-other"); + createdPod.setStatus(terminated("Succeeded", 20)); + + podWatcher.eventReceived(Watcher.Action.MODIFIED, createdPod); + + assertThat(stateManager.get(WORKFLOW_INSTANCE).state(), is(RunState.State.RUNNING)); + } }
['styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerTest.java', 'styx-scheduler-service/src/test/java/com/spotify/styx/docker/KubernetesDockerRunnerPodResourceTest.java', 'styx-scheduler-service/src/main/java/com/spotify/styx/docker/KubernetesDockerRunner.java']
{'.java': 3}
3
3
0
0
3
364,573
76,880
11,046
98
705
146
17
1
2,025
209
560
23
0
1
1970-01-01T00:24:40
267
Java
{'Java': 2439309, 'Shell': 2149, 'Dockerfile': 878, 'Python': 544}
Apache License 2.0
818
microsoft/azure-maven-plugins/1925/1848
microsoft
azure-maven-plugins
https://github.com/microsoft/azure-maven-plugins/issues/1848
https://github.com/microsoft/azure-maven-plugins/pull/1925
https://github.com/microsoft/azure-maven-plugins/pull/1925
1
fixes
Azure Function Deployment Fails when setting Key Vault access to Function
### Plugin name and version azure-functions-maven-plugin:1.14.1 ### Plugin configuration in your `pom.xml` <plugin> <groupId>com.microsoft.azure</groupId> <artifactId>azure-functions-maven-plugin</artifactId> <version>1.14.1</version> <configuration> <appName>${functionAppName}</appName> <resourceGroup>java-functions-group</resourceGroup> <appServicePlanName>java-functions-app-service-plan</appServicePlanName> <region>westus</region> <runtime> <os>windows</os> <javaVersion>8</javaVersion> </runtime> <appSettings> <property> <name>FUNCTIONS_EXTENSION_VERSION</name> <value>~3</value> </property> </appSettings> </configuration> <executions> <execution> <id>package-functions</id> <goals> <goal>package</goal> </goals> </execution> </executions> </plugin> ### Expected behavior Deploy Function to Azure Functions ### Actual behavior [ERROR] Failed to execute goal com.microsoft.azure:azure-functions-maven-plugin:1.14.1:deploy (default-cli) on project purchaselimitloader: deploy to Azure Function App with resource creation or updating: Invalid connection string. -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.microsoft.azure:azure-functions-maven-plugin:1.14.1:deploy (default-cli) on project purchaselimitloader: deploy to Azure Function App with resource creation or updating at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:567) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) Caused by: org.apache.maven.plugin.MojoExecutionException: deploy to Azure Function App with resource creation or updating at com.microsoft.azure.maven.AbstractAzureMojo.onMojoError (AbstractAzureMojo.java:575) at com.microsoft.azure.maven.AbstractAzureMojo.execute (AbstractAzureMojo.java:495) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:567) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) Caused by: com.microsoft.azure.toolkit.lib.common.operation.AzureOperationException: deploy to Azure Function App with resource creation or updating at com.microsoft.azure.toolkit.lib.common.operation.AzureOperationAspect.afterThrowing (AzureOperationAspect.java:81) at com.microsoft.azure.maven.function.DeployMojo.doExecute (DeployMojo.java:87) at com.microsoft.azure.maven.AbstractAzureMojo.execute (AbstractAzureMojo.java:490) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:567) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) Caused by: java.lang.IllegalArgumentException: Invalid connection string. at com.microsoft.azure.storage.CloudStorageAccount.parse (CloudStorageAccount.java:290) at com.microsoft.azure.toolkit.lib.appservice.service.impl.deploy.DeployUtils.lambda$getCloudStorageAccount$1 (DeployUtils.java:38) at java.util.Optional.map (Optional.java:258) at com.microsoft.azure.toolkit.lib.appservice.service.impl.deploy.DeployUtils.getCloudStorageAccount (DeployUtils.java:36) at com.microsoft.azure.toolkit.lib.appservice.service.impl.deploy.RunFromBlobFunctionDeployHandler.deploy (RunFromBlobFunctionDeployHandler.java:35) at com.microsoft.azure.toolkit.lib.appservice.service.impl.FunctionAppBase.deploy (FunctionAppBase.java:48) at com.microsoft.azure.toolkit.lib.appservice.service.impl.FunctionAppBase.deploy (FunctionAppBase.java:43) at com.microsoft.azure.toolkit.lib.appservice.task.DeployFunctionAppTask.deployArtifact (DeployFunctionAppTask.java:95) at com.microsoft.azure.toolkit.lib.appservice.task.DeployFunctionAppTask.execute (DeployFunctionAppTask.java:82) at com.microsoft.azure.maven.function.DeployMojo.deployArtifact (DeployMojo.java:183) at com.microsoft.azure.maven.function.DeployMojo.doExecute (DeployMojo.java:85) at com.microsoft.azure.maven.AbstractAzureMojo.execute (AbstractAzureMojo.java:490) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:567) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356) at org.codehaus.classworlds.Launcher.main (Launcher.java:47) [ERROR] [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException ### Steps to reproduce the problem 1. Deploy Function. 2. Grant Key Vault access to Function deployed. 3. Re-deploy the Function again.
97a5479a1088d7b18f5a6db8f0bb4b12fdbc4ae9
beace1236024bba3415abf9432d87ce49467af4f
https://github.com/microsoft/azure-maven-plugins/compare/97a5479a1088d7b18f5a6db8f0bb4b12fdbc4ae9...beace1236024bba3415abf9432d87ce49467af4f
diff --git a/azure-toolkit-libs/azure-toolkit-appservice-lib/src/main/java/com/microsoft/azure/toolkit/lib/appservice/service/impl/deploy/DeployUtils.java b/azure-toolkit-libs/azure-toolkit-appservice-lib/src/main/java/com/microsoft/azure/toolkit/lib/appservice/service/impl/deploy/DeployUtils.java index 78ad383c7..e27060bba 100644 --- a/azure-toolkit-libs/azure-toolkit-appservice-lib/src/main/java/com/microsoft/azure/toolkit/lib/appservice/service/impl/deploy/DeployUtils.java +++ b/azure-toolkit-libs/azure-toolkit-appservice-lib/src/main/java/com/microsoft/azure/toolkit/lib/appservice/service/impl/deploy/DeployUtils.java @@ -4,7 +4,6 @@ */ package com.microsoft.azure.toolkit.lib.appservice.service.impl.deploy; -import com.azure.resourcemanager.appservice.models.AppSetting; import com.azure.resourcemanager.appservice.models.FunctionApp; import com.azure.resourcemanager.appservice.models.FunctionDeploymentSlot; import com.azure.resourcemanager.appservice.models.WebAppBase; @@ -14,7 +13,6 @@ import org.apache.commons.lang3.StringUtils; import java.net.URISyntaxException; import java.security.InvalidKeyException; -import java.util.Map; import java.util.Optional; class DeployUtils { @@ -28,10 +26,9 @@ class DeployUtils { * @return StorageAccount specified in AzureWebJobsStorage */ static CloudStorageAccount getCloudStorageAccount(final WebAppBase functionApp) { - final Map<String, AppSetting> settingsMap = functionApp.getAppSettings(); - return Optional.ofNullable(settingsMap) + // Call functionApp.getSiteAppSettings() to get the app settings with key vault reference + return Optional.ofNullable(functionApp.getSiteAppSettings()) .map(map -> map.get(INTERNAL_STORAGE_KEY)) - .map(AppSetting::value) .filter(StringUtils::isNotEmpty) .map(key -> { try {
['azure-toolkit-libs/azure-toolkit-appservice-lib/src/main/java/com/microsoft/azure/toolkit/lib/appservice/service/impl/deploy/DeployUtils.java']
{'.java': 1}
1
1
0
0
1
1,497,595
292,132
36,956
424
428
81
7
1
12,908
501
2,724
165
1
0
1970-01-01T00:27:23
261
Java
{'Java': 2458063, 'Groovy': 14416, 'PowerShell': 7687, 'HTML': 123}
MIT License
817
microsoft/azure-maven-plugins/1943/1922
microsoft
azure-maven-plugins
https://github.com/microsoft/azure-maven-plugins/issues/1922
https://github.com/microsoft/azure-maven-plugins/pull/1943
https://github.com/microsoft/azure-maven-plugins/pull/1943
1
fixes
Failed to deploy webapp behind a http proxy with 2.3.0
### azure-webapp-maven-plugin:2.3.0 The configuration works with 2.2.1 but failed with 2.3.0. ### Plugin configuration in your `pom.xml` ``` <plugin> <groupId>com.microsoft.azure</groupId> <artifactId>azure-webapp-maven-plugin</artifactId> <version>2.3.0</version> <configuration> <schemaVersion>v2</schemaVersion> <subscriptionId>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</subscriptionId> <resourceGroup>xxxBotGroup</resourceGroup> <appName>xxxBot1</appName> <pricingTier>F1</pricingTier> <region>centralus</region> <runtime> <os>Linux</os> <javaVersion>Java 11</javaVersion> <webContainer>Java SE</webContainer> </runtime> <deployment> <resources> <resource> <directory>${project.basedir}/target</directory> <includes> <include>*.jar</include> </includes> </resource> </resources> </deployment> </configuration> </plugin> ``` ### Expected behavior The app can be deployed successfully ### Actual behavior [INFO] --- azure-webapp-maven-plugin:2.3.0:deploy (default-cli) @ echo --- [INFO] Use maven proxy: xxxxxxxxxxxx:8080 Auth type: AZURE_CLI Default subscription: xxxxxxxxxxxxxxxxxxxxxx Username: [email protected] [INFO] Subscription: xxxxx(xxxxxxxxxxxxxxxxxxxx-ab9e-48ef-a1ab-642db2930a5b) [WARNING] [e9d7b9b3, L:/10.30.28.166:52167 ! R:management.azure.com/13.78.109.96:443] The connection observed an error java.nio.channels.ClosedChannelException at io.netty.handler.ssl.SslHandler.channelInactive (SslHandler.java:1064) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:248) at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive (AbstractChannelHandlerContext.java:241) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive (DefaultChannelPipeline.java:1405) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:248) at io.netty.channel.DefaultChannelPipeline.fireChannelInactive (DefaultChannelPipeline.java:901) at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run (AbstractChannel.java:831) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute (AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks (SingleThreadEventExecutor.java:469) at io.netty.channel.nio.NioEventLoop.run (NioEventLoop.java:497) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run (SingleThreadEventExecutor.java:986) at io.netty.util.internal.ThreadExecutorMap$2.run (ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run (FastThreadLocalRunnable.java:30) at java.lang.Thread.run (Thread.java:833) [WARNING] [42562b75, L:/10.30.28.166:52168 ! R:management.azure.com/13.78.109.96:443] The connection observed an error java.nio.channels.ClosedChannelException at io.netty.handler.ssl.SslHandler.channelInactive (SslHandler.java:1064) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:248) at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive (AbstractChannelHandlerContext.java:241) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive (DefaultChannelPipeline.java:1405) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:248) at io.netty.channel.DefaultChannelPipeline.fireChannelInactive (DefaultChannelPipeline.java:901) at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run (AbstractChannel.java:831) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute (AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks (SingleThreadEventExecutor.java:469) at io.netty.channel.nio.NioEventLoop.run (NioEventLoop.java:497) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run (SingleThreadEventExecutor.java:986) at io.netty.util.internal.ThreadExecutorMap$2.run (ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run (FastThreadLocalRunnable.java:30) at java.lang.Thread.run (Thread.java:833) [WARNING] [292f9cd8, L:/10.30.28.166:52172 ! R:management.azure.com/13.78.109.96:443] The connection observed an error java.nio.channels.ClosedChannelException at io.netty.handler.ssl.SslHandler.channelInactive (SslHandler.java:1064) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:248) at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive (AbstractChannelHandlerContext.java:241) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive (DefaultChannelPipeline.java:1405) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:248) at io.netty.channel.DefaultChannelPipeline.fireChannelInactive (DefaultChannelPipeline.java:901) at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run (AbstractChannel.java:831) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute (AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks (SingleThreadEventExecutor.java:469) at io.netty.channel.nio.NioEventLoop.run (NioEventLoop.java:497) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run (SingleThreadEventExecutor.java:986) at io.netty.util.internal.ThreadExecutorMap$2.run (ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run (FastThreadLocalRunnable.java:30) at java.lang.Thread.run (Thread.java:833) [WARNING] [a23d1db8, L:/10.30.28.166:52173 ! R:management.azure.com/13.78.109.96:443] The connection observed an error java.nio.channels.ClosedChannelException at io.netty.handler.ssl.SslHandler.channelInactive (SslHandler.java:1064) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:248) at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive (AbstractChannelHandlerContext.java:241) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive (DefaultChannelPipeline.java:1405) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:262) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive (AbstractChannelHandlerContext.java:248) at io.netty.channel.DefaultChannelPipeline.fireChannelInactive (DefaultChannelPipeline.java:901) at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run (AbstractChannel.java:831) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute (AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks (SingleThreadEventExecutor.java:469) at io.netty.channel.nio.NioEventLoop.run (NioEventLoop.java:497) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run (SingleThreadEventExecutor.java:986) at io.netty.util.internal.ThreadExecutorMap$2.run (ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run (FastThreadLocalRunnable.java:30) at java.lang.Thread.run (Thread.java:833) ### Steps to reproduce the problem Run following command: mvn azure-webapp:deploy
e73faaf4ac86749cbbc6268d49cba301ff5c7004
dc15e685fb73cfe4e5f0c822681d62e786299158
https://github.com/microsoft/azure-maven-plugins/compare/e73faaf4ac86749cbbc6268d49cba301ff5c7004...dc15e685fb73cfe4e5f0c822681d62e786299158
diff --git a/azure-toolkit-libs/azure-toolkit-common-lib/src/main/java/com/microsoft/azure/toolkit/lib/AbstractAzureResourceModule.java b/azure-toolkit-libs/azure-toolkit-common-lib/src/main/java/com/microsoft/azure/toolkit/lib/AbstractAzureResourceModule.java index 22d351c9a..f17ac4d70 100644 --- a/azure-toolkit-libs/azure-toolkit-common-lib/src/main/java/com/microsoft/azure/toolkit/lib/AbstractAzureResourceModule.java +++ b/azure-toolkit-libs/azure-toolkit-common-lib/src/main/java/com/microsoft/azure/toolkit/lib/AbstractAzureResourceModule.java @@ -84,7 +84,8 @@ public abstract class AbstractAzureResourceModule<T extends IAzureBaseResource> final HttpLogDetailLevel logLevel = Optional.ofNullable(config.getLogLevel()).map(HttpLogDetailLevel::valueOf).orElse(HttpLogDetailLevel.NONE); final AzureProfile azureProfile = new AzureProfile(null, subscriptionId, account.getEnvironment()); final TokenCredential tokenCredential = account.getTokenCredential(subscriptionId); - final R configurable = configurableSupplier.get().withPolicy(getUserAgentPolicy(userAgent)).withLogLevel(logLevel); + final R configurable = configurableSupplier.get().withPolicy(getUserAgentPolicy(userAgent)).withLogLevel(logLevel) + .withHttpClient(AzureService.getDefaultHttpClient()); return authenticationMethod.apply(configurable, tokenCredential, azureProfile); }
['azure-toolkit-libs/azure-toolkit-common-lib/src/main/java/com/microsoft/azure/toolkit/lib/AbstractAzureResourceModule.java']
{'.java': 1}
1
1
0
0
1
1,562,071
304,564
38,481
434
319
56
3
1
8,867
331
1,848
123
0
1
1970-01-01T00:27:25
261
Java
{'Java': 2458063, 'Groovy': 14416, 'PowerShell': 7687, 'HTML': 123}
MIT License
1,177
hivemq/mqtt-cli/127/122
hivemq
mqtt-cli
https://github.com/hivemq/mqtt-cli/issues/122
https://github.com/hivemq/mqtt-cli/pull/127
https://github.com/hivemq/mqtt-cli/pull/127
1
resolve
Private key not recognized
## Expected behavior The `--key` option of `mqtt-cli` should recognize 4096-bit RSA private key files with just a private key in them. ## Actual behavior The `--key` option of `mqtt-cli` does not recognize 4096-bit RSA private keys with just a private key in them. ## To Reproduce I cannot provide my private key, but I have confirmed it works correctly with other mqtt clients that support client certificates. Here are some commands that will communicate what is going on: ``` > openssl rsa -text -noout -in app.key RSA Private-Key: (4096 bit, 2 primes) modulus: ... > mqtt sub -t '$my/topic/name' -h example.com -p 443 --cafile AmazonRootCA1.pem --key app.key --cert app.pem Invalid value for option '--key': cannot convert '/etc/mqtt_status/certs/probation.key' to PrivateKey (The private key could not be recognized.) ``` The source code in `FileToPrivateKeyConverter` suggests that the application is making it all the way down to where `UNRECOGNIZED_KEY` gets thrown. This means that the key is being parsed correctly (it isn't malformed), but it is not an `instanceof` either `PKCS8EncryptedPrivateKeyInfo` or `PEMKeyPair`. I'm not sure what it is an `instanceof` though. I'm not familiar with Java's crypto ecosystem. ## Details Version info from `mqtt` client: ``` > mqtt --version 1.1.1 Picocli 4.0.4 JVM: 11.0.5 (Private Build OpenJDK 64-Bit Server VM 11.0.5+10-post-Ubuntu-0ubuntu1.118.04) OS: Linux 4.15.0-65-generic amd64 ```
3449f304c2cd52c4041f1c9bb772790ab32f40f8
0f24145ecc8290e9ccdd58eacf5de64b108a1d35
https://github.com/hivemq/mqtt-cli/compare/3449f304c2cd52c4041f1c9bb772790ab32f40f8...0f24145ecc8290e9ccdd58eacf5de64b108a1d35
diff --git a/src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java b/src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java index 33e6e00..b760893 100644 --- a/src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java +++ b/src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java @@ -20,26 +20,24 @@ package com.hivemq.cli.converters; import com.hivemq.cli.utils.PasswordUtils; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.openssl.PEMException; -import org.bouncycastle.openssl.PEMKeyPair; -import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.openssl.*; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder; +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder; import org.bouncycastle.operator.InputDecryptorProvider; import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; -import org.bouncycastle.pkcs.PKCSException; import org.jetbrains.annotations.NotNull; import picocli.CommandLine; import java.io.File; import java.io.FileReader; +import java.security.KeyPair; import java.security.PrivateKey; import java.security.Security; public class FileToPrivateKeyConverter implements CommandLine.ITypeConverter<PrivateKey> { static final String UNRECOGNIZED_KEY = "The private key could not be recognized."; static final String MALFORMED_KEY = "The private key could not be read."; - static final String WRONG_PASSWORD = "The password for decrypting the private key was wrong."; @Override public PrivateKey convert(final @NotNull String s) throws Exception { @@ -63,30 +61,25 @@ public class FileToPrivateKeyConverter implements CommandLine.ITypeConverter<Pri final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); final PrivateKey privateKey; - if (object instanceof PKCS8EncryptedPrivateKeyInfo) { - // if encrypted key is password protected - decrypt it with given password - + if (object instanceof PEMEncryptedKeyPair) { + final char[] password = PasswordUtils.readPassword("Enter private key password: "); + final PEMEncryptedKeyPair encryptedPrivateKey = (PEMEncryptedKeyPair) object; + final PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(password); + final KeyPair keyPair = converter.getKeyPair(encryptedPrivateKey.decryptKeyPair(decryptorProvider)); + privateKey = keyPair.getPrivate(); + } + else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { final char[] password = PasswordUtils.readPassword("Enter private key password:"); - final PKCS8EncryptedPrivateKeyInfo encryptedPrivateKey = (PKCS8EncryptedPrivateKeyInfo) object; final InputDecryptorProvider decryptorProvider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password); - - final PrivateKeyInfo privateKeyInfo; - try { - privateKeyInfo = encryptedPrivateKey.decryptPrivateKeyInfo(decryptorProvider); - } catch (final PKCSException pkcse) { - throw new IllegalArgumentException(WRONG_PASSWORD); - } - + final PrivateKeyInfo privateKeyInfo = encryptedPrivateKey.decryptPrivateKeyInfo(decryptorProvider); privateKey = converter.getPrivateKey(privateKeyInfo); } else if (object instanceof PEMKeyPair) { - // if key pair is already decrypted privateKey = converter.getPrivateKey(((PEMKeyPair) object).getPrivateKeyInfo()); } else { throw new IllegalArgumentException(UNRECOGNIZED_KEY); } - // Convert extracted private key into native java Private key return privateKey; } -} +} \\ No newline at end of file diff --git a/src/test/java/com/hivemq/cli/converters/FileToPrivateKeyConverterTest.java b/src/test/java/com/hivemq/cli/converters/FileToPrivateKeyConverterTest.java index 265091a..fb9ced2 100644 --- a/src/test/java/com/hivemq/cli/converters/FileToPrivateKeyConverterTest.java +++ b/src/test/java/com/hivemq/cli/converters/FileToPrivateKeyConverterTest.java @@ -80,11 +80,4 @@ class FileToPrivateKeyConverterTest { assertEquals(FileToPrivateKeyConverter.MALFORMED_KEY, e.getMessage()); } - @Test - void convert_ENCRYPTED_RSA_KEY_WRONG_PASSWORD_FAILURE() throws Exception { - System.setIn(new ByteArrayInputStream("badpassword".getBytes())); - Exception e = assertThrows(Exception.class, () -> fileToPrivateKeyConverter.convert(pathToEncryptedRSAKey)); - assertEquals(FileToPrivateKeyConverter.WRONG_PASSWORD, e.getMessage()); - } - } \\ No newline at end of file
['src/test/java/com/hivemq/cli/converters/FileToPrivateKeyConverterTest.java', 'src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java']
{'.java': 2}
2
2
0
0
2
238,103
49,808
6,647
67
1,714
337
33
1
1,488
215
402
36
0
2
1970-01-01T00:26:18
253
Java
{'Java': 1349932, 'Kotlin': 35042, 'HTML': 15741, 'Shell': 11628, 'Ruby': 443, 'Batchfile': 44}
Apache License 2.0
8,663
uportal-project/uportal/1218/1217
uportal-project
uportal
https://github.com/uPortal-Project/uPortal/issues/1217
https://github.com/uPortal-Project/uPortal/pull/1218
https://github.com/uPortal-Project/uPortal/pull/1218
1
resolves
Multiple text columns not supported by older Oracle versions.
Older Oracle versions, more accurately the Hibernate dialects, do not support multiple text (LONG) columns in a single table. Only PortletPerferenceImpl.java currently defines such a thing.
c887cef65bfb3765a980951fe04bb2d6361af629
015f7070835a024726806bd43d4c3895113cf5ab
https://github.com/uportal-project/uportal/compare/c887cef65bfb3765a980951fe04bb2d6361af629...015f7070835a024726806bd43d4c3895113cf5ab
diff --git a/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java b/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java index 504a8a5b5..658ea460d 100644 --- a/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java +++ b/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java @@ -77,8 +77,8 @@ public class PortletPreferenceImpl implements IPortletPreference, Cloneable { @Column(name = "ENTITY_VERSION") private final long entityVersion; - @Column(name = "PREF_NAME", length = 100000) - @Type(type = "org.hibernate.type.TextType") + @Column(name = "PREF_NAME", length = 100000, columnDefinition = "CLOB") + @Type(type = "org.hibernate.type.StringType") @Lob private String name = null; @@ -89,8 +89,8 @@ public class PortletPreferenceImpl implements IPortletPreference, Cloneable { @JoinTable(name = "UP_PORTLET_PREF_VALUES", joinColumns = @JoinColumn(name = "PORTLET_PREF_ID")) @IndexColumn(name = "VALUE_ORDER") @Lob - @Column(name = "PREF_VALUE", length = 100000) - @Type(type = "org.hibernate.type.TextType") + @Column(name = "PREF_VALUE", length = 100000, columnDefinition = "CLOB") + @Type(type = "org.hibernate.type.StringType") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Fetch(FetchMode.JOIN) private List<String> values = new ArrayList<String>(0);
['uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java']
{'.java': 1}
1
1
0
0
1
8,178,351
1,586,987
205,394
1,592
455
126
8
1
189
26
39
1
0
0
1970-01-01T00:25:29
252
Java
{'Java': 10419076, 'JavaScript': 291612, 'XSLT': 258987, 'HTML': 219389, 'Less': 131846, 'Groovy': 56524, 'CSS': 1744, 'StringTemplate': 1107}
Apache License 2.0
8,662
uportal-project/uportal/1296/1295
uportal-project
uportal
https://github.com/uPortal-Project/uPortal/issues/1295
https://github.com/uPortal-Project/uPortal/pull/1296
https://github.com/uPortal-Project/uPortal/pull/1296
1
fixes
Db create fails on databases that do not support CLOB types
Error caused by Oracle supporting change that introduced setting a column to CLOB type.
3e06b4d3d1959e3bbc116e3c1ace39e3d39ad73c
244fc10e0d04b99c8d0e9cdf06bd9cdcb1be465d
https://github.com/uportal-project/uportal/compare/3e06b4d3d1959e3bbc116e3c1ace39e3d39ad73c...244fc10e0d04b99c8d0e9cdf06bd9cdcb1be465d
diff --git a/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java b/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java index e78b82038..81bb84b1d 100644 --- a/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java +++ b/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java @@ -74,7 +74,7 @@ public class PortletPreferenceImpl implements IPortletPreference, Cloneable { @Column(name = "ENTITY_VERSION") private final long entityVersion; - @Column(name = "PREF_NAME", length = 100000, columnDefinition = "CLOB") + @Column(name = "PREF_NAME", length = 100000) @Type(type = "org.hibernate.type.StringType") @Lob private String name = null; @@ -86,7 +86,7 @@ public class PortletPreferenceImpl implements IPortletPreference, Cloneable { @JoinTable(name = "UP_PORTLET_PREF_VALUES", joinColumns = @JoinColumn(name = "PORTLET_PREF_ID")) @IndexColumn(name = "VALUE_ORDER") @Lob - @Column(name = "PREF_VALUE", length = 100000, columnDefinition = "CLOB") + @Column(name = "PREF_VALUE", length = 100000) @Type(type = "org.hibernate.type.StringType") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Fetch(FetchMode.JOIN)
['uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/dao/jpa/PortletPreferenceImpl.java']
{'.java': 1}
1
1
0
0
1
8,203,870
1,591,159
205,917
1,594
255
78
4
1
89
14
16
2
0
0
1970-01-01T00:25:33
252
Java
{'Java': 10419076, 'JavaScript': 291612, 'XSLT': 258987, 'HTML': 219389, 'Less': 131846, 'Groovy': 56524, 'CSS': 1744, 'StringTemplate': 1107}
Apache License 2.0
8,661
uportal-project/uportal/1468/1467
uportal-project
uportal
https://github.com/uPortal-Project/uPortal/issues/1467
https://github.com/uPortal-Project/uPortal/pull/1468
https://github.com/uPortal-Project/uPortal/pull/1468
1
resolves
Guest user occasionally receives a portal page without a skin when using the dynamic-respondr-skin portlet
## Describe the bug Occasionally (but typically uncommonly) unauthenticated users will start receiving a portal page that does not include the `dynamic-respondr-skin` portlet and therefore has no skin. The affected page is completely unusable. This issue has been encountered by several, and has been discussed more than once on the `uportal-user` list: https://groups.google.com/a/apereo.org/forum/#!topic/uportal-user/JBy0Mp7YvG0 The issue stems from the `ThemeNameEqualsIgnoreCaseTester`. This PAGS tester requires an active `HttpServletRequest` to function, otherwise it always returns `false` (i.e. the user is not a member of the group). The problem is that this tester can be invoked within the Event Aggregation processes, which happen on a worker (non-request) thread. In a typical data set (since the portlet was introduced), users receive the `dynamic-respondr-skin` portlet by virtue of their membership in the `Respondr Theme Users` group -- a PAGS group based on the `ThemeNameEqualsIgnoreCaseTester`. Membership evaluations are cached in the portal. When a test for membership in the `Respondr Theme Users` group for the `guest` user returns `false`, that result will be cached for a period. During that period, real guest users will not receive the `dynamic-respondr-skin` portlet. ## How To Fix Clearly the `ThemeNameEqualsIgnoreCaseTester` has issues, and (furthermore) we don't need it the way we did when it was introduced. (The Universality theme has been removed.) We should deprecate it, remove all usages of it from data sets in uPortal-start, and publish the solution in the released notes.
dfeb314444fdb32679852df588e765ba5b6d0714
0fa06696b50da7e6338e464df76a35320ccd2dd3
https://github.com/uportal-project/uportal/compare/dfeb314444fdb32679852df588e765ba5b6d0714...0fa06696b50da7e6338e464df76a35320ccd2dd3
diff --git a/uPortal-events/src/main/java/org/apereo/portal/events/aggr/PortalEventProcessingManagerImpl.java b/uPortal-events/src/main/java/org/apereo/portal/events/aggr/PortalEventProcessingManagerImpl.java index 0dc3abb71..65cd976e1 100644 --- a/uPortal-events/src/main/java/org/apereo/portal/events/aggr/PortalEventProcessingManagerImpl.java +++ b/uPortal-events/src/main/java/org/apereo/portal/events/aggr/PortalEventProcessingManagerImpl.java @@ -63,7 +63,7 @@ public class PortalEventProcessingManagerImpl new ThreadLocal<Map<Class<?>, Collection<Serializable>>>() { @Override protected Map<Class<?>, Collection<Serializable>> initialValue() { - return new HashMap<Class<?>, Collection<Serializable>>(); + return new HashMap<>(); } }; private volatile boolean shutdown = false; @@ -122,7 +122,7 @@ public class PortalEventProcessingManagerImpl } @Override - public void destroy() throws Exception { + public void destroy() { this.shutdown = true; } @@ -426,7 +426,7 @@ public class PortalEventProcessingManagerImpl final Map<Class<?>, Collection<Serializable>> evictedEntities = evictedEntitiesHolder.get(); Collection<Serializable> ids = evictedEntities.get(entityClass); if (ids == null) { - ids = new ArrayList<Serializable>(); + ids = new ArrayList<>(); evictedEntities.put(entityClass, ids); } ids.add(identifier); diff --git a/uPortal-groups/uPortal-groups-pags/src/main/java/org/apereo/portal/groups/pags/testers/ThemeNameEqualsIgnoreCaseTester.java b/uPortal-groups/uPortal-groups-pags/src/main/java/org/apereo/portal/groups/pags/testers/ThemeNameEqualsIgnoreCaseTester.java index 6241c4597..950a48b52 100644 --- a/uPortal-groups/uPortal-groups-pags/src/main/java/org/apereo/portal/groups/pags/testers/ThemeNameEqualsIgnoreCaseTester.java +++ b/uPortal-groups/uPortal-groups-pags/src/main/java/org/apereo/portal/groups/pags/testers/ThemeNameEqualsIgnoreCaseTester.java @@ -33,7 +33,11 @@ import org.springframework.context.ApplicationContext; /** * This Group tester checks the current session's user profile theme against the test value ignoring * case. + * + * @deprecated Avoid this PAGS tester because (1) it doesn't function outside of a container request + * thread; and (2) it isn't necessary any longer (without Universality). */ +@Deprecated public class ThemeNameEqualsIgnoreCaseTester implements IPersonTester { protected Logger logger = LoggerFactory.getLogger(getClass()); @@ -77,23 +81,26 @@ public class ThemeNameEqualsIgnoreCaseTester implements IPersonTester { try { currentPortalRequest = portalRequestUtils.getCurrentPortalRequest(); } catch (IllegalStateException e) { - logger.warn("No portal request to test ui theme"); + logger.warn( + "No HttpServletRequest is available for testing, which may lead to " + + "surprising outcomes; ThemeNameEqualsIgnoreCaseTester is deprecated and should " + + "not be used.", + e); } return currentPortalRequest; } private IStylesheetDescriptor getCurrentUserProfileStyleSheetDescriptor( IPerson person, HttpServletRequest currentPortalRequest) { - final String currentFname = - this.profileMapper.getProfileFname(person, currentPortalRequest); - IUserProfile profile = this.userLayoutStore.getSystemProfileByFname(currentFname); + final String currentFname = profileMapper.getProfileFname(person, currentPortalRequest); + IUserProfile profile = userLayoutStore.getSystemProfileByFname(currentFname); int profileId = profile.getThemeStylesheetId(); - return this.stylesheetDescriptorDao.getStylesheetDescriptor(profileId); + return stylesheetDescriptorDao.getStylesheetDescriptor(profileId); } private void logDebugMessages(String uiTheme) { if (logger.isDebugEnabled()) { - logger.debug("themeTestValue: {}", this.themeTestValue); + logger.debug("themeTestValue: {}", themeTestValue); logger.debug("uiTheme: {}", uiTheme); logger.debug("getStringCompareResults(uiTheme): {}", getStringCompareResults(uiTheme)); } diff --git a/uPortal-persondir/src/main/java/org/apereo/portal/persondir/support/PersonManagerCurrentUserProvider.java b/uPortal-persondir/src/main/java/org/apereo/portal/persondir/support/PersonManagerCurrentUserProvider.java index 5ee3109ef..7364ac4b0 100644 --- a/uPortal-persondir/src/main/java/org/apereo/portal/persondir/support/PersonManagerCurrentUserProvider.java +++ b/uPortal-persondir/src/main/java/org/apereo/portal/persondir/support/PersonManagerCurrentUserProvider.java @@ -45,9 +45,6 @@ public class PersonManagerCurrentUserProvider implements ICurrentUserProvider { this.portalRequestUtils = portalRequestUtils; } - /* (non-Javadoc) - * @see org.jasig.services.persondir.support.ICurrentUserProvider#getCurrentUserName() - */ @Override public String getCurrentUserName() { final HttpServletRequest portalRequest;
['uPortal-events/src/main/java/org/apereo/portal/events/aggr/PortalEventProcessingManagerImpl.java', 'uPortal-persondir/src/main/java/org/apereo/portal/persondir/support/PersonManagerCurrentUserProvider.java', 'uPortal-groups/uPortal-groups-pags/src/main/java/org/apereo/portal/groups/pags/testers/ThemeNameEqualsIgnoreCaseTester.java']
{'.java': 3}
3
3
0
0
3
8,182,508
1,587,751
205,530
1,604
1,658
307
28
3
1,646
233
379
16
1
0
1970-01-01T00:25:44
252
Java
{'Java': 10419076, 'JavaScript': 291612, 'XSLT': 258987, 'HTML': 219389, 'Less': 131846, 'Groovy': 56524, 'CSS': 1744, 'StringTemplate': 1107}
Apache License 2.0
1,097
wso2/product-microgateway/3297/3298
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/3298
https://github.com/wso2/product-microgateway/pull/3297
https://github.com/wso2/product-microgateway/pull/3297
1
fixes
Websocket Analytics are not working
### Description Getting the following error log in the Enforcer. choreo-connect-with-apim-enforcer-1 | [2023-03-08 06:18:02,970][][] ERROR - {org.wso2.am.analytics.publisher.reporter.cloud.ParallelQueueWorker} - Builder instance is not duly filled. Event building failed [severity:Default error_code:0] choreo-connect-with-apim-enforcer-1 | org.wso2.am.analytics.publisher.exception.MetricReportingException: apiContext is missing in metric data. This metric event will not be processed further. choreo-connect-with-apim-enforcer-1 | at org.wso2.am.analytics.publisher.reporter.cloud.DefaultResponseMetricEventBuilder.validate(DefaultResponseMetricEventBuilder.java:62) ~[org.wso2.choreo.connect.enforcer-1.2.0-beta2-SNAPSHOT.jar:1.2.0-beta2-SNAPSHOT] choreo-connect-with-apim-enforcer-1 | at org.wso2.am.analytics.publisher.reporter.AbstractMetricEventBuilder.build(AbstractMetricEventBuilder.java:32) ~[org.wso2.choreo.connect.enforcer-1.2.0-beta2-SNAPSHOT.jar:1.2.0-beta2-SNAPSHOT] choreo-connect-with-apim-enforcer-1 | at org.wso2.am.analytics.publisher.reporter.cloud.ParallelQueueWorker.run(ParallelQueueWorker.java:56) ~[org.wso2.choreo.connect.enforcer-1.2.0-beta2-SNAPSHOT.jar:1.2.0-beta2-SNAPSHOT] choreo-connect-with-apim-enforcer-1 | at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:?] choreo-connect-with-apim-enforcer-1 | at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:?] choreo-connect-with-apim-enforcer-1 | at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[?:?] choreo-connect-with-apim-enforcer-1 | at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[?:?] choreo-connect-with-apim-enforcer-1 | at java.lang.Thread.run(Unknown Source) ~[?:?] ### Steps to Reproduce Invoke a web socket API with Analytics. ### Version 1.2.0-beta ### Environment Details (with versions) _No response_ ### Relevant Log Output _No response_ ### Related Issues _No response_ ### Suggested Labels _No response_
afd6dd1235f9bd7d575fab3f8a7f46b1e850aa86
e17d35328a1dd471c910cbe7db125487f9315b16
https://github.com/wso2/product-microgateway/compare/afd6dd1235f9bd7d575fab3f8a7f46b1e850aa86...e17d35328a1dd471c910cbe7db125487f9315b16
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/ChoreoAnalyticsForWSProvider.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/ChoreoAnalyticsForWSProvider.java index 47255d5fd..260a51d15 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/ChoreoAnalyticsForWSProvider.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/ChoreoAnalyticsForWSProvider.java @@ -26,6 +26,7 @@ import org.wso2.carbon.apimgt.common.analytics.exceptions.DataNotFoundException; import org.wso2.carbon.apimgt.common.analytics.publishers.dto.API; import org.wso2.carbon.apimgt.common.analytics.publishers.dto.Application; import org.wso2.carbon.apimgt.common.analytics.publishers.dto.Error; +import org.wso2.carbon.apimgt.common.analytics.publishers.dto.ExtendedAPI; import org.wso2.carbon.apimgt.common.analytics.publishers.dto.Latencies; import org.wso2.carbon.apimgt.common.analytics.publishers.dto.MetaInfo; import org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation; @@ -102,19 +103,25 @@ public class ChoreoAnalyticsForWSProvider implements AnalyticsDataProvider { @Override public API getApi() throws DataNotFoundException { - API api = new API(); + ExtendedAPI api = new ExtendedAPI(); String apiVersion = extAuthMetadata.get(MetadataConstants.API_VERSION_KEY); String apiName = extAuthMetadata.get(MetadataConstants.API_NAME_KEY); String apiId = extAuthMetadata.get(MetadataConstants.API_ID_KEY); String apiCreator = extAuthMetadata.get(MetadataConstants.API_CREATOR_KEY); String apiCreatorTenantDomain = extAuthMetadata.get(MetadataConstants.API_CREATOR_TENANT_DOMAIN_KEY); + String apiContext = extAuthMetadata.get(MetadataConstants.API_CONTEXT_KEY); + String org = extAuthMetadata.get(MetadataConstants.API_ORGANIZATION_ID); + api.setApiType(APIConstants.ApiType.WEB_SOCKET); api.setApiId(apiId); api.setApiName(apiName); api.setApiVersion(apiVersion); api.setApiCreatorTenantDomain(apiCreatorTenantDomain); api.setApiCreator(apiCreator); + api.setOrganizationId(org); + api.setApiContext(apiContext); + return api; } diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/DefaultAnalyticsEventPublisher.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/DefaultAnalyticsEventPublisher.java index 6f9d1e6e8..f805f62f3 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/DefaultAnalyticsEventPublisher.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/DefaultAnalyticsEventPublisher.java @@ -150,12 +150,12 @@ public class DefaultAnalyticsEventPublisher implements AnalyticsEventPublisher { && logEntry.getResponse().getResponseCodeDetails() .equals(AnalyticsConstants.EXT_AUTH_DENIED_RESPONSE_DETAIL) // Token endpoint calls needs to be removed as well - || (AnalyticsConstants.TOKEN_ENDPOINT_PATH.equals(logEntry.getRequest().getOriginalPath())) + || (AnalyticsConstants.TOKEN_ENDPOINT_PATH.equals(logEntry.getCommonProperties().getRouteName())) // Health endpoint calls are not published - || (AnalyticsConstants.HEALTH_ENDPOINT_PATH.equals(logEntry.getRequest().getOriginalPath())) + || (AnalyticsConstants.HEALTH_ENDPOINT_PATH.equals(logEntry.getCommonProperties().getRouteName())) // already published websocket log entries should not be published to the analytics again. // JWKS endpoint calls should not be published - || (AnalyticsConstants.JWKS_ENDPOINT_PATH.equals(logEntry.getRequest().getOriginalPath())) + || (AnalyticsConstants.JWKS_ENDPOINT_PATH.equals(logEntry.getCommonProperties().getRouteName())) || alreadyPublishedWebsocketHttpLogEntry(logEntry); } diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/metrics/MetricsUtils.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/metrics/MetricsUtils.java index 0d04493f4..4ff5368eb 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/metrics/MetricsUtils.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/metrics/MetricsUtils.java @@ -60,9 +60,11 @@ public class MetricsUtils { && logEntry.getResponse().getResponseCodeDetails() .equals(AnalyticsConstants.EXT_AUTH_DENIED_RESPONSE_DETAIL) // Token endpoint calls needs to be removed as well - || (AnalyticsConstants.TOKEN_ENDPOINT_PATH.equals(logEntry.getRequest().getOriginalPath())) + || (AnalyticsConstants.TOKEN_ENDPOINT_PATH.equals(logEntry.getCommonProperties().getRouteName())) // Health endpoint calls are not published - || (AnalyticsConstants.HEALTH_ENDPOINT_PATH.equals(logEntry.getRequest().getOriginalPath()))) { + || (AnalyticsConstants.HEALTH_ENDPOINT_PATH.equals(logEntry.getCommonProperties().getRouteName())) + // JWKS endpoint calls should not be published + || (AnalyticsConstants.JWKS_ENDPOINT_PATH.equals(logEntry.getCommonProperties().getRouteName()))) { LOGGER.debug("Metric is ignored as it is already published by the enforcer."); publishMetrics(metricsExporter, latencies); continue;
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/metrics/MetricsUtils.java', 'enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/DefaultAnalyticsEventPublisher.java', 'enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/ChoreoAnalyticsForWSProvider.java']
{'.java': 3}
3
3
0
0
3
4,939,582
1,077,728
136,432
579
1,727
309
21
3
2,026
128
555
38
0
0
1970-01-01T00:27:58
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,111
wso2/product-microgateway/2778/2751
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/2751
https://github.com/wso2/product-microgateway/pull/2778
https://github.com/wso2/product-microgateway/pull/2778
1
fixes
The error response of the blocked subscription should be fixed
### Description: <!-- Describe the issue --> The response for an api with blocked subscription error description says Subscription validation failed. `{"error_message":"The requested API is temporarily blocked","code":"900907","error_description":"User is NOT authorized to access the Resource. API Subscription validation failed."} ` This should be fixed to show the correct cause of the failure which is Blocked subscription in this case. ### Steps to reproduce: ### Affected Product Version: <!-- Members can use Affected/*** labels --> ### Environment details (with versions): - OS: - Client: - Env (Docker/K8s): --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
3a79271720941f05dc8e1de1e519a29e0593c988
4ae96141ef9018df8576ce91142a2754dcef9424
https://github.com/wso2/product-microgateway/compare/3a79271720941f05dc8e1de1e519a29e0593c988...4ae96141ef9018df8576ce91142a2754dcef9424
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java index 38e4b1869..7f84fec42 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java @@ -70,7 +70,7 @@ public class FaultCodeClassifier { case APISecurityConstants.API_AUTH_INCORRECT_ACCESS_TOKEN_TYPE: case APISecurityConstants.INVALID_SCOPE: return FaultSubCategories.Authentication.AUTHORIZATION_FAILURE; - case APISecurityConstants.API_BLOCKED: + case APISecurityConstants.API_SUBSCRIPTION_BLOCKED: case APISecurityConstants.API_AUTH_FORBIDDEN: case APISecurityConstants.SUBSCRIPTION_INACTIVE: return FaultSubCategories.Authentication.SUBSCRIPTION_VALIDATION_FAILURE; diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java index 9134f0e77..68a9df526 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java @@ -53,8 +53,9 @@ public class APISecurityConstants { public static final String API_AUTH_INCORRECT_API_RESOURCE_DESCRIPTION = "Check the API documentation and add a " + "proper REST resource path to the invocation URL"; - public static final int API_BLOCKED = 900907; - public static final String API_BLOCKED_MESSAGE = "The requested API is temporarily blocked"; + public static final int API_SUBSCRIPTION_BLOCKED = 900907; + public static final String API_SUBSCRIPTION_BLOCKED_MESSAGE = "The requested API is temporarily blocked"; + public static final String API_SUBSCRIPTION_BLOCKED_DESCRIPTION = "API Subscription is blocked"; public static final int API_AUTH_FORBIDDEN = 900908; public static final String API_AUTH_FORBIDDEN_MESSAGE = "Resource forbidden "; @@ -116,8 +117,8 @@ public class APISecurityConstants { case API_AUTH_INCORRECT_ACCESS_TOKEN_TYPE: errorMessage = API_AUTH_INCORRECT_ACCESS_TOKEN_TYPE_MESSAGE; break; - case API_BLOCKED: - errorMessage = API_BLOCKED_MESSAGE; + case API_SUBSCRIPTION_BLOCKED: + errorMessage = API_SUBSCRIPTION_BLOCKED_MESSAGE; break; case API_AUTH_FORBIDDEN: errorMessage = API_AUTH_FORBIDDEN_MESSAGE; diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/APIKeyAuthenticator.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/APIKeyAuthenticator.java index aa0fb985d..8be3f6d97 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/APIKeyAuthenticator.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/APIKeyAuthenticator.java @@ -193,6 +193,15 @@ public class APIKeyAuthenticator extends APIKeyHandler { throw new APISecurityException(APIConstants.StatusCodes.SERVICE_UNAVAILABLE .getCode(), validationInfoDto.getValidationStatus(), GeneralErrorCodeConstants.API_BLOCKED_MESSAGE); + } else if (APISecurityConstants.API_SUBSCRIPTION_BLOCKED == validationInfoDto + .getValidationStatus()) { + requestContext.getProperties().put(APIConstants.MessageFormat.ERROR_MESSAGE, + APISecurityConstants.API_SUBSCRIPTION_BLOCKED_MESSAGE); + requestContext.getProperties().put(APIConstants.MessageFormat.ERROR_DESCRIPTION, + APISecurityConstants.API_SUBSCRIPTION_BLOCKED_DESCRIPTION); + throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED + .getCode(), validationInfoDto.getValidationStatus(), + APISecurityConstants.API_SUBSCRIPTION_BLOCKED_MESSAGE); } throw new APISecurityException(APIConstants.StatusCodes.UNAUTHORIZED.getCode(), validationInfoDto.getValidationStatus(), diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java index 265c67a27..215bc29b8 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java @@ -225,6 +225,15 @@ public class JWTAuthenticator implements Authenticator { throw new APISecurityException(APIConstants.StatusCodes.SERVICE_UNAVAILABLE .getCode(), apiKeyValidationInfoDTO.getValidationStatus(), GeneralErrorCodeConstants.API_BLOCKED_MESSAGE); + } else if (APISecurityConstants.API_SUBSCRIPTION_BLOCKED == apiKeyValidationInfoDTO + .getValidationStatus()) { + requestContext.getProperties().put(APIConstants.MessageFormat.ERROR_MESSAGE, + APISecurityConstants.API_SUBSCRIPTION_BLOCKED_MESSAGE); + requestContext.getProperties().put(APIConstants.MessageFormat.ERROR_DESCRIPTION, + APISecurityConstants.API_SUBSCRIPTION_BLOCKED_DESCRIPTION); + throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED + .getCode(), apiKeyValidationInfoDTO.getValidationStatus(), + APISecurityConstants.API_SUBSCRIPTION_BLOCKED_MESSAGE); } throw new APISecurityException(APIConstants.StatusCodes.UNAUTHORIZED.getCode(), apiKeyValidationInfoDTO.getValidationStatus(), @@ -273,7 +282,7 @@ public class JWTAuthenticator implements Authenticator { getJwtConfigurationDto(); if (backendJwtConfig.isEnabled()) { JWTInfoDto jwtInfoDto = FilterUtils.generateJWTInfoDto(null, validationInfo, - apiKeyValidationInfoDTO, requestContext); + apiKeyValidationInfoDTO, requestContext); endUserToken = BackendJwtUtils.generateAndRetrieveJWTToken(jwtGenerator, jwtTokenIdentifier, jwtInfoDto, isGatewayTokenCacheEnabled); // Set generated jwt token as a response header
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/APIKeyAuthenticator.java', 'enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java', 'enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java', 'enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java']
{'.java': 4}
4
4
0
0
4
4,518,284
986,945
125,780
522
2,663
388
31
4
878
117
171
29
0
0
1970-01-01T00:27:28
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,109
wso2/product-microgateway/2808/2771
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/2771
https://github.com/wso2/product-microgateway/pull/2808
https://github.com/wso2/product-microgateway/pull/2808
1
fixes
Error log for OPA policies with GET request when analytics enabled
### Description: Getting below error log for OPA policies when analytics enabled with a get request. ### Steps to reproduce: 1. Create an API with OPA policies added to a GET operation and deploy. 2. Enable analytics in Choreo-Connect 3. Invoke the API. 4. Below log appears in Choreo Connect. ``` choreo-connect-with-apim-enforcer-1 | [2022-03-23 07:19:02,728][4b0ba5db-a07b-4f62-bf6a-3af2283bcb68][OPA, example.com, /t/example.com/opa/1.0.0] ERROR - {org.wso2.choreo.connect.enforcer.interceptor.MediationPolicyFilter} - OPA validation failed for the request: /t/example.com/opa/1.0.0/* [severity:Minor error_code:6101] choreo-connect-with-apim-enforcer-1 | Mar 23, 2022 7:19:02 AM io.grpc.internal.SerializingExecutor run choreo-connect-with-apim-enforcer-1 | SEVERE: Exception while executing runnable io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$1HalfClosed@37eb4496 choreo-connect-with-apim-enforcer-1 | java.lang.NullPointerException choreo-connect-with-apim-enforcer-1 | at org.wso2.carbon.apimgt.common.analytics.collectors.impl.fault.AbstractFaultDataCollector.processRequest(AbstractFaultDataCollector.java:53) choreo-connect-with-apim-enforcer-1 | at org.wso2.carbon.apimgt.common.analytics.collectors.impl.fault.AuthFaultDataCollector.collectFaultData(AuthFaultDataCollector.java:51) choreo-connect-with-apim-enforcer-1 | at org.wso2.carbon.apimgt.common.analytics.collectors.impl.FaultyRequestDataCollector.collectData(FaultyRequestDataCollector.java:63) choreo-connect-with-apim-enforcer-1 | at org.wso2.carbon.apimgt.common.analytics.collectors.impl.GenericRequestDataCollector.collectData(GenericRequestDataCollector.java:49) choreo-connect-with-apim-enforcer-1 | at org.wso2.choreo.connect.enforcer.analytics.AnalyticsFilter.handleFailureRequest(AnalyticsFilter.java:214) choreo-connect-with-apim-enforcer-1 | at org.wso2.choreo.connect.enforcer.api.RestAPI.process(RestAPI.java:232) choreo-connect-with-apim-enforcer-1 | at org.wso2.choreo.connect.enforcer.server.HttpRequestHandler.process(HttpRequestHandler.java:64) choreo-connect-with-apim-enforcer-1 | at org.wso2.choreo.connect.enforcer.grpc.ExtAuthService.check(ExtAuthService.java:80) choreo-connect-with-apim-enforcer-1 | at io.envoyproxy.envoy.service.auth.v3.AuthorizationGrpc$MethodHandlers.invoke(AuthorizationGrpc.java:245) choreo-connect-with-apim-enforcer-1 | at io.grpc.stub.ServerCalls$UnaryServerCallHandler$UnaryServerCallListener.onHalfClose(ServerCalls.java:180) choreo-connect-with-apim-enforcer-1 | at io.grpc.PartialForwardingServerCallListener.onHalfClose(PartialForwardingServerCallListener.java:35) choreo-connect-with-apim-enforcer-1 | at io.grpc.ForwardingServerCallListener.onHalfClose(ForwardingServerCallListener.java:23) choreo-connect-with-apim-enforcer-1 | at io.grpc.ForwardingServerCallListener$SimpleForwardingServerCallListener.onHalfClose(ForwardingServerCallListener.java:40) choreo-connect-with-apim-enforcer-1 | at io.grpc.Contexts$ContextualizedServerCallListener.onHalfClose(Contexts.java:86) choreo-connect-with-apim-enforcer-1 | at io.grpc.internal.ServerCallImpl$ServerStreamListenerImpl.halfClosed(ServerCallImpl.java:331) choreo-connect-with-apim-enforcer-1 | at io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$1HalfClosed.runInContext(ServerImpl.java:814) choreo-connect-with-apim-enforcer-1 | at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) choreo-connect-with-apim-enforcer-1 | at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123) choreo-connect-with-apim-enforcer-1 | at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) choreo-connect-with-apim-enforcer-1 | at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) choreo-connect-with-apim-enforcer-1 | at java.base/java.lang.Thread.run(Unknown Source) choreo-connect-with-apim-enforcer-1 | ``` ### Affected Product Version: Chreo-Connect-1.1.0-alpha2 ### Environment details (with versions): - OS: - Client: - Env (Docker/K8s): --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
c93650af02df7b16f3c82c83022499229784182e
95b9a0bdc5ea7de22b432eaafc4560ac830ac5db
https://github.com/wso2/product-microgateway/compare/c93650af02df7b16f3c82c83022499229784182e...95b9a0bdc5ea7de22b432eaafc4560ac830ac5db
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java index 7f84fec42..4896a67ed 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java @@ -69,13 +69,14 @@ public class FaultCodeClassifier { return FaultSubCategories.Authentication.AUTHENTICATION_FAILURE; case APISecurityConstants.API_AUTH_INCORRECT_ACCESS_TOKEN_TYPE: case APISecurityConstants.INVALID_SCOPE: + case APISecurityConstants.OPA_AUTH_FORBIDDEN: return FaultSubCategories.Authentication.AUTHORIZATION_FAILURE; case APISecurityConstants.API_SUBSCRIPTION_BLOCKED: case APISecurityConstants.API_AUTH_FORBIDDEN: case APISecurityConstants.SUBSCRIPTION_INACTIVE: return FaultSubCategories.Authentication.SUBSCRIPTION_VALIDATION_FAILURE; default: - return FaultSubCategories.TargetConnectivity.OTHER; + return FaultSubCategories.Authentication.OTHER; } } @@ -123,6 +124,11 @@ public class FaultCodeClassifier { } public boolean isResourceNotFound() { + // isResourceNotFound is not used when logEntry is not null, since 404 related events are published based on + // logEntries (not based on requestContext) + if (logEntry == null) { + return false; + } ResponseFlags responseFlags = logEntry.getCommonProperties().getResponseFlags(); if (responseFlags == null) { return false;
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/analytics/FaultCodeClassifier.java']
{'.java': 1}
1
1
0
0
1
4,528,694
988,870
125,983
524
434
84
8
1
4,388
229
1,178
61
0
1
1970-01-01T00:27:28
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,106
wso2/product-microgateway/2991/2918
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/2918
https://github.com/wso2/product-microgateway/pull/2991
https://github.com/wso2/product-microgateway/pull/2991
1
fixes
Choreo Connect does not start in Windows 10 with Docker WSL
### Description: The enforcer fails systematically in Exited status, and reporting the following error : docker logs choreo-connect_enforcer_1 java.lang.IllegalArgumentException: Illegal base64 character a at java.base/java.util.Base64$Decoder.decode0(Unknown Source) at java.base/java.util.Base64$Decoder.decode(Unknown Source) at java.base/java.util.Base64$Decoder.decode(Unknown Source) at org.wso2.choreo.connect.enforcer.util.JWTUtils.getPrivateKey(JWTUtils.java:166) at org.wso2.choreo.connect.enforcer.util.FilterUtils.createClientKeyStore(FilterUtils.java:155) at org.wso2.choreo.connect.enforcer.config.ConfigHolder.loadOpaClientKeyStore(ConfigHolder.java:355) at org.wso2.choreo.connect.enforcer.config.ConfigHolder.<init>(ConfigHolder.java:110) at org.wso2.choreo.connect.enforcer.config.ConfigHolder.getInstance(ConfigHolder.java:118) at org.wso2.choreo.connect.enforcer.server.AuthServer.main(AuthServer.java:75) ### Steps to reproduce: ### Affected Product Version: <!-- Members can use Affected/*** labels --> ### Environment details (with versions): - OS: Windows/ Docker WSL - Client: - Env (Docker/K8s): --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
1e4cbfa18a346fefd023e025b85926095ca514a0
4ec162e288c2e00c7933574745ba9dfc294aea1c
https://github.com/wso2/product-microgateway/compare/1e4cbfa18a346fefd023e025b85926095ca514a0...4ec162e288c2e00c7933574745ba9dfc294aea1c
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java index 02808ca66..20cd8802e 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java @@ -154,10 +154,7 @@ public class JWTUtils { Path keyPath = Paths.get(filePath); String key = Files.readString(keyPath, Charset.defaultCharset()); String lineSeparator = System.lineSeparator(); - // Change the lineSeparator to \\r\\n if it runs on WSL - if (System.getProperty("os.version").toLowerCase().contains("wsl")) { - lineSeparator = "\\r\\n"; - } + strKeyPEM = key .replace(Constants.BEGINING_OF_PRIVATE_KEY, "") .replaceAll(lineSeparator, "")
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java']
{'.java': 1}
1
1
0
0
1
4,551,381
993,247
126,428
528
219
45
5
1
1,460
106
325
35
0
0
1970-01-01T00:27:37
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,102
wso2/product-microgateway/3090/3089
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/3089
https://github.com/wso2/product-microgateway/pull/3090
https://github.com/wso2/product-microgateway/pull/3090
1
fixes
Enforcer is not starting when key-store certs are created in a Windows environment
### Description Enforcer is not starting when key-store certs are created in a Microsoft environment. Enforcer running in a Linux container and it does not match the cert generator environment and runtime environment. The new line separator is `\\r\\n` when certs are generated in a Microsoft environment and Enforcer only accepts certs with the new line separator `\\n`. ### Steps to Reproduce 1. Create key-store certs in a Microsoft environment 2. Mount and configure key-store certs for Enforcer 3. Start the deployment ### Version 1.0.0 ### Environment Details (with versions) OS: Microsoft Windows ### Relevant Log Output ```shell Error log in Enforcer [2022-09-30 11:05:51,663][][] ERROR - {org.wso2.choreo.connect.enforcer.discovery.ConfigDiscoveryClient} - Error occurred during Config discovery [%errorDetails] java.lang.IllegalArgumentException: Illegal base64 character 2d at java.util.Base64$Decoder.decode0(Unknown Source) ~[?:?] at java.util.Base64$Decoder.decode(Unknown Source) ~[?:?] at java.util.Base64$Decoder.decode(Unknown Source) ~[?:?] at org.wso2.choreo.connect.enforcer.util.JWTUtils.getPrivateKey(JWTUtils.java:161) ~[org.wso2.choreo.connect.enforcer-1.0.0.jar:1.0.0] at org.wso2.choreo.connect.enforcer.config.ConfigHolder.populateJWTIssuerConfigurations(ConfigHolder.java:545) ~[org.wso2.choreo.connect.enforcer-1.0.0.jar:1.0.0] at org.wso2.choreo.connect.enforcer.config.ConfigHolder.parseConfigs(ConfigHolder.java:160) ~[org.wso2.choreo.connect.enforcer-1.0.0.jar:1.0.0] at org.wso2.choreo.connect.enforcer.config.ConfigHolder.load(ConfigHolder.java:125) ~[org.wso2.choreo.connect.enforcer-1.0.0.jar:1.0.0] at org.wso2.choreo.connect.enforcer.discovery.ConfigDiscoveryClient.requestInitConfig(ConfigDiscoveryClient.java:122) [org.wso2.choreo.connect.enforcer-1.0.0.jar:1.0.0] at org.wso2.choreo.connect.enforcer.discovery.ConfigDiscoveryClient.run(ConfigDiscoveryClient.java:138) [org.wso2.choreo.connect.enforcer-1.0.0.jar:1.0.0] at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:?] at java.util.concurrent.FutureTask.runAndReset(Unknown Source) [?:?] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) [?:?] at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:?] at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:?] at java.lang.Thread.run(Unknown Source) [?:?] ``` ### Related Issues _No response_ ### Suggested Labels _No response_
5ed0320dc50453f69f5886af61b22175c5d03c12
75a0f5116a63b405ed7fc8dc31e81eff4b42e987
https://github.com/wso2/product-microgateway/compare/5ed0320dc50453f69f5886af61b22175c5d03c12...75a0f5116a63b405ed7fc8dc31e81eff4b42e987
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java index 09f9232dc..c87f72528 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java @@ -161,11 +161,10 @@ public class JWTUtils { String strKeyPEM; Path keyPath = Paths.get(filePath); String key = Files.readString(keyPath, Charset.defaultCharset()); - String lineSeparator = System.lineSeparator(); - + strKeyPEM = key .replace(Constants.BEGINING_OF_PRIVATE_KEY, "") - .replaceAll(lineSeparator, "") + .replaceAll("\\n", "").replaceAll("\\r", "") // certs could be created in a Unix/Windows platform .replace(Constants.END_OF_PRIVATE_KEY, ""); byte[] encoded = Base64.getDecoder().decode(strKeyPEM);
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/util/JWTUtils.java']
{'.java': 1}
1
1
0
0
1
4,879,116
1,063,338
134,781
570
244
42
5
1
2,538
184
659
52
0
1
1970-01-01T00:27:44
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,100
wso2/product-microgateway/3117/3118
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/3118
https://github.com/wso2/product-microgateway/pull/3117
https://github.com/wso2/product-microgateway/pull/3117
1
fixes
Enable security for prototyped APIs
### Problem Currently authentication is not required for APIs with prototyped lifecyclestatus within choreo connect. Since prototyped lifecycle state is changed to PreRelease, we need to enable authentication for those APIs. ### Solution Currently auth filter is not engaged for prototyped APIs. We need to change that logic such that auth filter is engaged. ### Implementation _No response_ ### Related Issues _No response_ ### Suggested Labels _No response_
a0a74541c673903055656e4de55f762562e871a6
5065f20a52d7146c6639637f0ecdc71023311b34
https://github.com/wso2/product-microgateway/compare/a0a74541c673903055656e4de55f762562e871a6...5065f20a52d7146c6639637f0ecdc71023311b34
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java index 2db00c6ab..1c0347810 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java @@ -120,17 +120,6 @@ public class AuthFilter implements Filter { @Override public boolean handleRequest(RequestContext requestContext) { - - // It is required to skip the auth Filter if the lifecycle status is prototype - if (APIConstants.PROTOTYPED_LIFE_CYCLE_STATUS.equals( - requestContext.getMatchedAPI().getApiLifeCycleState())) { - // For prototyped endpoints, only the production endpoints could be available. - requestContext.addOrModifyHeaders(AdapterConstants.CLUSTER_HEADER, - requestContext.getProdClusterHeader()); - requestContext.getRemoveHeaders().remove(AdapterConstants.CLUSTER_HEADER); - return true; - } - boolean canAuthenticated = false; for (Authenticator authenticator : authenticators) { if (authenticator.canAuthenticate(requestContext)) { diff --git a/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/withapim/PrototypedAPITestCase.java b/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/withapim/PrototypedAPITestCase.java index 89571ad08..5d5f71f0e 100644 --- a/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/withapim/PrototypedAPITestCase.java +++ b/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/withapim/PrototypedAPITestCase.java @@ -25,7 +25,9 @@ import net.minidev.json.parser.JSONParser; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import org.wso2.am.integration.clients.publisher.api.ApiResponse; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO; +import org.wso2.am.integration.clients.publisher.api.v1.dto.APIKeyDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.WorkflowResponseDTO; import org.wso2.am.integration.test.utils.bean.APILifeCycleAction; import org.wso2.am.integration.test.utils.bean.APIRequest; @@ -83,7 +85,7 @@ public class PrototypedAPITestCase extends ApimBaseTest { } @Test(description = "Test to check the PrototypedAPI is working") - public void invokePrototypeAPISuccessTest() throws Exception { + public void invokePrototypeAPITest() throws Exception { // Set header Map<String, String> headers = new HashMap<>(); org.wso2.choreo.connect.tests.util.HttpResponse response = @@ -91,6 +93,14 @@ public class PrototypedAPITestCase extends ApimBaseTest { Utils.getServiceURLHttps("/petstore-prototype/1.0.0/pet/findByStatus"), headers); Assert.assertNotNull(response); + Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED,"Response code mismatched"); + ApiResponse<APIKeyDTO> internalApiKeyDTO = + publisherRestClient.generateInternalApiKey(apiId); + + String internalKey = internalApiKeyDTO.getData().getApikey(); + headers.put("apikey", internalKey); + response = HttpsClientRequest.doGet( + Utils.getServiceURLHttps("/petstore-prototype/1.0.0/pet/findByStatus"), headers); Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,"Response code mismatched"); } }
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java', 'integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/withapim/PrototypedAPITestCase.java']
{'.java': 2}
2
2
0
0
2
4,127,731
899,466
115,236
488
587
105
11
1
469
68
92
19
0
0
1970-01-01T00:27:46
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,099
wso2/product-microgateway/3131/3129
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/3129
https://github.com/wso2/product-microgateway/pull/3131
https://github.com/wso2/product-microgateway/pull/3131
1
fixes
JsonSyntaxException when invoking API in choreo-connect with API-M 4.1.0.36 access token
### Description The following error occurs when invoking an API with an API-M access token. ``` Oct 27, 2022 6:18:53 AM io.grpc.internal.SerializingExecutor run [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: SEVERE: Exception while executing runnable io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$1HalfClosed@558d1139 [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 600 ``` Choreo Connect 1.1.0 API Manager 4.1.0.36 (docker image) ### Steps to Reproduce 1. Deploy and publish an API to Choreo Connect via API-M 2. Create an access token from the Developer portal 3. Invoke the API ### Version 1.1.0 ### Environment Details (with versions) _No response_ ### Relevant Log Output ```shell [INFO] [main] ERROR org.wso2.choreo.connect.tests.testcases.withapim.ExistingApiTestCase - testExistingApiWithSandboxKey: FAILED -> Status code mismatched. Endpoint:https://localhost:9095/existing_api/1.0.0/pet/findByStatus HttpResponse expected [200] but found [500] [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: Oct 27, 2022 6:18:53 AM io.grpc.internal.SerializingExecutor run [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: SEVERE: Exception while executing runnable io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$1HalfClosed@558d1139 [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 600 path $. [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.Gson.fromJson(Gson.java:975) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.Gson.fromJson(Gson.java:928) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.Gson.fromJson(Gson.java:877) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.throttle.utils.ThrottleUtils.getJWTClaims(ThrottleUtils.java:154) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.throttle.ThrottleFilter.getProperties(ThrottleFilter.java:497) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.throttle.ThrottleFilter.getThrottleEventMap(ThrottleFilter.java:384) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.throttle.ThrottleFilter.handleEventPublish(ThrottleFilter.java:124) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.throttle.ThrottleFilter.handleRequest(ThrottleFilter.java:113) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.api.API.executeFilterChain(API.java:42) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.api.RestAPI.process(RestAPI.java:190) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.server.HttpRequestHandler.process(HttpRequestHandler.java:69) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at org.wso2.choreo.connect.enforcer.grpc.ExtAuthService.check(ExtAuthService.java:80) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.envoyproxy.envoy.service.auth.v3.AuthorizationGrpc$MethodHandlers.invoke(AuthorizationGrpc.java:245) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.stub.ServerCalls$UnaryServerCallHandler$UnaryServerCallListener.onHalfClose(ServerCalls.java:180) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.PartialForwardingServerCallListener.onHalfClose(PartialForwardingServerCallListener.java:35) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.ForwardingServerCallListener.onHalfClose(ForwardingServerCallListener.java:23) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.ForwardingServerCallListener$SimpleForwardingServerCallListener.onHalfClose(ForwardingServerCallListener.java:40) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.Contexts$ContextualizedServerCallListener.onHalfClose(Contexts.java:86) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.internal.ServerCallImpl$ServerStreamListenerImpl.halfClosed(ServerCallImpl.java:340) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$1HalfClosed.runInContext(ServerImpl.java:866) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at java.base/java.lang.Thread.run(Unknown Source) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 600 path $. [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.stream.JsonReader.nextString(JsonReader.java:824) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.internal.bind.TypeAdapters$15.read(TypeAdapters.java:380) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.internal.bind.TypeAdapters$15.read(TypeAdapters.java:368) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:187) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: at com.google.gson.Gson.fromJson(Gson.java:963) [INFO] [docker-java-stream--1732710743] INFO Enforcer - STDERR: ... 24 more ``` ### Related Issues _No response_ ### Suggested Labels _No response_
72bfecdc19bca4699b63af6c5448d450dc1bdb6b
ab44b18de90b35e2ea84a69ef8196745a7b67b70
https://github.com/wso2/product-microgateway/compare/72bfecdc19bca4699b63af6c5448d450dc1bdb6b...ab44b18de90b35e2ea84a69ef8196745a7b67b70
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleDataHolder.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleDataHolder.java index fcf7e635c..e72e145a4 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleDataHolder.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleDataHolder.java @@ -18,6 +18,7 @@ package org.wso2.choreo.connect.enforcer.throttle; +import net.minidev.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -365,7 +366,7 @@ public class ThrottleDataHolder { } if (conf.isJwtClaimConditionsEnabled() && (claimConditions != null && !claimConditions.getValues().isEmpty())) { - Map<String, String> c = ThrottleUtils.getJWTClaims(req.getAuthenticationContext().getCallerToken()); + JSONObject c = ThrottleUtils.getJWTClaims(req.getAuthenticationContext().getCallerToken()); if (c == null || !isJwtClaimPresent(c, claimConditions)) { isThrottled = false; } @@ -521,11 +522,11 @@ public class ThrottleDataHolder { return status; } - private boolean isJwtClaimPresent(Map<String, String> claims, ThrottleCondition.JWTClaimConditions conditions) { + private boolean isJwtClaimPresent(JSONObject claims, ThrottleCondition.JWTClaimConditions conditions) { boolean status = true; for (Map.Entry<String, String> jwtClaim : conditions.getValues().entrySet()) { - String value = claims.get(jwtClaim.getKey()); + String value = claims.getAsString(jwtClaim.getKey()); if (value == null) { status = false; break; diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java index 6c4711bd9..917778228 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java @@ -498,7 +498,7 @@ public class ThrottleFilter implements Filter { String callerToken = requestContext.getAuthenticationContext().getCallerToken(); if (config.isJwtClaimConditionsEnabled() && callerToken != null) { - Map<String, String> claims = ThrottleUtils.getJWTClaims(callerToken); + net.minidev.json.JSONObject claims = ThrottleUtils.getJWTClaims(callerToken); for (String key : claims.keySet()) { jsonObMap.put(key, claims.get(key)); } diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/utils/ThrottleUtils.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/utils/ThrottleUtils.java index d2c36d57d..2eea4c8d4 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/utils/ThrottleUtils.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/utils/ThrottleUtils.java @@ -19,23 +19,25 @@ package org.wso2.choreo.connect.enforcer.throttle.utils; import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.nimbusds.jose.util.JSONObjectUtils; import org.apache.commons.codec.binary.Base64; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; import org.wso2.choreo.connect.enforcer.commons.model.RequestContext; import org.wso2.choreo.connect.enforcer.throttle.PolicyConstants; import org.wso2.choreo.connect.enforcer.throttle.ThrottleConstants; +import org.wso2.choreo.connect.enforcer.throttle.ThrottleFilter; import org.wso2.choreo.connect.enforcer.throttle.dto.ThrottleCondition; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; +import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.Map; import java.util.TimeZone; import java.util.regex.Pattern; @@ -43,6 +45,9 @@ import java.util.regex.Pattern; * Utilities related to throttling. */ public class ThrottleUtils { + + private static final Logger log = LogManager.getLogger(ThrottleFilter.class); + /** * Extract a {@code ThrottleCondition} from a provided compatible base64 encoded string. * @@ -135,23 +140,30 @@ public class ThrottleUtils { } /** - * Parse a JWT and returns it's claims and a Map. + * Parse a JWT and return its claims. * * @param token JWT token to parse. - * @return Map of claims. + * @return JSONObject containing the claims. */ - public static Map<String, String> getJWTClaims(String token) { - if (token == null) { - return null; - } - - // decoding JWT - String[] jwtTokenArray = token.split(Pattern.quote(".")); - byte[] jwtByteArray = Base64.decodeBase64(jwtTokenArray[1].getBytes(StandardCharsets.UTF_8)); - String jwtAssertion = new String(jwtByteArray, StandardCharsets.UTF_8); - Type mapType = new TypeToken<Map<String, String>>() { }.getType(); + public static net.minidev.json.JSONObject getJWTClaims(String token) { + try { + if (token == null) { + return null; + } - return new Gson().fromJson(jwtAssertion, mapType); + // decoding JWT + String[] jwtTokenArray = token.split(Pattern.quote(".")); + byte[] jwtByteArray = Base64.decodeBase64(jwtTokenArray[1].getBytes(StandardCharsets.UTF_8)); + String jwtAssertion = new String(jwtByteArray, StandardCharsets.UTF_8); + net.minidev.json.JSONObject claims = JSONObjectUtils.parse(jwtAssertion); + return claims; + } catch (ParseException e) { + // This exception is supposed to be unreachable. + // JSONObjectUtils.parse() used above is used within SignedJWT.parse(accessToken) + // and therefore has already been used in the auth filters. + log.error("Error while parsing the JWT payload.", e); + throw new RuntimeException(e); + } } /** diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketThrottleFilter.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketThrottleFilter.java index c02759036..145d6300d 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketThrottleFilter.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketThrottleFilter.java @@ -284,7 +284,7 @@ public class WebSocketThrottleFilter implements Filter { String callerToken = requestContext.getAuthenticationContext().getCallerToken(); if (config.isJwtClaimConditionsEnabled() && callerToken != null) { - Map<String, String> claims = ThrottleUtils.getJWTClaims(callerToken); + net.minidev.json.JSONObject claims = ThrottleUtils.getJWTClaims(callerToken); for (String key : claims.keySet()) { jsonObMap.put(key, claims.get(key)); } diff --git a/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/standalone/jwtValidator/JwtTestCase.java b/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/standalone/jwtValidator/JwtTestCase.java index 90d2ceb03..142d0fd62 100644 --- a/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/standalone/jwtValidator/JwtTestCase.java +++ b/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/standalone/jwtValidator/JwtTestCase.java @@ -20,9 +20,12 @@ package org.wso2.choreo.connect.tests.testcases.standalone.jwtValidator; import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.HttpStatus; import io.netty.handler.codec.http.HttpHeaderNames; +import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; +import org.wso2.choreo.connect.tests.common.model.API; +import org.wso2.choreo.connect.tests.common.model.ApplicationDTO; import org.wso2.choreo.connect.tests.util.HttpResponse; import org.wso2.choreo.connect.tests.util.HttpsClientRequest; import org.wso2.choreo.connect.tests.util.TestConstant; @@ -141,4 +144,29 @@ public class JwtTestCase { Assert.assertTrue(response.getHeaders().containsKey("www-authenticate"), "\\"www-authenticate\\" is not available"); } + + @Test(description = "Test to check a JWT that contains an object as a claim") + public void invokeWithJwtContainingObjectClaimSuccessTest() throws Exception { + // Generate JWT with an object as a claim + JSONObject realm = new JSONObject(); + realm.put("signing_tenant", "carbon.super"); + + JSONObject specificClaims = new JSONObject(); + specificClaims.put("realm", realm); + API api = new API(); + ApplicationDTO application = new ApplicationDTO(); + String jwtWithObjectClaim = TokenUtil.getJWT(api, application, "Unlimited", + TestConstant.KEY_TYPE_PRODUCTION, 3600, specificClaims); + + // Set header + Map<String, String> headers = new HashMap<String, String>(); + headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + jwtWithObjectClaim); + HttpResponse response = HttpsClientRequest.doGet(Utils.getServiceURLHttps( + "/v2/standard/pet/2") , headers); + + Assert.assertNotNull(response); + Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,"Response code mismatched"); + Assert.assertFalse(response.getHeaders().containsKey("www-authenticate"), + "\\"www-authenticate\\" is available"); + } }
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java', 'enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleDataHolder.java', 'enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketThrottleFilter.java', 'enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/utils/ThrottleUtils.java', 'integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testcases/standalone/jwtValidator/JwtTestCase.java']
{'.java': 5}
5
5
0
0
5
4,887,142
1,065,380
135,052
574
3,075
621
55
4
6,888
471
1,824
78
1
2
1970-01-01T00:27:47
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,112
wso2/product-microgateway/2764/2765
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/2765
https://github.com/wso2/product-microgateway/pull/2764
https://github.com/wso2/product-microgateway/pull/2764
1
fixes
[websocket] Send only the payload of a single frame at a time from enforcer to router
### Describe your problem(s) - We decode the batched of frames at enforcer side to get the exact count of frames - Thereafter, for each separate frame, we send a `WebSocketFrameResponse` back to the router - In the `WebSocketFrameResponse` object, although the payload size is updated for a single frame, the payload itself is still the same as the batch of frames. ### Describe your solution The payload must also be set to suit the frame that belongs to the iteration of the loop. ### How will you implement it <!-- If you like to suggest an approach or a design --> --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
15193b2e2e2a1074e04bfffdc6d863ee80218440
1f3027b8e98130f273f63c9dd6719d71f759dcd2
https://github.com/wso2/product-microgateway/compare/15193b2e2e2a1074e04bfffdc6d863ee80218440...1f3027b8e98130f273f63c9dd6719d71f759dcd2
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketResponseObserver.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketResponseObserver.java index a641efb95..f40e6f44c 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketResponseObserver.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketResponseObserver.java @@ -17,6 +17,7 @@ */ package org.wso2.choreo.connect.enforcer.websocket; +import com.google.protobuf.ByteString; import io.grpc.stub.StreamObserver; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -78,7 +79,9 @@ public class WebSocketResponseObserver implements StreamObserver<WebSocketFrameR if (framedata.getOpcode() == Opcode.TEXT || framedata.getOpcode() == Opcode.BINARY || framedata.getOpcode() == Opcode.CONTINUOUS) { WebSocketFrameRequest webSocketFrameRequestClone = webSocketFrameRequest.toBuilder() - .setFrameLength(framedata.getPayloadData().remaining()).build(); + .setFrameLength(framedata.getPayloadData().remaining()) + .setPayload(ByteString.copyFrom(framedata.getPayloadData())) + .build(); sendWebSocketFrameResponse(webSocketFrameRequestClone); } else { logger.debug("Websocket frame type not related to throttling: {}", framedata.getOpcode());
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/websocket/WebSocketResponseObserver.java']
{'.java': 1}
1
1
0
0
1
4,516,028
986,535
125,737
522
347
55
5
1
822
134
176
22
0
0
1970-01-01T00:27:28
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,114
wso2/product-microgateway/2637/2638
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/2638
https://github.com/wso2/product-microgateway/pull/2637
https://github.com/wso2/product-microgateway/pull/2637
1
fixes
Rename header operation policy
### Description: <!-- Describe the issue --> current implementation of rename_header written as equal to set_header policy. but rename_header has a different attribute list and it should be renaming the header name, not just updating the header value. ### Steps to reproduce: ### Affected Product Version: <!-- Members can use Affected/*** labels --> ### Environment details (with versions): - OS: - Client: - Env (Docker/K8s): --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
8f56cf366a928de81919c9b1a5505919e6457dfb
5ba7a8ad13d113176b102c2ccaa5cee5beb10080
https://github.com/wso2/product-microgateway/compare/8f56cf366a928de81919c9b1a5505919e6457dfb...5ba7a8ad13d113176b102c2ccaa5cee5beb10080
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/interceptor/MediationPolicyFilter.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/interceptor/MediationPolicyFilter.java index e08c8e3cd..51c67f2bf 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/interceptor/MediationPolicyFilter.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/interceptor/MediationPolicyFilter.java @@ -48,11 +48,14 @@ public class MediationPolicyFilter implements Filter { private void applyPolicy(RequestContext requestContext, Policy policy) { //todo(amali) check policy order switch (policy.getTemplateName()) { - case "SET_HEADER": - case "RENAME_HEADER": { + case "SET_HEADER": { addOrModifyHeader(requestContext, policy.getParameters()); break; } + case "RENAME_HEADER": { + renameHeader(requestContext, policy.getParameters()); + break; + } case "REMOVE_HEADER": { removeHeader(requestContext, policy.getParameters()); break; @@ -82,6 +85,16 @@ public class MediationPolicyFilter implements Filter { requestContext.addOrModifyHeaders(headerName, headerValue); } + private void renameHeader(RequestContext requestContext, Map<String, String> policyAttrib) { + String currentHeaderName = policyAttrib.get("currentHeaderName"); + String updatedHeaderValue = policyAttrib.get("updatedHeaderName"); + if (requestContext.getHeaders().containsKey(currentHeaderName)) { + String headerValue = requestContext.getHeaders().get(currentHeaderName); + requestContext.getRemoveHeaders().add(currentHeaderName); + requestContext.addOrModifyHeaders(updatedHeaderValue, headerValue); + } + } + private void removeHeader(RequestContext requestContext, Map<String, String> policyAttrib) { String headerName = policyAttrib.get("headerName"); requestContext.getRemoveHeaders().add(headerName);
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/interceptor/MediationPolicyFilter.java']
{'.java': 1}
1
1
0
0
1
4,226,377
922,775
118,088
492
831
149
17
1
685
97
137
26
0
0
1970-01-01T00:27:23
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,140
wso2/product-microgateway/1869/1713
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/1713
https://github.com/wso2/product-microgateway/pull/1869
https://github.com/wso2/product-microgateway/pull/1869
1
fixes
Add www-authenticate header to the authentication failed responses
### Describe your problem(s) $subject. ### Describe your solution <!-- Describe the feature/improvement --> ### How will you implement it <!-- If you like to suggest an approach or a design --> --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
b49d747dd1420e28e8044511fdff7b2b8a92d66f
231b93cb844e2bc1d0358857307a16544b00f8dc
https://github.com/wso2/product-microgateway/compare/b49d747dd1420e28e8044511fdff7b2b8a92d66f...231b93cb844e2bc1d0358857307a16544b00f8dc
diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APIConstants.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APIConstants.java index 0f6fc723d..2ae145572 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APIConstants.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APIConstants.java @@ -61,6 +61,7 @@ public class APIConstants { public static final String API_SECURITY_API_KEY = "api_key"; public static final String API_SECURITY_MUTUAL_SSL_MANDATORY = "mutualssl_mandatory"; public static final String API_SECURITY_OAUTH_BASIC_AUTH_API_KEY_MANDATORY = "oauth_basic_auth_api_key_mandatory"; + public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; public static final String BEGIN_CERTIFICATE_STRING = "-----BEGIN CERTIFICATE-----\\n"; public static final String END_CERTIFICATE_STRING = "-----END CERTIFICATE-----"; diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java index 933735907..e667d34d9 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java @@ -111,6 +111,10 @@ public class AuthFilter implements Filter { if (!canAuthenticated) { FilterUtils.setUnauthenticatedErrorToContext(requestContext); } + //set WWW_AUTHENTICATE header to error response + requestContext.addResponseHeaders(APIConstants.WWW_AUTHENTICATE, getAuthenticatorsChallengeString() + + ", error=\\"invalid_token\\"" + + ", error_description=\\"The provided token is invalid\\""); return false; } @@ -187,4 +191,14 @@ public class AuthFilter implements Filter { } } } + + private String getAuthenticatorsChallengeString() { + StringBuilder challengeString = new StringBuilder(); + if (authenticators != null) { + for (Authenticator authenticator : authenticators) { + challengeString.append(authenticator.getChallengeString()).append(" "); + } + } + return challengeString.toString().trim(); + } } diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/Authenticator.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/Authenticator.java index 0cccbddc7..f39fa2219 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/Authenticator.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/Authenticator.java @@ -30,5 +30,14 @@ public interface Authenticator { AuthenticationContext authenticate(RequestContext requestContext) throws APISecurityException; + /** + * Returns a string representation of the authentication challenge imposed by this + * authenticator. In case of an authentication failure this value will be sent back + * to the API consumer in the form of a WWW-Authenticate header. + * + * @return A string representation of the authentication challenge + */ + String getChallengeString(); + int getPriority(); } diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/InternalAPIKeyAuthenticator.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/InternalAPIKeyAuthenticator.java index 5feafb9d2..412f58fa6 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/InternalAPIKeyAuthenticator.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/InternalAPIKeyAuthenticator.java @@ -191,6 +191,11 @@ public class InternalAPIKeyAuthenticator implements Authenticator { APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE); } + @Override + public String getChallengeString() { + return ""; + } + public static JSONObject validateAPISubscription(String apiContext, String apiVersion, JWTClaimsSet payload, String[] splitToken, boolean isOauth) throws APISecurityException { diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java index 38ea1b06c..45f81601d 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java @@ -211,6 +211,11 @@ public class JWTAuthenticator implements Authenticator { } + @Override + public String getChallengeString() { + return "Bearer realm=\\"Choreo Connect\\""; + } + private String retrieveAuthHeaderValue(RequestContext requestContext) { Map<String, String> headers = requestContext.getHeaders(); String authHeader = requestContext.getMatchedAPI().getAPIConfig().getAuthHeader().toLowerCase(); diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/UnsecuredAPIAuthenticator.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/UnsecuredAPIAuthenticator.java index b846b7e6e..40c801c78 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/UnsecuredAPIAuthenticator.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/UnsecuredAPIAuthenticator.java @@ -44,6 +44,11 @@ public class UnsecuredAPIAuthenticator implements Authenticator { return FilterUtils.generateAuthenticationContext(requestContext); } + @Override + public String getChallengeString() { + return ""; + } + @Override public int getPriority() { return -20; } diff --git a/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java b/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java index d162dcf63..f6847b46b 100644 --- a/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java +++ b/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java @@ -65,6 +65,8 @@ public class JwtTestCase { Assert.assertNotNull(response); Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,"Response code mismatched"); + Assert.assertFalse(response.getHeaders().containsKey("www-authenticate"), + "\\"www-authenticate\\" is available"); } @Test(description = "Test to check the JWT auth validate invalida signature token") @@ -78,6 +80,8 @@ public class JwtTestCase { Assert.assertNotNull(response); Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED, "Response code mismatched"); + Assert.assertTrue(response.getHeaders().containsKey("www-authenticate"), + "\\"www-authenticate\\" is not available"); } @Test(description = "Test to check the JWT auth validate expired token") @@ -92,5 +96,7 @@ public class JwtTestCase { Assert.assertNotNull(response); Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED, "Response code mismatched"); + Assert.assertTrue(response.getHeaders().containsKey("www-authenticate"), + "\\"www-authenticate\\" is not available"); } }
['integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/Authenticator.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APIConstants.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/UnsecuredAPIAuthenticator.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/InternalAPIKeyAuthenticator.java']
{'.java': 7}
7
7
0
0
7
3,131,848
687,512
87,974
342
1,424
271
39
6
444
64
91
20
0
0
1970-01-01T00:26:57
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,142
wso2/product-microgateway/1846/1847
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/1847
https://github.com/wso2/product-microgateway/pull/1846
https://github.com/wso2/product-microgateway/pull/1846
1
fixes
Token validation is successful with malformed Authorization header
### Description: Token validation is successful in the following scenarios. 1. Authorization: <TOKEN> 2. Authorization: Bearer <TOKEN> 3. Authorization: something <TOKEN> This behaviour is a bug since the correct Authorization header format is not honoured. ### Steps to reproduce: ### Affected Product Version: <!-- Members can use Affected/*** labels --> ### Environment details (with versions): - OS: - Client: - Env (Docker/K8s): --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
94b1cd8cf31011429d8d1e336f3f6a4412850b10
7a38cc0ff5be17ddbf51d58c139041ab607c8b58
https://github.com/wso2/product-microgateway/compare/94b1cd8cf31011429d8d1e336f3f6a4412850b10...7a38cc0ff5be17ddbf51d58c139041ab607c8b58
diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java index 94d4c96e5..c3b06d008 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java @@ -34,7 +34,7 @@ public class APISecurityConstants { public static final int API_AUTH_MISSING_CREDENTIALS = 900902; public static final String API_AUTH_MISSING_CREDENTIALS_MESSAGE = "Missing Credentials"; public static final String API_AUTH_MISSING_CREDENTIALS_DESCRIPTION = "Make sure your API invocation call " - + "has a header: "; + + "has a header: Authorization: Bearer ACCESS_TOKEN"; public static final int API_AUTH_ACCESS_TOKEN_EXPIRED = 900903; public static final String API_AUTH_ACCESS_TOKEN_EXPIRED_MESSAGE = "Access Token Expired"; diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java index 640fa3ecd..125763080 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java @@ -86,7 +86,11 @@ public class JWTAuthenticator implements Authenticator { @Override public AuthenticationContext authenticate(RequestContext requestContext) throws APISecurityException { String jwtToken = retrieveAuthHeaderValue(requestContext); - String splitToken[] = jwtToken.split("\\\\s"); + if (jwtToken == null || !jwtToken.toLowerCase().contains(JWTConstants.BEARER)) { + throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED.getCode(), + APISecurityConstants.API_AUTH_MISSING_CREDENTIALS, "Missing Credentials"); + } + String[] splitToken = jwtToken.split("\\\\s"); // Extract the token when it is sent as bearer token. i.e Authorization: Bearer <token> if (splitToken.length > 1) { jwtToken = splitToken[1]; diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/validator/JWTConstants.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/validator/JWTConstants.java index 138f85b34..a2e3f1923 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/validator/JWTConstants.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/validator/JWTConstants.java @@ -24,6 +24,7 @@ package org.wso2.choreo.connect.enforcer.security.jwt.validator; public class JWTConstants { public static final String AUTHORIZATION = "authorization"; public static final String RSA = "RSA"; + public static final String BEARER = "bearer"; public static final String UNAVAILABLE = "Token is not available in cache"; public static final String VALID = "valid"; public static final String INVALID = "invalid"; diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/oauth/OAuthAuthenticator.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/oauth/OAuthAuthenticator.java index 5cbdcf2ae..5e2ea1662 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/oauth/OAuthAuthenticator.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/oauth/OAuthAuthenticator.java @@ -31,6 +31,9 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.wso2.choreo.connect.enforcer.api.RequestContext; +import org.wso2.choreo.connect.enforcer.constants.APIConstants; +import org.wso2.choreo.connect.enforcer.constants.APISecurityConstants; +import org.wso2.choreo.connect.enforcer.exception.APISecurityException; import org.wso2.choreo.connect.enforcer.security.AccessTokenInfo; import org.wso2.choreo.connect.enforcer.security.AuthenticationContext; import org.wso2.choreo.connect.enforcer.security.Authenticator; @@ -91,13 +94,15 @@ public class OAuthAuthenticator implements Authenticator { } @Override - public AuthenticationContext authenticate(RequestContext requestContext) { + public AuthenticationContext authenticate(RequestContext requestContext) throws APISecurityException { String token = requestContext.getHeaders().get("authorization"); AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); - if (token.toLowerCase().contains("bearer")) { - token = token.split("\\\\s")[1]; + if (token == null || !token.toLowerCase().contains("bearer")) { + throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED.getCode(), + APISecurityConstants.API_AUTH_MISSING_CREDENTIALS, "Missing Credentials"); } + token = token.split("\\\\s")[1]; try { IntrospectInfo introspectInfo = validateToken(token); diff --git a/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java b/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java index d162dcf63..1be3210ac 100644 --- a/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java +++ b/integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java @@ -80,6 +80,19 @@ public class JwtTestCase { Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED, "Response code mismatched"); } + @Test(description = "Test to check the invalid authorization header format") + public void invokeJWTHeaderInvalidAuthorizationHeader() throws Exception { + + // Set header + Map<String, String> headers = new HashMap<String, String>(); + headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Something " + TestConstant.INVALID_JWT_TOKEN); + HttpResponse response = HttpsClientRequest.doGet(Utils.getServiceURLHttps( + "/v2/pet/2") , headers); + + Assert.assertNotNull(response); + Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED, "Response code mismatched"); + } + @Test(description = "Test to check the JWT auth validate expired token") public void invokeJWTHeaderExpiredTokenTest() throws Exception {
['integration/test-integration/src/test/java/org/wso2/choreo/connect/tests/testCases/jwtValidator/JwtTestCase.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/constants/APISecurityConstants.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/oauth/OAuthAuthenticator.java', 'enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/validator/JWTConstants.java']
{'.java': 5}
5
5
0
0
5
3,126,656
686,607
87,890
342
1,351
271
20
4
697
94
143
30
0
0
1970-01-01T00:26:57
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,143
wso2/product-microgateway/1836/1829
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/1829
https://github.com/wso2/product-microgateway/pull/1836
https://github.com/wso2/product-microgateway/pull/1836
1
fixes
Array Index Out of Bounds Error when Jwt transformer is enabled in test cases.
### Description: Following error case is visible within logs. ``` docker-java-stream-1975420695] INFO Enforcer - STDOUT: [2021-04-05 18:39:21,153] ERROR - JWTAuthenticator Error while getting token from the cache [docker-java-stream-1975420695] INFO Enforcer - STDOUT: java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 [docker-java-stream-1975420695] INFO Enforcer - STDOUT: at org.wso2.micro.gateway.enforcer.security.jwt.JWTAuthenticator.generateAndRetrieveJWTToken(JWTAuthenticator.java:248) [org.wso2.micro.gateway.enforcer-4.0.0-m10-SNAPSHOT.jar:4.0.0-m10-SNAPSHOT] [docker-java-stream-1975420695] INFO Enforcer - STDOUT: at org.wso2.micro.gateway.enforcer.security.jwt.JWTAuthenticator.authenticate(JWTAuthenticator.java:189) [org.wso2.micro.gateway.enforcer-4.0.0-m10-SNAPSHOT.jar:4.0.0-m10-SNAPSHOT] [docker-java-stream-1975420695] INFO Enforcer - STDOUT: at org.wso2.micro.gateway.enforcer.security.AuthFilter.authenticate(AuthFilter.java:119) [org.wso2.micro.gateway.enforcer-4.0.0-m10-SNAPSHOT.jar:4.0.0-m10-SNAPSHOT] [docker-java-stream-1975420695] INFO Enforcer - STDOUT: at org.wso2.micro.gateway.enforcer.security.AuthFilter.handleRequest(AuthFilter.java:105) [org.wso2.micro.gateway.enforcer-4.0.0-m10-SNAPSHOT.jar:4.0.0-m10-SNAPSHOT] [docker-java-stream-1975420695 ``` ### Steps to reproduce: Run integration tests for JWT Transformer and CustomJWTTransformer ### Affected Product Version: 4.0.0-m10 ### Environment details (with versions): - OS: MacOS big sur - Client: - Env (Docker/K8s): --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
e3347584fff3f05f657a773f92accb86508a673f
8aaa5e16916b04fa99e26784f7c1ca855d5dfe5c
https://github.com/wso2/product-microgateway/compare/e3347584fff3f05f657a773f92accb86508a673f...8aaa5e16916b04fa99e26784f7c1ca855d5dfe5c
diff --git a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java index 38ea1b06c..640fa3ecd 100644 --- a/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java +++ b/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java @@ -48,6 +48,7 @@ import org.wso2.choreo.connect.enforcer.exception.MGWException; import org.wso2.choreo.connect.enforcer.security.AuthenticationContext; import org.wso2.choreo.connect.enforcer.security.Authenticator; import org.wso2.choreo.connect.enforcer.security.TokenValidationContext; +import org.wso2.choreo.connect.enforcer.security.jwt.validator.JWTConstants; import org.wso2.choreo.connect.enforcer.security.jwt.validator.JWTValidator; import org.wso2.choreo.connect.enforcer.security.jwt.validator.RevokedJWTDataHolder; import org.wso2.choreo.connect.enforcer.util.FilterUtils; @@ -242,7 +243,7 @@ public class JWTAuthenticator implements Authenticator { if (isGatewayTokenCacheEnabled) { try { Object token = CacheProvider.getGatewayJWTTokenCache().get(jwtTokenCacheKey); - if (token != null) { + if (token != null && !JWTConstants.UNAVAILABLE.equals(token)) { endUserToken = (String) token; String[] splitToken = ((String) token).split("\\\\."); org.json.JSONObject payload = new org.json.JSONObject(new String(Base64.getUrlDecoder().
['enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java']
{'.java': 1}
1
1
0
0
1
3,124,136
686,119
87,845
342
204
41
3
1
1,836
139
497
36
0
1
1970-01-01T00:26:57
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,115
wso2/product-microgateway/2577/2578
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/2578
https://github.com/wso2/product-microgateway/pull/2577
https://github.com/wso2/product-microgateway/pull/2577
1
fixes
UserId based deny policies are not working with InternalKey
### Description: If the deny policy is using UserID, it won't be enforced properly as the userID is not populated correctly. ### Steps to reproduce: Deploy an API. Create a deny policy for the user `[email protected]`. Use InternalKey to invoke. ### Affected Product Version: choreo-connect-1.0.0-rc1 ### Environment details (with versions): - OS: - Client: - Env (Docker/K8s): --- ### Optional Fields #### Related Issues: <!-- Any related issues from this/other repositories--> #### Suggested Labels: <!--Only to be used by non-members--> #### Suggested Assignees: <!--Only to be used by non-members-->
b8f16b655b6ef6e475f8a6bd4fe76808be0ba2de
2263f9302222b012f0c91cb9347aa16a27e963d6
https://github.com/wso2/product-microgateway/compare/b8f16b655b6ef6e475f8a6bd4fe76808be0ba2de...2263f9302222b012f0c91cb9347aa16a27e963d6
diff --git a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java index a006c434e..5431fe990 100644 --- a/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java +++ b/enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java @@ -132,7 +132,10 @@ public class ThrottleFilter implements Filter { String appTenant = authContext.getSubscriberTenantDomain(); String clientIp = reqContext.getClientIp(); String apiTenantDomain = FilterUtils.getTenantDomainFromRequestURL(apiContext); - String authorizedUser = FilterUtils.buildUsernameWithTenant(authContext.getUsername(), appTenant); + // API Tenant Domain is required to be taken in order to support internal Key scenario. + // Using apiTenant is valid as the choreo connect does not work in multi-tenant mode. + String authorizedUser = FilterUtils.buildUsernameWithTenant(authContext.getUsername(), + apiTenantDomain); boolean isApiLevelTriggered = false; if (!StringUtils.isEmpty(api.getTier())) { @@ -290,7 +293,9 @@ public class ThrottleFilter implements Filter { String apiTier = getApiTier(api); String tenantDomain = FilterUtils.getTenantDomainFromRequestURL(apiContext); String appTenant = authContext.getSubscriberTenantDomain(); - String authorizedUser = FilterUtils.buildUsernameWithTenant(authContext.getUsername(), appTenant); + // API Tenant Domain is required to be taken in order to support internal Key scenario. + // Using apiTenant is valid as the choreo connect does not work in multi-tenant mode. + String authorizedUser = FilterUtils.buildUsernameWithTenant(authContext.getUsername(), tenantDomain); String resourceTier; String resourceKey;
['enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/throttle/ThrottleFilter.java']
{'.java': 1}
1
1
0
0
1
4,107,223
895,149
114,646
485
881
152
9
1
637
89
146
27
0
0
1970-01-01T00:27:19
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0
1,145
wso2/product-microgateway/1768/1767
wso2
product-microgateway
https://github.com/wso2/product-microgateway/issues/1767
https://github.com/wso2/product-microgateway/pull/1768
https://github.com/wso2/product-microgateway/pull/1768
1
fixes
Throttle eventpublisher password is not resolved from ENV vars
### Description: <!-- Describe the issue --> Throttle publisher password in the config is not resolve from env vars when configured that way. ### Steps to reproduce: - enable throttling and configure publisher password similar to below. - start enforcer and check the errors. it says invalid username password when connecting to TM ```toml [enforcer.throttling.publisher] # Credentials required to establish connection between Traffic Manager username = "admin" password = "$env{cp_admin_pwd}" ``` ### Affected Product Version: <!-- Members can use Affected/*** labels --> 4.0.0-m10-snapshot ### Environment details (with versions): - OS: Mac - Client: - Env (Docker/K8s):
0496eb3bdeab13db7d7c2b00d4ffcf7fad35e7b7
0feb6c772c43eb119952b5f5aea48661f58b469d
https://github.com/wso2/product-microgateway/compare/0496eb3bdeab13db7d7c2b00d4ffcf7fad35e7b7...0feb6c772c43eb119952b5f5aea48661f58b469d
diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java index 2872e7c65..2aba559ef 100644 --- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java +++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java @@ -46,13 +46,13 @@ import org.wso2.micro.gateway.enforcer.config.dto.ExtendedTokenIssuerDto; import org.wso2.micro.gateway.enforcer.config.dto.JWTIssuerConfigurationDto; import org.wso2.micro.gateway.enforcer.config.dto.ThrottleAgentConfigDto; import org.wso2.micro.gateway.enforcer.config.dto.ThrottleConfigDto; +import org.wso2.micro.gateway.enforcer.config.dto.ThrottlePublisherConfigDto; import org.wso2.micro.gateway.enforcer.constants.Constants; import org.wso2.micro.gateway.enforcer.discovery.ConfigDiscoveryClient; import org.wso2.micro.gateway.enforcer.exception.DiscoveryException; import org.wso2.micro.gateway.enforcer.exception.MGWException; import org.wso2.micro.gateway.enforcer.security.jwt.JWTUtil; import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.conf.AgentConfiguration; -import org.wso2.micro.gateway.enforcer.throttle.databridge.publisher.PublisherConfiguration; import org.wso2.micro.gateway.enforcer.util.TLSUtils; import java.io.IOException; @@ -257,7 +257,7 @@ public class ConfigHolder { agentConf.setTrustStore(trustStore); PublisherPool pool = binary.getPool(); - PublisherConfiguration pubConf = PublisherConfiguration.getInstance(); + ThrottlePublisherConfigDto pubConf = new ThrottlePublisherConfigDto(); pubConf.setUserName(binary.getUsername()); pubConf.setPassword(binary.getPassword()); pubConf.setInitIdleObjectDataPublishingAgents(pool.getInitIdleObjectDataPublishingAgents()); @@ -301,7 +301,7 @@ public class ConfigHolder { * such that to make them compatible with the binary agent. */ private void processTMPublisherURLGroup(List<TMURLGroup> urlGroups, - PublisherConfiguration pubConfiguration) { + ThrottlePublisherConfigDto pubConfiguration) { StringBuilder restructuredReceiverURL = new StringBuilder(); StringBuilder restructuredAuthURL = new StringBuilder(); diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleAgentConfigDto.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleAgentConfigDto.java index 0b54b8244..2eb15770e 100644 --- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleAgentConfigDto.java +++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleAgentConfigDto.java @@ -19,7 +19,6 @@ package org.wso2.micro.gateway.enforcer.config.dto; import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.conf.AgentConfiguration; -import org.wso2.micro.gateway.enforcer.throttle.databridge.publisher.PublisherConfiguration; import java.util.ArrayList; import java.util.List; @@ -31,7 +30,7 @@ public class ThrottleAgentConfigDto { String username; String password; List<ThrottleURLGroupDto> urlGroup = new ArrayList<>(); - PublisherConfiguration publisher; + ThrottlePublisherConfigDto publisher; AgentConfiguration agent; public String getUsername() { @@ -58,11 +57,11 @@ public class ThrottleAgentConfigDto { this.urlGroup = urlGroup; } - public PublisherConfiguration getPublisher() { + public ThrottlePublisherConfigDto getPublisher() { return publisher; } - public void setPublisher(PublisherConfiguration publisher) { + public void setPublisher(ThrottlePublisherConfigDto publisher) { this.publisher = publisher; } diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/PublisherConfiguration.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottlePublisherConfigDto.java similarity index 89% rename from enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/PublisherConfiguration.java rename to enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottlePublisherConfigDto.java index 6519173a1..793450fcb 100644 --- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/PublisherConfiguration.java +++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottlePublisherConfigDto.java @@ -16,18 +16,19 @@ * under the License. */ -package org.wso2.micro.gateway.enforcer.throttle.databridge.publisher; +package org.wso2.micro.gateway.enforcer.config.dto; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.wso2.micro.gateway.enforcer.throttle.databridge.publisher.DataPublisherConstants; import java.util.Map; /** * This class holds the configurations related to binary data publisher. */ -public class PublisherConfiguration { - private static final Logger log = LogManager.getLogger(PublisherConfiguration.class); +public class ThrottlePublisherConfigDto { + private static final Logger log = LogManager.getLogger(ThrottlePublisherConfigDto.class); private int maxIdleDataPublishingAgents; private int initIdleObjectDataPublishingAgents; @@ -40,11 +41,6 @@ public class PublisherConfiguration { private String userName; private char[] password; - private static PublisherConfiguration instance = new PublisherConfiguration(); - - private PublisherConfiguration() { - } - public void setMaxIdleDataPublishingAgents(int maxIdleDataPublishingAgents) { this.maxIdleDataPublishingAgents = maxIdleDataPublishingAgents; } @@ -117,14 +113,6 @@ public class PublisherConfiguration { return String.valueOf(password); } - public static PublisherConfiguration getInstance() { - return instance; - } - - public static synchronized void setInstance(PublisherConfiguration publisherConfiguration) { - instance = publisherConfiguration; - } - public void setConfiguration(Map<String, Object> publisherConfiguration) { this.receiverUrlGroup = String.valueOf(publisherConfiguration.get(DataPublisherConstants.RECEIVER_URL_GROUP)); this.authUrlGroup = String.valueOf(publisherConfiguration.get(DataPublisherConstants.AUTH_URL_GROUP)); diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisher.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisher.java index 13b7f15ef..c15e7a1a2 100644 --- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisher.java +++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisher.java @@ -21,6 +21,8 @@ package org.wso2.micro.gateway.enforcer.throttle.databridge.publisher; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.wso2.carbon.databridge.commons.exception.TransportException; +import org.wso2.micro.gateway.enforcer.config.ConfigHolder; +import org.wso2.micro.gateway.enforcer.config.dto.ThrottlePublisherConfigDto; import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.DataPublisher; import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.exception.DataEndpointAuthenticationException; import org.wso2.micro.gateway.enforcer.throttle.databridge.agent.exception.DataEndpointConfigurationException; @@ -57,19 +59,20 @@ public class ThrottleDataPublisher { */ public ThrottleDataPublisher() { dataPublisherPool = ThrottleDataPublisherPool.getInstance(); - PublisherConfiguration publisherConfiguration = PublisherConfiguration.getInstance(); + ThrottlePublisherConfigDto throttlePublisherConfigDto = ConfigHolder.getInstance().getConfig(). + getThrottleConfig().getThrottleAgent().getPublisher(); try { executor = new DataPublisherThreadPoolExecutor( - publisherConfiguration.getPublisherThreadPoolCoreSize(), - publisherConfiguration.getPublisherThreadPoolMaximumSize(), - publisherConfiguration.getPublisherThreadPoolKeepAliveTime(), + throttlePublisherConfigDto.getPublisherThreadPoolCoreSize(), + throttlePublisherConfigDto.getPublisherThreadPoolMaximumSize(), + throttlePublisherConfigDto.getPublisherThreadPoolKeepAliveTime(), TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>() { }); - dataPublisher = new DataPublisher(publisherConfiguration.getReceiverUrlGroup(), - publisherConfiguration.getAuthUrlGroup(), publisherConfiguration.getUserName(), - publisherConfiguration.getPassword()); + dataPublisher = new DataPublisher(throttlePublisherConfigDto.getReceiverUrlGroup(), + throttlePublisherConfigDto.getAuthUrlGroup(), throttlePublisherConfigDto.getUserName(), + throttlePublisherConfigDto.getPassword()); } catch (DataEndpointException | DataEndpointConfigurationException | DataEndpointAuthenticationException | TransportException e) { diff --git a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisherPool.java b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisherPool.java index a8257ac94..a60e2748e 100644 --- a/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisherPool.java +++ b/enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisherPool.java @@ -23,6 +23,8 @@ import org.apache.commons.pool.ObjectPool; import org.apache.commons.pool.impl.StackObjectPool; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.wso2.micro.gateway.enforcer.config.ConfigHolder; +import org.wso2.micro.gateway.enforcer.config.dto.ThrottlePublisherConfigDto; /** * This class implemented to hold throttle data publishing agent pool. Reason for implement this is to @@ -43,7 +45,8 @@ public class ThrottleDataPublisherPool { // active" instance created by the pool, but is quite useful for re-using Objects without introducing // artificial limits. //Proper tuning is mandatory for good performance according to system load. - PublisherConfiguration configuration = PublisherConfiguration.getInstance(); + ThrottlePublisherConfigDto configuration = ConfigHolder.getInstance().getConfig().getThrottleConfig() + .getThrottleAgent().getPublisher(); clientPool = new StackObjectPool(new BasePoolableObjectFactory() { @Override public Object makeObject() throws Exception {
['enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/dto/ThrottleAgentConfigDto.java', 'enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/PublisherConfiguration.java', 'enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisher.java', 'enforcer/src/main/java/org/wso2/micro/gateway/enforcer/throttle/databridge/publisher/ThrottleDataPublisherPool.java', 'enforcer/src/main/java/org/wso2/micro/gateway/enforcer/config/ConfigHolder.java']
{'.java': 5}
5
5
0
0
5
2,784,312
608,089
79,278
313
2,751
427
35
5
708
96
154
21
0
1
1970-01-01T00:26:56
247
Java
{'Java': 2861210, 'Go': 979303, 'Lua': 49518, 'Shell': 37030, 'C++': 27281, 'Dockerfile': 16279, 'HTML': 5630, 'Starlark': 2894, 'Jinja': 1646, 'Open Policy Agent': 539}
Apache License 2.0